Always call circuit_n_chan_done(chan, 0) from channel_closed()
[tor.git] / src / or / channel.c
blob1fb39b88cac42bc6ac36cc234dd13810b12ff4e9
1 /* * Copyright (c) 2012-2013, The Tor Project, Inc. */
2 /* See LICENSE for licensing information */
4 /**
5 * \file channel.c
6 * \brief OR-to-OR channel abstraction layer
7 **/
9 /*
10 * Define this so channel.h gives us things only channel_t subclasses
11 * should touch.
14 #define TOR_CHANNEL_INTERNAL_
16 #include "or.h"
17 #include "channel.h"
18 #include "channeltls.h"
19 #include "circuitbuild.h"
20 #include "circuitlist.h"
21 #include "circuitstats.h"
22 #include "connection_or.h" /* For var_cell_free() */
23 #include "circuitmux.h"
24 #include "entrynodes.h"
25 #include "geoip.h"
26 #include "nodelist.h"
27 #include "relay.h"
28 #include "rephist.h"
29 #include "router.h"
30 #include "routerlist.h"
32 /* Cell queue structure */
34 typedef struct cell_queue_entry_s cell_queue_entry_t;
35 struct cell_queue_entry_s {
36 TOR_SIMPLEQ_ENTRY(cell_queue_entry_s) next;
37 enum {
38 CELL_QUEUE_FIXED,
39 CELL_QUEUE_VAR,
40 CELL_QUEUE_PACKED
41 } type;
42 union {
43 struct {
44 cell_t *cell;
45 } fixed;
46 struct {
47 var_cell_t *var_cell;
48 } var;
49 struct {
50 packed_cell_t *packed_cell;
51 } packed;
52 } u;
55 /* Global lists of channels */
57 /* All channel_t instances */
58 static smartlist_t *all_channels = NULL;
60 /* All channel_t instances not in ERROR or CLOSED states */
61 static smartlist_t *active_channels = NULL;
63 /* All channel_t instances in ERROR or CLOSED states */
64 static smartlist_t *finished_channels = NULL;
66 /* All channel_listener_t instances */
67 static smartlist_t *all_listeners = NULL;
69 /* All channel_listener_t instances in LISTENING state */
70 static smartlist_t *active_listeners = NULL;
72 /* All channel_listener_t instances in LISTENING state */
73 static smartlist_t *finished_listeners = NULL;
75 /* Counter for ID numbers */
76 static uint64_t n_channels_allocated = 0;
78 /* Digest->channel map
80 * Similar to the one used in connection_or.c, this maps from the identity
81 * digest of a remote endpoint to a channel_t to that endpoint. Channels
82 * should be placed here when registered and removed when they close or error.
83 * If more than one channel exists, follow the next_with_same_id pointer
84 * as a linked list.
86 HT_HEAD(channel_idmap, channel_idmap_entry_s) channel_identity_map =
87 HT_INITIALIZER();
89 typedef struct channel_idmap_entry_s {
90 HT_ENTRY(channel_idmap_entry_s) node;
91 uint8_t digest[DIGEST_LEN];
92 TOR_LIST_HEAD(channel_list_s, channel_s) channel_list;
93 } channel_idmap_entry_t;
95 static INLINE unsigned
96 channel_idmap_hash(const channel_idmap_entry_t *ent)
98 const unsigned *a = (const unsigned *)ent->digest;
99 #if SIZEOF_INT == 4
100 return a[0] ^ a[1] ^ a[2] ^ a[3] ^ a[4];
101 #elif SIZEOF_INT == 8
102 return a[0] ^ a[1];
103 #endif
106 static INLINE int
107 channel_idmap_eq(const channel_idmap_entry_t *a,
108 const channel_idmap_entry_t *b)
110 return tor_memeq(a->digest, b->digest, DIGEST_LEN);
113 HT_PROTOTYPE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
114 channel_idmap_eq);
115 HT_GENERATE(channel_idmap, channel_idmap_entry_s, node, channel_idmap_hash,
116 channel_idmap_eq, 0.5, tor_malloc, tor_realloc, tor_free_);
118 static cell_queue_entry_t * cell_queue_entry_dup(cell_queue_entry_t *q);
119 static void cell_queue_entry_free(cell_queue_entry_t *q, int handed_off);
120 static int cell_queue_entry_is_padding(cell_queue_entry_t *q);
121 static cell_queue_entry_t *
122 cell_queue_entry_new_fixed(cell_t *cell);
123 static cell_queue_entry_t *
124 cell_queue_entry_new_var(var_cell_t *var_cell);
126 /* Functions to maintain the digest map */
127 static void channel_add_to_digest_map(channel_t *chan);
128 static void channel_remove_from_digest_map(channel_t *chan);
131 * Flush cells from just the outgoing queue without trying to get them
132 * from circuits; used internall by channel_flush_some_cells().
134 static ssize_t
135 channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
136 ssize_t num_cells);
137 static void channel_force_free(channel_t *chan);
138 static void
139 channel_free_list(smartlist_t *channels, int mark_for_close);
140 static void
141 channel_listener_free_list(smartlist_t *channels, int mark_for_close);
142 static void channel_listener_force_free(channel_listener_t *chan_l);
143 static void
144 channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q);
146 /***********************************
147 * Channel state utility functions *
148 **********************************/
151 * Indicate whether a given channel state is valid
155 channel_state_is_valid(channel_state_t state)
157 int is_valid;
159 switch (state) {
160 case CHANNEL_STATE_CLOSED:
161 case CHANNEL_STATE_CLOSING:
162 case CHANNEL_STATE_ERROR:
163 case CHANNEL_STATE_MAINT:
164 case CHANNEL_STATE_OPENING:
165 case CHANNEL_STATE_OPEN:
166 is_valid = 1;
167 break;
168 case CHANNEL_STATE_LAST:
169 default:
170 is_valid = 0;
173 return is_valid;
177 * Indicate whether a given channel listener state is valid
181 channel_listener_state_is_valid(channel_listener_state_t state)
183 int is_valid;
185 switch (state) {
186 case CHANNEL_LISTENER_STATE_CLOSED:
187 case CHANNEL_LISTENER_STATE_LISTENING:
188 case CHANNEL_LISTENER_STATE_CLOSING:
189 case CHANNEL_LISTENER_STATE_ERROR:
190 is_valid = 1;
191 break;
192 case CHANNEL_LISTENER_STATE_LAST:
193 default:
194 is_valid = 0;
197 return is_valid;
201 * Indicate whether a channel state transition is valid
203 * This function takes two channel states and indicates whether a
204 * transition between them is permitted (see the state definitions and
205 * transition table in or.h at the channel_state_t typedef).
209 channel_state_can_transition(channel_state_t from, channel_state_t to)
211 int is_valid;
213 switch (from) {
214 case CHANNEL_STATE_CLOSED:
215 is_valid = (to == CHANNEL_STATE_OPENING);
216 break;
217 case CHANNEL_STATE_CLOSING:
218 is_valid = (to == CHANNEL_STATE_CLOSED ||
219 to == CHANNEL_STATE_ERROR);
220 break;
221 case CHANNEL_STATE_ERROR:
222 is_valid = 0;
223 break;
224 case CHANNEL_STATE_MAINT:
225 is_valid = (to == CHANNEL_STATE_CLOSING ||
226 to == CHANNEL_STATE_ERROR ||
227 to == CHANNEL_STATE_OPEN);
228 break;
229 case CHANNEL_STATE_OPENING:
230 is_valid = (to == CHANNEL_STATE_CLOSING ||
231 to == CHANNEL_STATE_ERROR ||
232 to == CHANNEL_STATE_OPEN);
233 break;
234 case CHANNEL_STATE_OPEN:
235 is_valid = (to == CHANNEL_STATE_CLOSING ||
236 to == CHANNEL_STATE_ERROR ||
237 to == CHANNEL_STATE_MAINT);
238 break;
239 case CHANNEL_STATE_LAST:
240 default:
241 is_valid = 0;
244 return is_valid;
248 * Indicate whether a channel listener state transition is valid
250 * This function takes two channel listener states and indicates whether a
251 * transition between them is permitted (see the state definitions and
252 * transition table in or.h at the channel_listener_state_t typedef).
256 channel_listener_state_can_transition(channel_listener_state_t from,
257 channel_listener_state_t to)
259 int is_valid;
261 switch (from) {
262 case CHANNEL_LISTENER_STATE_CLOSED:
263 is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
264 break;
265 case CHANNEL_LISTENER_STATE_CLOSING:
266 is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
267 to == CHANNEL_LISTENER_STATE_ERROR);
268 break;
269 case CHANNEL_LISTENER_STATE_ERROR:
270 is_valid = 0;
271 break;
272 case CHANNEL_LISTENER_STATE_LISTENING:
273 is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
274 to == CHANNEL_LISTENER_STATE_ERROR);
275 break;
276 case CHANNEL_LISTENER_STATE_LAST:
277 default:
278 is_valid = 0;
281 return is_valid;
285 * Return a human-readable description for a channel state
288 const char *
289 channel_state_to_string(channel_state_t state)
291 const char *descr;
293 switch (state) {
294 case CHANNEL_STATE_CLOSED:
295 descr = "closed";
296 break;
297 case CHANNEL_STATE_CLOSING:
298 descr = "closing";
299 break;
300 case CHANNEL_STATE_ERROR:
301 descr = "channel error";
302 break;
303 case CHANNEL_STATE_MAINT:
304 descr = "temporarily suspended for maintenance";
305 break;
306 case CHANNEL_STATE_OPENING:
307 descr = "opening";
308 break;
309 case CHANNEL_STATE_OPEN:
310 descr = "open";
311 break;
312 case CHANNEL_STATE_LAST:
313 default:
314 descr = "unknown or invalid channel state";
317 return descr;
321 * Return a human-readable description for a channel listenier state
324 const char *
325 channel_listener_state_to_string(channel_listener_state_t state)
327 const char *descr;
329 switch (state) {
330 case CHANNEL_LISTENER_STATE_CLOSED:
331 descr = "closed";
332 break;
333 case CHANNEL_LISTENER_STATE_CLOSING:
334 descr = "closing";
335 break;
336 case CHANNEL_LISTENER_STATE_ERROR:
337 descr = "channel listener error";
338 break;
339 case CHANNEL_LISTENER_STATE_LISTENING:
340 descr = "listening";
341 break;
342 case CHANNEL_LISTENER_STATE_LAST:
343 default:
344 descr = "unknown or invalid channel listener state";
347 return descr;
350 /***************************************
351 * Channel registration/unregistration *
352 ***************************************/
355 * Register a channel
357 * This function registers a newly created channel in the global lists/maps
358 * of active channels.
361 void
362 channel_register(channel_t *chan)
364 tor_assert(chan);
366 /* No-op if already registered */
367 if (chan->registered) return;
369 log_debug(LD_CHANNEL,
370 "Registering channel %p (ID " U64_FORMAT ") "
371 "in state %s (%d) with digest %s",
372 chan, U64_PRINTF_ARG(chan->global_identifier),
373 channel_state_to_string(chan->state), chan->state,
374 hex_str(chan->identity_digest, DIGEST_LEN));
376 /* Make sure we have all_channels, then add it */
377 if (!all_channels) all_channels = smartlist_new();
378 smartlist_add(all_channels, chan);
380 /* Is it finished? */
381 if (chan->state == CHANNEL_STATE_CLOSED ||
382 chan->state == CHANNEL_STATE_ERROR) {
383 /* Put it in the finished list, creating it if necessary */
384 if (!finished_channels) finished_channels = smartlist_new();
385 smartlist_add(finished_channels, chan);
386 } else {
387 /* Put it in the active list, creating it if necessary */
388 if (!active_channels) active_channels = smartlist_new();
389 smartlist_add(active_channels, chan);
391 if (chan->state != CHANNEL_STATE_CLOSING) {
392 /* It should have a digest set */
393 if (!tor_digest_is_zero(chan->identity_digest)) {
394 /* Yeah, we're good, add it to the map */
395 channel_add_to_digest_map(chan);
396 } else {
397 log_info(LD_CHANNEL,
398 "Channel %p (global ID " U64_FORMAT ") "
399 "in state %s (%d) registered with no identity digest",
400 chan, U64_PRINTF_ARG(chan->global_identifier),
401 channel_state_to_string(chan->state), chan->state);
406 /* Mark it as registered */
407 chan->registered = 1;
411 * Unregister a channel
413 * This function removes a channel from the global lists and maps and is used
414 * when freeing a closed/errored channel.
417 void
418 channel_unregister(channel_t *chan)
420 tor_assert(chan);
422 /* No-op if not registered */
423 if (!(chan->registered)) return;
425 /* Is it finished? */
426 if (chan->state == CHANNEL_STATE_CLOSED ||
427 chan->state == CHANNEL_STATE_ERROR) {
428 /* Get it out of the finished list */
429 if (finished_channels) smartlist_remove(finished_channels, chan);
430 } else {
431 /* Get it out of the active list */
432 if (active_channels) smartlist_remove(active_channels, chan);
435 /* Get it out of all_channels */
436 if (all_channels) smartlist_remove(all_channels, chan);
438 /* Mark it as unregistered */
439 chan->registered = 0;
441 /* Should it be in the digest map? */
442 if (!tor_digest_is_zero(chan->identity_digest) &&
443 !(chan->state == CHANNEL_STATE_CLOSING ||
444 chan->state == CHANNEL_STATE_CLOSED ||
445 chan->state == CHANNEL_STATE_ERROR)) {
446 /* Remove it */
447 channel_remove_from_digest_map(chan);
452 * Register a channel listener
454 * This function registers a newly created channel listner in the global
455 * lists/maps of active channel listeners.
458 void
459 channel_listener_register(channel_listener_t *chan_l)
461 tor_assert(chan_l);
463 /* No-op if already registered */
464 if (chan_l->registered) return;
466 log_debug(LD_CHANNEL,
467 "Registering channel listener %p (ID " U64_FORMAT ") "
468 "in state %s (%d)",
469 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
470 channel_listener_state_to_string(chan_l->state),
471 chan_l->state);
473 /* Make sure we have all_channels, then add it */
474 if (!all_listeners) all_listeners = smartlist_new();
475 smartlist_add(all_listeners, chan_l);
477 /* Is it finished? */
478 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
479 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
480 /* Put it in the finished list, creating it if necessary */
481 if (!finished_listeners) finished_listeners = smartlist_new();
482 smartlist_add(finished_listeners, chan_l);
483 } else {
484 /* Put it in the active list, creating it if necessary */
485 if (!active_listeners) active_listeners = smartlist_new();
486 smartlist_add(active_listeners, chan_l);
489 /* Mark it as registered */
490 chan_l->registered = 1;
494 * Unregister a channel listener
496 * This function removes a channel listener from the global lists and maps
497 * and is used when freeing a closed/errored channel listener.
500 void
501 channel_listener_unregister(channel_listener_t *chan_l)
503 tor_assert(chan_l);
505 /* No-op if not registered */
506 if (!(chan_l->registered)) return;
508 /* Is it finished? */
509 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
510 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
511 /* Get it out of the finished list */
512 if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
513 } else {
514 /* Get it out of the active list */
515 if (active_listeners) smartlist_remove(active_listeners, chan_l);
518 /* Get it out of all_channels */
519 if (all_listeners) smartlist_remove(all_listeners, chan_l);
521 /* Mark it as unregistered */
522 chan_l->registered = 0;
525 /*********************************
526 * Channel digest map maintenance
527 *********************************/
530 * Add a channel to the digest map
532 * This function adds a channel to the digest map and inserts it into the
533 * correct linked list if channels with that remote endpoint identity digest
534 * already exist.
537 static void
538 channel_add_to_digest_map(channel_t *chan)
540 channel_idmap_entry_t *ent, search;
542 tor_assert(chan);
544 /* Assert that the state makes sense */
545 tor_assert(!(chan->state == CHANNEL_STATE_CLOSING ||
546 chan->state == CHANNEL_STATE_CLOSED ||
547 chan->state == CHANNEL_STATE_ERROR));
549 /* Assert that there is a digest */
550 tor_assert(!tor_digest_is_zero(chan->identity_digest));
552 memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
553 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
554 if (! ent) {
555 ent = tor_malloc(sizeof(channel_idmap_entry_t));
556 memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
557 TOR_LIST_INIT(&ent->channel_list);
558 HT_INSERT(channel_idmap, &channel_identity_map, ent);
560 TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
562 log_debug(LD_CHANNEL,
563 "Added channel %p (global ID " U64_FORMAT ") "
564 "to identity map in state %s (%d) with digest %s",
565 chan, U64_PRINTF_ARG(chan->global_identifier),
566 channel_state_to_string(chan->state), chan->state,
567 hex_str(chan->identity_digest, DIGEST_LEN));
571 * Remove a channel from the digest map
573 * This function removes a channel from the digest map and the linked list of
574 * channels for that digest if more than one exists.
577 static void
578 channel_remove_from_digest_map(channel_t *chan)
580 channel_idmap_entry_t *ent, search;
582 tor_assert(chan);
584 /* Assert that there is a digest */
585 tor_assert(!tor_digest_is_zero(chan->identity_digest));
587 #if 0
588 /* Make sure we have a map */
589 if (!channel_identity_map) {
591 * No identity map, so we can't find it by definition. This
592 * case is similar to digestmap_get() failing below.
594 log_warn(LD_BUG,
595 "Trying to remove channel %p (global ID " U64_FORMAT ") "
596 "with digest %s from identity map, but didn't have any identity "
597 "map",
598 chan, U64_PRINTF_ARG(chan->global_identifier),
599 hex_str(chan->identity_digest, DIGEST_LEN));
600 /* Clear out its next/prev pointers */
601 if (chan->next_with_same_id) {
602 chan->next_with_same_id->prev_with_same_id = chan->prev_with_same_id;
604 if (chan->prev_with_same_id) {
605 chan->prev_with_same_id->next_with_same_id = chan->next_with_same_id;
607 chan->next_with_same_id = NULL;
608 chan->prev_with_same_id = NULL;
610 return;
612 #endif
614 /* Pull it out of its list, wherever that list is */
615 TOR_LIST_REMOVE(chan, next_with_same_id);
617 memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
618 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
620 /* Look for it in the map */
621 if (ent) {
622 /* Okay, it's here */
624 if (TOR_LIST_EMPTY(&ent->channel_list)) {
625 HT_REMOVE(channel_idmap, &channel_identity_map, ent);
626 tor_free(ent);
629 log_debug(LD_CHANNEL,
630 "Removed channel %p (global ID " U64_FORMAT ") from "
631 "identity map in state %s (%d) with digest %s",
632 chan, U64_PRINTF_ARG(chan->global_identifier),
633 channel_state_to_string(chan->state), chan->state,
634 hex_str(chan->identity_digest, DIGEST_LEN));
635 } else {
636 /* Shouldn't happen */
637 log_warn(LD_BUG,
638 "Trying to remove channel %p (global ID " U64_FORMAT ") with "
639 "digest %s from identity map, but couldn't find any with "
640 "that digest",
641 chan, U64_PRINTF_ARG(chan->global_identifier),
642 hex_str(chan->identity_digest, DIGEST_LEN));
646 /****************************
647 * Channel lookup functions *
648 ***************************/
651 * Find channel by global ID
653 * This function searches for a channel by the global_identifier assigned
654 * at initialization time. This identifier is unique for the lifetime of the
655 * Tor process.
658 channel_t *
659 channel_find_by_global_id(uint64_t global_identifier)
661 channel_t *rv = NULL;
663 if (all_channels && smartlist_len(all_channels) > 0) {
664 SMARTLIST_FOREACH_BEGIN(all_channels, channel_t *, curr) {
665 if (curr->global_identifier == global_identifier) {
666 rv = curr;
667 break;
669 } SMARTLIST_FOREACH_END(curr);
672 return rv;
676 * Find channel by digest of the remote endpoint
678 * This function looks up a channel by the digest of its remote endpoint in
679 * the channel digest map. It's possible that more than one channel to a
680 * given endpoint exists. Use channel_next_with_digest() to walk the list.
683 channel_t *
684 channel_find_by_remote_digest(const char *identity_digest)
686 channel_t *rv = NULL;
687 channel_idmap_entry_t *ent, search;
689 tor_assert(identity_digest);
691 memcpy(search.digest, identity_digest, DIGEST_LEN);
692 ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
693 if (ent) {
694 rv = TOR_LIST_FIRST(&ent->channel_list);
697 return rv;
701 * Get next channel with digest
703 * This function takes a channel and finds the next channel in the list
704 * with the same digest.
707 channel_t *
708 channel_next_with_digest(channel_t *chan)
710 tor_assert(chan);
712 return TOR_LIST_NEXT(chan, next_with_same_id);
716 * Initialize a channel
718 * This function should be called by subclasses to set up some per-channel
719 * variables. I.e., this is the superclass constructor. Before this, the
720 * channel should be allocated with tor_malloc_zero().
723 void
724 channel_init(channel_t *chan)
726 tor_assert(chan);
728 /* Assign an ID and bump the counter */
729 chan->global_identifier = n_channels_allocated++;
731 /* Init timestamp */
732 chan->timestamp_last_added_nonpadding = time(NULL);
734 /* Init next_circ_id */
735 chan->next_circ_id = crypto_rand_int(1 << 15);
737 /* Initialize queues. */
738 TOR_SIMPLEQ_INIT(&chan->incoming_queue);
739 TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
741 /* Initialize list entries. */
742 memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));
744 /* Timestamp it */
745 channel_timestamp_created(chan);
749 * Initialize a channel listener
751 * This function should be called by subclasses to set up some per-channel
752 * variables. I.e., this is the superclass constructor. Before this, the
753 * channel listener should be allocated with tor_malloc_zero().
756 void
757 channel_init_listener(channel_listener_t *chan_l)
759 tor_assert(chan_l);
761 /* Assign an ID and bump the counter */
762 chan_l->global_identifier = n_channels_allocated++;
764 /* Timestamp it */
765 channel_listener_timestamp_created(chan_l);
769 * Free a channel; nothing outside of channel.c and subclasses should call
770 * this - it frees channels after they have closed and been unregistered.
773 void
774 channel_free(channel_t *chan)
776 if (!chan) return;
778 /* It must be closed or errored */
779 tor_assert(chan->state == CHANNEL_STATE_CLOSED ||
780 chan->state == CHANNEL_STATE_ERROR);
781 /* It must be deregistered */
782 tor_assert(!(chan->registered));
784 log_debug(LD_CHANNEL,
785 "Freeing channel " U64_FORMAT " at %p",
786 U64_PRINTF_ARG(chan->global_identifier), chan);
789 * Get rid of cmux policy before we do anything, so cmux policies don't
790 * see channels in weird half-freed states.
792 if (chan->cmux) {
793 circuitmux_set_policy(chan->cmux, NULL);
796 /* Call a free method if there is one */
797 if (chan->free) chan->free(chan);
799 channel_clear_remote_end(chan);
801 /* Get rid of cmux */
802 if (chan->cmux) {
803 circuitmux_detach_all_circuits(chan->cmux);
804 circuitmux_free(chan->cmux);
805 chan->cmux = NULL;
808 /* We're in CLOSED or ERROR, so the cell queue is already empty */
810 tor_free(chan);
814 * Free a channel listener; nothing outside of channel.c and subclasses
815 * should call this - it frees channel listeners after they have closed and
816 * been unregistered.
819 void
820 channel_listener_free(channel_listener_t *chan_l)
822 if (!chan_l) return;
824 log_debug(LD_CHANNEL,
825 "Freeing channel_listener_t " U64_FORMAT " at %p",
826 U64_PRINTF_ARG(chan_l->global_identifier),
827 chan_l);
829 /* It must be closed or errored */
830 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
831 chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
832 /* It must be deregistered */
833 tor_assert(!(chan_l->registered));
835 /* Call a free method if there is one */
836 if (chan_l->free) chan_l->free(chan_l);
839 * We're in CLOSED or ERROR, so the incoming channel queue is already
840 * empty.
843 tor_free(chan_l);
847 * Free a channel and skip the state/registration asserts; this internal-
848 * use-only function should be called only from channel_free_all() when
849 * shutting down the Tor process.
852 static void
853 channel_force_free(channel_t *chan)
855 cell_queue_entry_t *cell, *cell_tmp;
856 tor_assert(chan);
858 log_debug(LD_CHANNEL,
859 "Force-freeing channel " U64_FORMAT " at %p",
860 U64_PRINTF_ARG(chan->global_identifier), chan);
863 * Get rid of cmux policy before we do anything, so cmux policies don't
864 * see channels in weird half-freed states.
866 if (chan->cmux) {
867 circuitmux_set_policy(chan->cmux, NULL);
870 /* Call a free method if there is one */
871 if (chan->free) chan->free(chan);
873 channel_clear_remote_end(chan);
875 /* Get rid of cmux */
876 if (chan->cmux) {
877 circuitmux_free(chan->cmux);
878 chan->cmux = NULL;
881 /* We might still have a cell queue; kill it */
882 TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->incoming_queue, next, cell_tmp) {
883 cell_queue_entry_free(cell, 0);
885 TOR_SIMPLEQ_INIT(&chan->incoming_queue);
887 /* Outgoing cell queue is similar, but we can have to free packed cells */
888 TOR_SIMPLEQ_FOREACH_SAFE(cell, &chan->outgoing_queue, next, cell_tmp) {
889 cell_queue_entry_free(cell, 0);
891 TOR_SIMPLEQ_INIT(&chan->outgoing_queue);
893 tor_free(chan);
897 * Free a channel listener and skip the state/reigstration asserts; this
898 * internal-use-only function should be called only from channel_free_all()
899 * when shutting down the Tor process.
902 static void
903 channel_listener_force_free(channel_listener_t *chan_l)
905 tor_assert(chan_l);
907 log_debug(LD_CHANNEL,
908 "Force-freeing channel_listener_t " U64_FORMAT " at %p",
909 U64_PRINTF_ARG(chan_l->global_identifier),
910 chan_l);
912 /* Call a free method if there is one */
913 if (chan_l->free) chan_l->free(chan_l);
916 * The incoming list just gets emptied and freed; we request close on
917 * any channels we find there, but since we got called while shutting
918 * down they will get deregistered and freed elsewhere anyway.
920 if (chan_l->incoming_list) {
921 SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
922 channel_t *, qchan) {
923 channel_mark_for_close(qchan);
924 } SMARTLIST_FOREACH_END(qchan);
926 smartlist_free(chan_l->incoming_list);
927 chan_l->incoming_list = NULL;
930 tor_free(chan_l);
934 * Return the current registered listener for a channel listener
936 * This function returns a function pointer to the current registered
937 * handler for new incoming channels on a channel listener.
940 channel_listener_fn_ptr
941 channel_listener_get_listener_fn(channel_listener_t *chan_l)
943 tor_assert(chan_l);
945 if (chan_l->state == CHANNEL_LISTENER_STATE_LISTENING)
946 return chan_l->listener;
948 return NULL;
952 * Set the listener for a channel listener
954 * This function sets the handler for new incoming channels on a channel
955 * listener.
958 void
959 channel_listener_set_listener_fn(channel_listener_t *chan_l,
960 channel_listener_fn_ptr listener)
962 tor_assert(chan_l);
963 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
965 log_debug(LD_CHANNEL,
966 "Setting listener callback for channel listener %p "
967 "(global ID " U64_FORMAT ") to %p",
968 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
969 listener);
971 chan_l->listener = listener;
972 if (chan_l->listener) channel_listener_process_incoming(chan_l);
976 * Return the fixed-length cell handler for a channel
978 * This function gets the handler for incoming fixed-length cells installed
979 * on a channel.
982 channel_cell_handler_fn_ptr
983 channel_get_cell_handler(channel_t *chan)
985 tor_assert(chan);
987 if (chan->state == CHANNEL_STATE_OPENING ||
988 chan->state == CHANNEL_STATE_OPEN ||
989 chan->state == CHANNEL_STATE_MAINT)
990 return chan->cell_handler;
992 return NULL;
996 * Return the variable-length cell handler for a channel
998 * This function gets the handler for incoming variable-length cells
999 * installed on a channel.
1002 channel_var_cell_handler_fn_ptr
1003 channel_get_var_cell_handler(channel_t *chan)
1005 tor_assert(chan);
1007 if (chan->state == CHANNEL_STATE_OPENING ||
1008 chan->state == CHANNEL_STATE_OPEN ||
1009 chan->state == CHANNEL_STATE_MAINT)
1010 return chan->var_cell_handler;
1012 return NULL;
1016 * Set both cell handlers for a channel
1018 * This function sets both the fixed-length and variable length cell handlers
1019 * for a channel and processes any incoming cells that had been blocked in the
1020 * queue because none were available.
1023 void
1024 channel_set_cell_handlers(channel_t *chan,
1025 channel_cell_handler_fn_ptr cell_handler,
1026 channel_var_cell_handler_fn_ptr
1027 var_cell_handler)
1029 int try_again = 0;
1031 tor_assert(chan);
1032 tor_assert(chan->state == CHANNEL_STATE_OPENING ||
1033 chan->state == CHANNEL_STATE_OPEN ||
1034 chan->state == CHANNEL_STATE_MAINT);
1036 log_debug(LD_CHANNEL,
1037 "Setting cell_handler callback for channel %p to %p",
1038 chan, cell_handler);
1039 log_debug(LD_CHANNEL,
1040 "Setting var_cell_handler callback for channel %p to %p",
1041 chan, var_cell_handler);
1043 /* Should we try the queue? */
1044 if (cell_handler &&
1045 cell_handler != chan->cell_handler) try_again = 1;
1046 if (var_cell_handler &&
1047 var_cell_handler != chan->var_cell_handler) try_again = 1;
1049 /* Change them */
1050 chan->cell_handler = cell_handler;
1051 chan->var_cell_handler = var_cell_handler;
1053 /* Re-run the queue if we have one and there's any reason to */
1054 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue) &&
1055 try_again &&
1056 (chan->cell_handler ||
1057 chan->var_cell_handler)) channel_process_cells(chan);
1061 * On closing channels
1063 * There are three functions that close channels, for use in
1064 * different circumstances:
1066 * - Use channel_mark_for_close() for most cases
1067 * - Use channel_close_from_lower_layer() if you are connection_or.c
1068 * and the other end closes the underlying connection.
1069 * - Use channel_close_for_error() if you are connection_or.c and
1070 * some sort of error has occurred.
1074 * Mark a channel for closure
1076 * This function tries to close a channel_t; it will go into the CLOSING
1077 * state, and eventually the lower layer should put it into the CLOSED or
1078 * ERROR state. Then, channel_run_cleanup() will eventually free it.
1081 void
1082 channel_mark_for_close(channel_t *chan)
1084 tor_assert(chan != NULL);
1085 tor_assert(chan->close != NULL);
1087 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1088 if (chan->state == CHANNEL_STATE_CLOSING ||
1089 chan->state == CHANNEL_STATE_CLOSED ||
1090 chan->state == CHANNEL_STATE_ERROR) return;
1092 log_debug(LD_CHANNEL,
1093 "Closing channel %p (global ID " U64_FORMAT ") "
1094 "by request",
1095 chan, U64_PRINTF_ARG(chan->global_identifier));
1097 /* Note closing by request from above */
1098 chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
1100 /* Change state to CLOSING */
1101 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1103 /* Tell the lower layer */
1104 chan->close(chan);
1107 * It's up to the lower layer to change state to CLOSED or ERROR when we're
1108 * ready; we'll try to free channels that are in the finished list from
1109 * channel_run_cleanup(). The lower layer should do this by calling
1110 * channel_closed().
1115 * Mark a channel listener for closure
1117 * This function tries to close a channel_listener_t; it will go into the
1118 * CLOSING state, and eventually the lower layer should put it into the CLOSED
1119 * or ERROR state. Then, channel_run_cleanup() will eventually free it.
1122 void
1123 channel_listener_mark_for_close(channel_listener_t *chan_l)
1125 tor_assert(chan_l != NULL);
1126 tor_assert(chan_l->close != NULL);
1128 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1129 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1130 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1131 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1133 log_debug(LD_CHANNEL,
1134 "Closing channel listener %p (global ID " U64_FORMAT ") "
1135 "by request",
1136 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1138 /* Note closing by request from above */
1139 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
1141 /* Change state to CLOSING */
1142 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1144 /* Tell the lower layer */
1145 chan_l->close(chan_l);
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_listener_closed().
1156 * Close a channel from the lower layer
1158 * Notify the channel code that the channel is being closed due to a non-error
1159 * condition in the lower layer. This does not call the close() method, since
1160 * the lower layer already knows.
1163 void
1164 channel_close_from_lower_layer(channel_t *chan)
1166 tor_assert(chan != NULL);
1168 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1169 if (chan->state == CHANNEL_STATE_CLOSING ||
1170 chan->state == CHANNEL_STATE_CLOSED ||
1171 chan->state == CHANNEL_STATE_ERROR) return;
1173 log_debug(LD_CHANNEL,
1174 "Closing channel %p (global ID " U64_FORMAT ") "
1175 "due to lower-layer event",
1176 chan, U64_PRINTF_ARG(chan->global_identifier));
1178 /* Note closing by event from below */
1179 chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
1181 /* Change state to CLOSING */
1182 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1186 * Close a channel listener from the lower layer
1188 * Notify the channel code that the channel listener is being closed due to a
1189 * non-error condition in the lower layer. This does not call the close()
1190 * method, since the lower layer already knows.
1193 void
1194 channel_listener_close_from_lower_layer(channel_listener_t *chan_l)
1196 tor_assert(chan_l != NULL);
1198 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1199 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1200 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1201 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1203 log_debug(LD_CHANNEL,
1204 "Closing channel listener %p (global ID " U64_FORMAT ") "
1205 "due to lower-layer event",
1206 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1208 /* Note closing by event from below */
1209 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FROM_BELOW;
1211 /* Change state to CLOSING */
1212 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1216 * Notify that the channel is being closed due to an error condition
1218 * This function is called by the lower layer implementing the transport
1219 * when a channel must be closed due to an error condition. This does not
1220 * call the channel's close method, since the lower layer already knows.
1223 void
1224 channel_close_for_error(channel_t *chan)
1226 tor_assert(chan != NULL);
1228 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1229 if (chan->state == CHANNEL_STATE_CLOSING ||
1230 chan->state == CHANNEL_STATE_CLOSED ||
1231 chan->state == CHANNEL_STATE_ERROR) return;
1233 log_debug(LD_CHANNEL,
1234 "Closing channel %p due to lower-layer error",
1235 chan);
1237 /* Note closing by event from below */
1238 chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
1240 /* Change state to CLOSING */
1241 channel_change_state(chan, CHANNEL_STATE_CLOSING);
1245 * Notify that the channel listener is being closed due to an error condition
1247 * This function is called by the lower layer implementing the transport
1248 * when a channel listener must be closed due to an error condition. This
1249 * does not call the channel listener's close method, since the lower layer
1250 * already knows.
1253 void
1254 channel_listener_close_for_error(channel_listener_t *chan_l)
1256 tor_assert(chan_l != NULL);
1258 /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1259 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1260 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1261 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1263 log_debug(LD_CHANNEL,
1264 "Closing channel listener %p (global ID " U64_FORMAT ") "
1265 "due to lower-layer error",
1266 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1268 /* Note closing by event from below */
1269 chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_FOR_ERROR;
1271 /* Change state to CLOSING */
1272 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1276 * Notify that the lower layer is finished closing the channel
1278 * This function should be called by the lower layer when a channel
1279 * is finished closing and it should be regarded as inactive and
1280 * freed by the channel code.
1283 void
1284 channel_closed(channel_t *chan)
1286 tor_assert(chan);
1287 tor_assert(chan->state == CHANNEL_STATE_CLOSING ||
1288 chan->state == CHANNEL_STATE_CLOSED ||
1289 chan->state == CHANNEL_STATE_ERROR);
1291 /* No-op if already inactive */
1292 if (chan->state == CHANNEL_STATE_CLOSED ||
1293 chan->state == CHANNEL_STATE_ERROR) return;
1295 /* Inform any pending (not attached) circs that they should
1296 * give up. */
1297 circuit_n_chan_done(chan, 0);
1299 /* Now close all the attached circuits on it. */
1300 circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
1302 if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
1303 channel_change_state(chan, CHANNEL_STATE_CLOSED);
1304 } else {
1305 channel_change_state(chan, CHANNEL_STATE_ERROR);
1310 * Notify that the lower layer is finished closing the channel listener
1312 * This function should be called by the lower layer when a channel listener
1313 * is finished closing and it should be regarded as inactive and
1314 * freed by the channel code.
1317 void
1318 channel_listener_closed(channel_listener_t *chan_l)
1320 tor_assert(chan_l);
1321 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1322 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1323 chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
1325 /* No-op if already inactive */
1326 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1327 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1329 if (chan_l->reason_for_closing != CHANNEL_LISTENER_CLOSE_FOR_ERROR) {
1330 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
1331 } else {
1332 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_ERROR);
1337 * Clear the identity_digest of a channel
1339 * This function clears the identity digest of the remote endpoint for a
1340 * channel; this is intended for use by the lower layer.
1343 void
1344 channel_clear_identity_digest(channel_t *chan)
1346 int state_not_in_map;
1348 tor_assert(chan);
1350 log_debug(LD_CHANNEL,
1351 "Clearing remote endpoint digest on channel %p with "
1352 "global ID " U64_FORMAT,
1353 chan, U64_PRINTF_ARG(chan->global_identifier));
1355 state_not_in_map =
1356 (chan->state == CHANNEL_STATE_CLOSING ||
1357 chan->state == CHANNEL_STATE_CLOSED ||
1358 chan->state == CHANNEL_STATE_ERROR);
1360 if (!state_not_in_map && chan->registered &&
1361 !tor_digest_is_zero(chan->identity_digest))
1362 /* if it's registered get it out of the digest map */
1363 channel_remove_from_digest_map(chan);
1365 memset(chan->identity_digest, 0,
1366 sizeof(chan->identity_digest));
1370 * Set the identity_digest of a channel
1372 * This function sets the identity digest of the remote endpoint for a
1373 * channel; this is intended for use by the lower layer.
1376 void
1377 channel_set_identity_digest(channel_t *chan,
1378 const char *identity_digest)
1380 int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1382 tor_assert(chan);
1384 log_debug(LD_CHANNEL,
1385 "Setting remote endpoint digest on channel %p with "
1386 "global ID " U64_FORMAT " to digest %s",
1387 chan, U64_PRINTF_ARG(chan->global_identifier),
1388 identity_digest ?
1389 hex_str(identity_digest, DIGEST_LEN) : "(null)");
1391 state_not_in_map =
1392 (chan->state == CHANNEL_STATE_CLOSING ||
1393 chan->state == CHANNEL_STATE_CLOSED ||
1394 chan->state == CHANNEL_STATE_ERROR);
1395 was_in_digest_map =
1396 !state_not_in_map &&
1397 chan->registered &&
1398 !tor_digest_is_zero(chan->identity_digest);
1399 should_be_in_digest_map =
1400 !state_not_in_map &&
1401 chan->registered &&
1402 (identity_digest &&
1403 !tor_digest_is_zero(identity_digest));
1405 if (was_in_digest_map)
1406 /* We should always remove it; we'll add it back if we're writing
1407 * in a new digest.
1409 channel_remove_from_digest_map(chan);
1411 if (identity_digest) {
1412 memcpy(chan->identity_digest,
1413 identity_digest,
1414 sizeof(chan->identity_digest));
1415 } else {
1416 memset(chan->identity_digest, 0,
1417 sizeof(chan->identity_digest));
1420 /* Put it in the digest map if we should */
1421 if (should_be_in_digest_map)
1422 channel_add_to_digest_map(chan);
1426 * Clear the remote end metadata (identity_digest/nickname) of a channel
1428 * This function clears all the remote end info from a channel; this is
1429 * intended for use by the lower layer.
1432 void
1433 channel_clear_remote_end(channel_t *chan)
1435 int state_not_in_map;
1437 tor_assert(chan);
1439 log_debug(LD_CHANNEL,
1440 "Clearing remote endpoint identity on channel %p with "
1441 "global ID " U64_FORMAT,
1442 chan, U64_PRINTF_ARG(chan->global_identifier));
1444 state_not_in_map =
1445 (chan->state == CHANNEL_STATE_CLOSING ||
1446 chan->state == CHANNEL_STATE_CLOSED ||
1447 chan->state == CHANNEL_STATE_ERROR);
1449 if (!state_not_in_map && chan->registered &&
1450 !tor_digest_is_zero(chan->identity_digest))
1451 /* if it's registered get it out of the digest map */
1452 channel_remove_from_digest_map(chan);
1454 memset(chan->identity_digest, 0,
1455 sizeof(chan->identity_digest));
1456 tor_free(chan->nickname);
1460 * Set the remote end metadata (identity_digest/nickname) of a channel
1462 * This function sets new remote end info on a channel; this is intended
1463 * for use by the lower layer.
1466 void
1467 channel_set_remote_end(channel_t *chan,
1468 const char *identity_digest,
1469 const char *nickname)
1471 int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1473 tor_assert(chan);
1475 log_debug(LD_CHANNEL,
1476 "Setting remote endpoint identity on channel %p with "
1477 "global ID " U64_FORMAT " to nickname %s, digest %s",
1478 chan, U64_PRINTF_ARG(chan->global_identifier),
1479 nickname ? nickname : "(null)",
1480 identity_digest ?
1481 hex_str(identity_digest, DIGEST_LEN) : "(null)");
1483 state_not_in_map =
1484 (chan->state == CHANNEL_STATE_CLOSING ||
1485 chan->state == CHANNEL_STATE_CLOSED ||
1486 chan->state == CHANNEL_STATE_ERROR);
1487 was_in_digest_map =
1488 !state_not_in_map &&
1489 chan->registered &&
1490 !tor_digest_is_zero(chan->identity_digest);
1491 should_be_in_digest_map =
1492 !state_not_in_map &&
1493 chan->registered &&
1494 (identity_digest &&
1495 !tor_digest_is_zero(identity_digest));
1497 if (was_in_digest_map)
1498 /* We should always remove it; we'll add it back if we're writing
1499 * in a new digest.
1501 channel_remove_from_digest_map(chan);
1503 if (identity_digest) {
1504 memcpy(chan->identity_digest,
1505 identity_digest,
1506 sizeof(chan->identity_digest));
1508 } else {
1509 memset(chan->identity_digest, 0,
1510 sizeof(chan->identity_digest));
1513 tor_free(chan->nickname);
1514 if (nickname)
1515 chan->nickname = tor_strdup(nickname);
1517 /* Put it in the digest map if we should */
1518 if (should_be_in_digest_map)
1519 channel_add_to_digest_map(chan);
1523 * Duplicate a cell queue entry; this is a shallow copy intended for use
1524 * in channel_write_cell_queue_entry().
1527 static cell_queue_entry_t *
1528 cell_queue_entry_dup(cell_queue_entry_t *q)
1530 cell_queue_entry_t *rv = NULL;
1532 tor_assert(q);
1534 rv = tor_malloc(sizeof(*rv));
1535 memcpy(rv, q, sizeof(*rv));
1537 return rv;
1541 * Free a cell_queue_entry_t; the handed_off parameter indicates whether
1542 * the contents were passed to the lower layer (it is responsible for
1543 * them) or not (we should free).
1546 static void
1547 cell_queue_entry_free(cell_queue_entry_t *q, int handed_off)
1549 if (!q) return;
1551 if (!handed_off) {
1553 * If we handed it off, the recipient becomes responsible (or
1554 * with packed cells the channel_t subclass calls packed_cell
1555 * free after writing out its contents; see, e.g.,
1556 * channel_tls_write_packed_cell_method(). Otherwise, we have
1557 * to take care of it here if possible.
1559 switch (q->type) {
1560 case CELL_QUEUE_FIXED:
1561 if (q->u.fixed.cell) {
1563 * There doesn't seem to be a cell_free() function anywhere in the
1564 * pre-channel code; just use tor_free()
1566 tor_free(q->u.fixed.cell);
1568 break;
1569 case CELL_QUEUE_PACKED:
1570 if (q->u.packed.packed_cell) {
1571 packed_cell_free(q->u.packed.packed_cell);
1573 break;
1574 case CELL_QUEUE_VAR:
1575 if (q->u.var.var_cell) {
1577 * This one's in connection_or.c; it'd be nice to figure out the
1578 * whole flow of cells from one end to the other and factor the
1579 * cell memory management functions like this out of the specific
1580 * TLS lower layer.
1582 var_cell_free(q->u.var.var_cell);
1584 break;
1585 default:
1587 * Nothing we can do if we don't know the type; this will
1588 * have been warned about elsewhere.
1590 break;
1593 tor_free(q);
1597 * Check whether a cell queue entry is padding; this is a helper function
1598 * for channel_write_cell_queue_entry()
1601 static int
1602 cell_queue_entry_is_padding(cell_queue_entry_t *q)
1604 tor_assert(q);
1606 if (q->type == CELL_QUEUE_FIXED) {
1607 if (q->u.fixed.cell) {
1608 if (q->u.fixed.cell->command == CELL_PADDING ||
1609 q->u.fixed.cell->command == CELL_VPADDING) {
1610 return 1;
1613 } else if (q->type == CELL_QUEUE_VAR) {
1614 if (q->u.var.var_cell) {
1615 if (q->u.var.var_cell->command == CELL_PADDING ||
1616 q->u.var.var_cell->command == CELL_VPADDING) {
1617 return 1;
1622 return 0;
1626 * Allocate a new cell queue entry for a fixed-size cell
1629 static cell_queue_entry_t *
1630 cell_queue_entry_new_fixed(cell_t *cell)
1632 cell_queue_entry_t *q = NULL;
1634 tor_assert(cell);
1636 q = tor_malloc(sizeof(*q));
1637 q->type = CELL_QUEUE_FIXED;
1638 q->u.fixed.cell = cell;
1640 return q;
1644 * Allocate a new cell queue entry for a variable-size cell
1647 static cell_queue_entry_t *
1648 cell_queue_entry_new_var(var_cell_t *var_cell)
1650 cell_queue_entry_t *q = NULL;
1652 tor_assert(var_cell);
1654 q = tor_malloc(sizeof(*q));
1655 q->type = CELL_QUEUE_VAR;
1656 q->u.var.var_cell = var_cell;
1658 return q;
1662 * Write to a channel based on a cell_queue_entry_t
1664 * Given a cell_queue_entry_t filled out by the caller, try to send the cell
1665 * and queue it if we can't.
1668 static void
1669 channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q)
1671 int result = 0, sent = 0;
1672 cell_queue_entry_t *tmp = NULL;
1674 tor_assert(chan);
1675 tor_assert(q);
1677 /* Assert that the state makes sense for a cell write */
1678 tor_assert(chan->state == CHANNEL_STATE_OPENING ||
1679 chan->state == CHANNEL_STATE_OPEN ||
1680 chan->state == CHANNEL_STATE_MAINT);
1682 /* Increment the timestamp unless it's padding */
1683 if (!cell_queue_entry_is_padding(q)) {
1684 chan->timestamp_last_added_nonpadding = approx_time();
1687 /* Can we send it right out? If so, try */
1688 if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue) &&
1689 chan->state == CHANNEL_STATE_OPEN) {
1690 /* Pick the right write function for this cell type and save the result */
1691 switch (q->type) {
1692 case CELL_QUEUE_FIXED:
1693 tor_assert(chan->write_cell);
1694 tor_assert(q->u.fixed.cell);
1695 result = chan->write_cell(chan, q->u.fixed.cell);
1696 break;
1697 case CELL_QUEUE_PACKED:
1698 tor_assert(chan->write_packed_cell);
1699 tor_assert(q->u.packed.packed_cell);
1700 result = chan->write_packed_cell(chan, q->u.packed.packed_cell);
1701 break;
1702 case CELL_QUEUE_VAR:
1703 tor_assert(chan->write_var_cell);
1704 tor_assert(q->u.var.var_cell);
1705 result = chan->write_var_cell(chan, q->u.var.var_cell);
1706 break;
1707 default:
1708 tor_assert(1);
1711 /* Check if we got it out */
1712 if (result > 0) {
1713 sent = 1;
1714 /* Timestamp for transmission */
1715 channel_timestamp_xmit(chan);
1716 /* If we're here the queue is empty, so it's drained too */
1717 channel_timestamp_drained(chan);
1718 /* Update the counter */
1719 ++(chan->n_cells_xmitted);
1723 if (!sent) {
1724 /* Not sent, queue it */
1726 * We have to copy the queue entry passed in, since the caller probably
1727 * used the stack.
1729 tmp = cell_queue_entry_dup(q);
1730 TOR_SIMPLEQ_INSERT_TAIL(&chan->outgoing_queue, tmp, next);
1731 /* Try to process the queue? */
1732 if (chan->state == CHANNEL_STATE_OPEN) channel_flush_cells(chan);
1737 * Write a cell to a channel
1739 * Write a fixed-length cell to a channel using the write_cell() method.
1740 * This is equivalent to the pre-channels connection_or_write_cell_to_buf();
1741 * it is called by the transport-independent code to deliver a cell to a
1742 * channel for transmission.
1745 void
1746 channel_write_cell(channel_t *chan, cell_t *cell)
1748 cell_queue_entry_t q;
1750 tor_assert(chan);
1751 tor_assert(cell);
1753 if (chan->state == CHANNEL_STATE_CLOSING) {
1754 log_debug(LD_CHANNEL, "Discarding cell_t %p on closing channel %p with "
1755 "global ID "U64_FORMAT, cell, chan,
1756 U64_PRINTF_ARG(chan->global_identifier));
1757 tor_free(cell);
1758 return;
1761 log_debug(LD_CHANNEL,
1762 "Writing cell_t %p to channel %p with global ID "
1763 U64_FORMAT,
1764 cell, chan, U64_PRINTF_ARG(chan->global_identifier));
1766 q.type = CELL_QUEUE_FIXED;
1767 q.u.fixed.cell = cell;
1768 channel_write_cell_queue_entry(chan, &q);
1772 * Write a packed cell to a channel
1774 * Write a packed cell to a channel using the write_cell() method. This is
1775 * called by the transport-independent code to deliver a packed cell to a
1776 * channel for transmission.
1779 void
1780 channel_write_packed_cell(channel_t *chan, packed_cell_t *packed_cell)
1782 cell_queue_entry_t q;
1784 tor_assert(chan);
1785 tor_assert(packed_cell);
1787 if (chan->state == CHANNEL_STATE_CLOSING) {
1788 log_debug(LD_CHANNEL, "Discarding packed_cell_t %p on closing channel %p "
1789 "with global ID "U64_FORMAT, packed_cell, chan,
1790 U64_PRINTF_ARG(chan->global_identifier));
1791 packed_cell_free(packed_cell);
1792 return;
1795 log_debug(LD_CHANNEL,
1796 "Writing packed_cell_t %p to channel %p with global ID "
1797 U64_FORMAT,
1798 packed_cell, chan,
1799 U64_PRINTF_ARG(chan->global_identifier));
1801 q.type = CELL_QUEUE_PACKED;
1802 q.u.packed.packed_cell = packed_cell;
1803 channel_write_cell_queue_entry(chan, &q);
1807 * Write a variable-length cell to a channel
1809 * Write a variable-length cell to a channel using the write_cell() method.
1810 * This is equivalent to the pre-channels
1811 * connection_or_write_var_cell_to_buf(); it's called by the transport-
1812 * independent code to deliver a var_cell to a channel for transmission.
1815 void
1816 channel_write_var_cell(channel_t *chan, var_cell_t *var_cell)
1818 cell_queue_entry_t q;
1820 tor_assert(chan);
1821 tor_assert(var_cell);
1823 if (chan->state == CHANNEL_STATE_CLOSING) {
1824 log_debug(LD_CHANNEL, "Discarding var_cell_t %p on closing channel %p "
1825 "with global ID "U64_FORMAT, var_cell, chan,
1826 U64_PRINTF_ARG(chan->global_identifier));
1827 var_cell_free(var_cell);
1828 return;
1831 log_debug(LD_CHANNEL,
1832 "Writing var_cell_t %p to channel %p with global ID "
1833 U64_FORMAT,
1834 var_cell, chan,
1835 U64_PRINTF_ARG(chan->global_identifier));
1837 q.type = CELL_QUEUE_VAR;
1838 q.u.var.var_cell = var_cell;
1839 channel_write_cell_queue_entry(chan, &q);
1843 * Change channel state
1845 * This internal and subclass use only function is used to change channel
1846 * state, performing all transition validity checks and whatever actions
1847 * are appropriate to the state transition in question.
1850 void
1851 channel_change_state(channel_t *chan, channel_state_t to_state)
1853 channel_state_t from_state;
1854 unsigned char was_active, is_active;
1855 unsigned char was_in_id_map, is_in_id_map;
1857 tor_assert(chan);
1858 from_state = chan->state;
1860 tor_assert(channel_state_is_valid(from_state));
1861 tor_assert(channel_state_is_valid(to_state));
1862 tor_assert(channel_state_can_transition(chan->state, to_state));
1864 /* Check for no-op transitions */
1865 if (from_state == to_state) {
1866 log_debug(LD_CHANNEL,
1867 "Got no-op transition from \"%s\" to itself on channel %p"
1868 "(global ID " U64_FORMAT ")",
1869 channel_state_to_string(to_state),
1870 chan, U64_PRINTF_ARG(chan->global_identifier));
1871 return;
1874 /* If we're going to a closing or closed state, we must have a reason set */
1875 if (to_state == CHANNEL_STATE_CLOSING ||
1876 to_state == CHANNEL_STATE_CLOSED ||
1877 to_state == CHANNEL_STATE_ERROR) {
1878 tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
1882 * We need to maintain the queues here for some transitions:
1883 * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
1884 * we may have a backlog of cells to transmit, so drain the queues in
1885 * that case, and when going to CHANNEL_STATE_CLOSED the subclass
1886 * should have made sure to finish sending things (or gone to
1887 * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
1890 log_debug(LD_CHANNEL,
1891 "Changing state of channel %p (global ID " U64_FORMAT
1892 ") from \"%s\" to \"%s\"",
1893 chan,
1894 U64_PRINTF_ARG(chan->global_identifier),
1895 channel_state_to_string(chan->state),
1896 channel_state_to_string(to_state));
1898 chan->state = to_state;
1900 /* Need to add to the right lists if the channel is registered */
1901 if (chan->registered) {
1902 was_active = !(from_state == CHANNEL_STATE_CLOSED ||
1903 from_state == CHANNEL_STATE_ERROR);
1904 is_active = !(to_state == CHANNEL_STATE_CLOSED ||
1905 to_state == CHANNEL_STATE_ERROR);
1907 /* Need to take off active list and put on finished list? */
1908 if (was_active && !is_active) {
1909 if (active_channels) smartlist_remove(active_channels, chan);
1910 if (!finished_channels) finished_channels = smartlist_new();
1911 smartlist_add(finished_channels, chan);
1913 /* Need to put on active list? */
1914 else if (!was_active && is_active) {
1915 if (finished_channels) smartlist_remove(finished_channels, chan);
1916 if (!active_channels) active_channels = smartlist_new();
1917 smartlist_add(active_channels, chan);
1920 if (!tor_digest_is_zero(chan->identity_digest)) {
1921 /* Now we need to handle the identity map */
1922 was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
1923 from_state == CHANNEL_STATE_CLOSED ||
1924 from_state == CHANNEL_STATE_ERROR);
1925 is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
1926 to_state == CHANNEL_STATE_CLOSED ||
1927 to_state == CHANNEL_STATE_ERROR);
1929 if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
1930 else if (was_in_id_map && !is_in_id_map)
1931 channel_remove_from_digest_map(chan);
1935 /* Tell circuits if we opened and stuff */
1936 if (to_state == CHANNEL_STATE_OPEN) {
1937 channel_do_open_actions(chan);
1939 /* Check for queued cells to process */
1940 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
1941 channel_process_cells(chan);
1942 if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue))
1943 channel_flush_cells(chan);
1944 } else if (to_state == CHANNEL_STATE_CLOSED ||
1945 to_state == CHANNEL_STATE_ERROR) {
1946 /* Assert that all queues are empty */
1947 tor_assert(TOR_SIMPLEQ_EMPTY(&chan->incoming_queue));
1948 tor_assert(TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue));
1953 * Change channel listener state
1955 * This internal and subclass use only function is used to change channel
1956 * listener state, performing all transition validity checks and whatever
1957 * actions are appropriate to the state transition in question.
1960 void
1961 channel_listener_change_state(channel_listener_t *chan_l,
1962 channel_listener_state_t to_state)
1964 channel_listener_state_t from_state;
1965 unsigned char was_active, is_active;
1967 tor_assert(chan_l);
1968 from_state = chan_l->state;
1970 tor_assert(channel_listener_state_is_valid(from_state));
1971 tor_assert(channel_listener_state_is_valid(to_state));
1972 tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
1974 /* Check for no-op transitions */
1975 if (from_state == to_state) {
1976 log_debug(LD_CHANNEL,
1977 "Got no-op transition from \"%s\" to itself on channel "
1978 "listener %p (global ID " U64_FORMAT ")",
1979 channel_listener_state_to_string(to_state),
1980 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1981 return;
1984 /* If we're going to a closing or closed state, we must have a reason set */
1985 if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
1986 to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1987 to_state == CHANNEL_LISTENER_STATE_ERROR) {
1988 tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
1992 * We need to maintain the queues here for some transitions:
1993 * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
1994 * we may have a backlog of cells to transmit, so drain the queues in
1995 * that case, and when going to CHANNEL_STATE_CLOSED the subclass
1996 * should have made sure to finish sending things (or gone to
1997 * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
2000 log_debug(LD_CHANNEL,
2001 "Changing state of channel listener %p (global ID " U64_FORMAT
2002 "from \"%s\" to \"%s\"",
2003 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
2004 channel_listener_state_to_string(chan_l->state),
2005 channel_listener_state_to_string(to_state));
2007 chan_l->state = to_state;
2009 /* Need to add to the right lists if the channel listener is registered */
2010 if (chan_l->registered) {
2011 was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
2012 from_state == CHANNEL_LISTENER_STATE_ERROR);
2013 is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2014 to_state == CHANNEL_LISTENER_STATE_ERROR);
2016 /* Need to take off active list and put on finished list? */
2017 if (was_active && !is_active) {
2018 if (active_listeners) smartlist_remove(active_listeners, chan_l);
2019 if (!finished_listeners) finished_listeners = smartlist_new();
2020 smartlist_add(finished_listeners, chan_l);
2022 /* Need to put on active list? */
2023 else if (!was_active && is_active) {
2024 if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
2025 if (!active_listeners) active_listeners = smartlist_new();
2026 smartlist_add(active_listeners, chan_l);
2030 if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2031 to_state == CHANNEL_LISTENER_STATE_ERROR) {
2032 /* Assert that the queue is empty */
2033 tor_assert(!(chan_l->incoming_list) ||
2034 smartlist_len(chan_l->incoming_list) == 0);
2039 * Try to flush cells to the lower layer
2041 * this is called by the lower layer to indicate that it wants more cells;
2042 * it will try to write up to num_cells cells from the channel's cell queue or
2043 * from circuits active on that channel, or as many as it has available if
2044 * num_cells == -1.
2047 #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
2049 ssize_t
2050 channel_flush_some_cells(channel_t *chan, ssize_t num_cells)
2052 unsigned int unlimited = 0;
2053 ssize_t flushed = 0;
2054 int num_cells_from_circs, clamped_num_cells;
2056 tor_assert(chan);
2058 if (num_cells < 0) unlimited = 1;
2059 if (!unlimited && num_cells <= flushed) goto done;
2061 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
2062 if (chan->state == CHANNEL_STATE_OPEN) {
2063 /* Try to flush as much as we can that's already queued */
2064 flushed += channel_flush_some_cells_from_outgoing_queue(chan,
2065 (unlimited ? -1 : num_cells - flushed));
2066 if (!unlimited && num_cells <= flushed) goto done;
2068 if (circuitmux_num_cells(chan->cmux) > 0) {
2069 /* Calculate number of cells, including clamp */
2070 if (unlimited) {
2071 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
2072 } else {
2073 if (num_cells - flushed >
2074 MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
2075 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
2076 } else {
2077 clamped_num_cells = (int)(num_cells - flushed);
2080 /* Try to get more cells from any active circuits */
2081 num_cells_from_circs = channel_flush_from_first_active_circuit(
2082 chan, clamped_num_cells);
2084 /* If it claims we got some, process the queue again */
2085 if (num_cells_from_circs > 0) {
2086 flushed += channel_flush_some_cells_from_outgoing_queue(chan,
2087 (unlimited ? -1 : num_cells - flushed));
2092 done:
2093 return flushed;
2097 * Flush cells from just the channel's outgoing cell queue
2099 * This gets called from channel_flush_some_cells() above to flush cells
2100 * just from the queue without trying for active_circuits.
2103 static ssize_t
2104 channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
2105 ssize_t num_cells)
2107 unsigned int unlimited = 0;
2108 ssize_t flushed = 0;
2109 cell_queue_entry_t *q = NULL;
2111 tor_assert(chan);
2112 tor_assert(chan->write_cell);
2113 tor_assert(chan->write_packed_cell);
2114 tor_assert(chan->write_var_cell);
2116 if (num_cells < 0) unlimited = 1;
2117 if (!unlimited && num_cells <= flushed) return 0;
2119 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
2120 if (chan->state == CHANNEL_STATE_OPEN) {
2121 while ((unlimited || num_cells > flushed) &&
2122 NULL != (q = TOR_SIMPLEQ_FIRST(&chan->outgoing_queue))) {
2124 if (1) {
2126 * Okay, we have a good queue entry, try to give it to the lower
2127 * layer.
2129 switch (q->type) {
2130 case CELL_QUEUE_FIXED:
2131 if (q->u.fixed.cell) {
2132 if (chan->write_cell(chan,
2133 q->u.fixed.cell)) {
2134 ++flushed;
2135 channel_timestamp_xmit(chan);
2136 ++(chan->n_cells_xmitted);
2137 cell_queue_entry_free(q, 1);
2138 q = NULL;
2140 /* Else couldn't write it; leave it on the queue */
2141 } else {
2142 /* This shouldn't happen */
2143 log_info(LD_CHANNEL,
2144 "Saw broken cell queue entry of type CELL_QUEUE_FIXED "
2145 "with no cell on channel %p "
2146 "(global ID " U64_FORMAT ").",
2147 chan, U64_PRINTF_ARG(chan->global_identifier));
2148 /* Throw it away */
2149 cell_queue_entry_free(q, 0);
2150 q = NULL;
2152 break;
2153 case CELL_QUEUE_PACKED:
2154 if (q->u.packed.packed_cell) {
2155 if (chan->write_packed_cell(chan,
2156 q->u.packed.packed_cell)) {
2157 ++flushed;
2158 channel_timestamp_xmit(chan);
2159 ++(chan->n_cells_xmitted);
2160 cell_queue_entry_free(q, 1);
2161 q = NULL;
2163 /* Else couldn't write it; leave it on the queue */
2164 } else {
2165 /* This shouldn't happen */
2166 log_info(LD_CHANNEL,
2167 "Saw broken cell queue entry of type CELL_QUEUE_PACKED "
2168 "with no cell on channel %p "
2169 "(global ID " U64_FORMAT ").",
2170 chan, U64_PRINTF_ARG(chan->global_identifier));
2171 /* Throw it away */
2172 cell_queue_entry_free(q, 0);
2173 q = NULL;
2175 break;
2176 case CELL_QUEUE_VAR:
2177 if (q->u.var.var_cell) {
2178 if (chan->write_var_cell(chan,
2179 q->u.var.var_cell)) {
2180 ++flushed;
2181 channel_timestamp_xmit(chan);
2182 ++(chan->n_cells_xmitted);
2183 cell_queue_entry_free(q, 1);
2184 q = NULL;
2186 /* Else couldn't write it; leave it on the queue */
2187 } else {
2188 /* This shouldn't happen */
2189 log_info(LD_CHANNEL,
2190 "Saw broken cell queue entry of type CELL_QUEUE_VAR "
2191 "with no cell on channel %p "
2192 "(global ID " U64_FORMAT ").",
2193 chan, U64_PRINTF_ARG(chan->global_identifier));
2194 /* Throw it away */
2195 cell_queue_entry_free(q, 0);
2196 q = NULL;
2198 break;
2199 default:
2200 /* Unknown type, log and free it */
2201 log_info(LD_CHANNEL,
2202 "Saw an unknown cell queue entry type %d on channel %p "
2203 "(global ID " U64_FORMAT "; ignoring it."
2204 " Someone should fix this.",
2205 q->type, chan, U64_PRINTF_ARG(chan->global_identifier));
2206 cell_queue_entry_free(q, 0);
2207 q = NULL;
2210 /* if q got NULLed out, we used it and should remove the queue entry */
2211 if (!q) TOR_SIMPLEQ_REMOVE_HEAD(&chan->outgoing_queue, next);
2212 /* No cell removed from list, so we can't go on any further */
2213 else break;
2218 /* Did we drain the queue? */
2219 if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
2220 channel_timestamp_drained(chan);
2223 return flushed;
2227 * Flush as many cells as we possibly can from the queue
2229 * This tries to flush as many cells from the queue as the lower layer
2230 * will take. It just calls channel_flush_some_cells_from_outgoing_queue()
2231 * in unlimited mode.
2234 void
2235 channel_flush_cells(channel_t *chan)
2237 channel_flush_some_cells_from_outgoing_queue(chan, -1);
2241 * Check if any cells are available
2243 * This gets used from the lower layer to check if any more cells are
2244 * available.
2248 channel_more_to_flush(channel_t *chan)
2250 tor_assert(chan);
2252 /* Check if we have any queued */
2253 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2254 return 1;
2256 /* Check if any circuits would like to queue some */
2257 if (circuitmux_num_cells(chan->cmux) > 0) return 1;
2259 /* Else no */
2260 return 0;
2264 * Notify the channel we're done flushing the output in the lower layer
2266 * Connection.c will call this when we've flushed the output; there's some
2267 * dirreq-related maintenance to do.
2270 void
2271 channel_notify_flushed(channel_t *chan)
2273 tor_assert(chan);
2275 if (chan->dirreq_id != 0)
2276 geoip_change_dirreq_state(chan->dirreq_id,
2277 DIRREQ_TUNNELED,
2278 DIRREQ_CHANNEL_BUFFER_FLUSHED);
2282 * Process the queue of incoming channels on a listener
2284 * Use a listener's registered callback to process as many entries in the
2285 * queue of incoming channels as possible.
2288 void
2289 channel_listener_process_incoming(channel_listener_t *listener)
2291 tor_assert(listener);
2294 * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
2295 * while closing a listener.
2297 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
2298 listener->state == CHANNEL_LISTENER_STATE_CLOSING);
2299 tor_assert(listener->listener);
2301 log_debug(LD_CHANNEL,
2302 "Processing queue of incoming connections for channel "
2303 "listener %p (global ID " U64_FORMAT ")",
2304 listener, U64_PRINTF_ARG(listener->global_identifier));
2306 if (!(listener->incoming_list)) return;
2308 SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
2309 channel_t *, chan) {
2310 tor_assert(chan);
2312 log_debug(LD_CHANNEL,
2313 "Handling incoming channel %p (" U64_FORMAT ") "
2314 "for listener %p (" U64_FORMAT ")",
2315 chan,
2316 U64_PRINTF_ARG(chan->global_identifier),
2317 listener,
2318 U64_PRINTF_ARG(listener->global_identifier));
2319 /* Make sure this is set correctly */
2320 channel_mark_incoming(chan);
2321 listener->listener(listener, chan);
2322 } SMARTLIST_FOREACH_END(chan);
2324 smartlist_free(listener->incoming_list);
2325 listener->incoming_list = NULL;
2329 * Take actions required when a channel becomes open
2331 * Handle actions we should do when we know a channel is open; a lot of
2332 * this comes from the old connection_or_set_state_open() of connection_or.c.
2334 * Because of this mechanism, future channel_t subclasses should take care
2335 * not to change a channel to from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
2336 * until there is positive confirmation that the network is operational.
2337 * In particular, anything UDP-based should not make this transition until a
2338 * packet is received from the other side.
2341 void
2342 channel_do_open_actions(channel_t *chan)
2344 tor_addr_t remote_addr;
2345 int started_here, not_using = 0;
2346 time_t now = time(NULL);
2348 tor_assert(chan);
2350 started_here = channel_is_outgoing(chan);
2352 if (started_here) {
2353 circuit_build_times_network_is_live(&circ_times);
2354 rep_hist_note_connect_succeeded(chan->identity_digest, now);
2355 if (entry_guard_register_connect_status(
2356 chan->identity_digest, 1, 0, now) < 0) {
2357 /* Close any circuits pending on this channel. We leave it in state
2358 * 'open' though, because it didn't actually *fail* -- we just
2359 * chose not to use it. */
2360 log_debug(LD_OR,
2361 "New entry guard was reachable, but closing this "
2362 "connection so we can retry the earlier entry guards.");
2363 circuit_n_chan_done(chan, 0);
2364 not_using = 1;
2366 router_set_status(chan->identity_digest, 1);
2367 } else {
2368 /* only report it to the geoip module if it's not a known router */
2369 if (!router_get_by_id_digest(chan->identity_digest)) {
2370 if (channel_get_addr_if_possible(chan, &remote_addr)) {
2371 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &remote_addr,
2372 now);
2374 /* Otherwise the underlying transport can't tell us this, so skip it */
2378 if (!not_using) circuit_n_chan_done(chan, 1);
2382 * Queue an incoming channel on a listener
2384 * Internal and subclass use only function to queue an incoming channel from
2385 * a listener. A subclass of channel_listener_t should call this when a new
2386 * incoming channel is created.
2389 void
2390 channel_listener_queue_incoming(channel_listener_t *listener,
2391 channel_t *incoming)
2393 int need_to_queue = 0;
2395 tor_assert(listener);
2396 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
2397 tor_assert(incoming);
2399 log_debug(LD_CHANNEL,
2400 "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
2401 "channel listener %p (global ID " U64_FORMAT ")",
2402 incoming, U64_PRINTF_ARG(incoming->global_identifier),
2403 listener, U64_PRINTF_ARG(listener->global_identifier));
2405 /* Do we need to queue it, or can we just call the listener right away? */
2406 if (!(listener->listener)) need_to_queue = 1;
2407 if (listener->incoming_list &&
2408 (smartlist_len(listener->incoming_list) > 0))
2409 need_to_queue = 1;
2411 /* If we need to queue and have no queue, create one */
2412 if (need_to_queue && !(listener->incoming_list)) {
2413 listener->incoming_list = smartlist_new();
2416 /* Bump the counter and timestamp it */
2417 channel_listener_timestamp_active(listener);
2418 channel_listener_timestamp_accepted(listener);
2419 ++(listener->n_accepted);
2421 /* If we don't need to queue, process it right away */
2422 if (!need_to_queue) {
2423 tor_assert(listener->listener);
2424 listener->listener(listener, incoming);
2427 * Otherwise, we need to queue; queue and then process the queue if
2428 * we can.
2430 else {
2431 tor_assert(listener->incoming_list);
2432 smartlist_add(listener->incoming_list, incoming);
2433 if (listener->listener) channel_listener_process_incoming(listener);
2438 * Process queued incoming cells
2440 * Process as many queued cells as we can from the incoming
2441 * cell queue.
2444 void
2445 channel_process_cells(channel_t *chan)
2447 cell_queue_entry_t *q;
2448 tor_assert(chan);
2449 tor_assert(chan->state == CHANNEL_STATE_CLOSING ||
2450 chan->state == CHANNEL_STATE_MAINT ||
2451 chan->state == CHANNEL_STATE_OPEN);
2453 log_debug(LD_CHANNEL,
2454 "Processing as many incoming cells as we can for channel %p",
2455 chan);
2457 /* Nothing we can do if we have no registered cell handlers */
2458 if (!(chan->cell_handler ||
2459 chan->var_cell_handler)) return;
2460 /* Nothing we can do if we have no cells */
2461 if (TOR_SIMPLEQ_EMPTY(&chan->incoming_queue)) return;
2464 * Process cells until we're done or find one we have no current handler
2465 * for.
2467 while (NULL != (q = TOR_SIMPLEQ_FIRST(&chan->incoming_queue))) {
2468 tor_assert(q);
2469 tor_assert(q->type == CELL_QUEUE_FIXED ||
2470 q->type == CELL_QUEUE_VAR);
2472 if (q->type == CELL_QUEUE_FIXED &&
2473 chan->cell_handler) {
2474 /* Handle a fixed-length cell */
2475 TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
2476 tor_assert(q->u.fixed.cell);
2477 log_debug(LD_CHANNEL,
2478 "Processing incoming cell_t %p for channel %p (global ID "
2479 U64_FORMAT ")",
2480 q->u.fixed.cell, chan,
2481 U64_PRINTF_ARG(chan->global_identifier));
2482 chan->cell_handler(chan, q->u.fixed.cell);
2483 tor_free(q);
2484 } else if (q->type == CELL_QUEUE_VAR &&
2485 chan->var_cell_handler) {
2486 /* Handle a variable-length cell */
2487 TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
2488 tor_assert(q->u.var.var_cell);
2489 log_debug(LD_CHANNEL,
2490 "Processing incoming var_cell_t %p for channel %p (global ID "
2491 U64_FORMAT ")",
2492 q->u.var.var_cell, chan,
2493 U64_PRINTF_ARG(chan->global_identifier));
2494 chan->var_cell_handler(chan, q->u.var.var_cell);
2495 tor_free(q);
2496 } else {
2497 /* Can't handle this one */
2498 break;
2504 * Queue incoming cell
2506 * This should be called by a channel_t subclass to queue an incoming fixed-
2507 * length cell for processing, and process it if possible.
2510 void
2511 channel_queue_cell(channel_t *chan, cell_t *cell)
2513 int need_to_queue = 0;
2514 cell_queue_entry_t *q;
2516 tor_assert(chan);
2517 tor_assert(cell);
2518 tor_assert(chan->state == CHANNEL_STATE_OPEN);
2520 /* Do we need to queue it, or can we just call the handler right away? */
2521 if (!(chan->cell_handler)) need_to_queue = 1;
2522 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2523 need_to_queue = 1;
2525 /* Timestamp for receiving */
2526 channel_timestamp_recv(chan);
2528 /* Update the counter */
2529 ++(chan->n_cells_recved);
2531 /* If we don't need to queue we can just call cell_handler */
2532 if (!need_to_queue) {
2533 tor_assert(chan->cell_handler);
2534 log_debug(LD_CHANNEL,
2535 "Directly handling incoming cell_t %p for channel %p "
2536 "(global ID " U64_FORMAT ")",
2537 cell, chan,
2538 U64_PRINTF_ARG(chan->global_identifier));
2539 chan->cell_handler(chan, cell);
2540 } else {
2541 /* Otherwise queue it and then process the queue if possible. */
2542 q = cell_queue_entry_new_fixed(cell);
2543 log_debug(LD_CHANNEL,
2544 "Queueing incoming cell_t %p for channel %p "
2545 "(global ID " U64_FORMAT ")",
2546 cell, chan,
2547 U64_PRINTF_ARG(chan->global_identifier));
2548 TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
2549 if (chan->cell_handler ||
2550 chan->var_cell_handler) {
2551 channel_process_cells(chan);
2557 * Queue incoming variable-length cell
2559 * This should be called by a channel_t subclass to queue an incoming
2560 * variable-length cell for processing, and process it if possible.
2563 void
2564 channel_queue_var_cell(channel_t *chan, var_cell_t *var_cell)
2566 int need_to_queue = 0;
2567 cell_queue_entry_t *q;
2569 tor_assert(chan);
2570 tor_assert(var_cell);
2571 tor_assert(chan->state == CHANNEL_STATE_OPEN);
2573 /* Do we need to queue it, or can we just call the handler right away? */
2574 if (!(chan->var_cell_handler)) need_to_queue = 1;
2575 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2576 need_to_queue = 1;
2578 /* Timestamp for receiving */
2579 channel_timestamp_recv(chan);
2581 /* Update the counter */
2582 ++(chan->n_cells_recved);
2584 /* If we don't need to queue we can just call cell_handler */
2585 if (!need_to_queue) {
2586 tor_assert(chan->var_cell_handler);
2587 log_debug(LD_CHANNEL,
2588 "Directly handling incoming var_cell_t %p for channel %p "
2589 "(global ID " U64_FORMAT ")",
2590 var_cell, chan,
2591 U64_PRINTF_ARG(chan->global_identifier));
2592 chan->var_cell_handler(chan, var_cell);
2593 } else {
2594 /* Otherwise queue it and then process the queue if possible. */
2595 q = cell_queue_entry_new_var(var_cell);
2596 log_debug(LD_CHANNEL,
2597 "Queueing incoming var_cell_t %p for channel %p "
2598 "(global ID " U64_FORMAT ")",
2599 var_cell, chan,
2600 U64_PRINTF_ARG(chan->global_identifier));
2601 TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
2602 if (chan->cell_handler ||
2603 chan->var_cell_handler) {
2604 channel_process_cells(chan);
2610 * Send destroy cell on a channel
2612 * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
2613 * onto channel <b>chan</b>. Don't perform range-checking on reason:
2614 * we may want to propagate reasons from other cells.
2618 channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
2620 cell_t cell;
2622 tor_assert(chan);
2624 /* Check to make sure we can send on this channel first */
2625 if (!(chan->state == CHANNEL_STATE_CLOSING ||
2626 chan->state == CHANNEL_STATE_CLOSED ||
2627 chan->state == CHANNEL_STATE_ERROR)) {
2628 memset(&cell, 0, sizeof(cell_t));
2629 cell.circ_id = circ_id;
2630 cell.command = CELL_DESTROY;
2631 cell.payload[0] = (uint8_t) reason;
2632 log_debug(LD_OR,
2633 "Sending destroy (circID %u) on channel %p "
2634 "(global ID " U64_FORMAT ")",
2635 (unsigned)circ_id, chan,
2636 U64_PRINTF_ARG(chan->global_identifier));
2638 channel_write_cell(chan, &cell);
2639 } else {
2640 log_warn(LD_BUG,
2641 "Someone called channel_send_destroy() for circID %u "
2642 "on a channel " U64_FORMAT " at %p in state %s (%d)",
2643 (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
2644 chan, channel_state_to_string(chan->state),
2645 chan->state);
2648 return 0;
2652 * Dump channel statistics to the log
2654 * This is called from dumpstats() in main.c and spams the log with
2655 * statistics on channels.
2658 void
2659 channel_dumpstats(int severity)
2661 if (all_channels && smartlist_len(all_channels) > 0) {
2662 tor_log(severity, LD_GENERAL,
2663 "Dumping statistics about %d channels:",
2664 smartlist_len(all_channels));
2665 tor_log(severity, LD_GENERAL,
2666 "%d are active, and %d are done and waiting for cleanup",
2667 (active_channels != NULL) ?
2668 smartlist_len(active_channels) : 0,
2669 (finished_channels != NULL) ?
2670 smartlist_len(finished_channels) : 0);
2672 SMARTLIST_FOREACH(all_channels, channel_t *, chan,
2673 channel_dump_statistics(chan, severity));
2675 tor_log(severity, LD_GENERAL,
2676 "Done spamming about channels now");
2677 } else {
2678 tor_log(severity, LD_GENERAL,
2679 "No channels to dump");
2684 * Dump channel listener statistics to the log
2686 * This is called from dumpstats() in main.c and spams the log with
2687 * statistics on channel listeners.
2690 void
2691 channel_listener_dumpstats(int severity)
2693 if (all_listeners && smartlist_len(all_listeners) > 0) {
2694 tor_log(severity, LD_GENERAL,
2695 "Dumping statistics about %d channel listeners:",
2696 smartlist_len(all_listeners));
2697 tor_log(severity, LD_GENERAL,
2698 "%d are active and %d are done and waiting for cleanup",
2699 (active_listeners != NULL) ?
2700 smartlist_len(active_listeners) : 0,
2701 (finished_listeners != NULL) ?
2702 smartlist_len(finished_listeners) : 0);
2704 SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
2705 channel_listener_dump_statistics(chan_l, severity));
2707 tor_log(severity, LD_GENERAL,
2708 "Done spamming about channel listeners now");
2709 } else {
2710 tor_log(severity, LD_GENERAL,
2711 "No channel listeners to dump");
2716 * Set the cmux policy on all active channels
2719 void
2720 channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
2722 if (!active_channels) return;
2724 SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
2725 if (curr->cmux) {
2726 circuitmux_set_policy(curr->cmux, pol);
2728 } SMARTLIST_FOREACH_END(curr);
2732 * Clean up channels
2734 * This gets called periodically from run_scheduled_events() in main.c;
2735 * it cleans up after closed channels.
2738 void
2739 channel_run_cleanup(void)
2741 channel_t *tmp = NULL;
2743 /* Check if we need to do anything */
2744 if (!finished_channels || smartlist_len(finished_channels) == 0) return;
2746 /* Iterate through finished_channels and get rid of them */
2747 SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
2748 tmp = curr;
2749 /* Remove it from the list */
2750 SMARTLIST_DEL_CURRENT(finished_channels, curr);
2751 /* Also unregister it */
2752 channel_unregister(tmp);
2753 /* ... and free it */
2754 channel_free(tmp);
2755 } SMARTLIST_FOREACH_END(curr);
2759 * Clean up channel listeners
2761 * This gets called periodically from run_scheduled_events() in main.c;
2762 * it cleans up after closed channel listeners.
2765 void
2766 channel_listener_run_cleanup(void)
2768 channel_listener_t *tmp = NULL;
2770 /* Check if we need to do anything */
2771 if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
2773 /* Iterate through finished_channels and get rid of them */
2774 SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
2775 tmp = curr;
2776 /* Remove it from the list */
2777 SMARTLIST_DEL_CURRENT(finished_listeners, curr);
2778 /* Also unregister it */
2779 channel_listener_unregister(tmp);
2780 /* ... and free it */
2781 channel_listener_free(tmp);
2782 } SMARTLIST_FOREACH_END(curr);
2786 * Free a list of channels for channel_free_all()
2789 static void
2790 channel_free_list(smartlist_t *channels, int mark_for_close)
2792 if (!channels) return;
2794 SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
2795 /* Deregister and free it */
2796 tor_assert(curr);
2797 log_debug(LD_CHANNEL,
2798 "Cleaning up channel %p (global ID " U64_FORMAT ") "
2799 "in state %s (%d)",
2800 curr, U64_PRINTF_ARG(curr->global_identifier),
2801 channel_state_to_string(curr->state), curr->state);
2802 /* Detach circuits early so they can find the channel */
2803 if (curr->cmux) {
2804 circuitmux_detach_all_circuits(curr->cmux);
2806 channel_unregister(curr);
2807 if (mark_for_close) {
2808 if (!(curr->state == CHANNEL_STATE_CLOSING ||
2809 curr->state == CHANNEL_STATE_CLOSED ||
2810 curr->state == CHANNEL_STATE_ERROR)) {
2811 channel_mark_for_close(curr);
2813 channel_force_free(curr);
2814 } else channel_free(curr);
2815 } SMARTLIST_FOREACH_END(curr);
2819 * Free a list of channel listeners for channel_free_all()
2822 static void
2823 channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
2825 if (!listeners) return;
2827 SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
2828 /* Deregister and free it */
2829 tor_assert(curr);
2830 log_debug(LD_CHANNEL,
2831 "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
2832 "in state %s (%d)",
2833 curr, U64_PRINTF_ARG(curr->global_identifier),
2834 channel_listener_state_to_string(curr->state), curr->state);
2835 channel_listener_unregister(curr);
2836 if (mark_for_close) {
2837 if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
2838 curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
2839 curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
2840 channel_listener_mark_for_close(curr);
2842 channel_listener_force_free(curr);
2843 } else channel_listener_free(curr);
2844 } SMARTLIST_FOREACH_END(curr);
2848 * Close all channels and free everything
2850 * This gets called from tor_free_all() in main.c to clean up on exit.
2851 * It will close all registered channels and free associated storage,
2852 * then free the all_channels, active_channels, listening_channels and
2853 * finished_channels lists and also channel_identity_map.
2856 void
2857 channel_free_all(void)
2859 log_debug(LD_CHANNEL,
2860 "Shutting down channels...");
2862 /* First, let's go for finished channels */
2863 if (finished_channels) {
2864 channel_free_list(finished_channels, 0);
2865 smartlist_free(finished_channels);
2866 finished_channels = NULL;
2869 /* Now the finished listeners */
2870 if (finished_listeners) {
2871 channel_listener_free_list(finished_listeners, 0);
2872 smartlist_free(finished_listeners);
2873 finished_listeners = NULL;
2876 /* Now all active channels */
2877 if (active_channels) {
2878 channel_free_list(active_channels, 1);
2879 smartlist_free(active_channels);
2880 active_channels = NULL;
2883 /* Now all active listeners */
2884 if (active_listeners) {
2885 channel_listener_free_list(active_listeners, 1);
2886 smartlist_free(active_listeners);
2887 active_listeners = NULL;
2890 /* Now all channels, in case any are left over */
2891 if (all_channels) {
2892 channel_free_list(all_channels, 1);
2893 smartlist_free(all_channels);
2894 all_channels = NULL;
2897 /* Now all listeners, in case any are left over */
2898 if (all_listeners) {
2899 channel_listener_free_list(all_listeners, 1);
2900 smartlist_free(all_listeners);
2901 all_listeners = NULL;
2904 /* Now free channel_identity_map */
2905 log_debug(LD_CHANNEL,
2906 "Freeing channel_identity_map");
2907 /* Geez, anything still left over just won't die ... let it leak then */
2908 HT_CLEAR(channel_idmap, &channel_identity_map);
2910 log_debug(LD_CHANNEL,
2911 "Done cleaning up after channels");
2915 * Connect to a given addr/port/digest
2917 * This sets up a new outgoing channel; in the future if multiple
2918 * channel_t subclasses are available, this is where the selection policy
2919 * should go. It may also be desirable to fold port into tor_addr_t
2920 * or make a new type including a tor_addr_t and port, so we have a
2921 * single abstract object encapsulating all the protocol details of
2922 * how to contact an OR.
2925 channel_t *
2926 channel_connect(const tor_addr_t *addr, uint16_t port,
2927 const char *id_digest)
2929 return channel_tls_connect(addr, port, id_digest);
2933 * Decide which of two channels to prefer for extending a circuit
2935 * This function is called while extending a circuit and returns true iff
2936 * a is 'better' than b. The most important criterion here is that a
2937 * canonical channel is always better than a non-canonical one, but the
2938 * number of circuits and the age are used as tie-breakers.
2940 * This is based on the former connection_or_is_better() of connection_or.c
2944 channel_is_better(time_t now, channel_t *a, channel_t *b,
2945 int forgive_new_connections)
2947 int a_grace, b_grace;
2948 int a_is_canonical, b_is_canonical;
2949 int a_has_circs, b_has_circs;
2952 * Do not definitively deprecate a new channel with no circuits on it
2953 * until this much time has passed.
2955 #define NEW_CHAN_GRACE_PERIOD (15*60)
2957 tor_assert(a);
2958 tor_assert(b);
2960 /* Check if one is canonical and the other isn't first */
2961 a_is_canonical = channel_is_canonical(a);
2962 b_is_canonical = channel_is_canonical(b);
2964 if (a_is_canonical && !b_is_canonical) return 1;
2965 if (!a_is_canonical && b_is_canonical) return 0;
2968 * Okay, if we're here they tied on canonicity. Next we check if
2969 * they have any circuits, and if one does and the other doesn't,
2970 * we prefer the one that does, unless we are forgiving and the
2971 * one that has no circuits is in its grace period.
2974 a_has_circs = (channel_num_circuits(a) > 0);
2975 b_has_circs = (channel_num_circuits(b) > 0);
2976 a_grace = (forgive_new_connections &&
2977 (now < channel_when_created(a) + NEW_CHAN_GRACE_PERIOD));
2978 b_grace = (forgive_new_connections &&
2979 (now < channel_when_created(b) + NEW_CHAN_GRACE_PERIOD));
2981 if (a_has_circs && !b_has_circs && !b_grace) return 1;
2982 if (!a_has_circs && b_has_circs && !a_grace) return 0;
2984 /* They tied on circuits too; just prefer whichever is newer */
2986 if (channel_when_created(a) > channel_when_created(b)) return 1;
2987 else return 0;
2991 * Get a channel to extend a circuit
2993 * Pick a suitable channel to extend a circuit to given the desired digest
2994 * the address we believe is correct for that digest; this tries to see
2995 * if we already have one for the requested endpoint, but if there is no good
2996 * channel, set *msg_out to a message describing the channel's state
2997 * and our next action, and set *launch_out to a boolean indicated whether
2998 * the caller should try to launch a new channel with channel_connect().
3001 channel_t *
3002 channel_get_for_extend(const char *digest,
3003 const tor_addr_t *target_addr,
3004 const char **msg_out,
3005 int *launch_out)
3007 channel_t *chan, *best = NULL;
3008 int n_inprogress_goodaddr = 0, n_old = 0;
3009 int n_noncanonical = 0, n_possible = 0;
3010 time_t now = approx_time();
3012 tor_assert(msg_out);
3013 tor_assert(launch_out);
3015 chan = channel_find_by_remote_digest(digest);
3017 /* Walk the list, unrefing the old one and refing the new at each
3018 * iteration.
3020 for (; chan; chan = channel_next_with_digest(chan)) {
3021 tor_assert(tor_memeq(chan->identity_digest,
3022 digest, DIGEST_LEN));
3024 if (chan->state == CHANNEL_STATE_CLOSING ||
3025 chan->state == CHANNEL_STATE_CLOSED ||
3026 chan->state == CHANNEL_STATE_ERROR)
3027 continue;
3029 /* Never return a channel on which the other end appears to be
3030 * a client. */
3031 if (channel_is_client(chan)) {
3032 continue;
3035 /* Never return a non-open connection. */
3036 if (chan->state != CHANNEL_STATE_OPEN) {
3037 /* If the address matches, don't launch a new connection for this
3038 * circuit. */
3039 if (channel_matches_target_addr_for_extend(chan, target_addr))
3040 ++n_inprogress_goodaddr;
3041 continue;
3044 /* Never return a connection that shouldn't be used for circs. */
3045 if (channel_is_bad_for_new_circs(chan)) {
3046 ++n_old;
3047 continue;
3050 /* Never return a non-canonical connection using a recent link protocol
3051 * if the address is not what we wanted.
3053 * The channel_is_canonical_is_reliable() function asks the lower layer
3054 * if we should trust channel_is_canonical(). The below is from the
3055 * comments of the old circuit_or_get_for_extend() and applies when
3056 * the lower-layer transport is channel_tls_t.
3058 * (For old link protocols, we can't rely on is_canonical getting
3059 * set properly if we're talking to the right address, since we might
3060 * have an out-of-date descriptor, and we will get no NETINFO cell to
3061 * tell us about the right address.)
3063 if (!channel_is_canonical(chan) &&
3064 channel_is_canonical_is_reliable(chan) &&
3065 !channel_matches_target_addr_for_extend(chan, target_addr)) {
3066 ++n_noncanonical;
3067 continue;
3070 ++n_possible;
3072 if (!best) {
3073 best = chan; /* If we have no 'best' so far, this one is good enough. */
3074 continue;
3077 if (channel_is_better(now, chan, best, 0))
3078 best = chan;
3081 if (best) {
3082 *msg_out = "Connection is fine; using it.";
3083 *launch_out = 0;
3084 return best;
3085 } else if (n_inprogress_goodaddr) {
3086 *msg_out = "Connection in progress; waiting.";
3087 *launch_out = 0;
3088 return NULL;
3089 } else if (n_old || n_noncanonical) {
3090 *msg_out = "Connections all too old, or too non-canonical. "
3091 " Launching a new one.";
3092 *launch_out = 1;
3093 return NULL;
3094 } else {
3095 *msg_out = "Not connected. Connecting.";
3096 *launch_out = 1;
3097 return NULL;
3102 * Describe the transport subclass for a channel
3104 * Invoke a method to get a string description of the lower-layer
3105 * transport for this channel.
3108 const char *
3109 channel_describe_transport(channel_t *chan)
3111 tor_assert(chan);
3112 tor_assert(chan->describe_transport);
3114 return chan->describe_transport(chan);
3118 * Describe the transport subclass for a channel listener
3120 * Invoke a method to get a string description of the lower-layer
3121 * transport for this channel listener.
3124 const char *
3125 channel_listener_describe_transport(channel_listener_t *chan_l)
3127 tor_assert(chan_l);
3128 tor_assert(chan_l->describe_transport);
3130 return chan_l->describe_transport(chan_l);
3134 * Return the number of entries in <b>queue</b>
3136 static int
3137 chan_cell_queue_len(const chan_cell_queue_t *queue)
3139 int r = 0;
3140 cell_queue_entry_t *cell;
3141 TOR_SIMPLEQ_FOREACH(cell, queue, next)
3142 ++r;
3143 return r;
3147 * Dump channel statistics
3149 * Dump statistics for one channel to the log
3152 void
3153 channel_dump_statistics(channel_t *chan, int severity)
3155 double avg, interval, age;
3156 time_t now = time(NULL);
3157 tor_addr_t remote_addr;
3158 int have_remote_addr;
3159 char *remote_addr_str;
3161 tor_assert(chan);
3163 age = (double)(now - chan->timestamp_created);
3165 tor_log(severity, LD_GENERAL,
3166 "Channel " U64_FORMAT " (at %p) with transport %s is in state "
3167 "%s (%d)",
3168 U64_PRINTF_ARG(chan->global_identifier), chan,
3169 channel_describe_transport(chan),
3170 channel_state_to_string(chan->state), chan->state);
3171 tor_log(severity, LD_GENERAL,
3172 " * Channel " U64_FORMAT " was created at " U64_FORMAT
3173 " (" U64_FORMAT " seconds ago) "
3174 "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3175 U64_PRINTF_ARG(chan->global_identifier),
3176 U64_PRINTF_ARG(chan->timestamp_created),
3177 U64_PRINTF_ARG(now - chan->timestamp_created),
3178 U64_PRINTF_ARG(chan->timestamp_active),
3179 U64_PRINTF_ARG(now - chan->timestamp_active));
3181 /* Handle digest and nickname */
3182 if (!tor_digest_is_zero(chan->identity_digest)) {
3183 if (chan->nickname) {
3184 tor_log(severity, LD_GENERAL,
3185 " * Channel " U64_FORMAT " says it is connected "
3186 "to an OR with digest %s and nickname %s",
3187 U64_PRINTF_ARG(chan->global_identifier),
3188 hex_str(chan->identity_digest, DIGEST_LEN),
3189 chan->nickname);
3190 } else {
3191 tor_log(severity, LD_GENERAL,
3192 " * Channel " U64_FORMAT " says it is connected "
3193 "to an OR with digest %s and no known nickname",
3194 U64_PRINTF_ARG(chan->global_identifier),
3195 hex_str(chan->identity_digest, DIGEST_LEN));
3197 } else {
3198 if (chan->nickname) {
3199 tor_log(severity, LD_GENERAL,
3200 " * Channel " U64_FORMAT " does not know the digest"
3201 " of the OR it is connected to, but reports its nickname is %s",
3202 U64_PRINTF_ARG(chan->global_identifier),
3203 chan->nickname);
3204 } else {
3205 tor_log(severity, LD_GENERAL,
3206 " * Channel " U64_FORMAT " does not know the digest"
3207 " or the nickname of the OR it is connected to",
3208 U64_PRINTF_ARG(chan->global_identifier));
3212 /* Handle remote address and descriptions */
3213 have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
3214 if (have_remote_addr) {
3215 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
3216 remote_addr_str = tor_dup_addr(&remote_addr);
3217 tor_log(severity, LD_GENERAL,
3218 " * Channel " U64_FORMAT " says its remote address"
3219 " is %s, and gives a canonical description of \"%s\" and an "
3220 "actual description of \"%s\"",
3221 U64_PRINTF_ARG(chan->global_identifier),
3222 remote_addr_str,
3223 channel_get_canonical_remote_descr(chan),
3224 actual);
3225 tor_free(remote_addr_str);
3226 tor_free(actual);
3227 } else {
3228 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
3229 tor_log(severity, LD_GENERAL,
3230 " * Channel " U64_FORMAT " does not know its remote "
3231 "address, but gives a canonical description of \"%s\" and an "
3232 "actual description of \"%s\"",
3233 U64_PRINTF_ARG(chan->global_identifier),
3234 channel_get_canonical_remote_descr(chan),
3235 actual);
3236 tor_free(actual);
3239 /* Handle marks */
3240 tor_log(severity, LD_GENERAL,
3241 " * Channel " U64_FORMAT " has these marks: %s %s %s "
3242 "%s %s %s",
3243 U64_PRINTF_ARG(chan->global_identifier),
3244 channel_is_bad_for_new_circs(chan) ?
3245 "bad_for_new_circs" : "!bad_for_new_circs",
3246 channel_is_canonical(chan) ?
3247 "canonical" : "!canonical",
3248 channel_is_canonical_is_reliable(chan) ?
3249 "is_canonical_is_reliable" :
3250 "!is_canonical_is_reliable",
3251 channel_is_client(chan) ?
3252 "client" : "!client",
3253 channel_is_local(chan) ?
3254 "local" : "!local",
3255 channel_is_incoming(chan) ?
3256 "incoming" : "outgoing");
3258 /* Describe queues */
3259 tor_log(severity, LD_GENERAL,
3260 " * Channel " U64_FORMAT " has %d queued incoming cells"
3261 " and %d queued outgoing cells",
3262 U64_PRINTF_ARG(chan->global_identifier),
3263 chan_cell_queue_len(&chan->incoming_queue),
3264 chan_cell_queue_len(&chan->outgoing_queue));
3266 /* Describe circuits */
3267 tor_log(severity, LD_GENERAL,
3268 " * Channel " U64_FORMAT " has %d active circuits out of"
3269 " %d in total",
3270 U64_PRINTF_ARG(chan->global_identifier),
3271 (chan->cmux != NULL) ?
3272 circuitmux_num_active_circuits(chan->cmux) : 0,
3273 (chan->cmux != NULL) ?
3274 circuitmux_num_circuits(chan->cmux) : 0);
3276 /* Describe timestamps */
3277 tor_log(severity, LD_GENERAL,
3278 " * Channel " U64_FORMAT " was last used by a "
3279 "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3280 U64_PRINTF_ARG(chan->global_identifier),
3281 U64_PRINTF_ARG(chan->timestamp_client),
3282 U64_PRINTF_ARG(now - chan->timestamp_client));
3283 tor_log(severity, LD_GENERAL,
3284 " * Channel " U64_FORMAT " was last drained at "
3285 U64_FORMAT " (" U64_FORMAT " seconds ago)",
3286 U64_PRINTF_ARG(chan->global_identifier),
3287 U64_PRINTF_ARG(chan->timestamp_drained),
3288 U64_PRINTF_ARG(now - chan->timestamp_drained));
3289 tor_log(severity, LD_GENERAL,
3290 " * Channel " U64_FORMAT " last received a cell "
3291 "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3292 U64_PRINTF_ARG(chan->global_identifier),
3293 U64_PRINTF_ARG(chan->timestamp_recv),
3294 U64_PRINTF_ARG(now - chan->timestamp_recv));
3295 tor_log(severity, LD_GENERAL,
3296 " * Channel " U64_FORMAT " last trasmitted a cell "
3297 "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3298 U64_PRINTF_ARG(chan->global_identifier),
3299 U64_PRINTF_ARG(chan->timestamp_xmit),
3300 U64_PRINTF_ARG(now - chan->timestamp_xmit));
3302 /* Describe counters and rates */
3303 tor_log(severity, LD_GENERAL,
3304 " * Channel " U64_FORMAT " has received "
3305 U64_FORMAT " cells and transmitted " U64_FORMAT,
3306 U64_PRINTF_ARG(chan->global_identifier),
3307 U64_PRINTF_ARG(chan->n_cells_recved),
3308 U64_PRINTF_ARG(chan->n_cells_xmitted));
3309 if (now > chan->timestamp_created &&
3310 chan->timestamp_created > 0) {
3311 if (chan->n_cells_recved > 0) {
3312 avg = (double)(chan->n_cells_recved) / age;
3313 if (avg >= 1.0) {
3314 tor_log(severity, LD_GENERAL,
3315 " * Channel " U64_FORMAT " has averaged %f "
3316 "cells received per second",
3317 U64_PRINTF_ARG(chan->global_identifier), avg);
3318 } else if (avg >= 0.0) {
3319 interval = 1.0 / avg;
3320 tor_log(severity, LD_GENERAL,
3321 " * Channel " U64_FORMAT " has averaged %f "
3322 "seconds between received cells",
3323 U64_PRINTF_ARG(chan->global_identifier), interval);
3326 if (chan->n_cells_xmitted > 0) {
3327 avg = (double)(chan->n_cells_xmitted) / age;
3328 if (avg >= 1.0) {
3329 tor_log(severity, LD_GENERAL,
3330 " * Channel " U64_FORMAT " has averaged %f "
3331 "cells transmitted per second",
3332 U64_PRINTF_ARG(chan->global_identifier), avg);
3333 } else if (avg >= 0.0) {
3334 interval = 1.0 / avg;
3335 tor_log(severity, LD_GENERAL,
3336 " * Channel " U64_FORMAT " has averaged %f "
3337 "seconds between transmitted cells",
3338 U64_PRINTF_ARG(chan->global_identifier), interval);
3343 /* Dump anything the lower layer has to say */
3344 channel_dump_transport_statistics(chan, severity);
3348 * Dump channel listener statistics
3350 * Dump statistics for one channel listener to the log
3353 void
3354 channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
3356 double avg, interval, age;
3357 time_t now = time(NULL);
3359 tor_assert(chan_l);
3361 age = (double)(now - chan_l->timestamp_created);
3363 tor_log(severity, LD_GENERAL,
3364 "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
3365 "state %s (%d)",
3366 U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
3367 channel_listener_describe_transport(chan_l),
3368 channel_listener_state_to_string(chan_l->state), chan_l->state);
3369 tor_log(severity, LD_GENERAL,
3370 " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
3371 " (" U64_FORMAT " seconds ago) "
3372 "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3373 U64_PRINTF_ARG(chan_l->global_identifier),
3374 U64_PRINTF_ARG(chan_l->timestamp_created),
3375 U64_PRINTF_ARG(now - chan_l->timestamp_created),
3376 U64_PRINTF_ARG(chan_l->timestamp_active),
3377 U64_PRINTF_ARG(now - chan_l->timestamp_active));
3379 tor_log(severity, LD_GENERAL,
3380 " * Channel listener " U64_FORMAT " last accepted an incoming "
3381 "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
3382 "and has accepted " U64_FORMAT " channels in total",
3383 U64_PRINTF_ARG(chan_l->global_identifier),
3384 U64_PRINTF_ARG(chan_l->timestamp_accepted),
3385 U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
3386 U64_PRINTF_ARG(chan_l->n_accepted));
3389 * If it's sensible to do so, get the rate of incoming channels on this
3390 * listener
3392 if (now > chan_l->timestamp_created &&
3393 chan_l->timestamp_created > 0 &&
3394 chan_l->n_accepted > 0) {
3395 avg = (double)(chan_l->n_accepted) / age;
3396 if (avg >= 1.0) {
3397 tor_log(severity, LD_GENERAL,
3398 " * Channel listener " U64_FORMAT " has averaged %f incoming "
3399 "channels per second",
3400 U64_PRINTF_ARG(chan_l->global_identifier), avg);
3401 } else if (avg >= 0.0) {
3402 interval = 1.0 / avg;
3403 tor_log(severity, LD_GENERAL,
3404 " * Channel listener " U64_FORMAT " has averaged %f seconds "
3405 "between incoming channels",
3406 U64_PRINTF_ARG(chan_l->global_identifier), interval);
3410 /* Dump anything the lower layer has to say */
3411 channel_listener_dump_transport_statistics(chan_l, severity);
3415 * Invoke transport-specific stats dump for channel
3417 * If there is a lower-layer statistics dump method, invoke it
3420 void
3421 channel_dump_transport_statistics(channel_t *chan, int severity)
3423 tor_assert(chan);
3425 if (chan->dumpstats) chan->dumpstats(chan, severity);
3429 * Invoke transport-specific stats dump for channel listener
3431 * If there is a lower-layer statistics dump method, invoke it
3434 void
3435 channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
3436 int severity)
3438 tor_assert(chan_l);
3440 if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
3444 * Return text description of the remote endpoint
3446 * This function return a test provided by the lower layer of the remote
3447 * endpoint for this channel; it should specify the actual address connected
3448 * to/from.
3450 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3451 * may invalidate the return value from this function.
3453 const char *
3454 channel_get_actual_remote_descr(channel_t *chan)
3456 tor_assert(chan);
3457 tor_assert(chan->get_remote_descr);
3459 /* Param 1 indicates the actual description */
3460 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
3464 * Return the text address of the remote endpoint.
3466 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3467 * may invalidate the return value from this function.
3469 const char *
3470 channel_get_actual_remote_address(channel_t *chan)
3472 /* Param 1 indicates the actual description */
3473 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
3477 * Return text description of the remote endpoint canonical address
3479 * This function return a test provided by the lower layer of the remote
3480 * endpoint for this channel; it should use the known canonical address for
3481 * this OR's identity digest if possible.
3483 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3484 * may invalidate the return value from this function.
3486 const char *
3487 channel_get_canonical_remote_descr(channel_t *chan)
3489 tor_assert(chan);
3490 tor_assert(chan->get_remote_descr);
3492 /* Param 0 indicates the canonicalized description */
3493 return chan->get_remote_descr(chan, 0);
3497 * Get remote address if possible.
3499 * Write the remote address out to a tor_addr_t if the underlying transport
3500 * supports this operation, and return 1. Return 0 if the underlying transport
3501 * doesn't let us do this.
3504 channel_get_addr_if_possible(channel_t *chan, tor_addr_t *addr_out)
3506 tor_assert(chan);
3507 tor_assert(addr_out);
3509 if (chan->get_remote_addr)
3510 return chan->get_remote_addr(chan, addr_out);
3511 /* Else no support, method not implemented */
3512 else return 0;
3516 * Check if there are outgoing queue writes on this channel
3518 * Indicate if either we have queued cells, or if not, whether the underlying
3519 * lower-layer transport thinks it has an output queue.
3523 channel_has_queued_writes(channel_t *chan)
3525 int has_writes = 0;
3527 tor_assert(chan);
3528 tor_assert(chan->has_queued_writes);
3530 if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
3531 has_writes = 1;
3532 } else {
3533 /* Check with the lower layer */
3534 has_writes = chan->has_queued_writes(chan);
3537 return has_writes;
3541 * Check the is_bad_for_new_circs flag
3543 * This function returns the is_bad_for_new_circs flag of the specified
3544 * channel.
3548 channel_is_bad_for_new_circs(channel_t *chan)
3550 tor_assert(chan);
3552 return chan->is_bad_for_new_circs;
3556 * Mark a channel as bad for new circuits
3558 * Set the is_bad_for_new_circs_flag on chan.
3561 void
3562 channel_mark_bad_for_new_circs(channel_t *chan)
3564 tor_assert(chan);
3566 chan->is_bad_for_new_circs = 1;
3570 * Get the client flag
3572 * This returns the client flag of a channel, which will be set if
3573 * command_process_create_cell() in command.c thinks this is a connection
3574 * from a client.
3578 channel_is_client(channel_t *chan)
3580 tor_assert(chan);
3582 return chan->is_client;
3586 * Set the client flag
3588 * Mark a channel as being from a client
3591 void
3592 channel_mark_client(channel_t *chan)
3594 tor_assert(chan);
3596 chan->is_client = 1;
3600 * Get the canonical flag for a channel
3602 * This returns the is_canonical for a channel; this flag is determined by
3603 * the lower layer and can't be set in a transport-independent way.
3607 channel_is_canonical(channel_t *chan)
3609 tor_assert(chan);
3610 tor_assert(chan->is_canonical);
3612 return chan->is_canonical(chan, 0);
3616 * Test if the canonical flag is reliable
3618 * This function asks if the lower layer thinks it's safe to trust the
3619 * result of channel_is_canonical()
3623 channel_is_canonical_is_reliable(channel_t *chan)
3625 tor_assert(chan);
3626 tor_assert(chan->is_canonical);
3628 return chan->is_canonical(chan, 1);
3632 * Test incoming flag
3634 * This function gets the incoming flag; this is set when a listener spawns
3635 * a channel. If this returns true the channel was remotely initiated.
3639 channel_is_incoming(channel_t *chan)
3641 tor_assert(chan);
3643 return chan->is_incoming;
3647 * Set the incoming flag
3649 * This function is called when a channel arrives on a listening channel
3650 * to mark it as incoming.
3653 void
3654 channel_mark_incoming(channel_t *chan)
3656 tor_assert(chan);
3658 chan->is_incoming = 1;
3662 * Test local flag
3664 * This function gets the local flag; the lower layer should set this when
3665 * setting up the channel if is_local_addr() is true for all of the
3666 * destinations it will communicate with on behalf of this channel. It's
3667 * used to decide whether to declare the network reachable when seeing incoming
3668 * traffic on the channel.
3672 channel_is_local(channel_t *chan)
3674 tor_assert(chan);
3676 return chan->is_local;
3680 * Set the local flag
3682 * This internal-only function should be called by the lower layer if the
3683 * channel is to a local address. See channel_is_local() above or the
3684 * description of the is_local bit in channel.h
3687 void
3688 channel_mark_local(channel_t *chan)
3690 tor_assert(chan);
3692 chan->is_local = 1;
3696 * Test outgoing flag
3698 * This function gets the outgoing flag; this is the inverse of the incoming
3699 * bit set when a listener spawns a channel. If this returns true the channel
3700 * was locally initiated.
3704 channel_is_outgoing(channel_t *chan)
3706 tor_assert(chan);
3708 return !(chan->is_incoming);
3712 * Mark a channel as outgoing
3714 * This function clears the incoming flag and thus marks a channel as
3715 * outgoing.
3718 void
3719 channel_mark_outgoing(channel_t *chan)
3721 tor_assert(chan);
3723 chan->is_incoming = 0;
3726 /*********************
3727 * Timestamp updates *
3728 ********************/
3731 * Update the created timestamp for a channel
3733 * This updates the channel's created timestamp and should only be called
3734 * from channel_init().
3737 void
3738 channel_timestamp_created(channel_t *chan)
3740 time_t now = time(NULL);
3742 tor_assert(chan);
3744 chan->timestamp_created = now;
3748 * Update the created timestamp for a channel listener
3750 * This updates the channel listener's created timestamp and should only be
3751 * called from channel_init_listener().
3754 void
3755 channel_listener_timestamp_created(channel_listener_t *chan_l)
3757 time_t now = time(NULL);
3759 tor_assert(chan_l);
3761 chan_l->timestamp_created = now;
3765 * Update the last active timestamp for a channel
3767 * This function updates the channel's last active timestamp; it should be
3768 * called by the lower layer whenever there is activity on the channel which
3769 * does not lead to a cell being transmitted or received; the active timestamp
3770 * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
3771 * but it should be updated for things like the v3 handshake and stuff that
3772 * produce activity only visible to the lower layer.
3775 void
3776 channel_timestamp_active(channel_t *chan)
3778 time_t now = time(NULL);
3780 tor_assert(chan);
3782 chan->timestamp_active = now;
3786 * Update the last active timestamp for a channel listener
3789 void
3790 channel_listener_timestamp_active(channel_listener_t *chan_l)
3792 time_t now = time(NULL);
3794 tor_assert(chan_l);
3796 chan_l->timestamp_active = now;
3800 * Update the last accepted timestamp.
3802 * This function updates the channel listener's last accepted timestamp; it
3803 * should be called whenever a new incoming channel is accepted on a
3804 * listener.
3807 void
3808 channel_listener_timestamp_accepted(channel_listener_t *chan_l)
3810 time_t now = time(NULL);
3812 tor_assert(chan_l);
3814 chan_l->timestamp_active = now;
3815 chan_l->timestamp_accepted = now;
3819 * Update client timestamp
3821 * This function is called by relay.c to timestamp a channel that appears to
3822 * be used as a client.
3825 void
3826 channel_timestamp_client(channel_t *chan)
3828 time_t now = time(NULL);
3830 tor_assert(chan);
3832 chan->timestamp_client = now;
3836 * Update the last drained timestamp
3838 * This is called whenever we transmit a cell which leaves the outgoing cell
3839 * queue completely empty. It also updates the xmit time and the active time.
3842 void
3843 channel_timestamp_drained(channel_t *chan)
3845 time_t now = time(NULL);
3847 tor_assert(chan);
3849 chan->timestamp_active = now;
3850 chan->timestamp_drained = now;
3851 chan->timestamp_xmit = now;
3855 * Update the recv timestamp
3857 * This is called whenever we get an incoming cell from the lower layer.
3858 * This also updates the active timestamp.
3861 void
3862 channel_timestamp_recv(channel_t *chan)
3864 time_t now = time(NULL);
3866 tor_assert(chan);
3868 chan->timestamp_active = now;
3869 chan->timestamp_recv = now;
3873 * Update the xmit timestamp
3874 * This is called whenever we pass an outgoing cell to the lower layer. This
3875 * also updates the active timestamp.
3878 void
3879 channel_timestamp_xmit(channel_t *chan)
3881 time_t now = time(NULL);
3883 tor_assert(chan);
3885 chan->timestamp_active = now;
3886 chan->timestamp_xmit = now;
3889 /***************************************************************
3890 * Timestamp queries - see above for definitions of timestamps *
3891 **************************************************************/
3894 * Query created timestamp for a channel
3897 time_t
3898 channel_when_created(channel_t *chan)
3900 tor_assert(chan);
3902 return chan->timestamp_created;
3906 * Query created timestamp for a channel listener
3909 time_t
3910 channel_listener_when_created(channel_listener_t *chan_l)
3912 tor_assert(chan_l);
3914 return chan_l->timestamp_created;
3918 * Query last active timestamp for a channel
3921 time_t
3922 channel_when_last_active(channel_t *chan)
3924 tor_assert(chan);
3926 return chan->timestamp_active;
3930 * Query last active timestamp for a channel listener
3933 time_t
3934 channel_listener_when_last_active(channel_listener_t *chan_l)
3936 tor_assert(chan_l);
3938 return chan_l->timestamp_active;
3942 * Query last accepted timestamp for a channel listener
3945 time_t
3946 channel_listener_when_last_accepted(channel_listener_t *chan_l)
3948 tor_assert(chan_l);
3950 return chan_l->timestamp_accepted;
3954 * Query client timestamp
3957 time_t
3958 channel_when_last_client(channel_t *chan)
3960 tor_assert(chan);
3962 return chan->timestamp_client;
3966 * Query drained timestamp
3969 time_t
3970 channel_when_last_drained(channel_t *chan)
3972 tor_assert(chan);
3974 return chan->timestamp_drained;
3978 * Query recv timestamp
3981 time_t
3982 channel_when_last_recv(channel_t *chan)
3984 tor_assert(chan);
3986 return chan->timestamp_recv;
3990 * Query xmit timestamp
3993 time_t
3994 channel_when_last_xmit(channel_t *chan)
3996 tor_assert(chan);
3998 return chan->timestamp_xmit;
4002 * Query accepted counter
4005 uint64_t
4006 channel_listener_count_accepted(channel_listener_t *chan_l)
4008 tor_assert(chan_l);
4010 return chan_l->n_accepted;
4014 * Query received cell counter
4017 uint64_t
4018 channel_count_recved(channel_t *chan)
4020 tor_assert(chan);
4022 return chan->n_cells_recved;
4026 * Query transmitted cell counter
4029 uint64_t
4030 channel_count_xmitted(channel_t *chan)
4032 tor_assert(chan);
4034 return chan->n_cells_xmitted;
4038 * Check if a channel matches an extend_info_t
4040 * This function calls the lower layer and asks if this channel matches a
4041 * given extend_info_t.
4045 channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
4047 tor_assert(chan);
4048 tor_assert(chan->matches_extend_info);
4049 tor_assert(extend_info);
4051 return chan->matches_extend_info(chan, extend_info);
4055 * Check if a channel matches a given target address; return true iff we do.
4057 * This function calls into the lower layer and asks if this channel thinks
4058 * it matches a given target address for circuit extension purposes.
4062 channel_matches_target_addr_for_extend(channel_t *chan,
4063 const tor_addr_t *target)
4065 tor_assert(chan);
4066 tor_assert(chan->matches_target);
4067 tor_assert(target);
4069 return chan->matches_target(chan, target);
4073 * Return the total number of circuits used by a channel
4075 * @param chan Channel to query
4076 * @return Number of circuits using this as n_chan or p_chan
4079 unsigned int
4080 channel_num_circuits(channel_t *chan)
4082 tor_assert(chan);
4084 return chan->num_n_circuits +
4085 chan->num_p_circuits;
4089 * Set up circuit ID generation
4091 * This is called when setting up a channel and replaces the old
4092 * connection_or_set_circid_type()
4094 void
4095 channel_set_circid_type(channel_t *chan,
4096 crypto_pk_t *identity_rcvd,
4097 int consider_identity)
4099 int started_here;
4100 crypto_pk_t *our_identity;
4102 tor_assert(chan);
4104 started_here = channel_is_outgoing(chan);
4106 if (! consider_identity) {
4107 if (started_here)
4108 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
4109 else
4110 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
4111 return;
4114 our_identity = started_here ?
4115 get_tlsclient_identity_key() : get_server_identity_key();
4117 if (identity_rcvd) {
4118 if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
4119 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
4120 } else {
4121 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
4123 } else {
4124 chan->circ_id_type = CIRC_ID_TYPE_NEITHER;