Bug 6572: Use timestamp_created for liveness sanity checks.
[tor.git] / src / or / channel.c
blob4e9086f2e648aaa69078551462ae4ddf4d35ab00
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 if (chan->reason_for_closing == CHANNEL_CLOSE_FOR_ERROR) {
1296 /* Inform any pending (not attached) circs that they should
1297 * give up. */
1298 circuit_n_chan_done(chan, 0);
1300 /* Now close all the attached circuits on it. */
1301 circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
1303 if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
1304 channel_change_state(chan, CHANNEL_STATE_CLOSED);
1305 } else {
1306 channel_change_state(chan, CHANNEL_STATE_ERROR);
1311 * Notify that the lower layer is finished closing the channel listener
1313 * This function should be called by the lower layer when a channel listener
1314 * is finished closing and it should be regarded as inactive and
1315 * freed by the channel code.
1318 void
1319 channel_listener_closed(channel_listener_t *chan_l)
1321 tor_assert(chan_l);
1322 tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1323 chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1324 chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
1326 /* No-op if already inactive */
1327 if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1328 chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1330 if (chan_l->reason_for_closing != CHANNEL_LISTENER_CLOSE_FOR_ERROR) {
1331 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSED);
1332 } else {
1333 channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_ERROR);
1338 * Clear the identity_digest of a channel
1340 * This function clears the identity digest of the remote endpoint for a
1341 * channel; this is intended for use by the lower layer.
1344 void
1345 channel_clear_identity_digest(channel_t *chan)
1347 int state_not_in_map;
1349 tor_assert(chan);
1351 log_debug(LD_CHANNEL,
1352 "Clearing remote endpoint digest on channel %p with "
1353 "global ID " U64_FORMAT,
1354 chan, U64_PRINTF_ARG(chan->global_identifier));
1356 state_not_in_map =
1357 (chan->state == CHANNEL_STATE_CLOSING ||
1358 chan->state == CHANNEL_STATE_CLOSED ||
1359 chan->state == CHANNEL_STATE_ERROR);
1361 if (!state_not_in_map && chan->registered &&
1362 !tor_digest_is_zero(chan->identity_digest))
1363 /* if it's registered get it out of the digest map */
1364 channel_remove_from_digest_map(chan);
1366 memset(chan->identity_digest, 0,
1367 sizeof(chan->identity_digest));
1371 * Set the identity_digest of a channel
1373 * This function sets the identity digest of the remote endpoint for a
1374 * channel; this is intended for use by the lower layer.
1377 void
1378 channel_set_identity_digest(channel_t *chan,
1379 const char *identity_digest)
1381 int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1383 tor_assert(chan);
1385 log_debug(LD_CHANNEL,
1386 "Setting remote endpoint digest on channel %p with "
1387 "global ID " U64_FORMAT " to digest %s",
1388 chan, U64_PRINTF_ARG(chan->global_identifier),
1389 identity_digest ?
1390 hex_str(identity_digest, DIGEST_LEN) : "(null)");
1392 state_not_in_map =
1393 (chan->state == CHANNEL_STATE_CLOSING ||
1394 chan->state == CHANNEL_STATE_CLOSED ||
1395 chan->state == CHANNEL_STATE_ERROR);
1396 was_in_digest_map =
1397 !state_not_in_map &&
1398 chan->registered &&
1399 !tor_digest_is_zero(chan->identity_digest);
1400 should_be_in_digest_map =
1401 !state_not_in_map &&
1402 chan->registered &&
1403 (identity_digest &&
1404 !tor_digest_is_zero(identity_digest));
1406 if (was_in_digest_map)
1407 /* We should always remove it; we'll add it back if we're writing
1408 * in a new digest.
1410 channel_remove_from_digest_map(chan);
1412 if (identity_digest) {
1413 memcpy(chan->identity_digest,
1414 identity_digest,
1415 sizeof(chan->identity_digest));
1416 } else {
1417 memset(chan->identity_digest, 0,
1418 sizeof(chan->identity_digest));
1421 /* Put it in the digest map if we should */
1422 if (should_be_in_digest_map)
1423 channel_add_to_digest_map(chan);
1427 * Clear the remote end metadata (identity_digest/nickname) of a channel
1429 * This function clears all the remote end info from a channel; this is
1430 * intended for use by the lower layer.
1433 void
1434 channel_clear_remote_end(channel_t *chan)
1436 int state_not_in_map;
1438 tor_assert(chan);
1440 log_debug(LD_CHANNEL,
1441 "Clearing remote endpoint identity on channel %p with "
1442 "global ID " U64_FORMAT,
1443 chan, U64_PRINTF_ARG(chan->global_identifier));
1445 state_not_in_map =
1446 (chan->state == CHANNEL_STATE_CLOSING ||
1447 chan->state == CHANNEL_STATE_CLOSED ||
1448 chan->state == CHANNEL_STATE_ERROR);
1450 if (!state_not_in_map && chan->registered &&
1451 !tor_digest_is_zero(chan->identity_digest))
1452 /* if it's registered get it out of the digest map */
1453 channel_remove_from_digest_map(chan);
1455 memset(chan->identity_digest, 0,
1456 sizeof(chan->identity_digest));
1457 tor_free(chan->nickname);
1461 * Set the remote end metadata (identity_digest/nickname) of a channel
1463 * This function sets new remote end info on a channel; this is intended
1464 * for use by the lower layer.
1467 void
1468 channel_set_remote_end(channel_t *chan,
1469 const char *identity_digest,
1470 const char *nickname)
1472 int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1474 tor_assert(chan);
1476 log_debug(LD_CHANNEL,
1477 "Setting remote endpoint identity on channel %p with "
1478 "global ID " U64_FORMAT " to nickname %s, digest %s",
1479 chan, U64_PRINTF_ARG(chan->global_identifier),
1480 nickname ? nickname : "(null)",
1481 identity_digest ?
1482 hex_str(identity_digest, DIGEST_LEN) : "(null)");
1484 state_not_in_map =
1485 (chan->state == CHANNEL_STATE_CLOSING ||
1486 chan->state == CHANNEL_STATE_CLOSED ||
1487 chan->state == CHANNEL_STATE_ERROR);
1488 was_in_digest_map =
1489 !state_not_in_map &&
1490 chan->registered &&
1491 !tor_digest_is_zero(chan->identity_digest);
1492 should_be_in_digest_map =
1493 !state_not_in_map &&
1494 chan->registered &&
1495 (identity_digest &&
1496 !tor_digest_is_zero(identity_digest));
1498 if (was_in_digest_map)
1499 /* We should always remove it; we'll add it back if we're writing
1500 * in a new digest.
1502 channel_remove_from_digest_map(chan);
1504 if (identity_digest) {
1505 memcpy(chan->identity_digest,
1506 identity_digest,
1507 sizeof(chan->identity_digest));
1509 } else {
1510 memset(chan->identity_digest, 0,
1511 sizeof(chan->identity_digest));
1514 tor_free(chan->nickname);
1515 if (nickname)
1516 chan->nickname = tor_strdup(nickname);
1518 /* Put it in the digest map if we should */
1519 if (should_be_in_digest_map)
1520 channel_add_to_digest_map(chan);
1524 * Duplicate a cell queue entry; this is a shallow copy intended for use
1525 * in channel_write_cell_queue_entry().
1528 static cell_queue_entry_t *
1529 cell_queue_entry_dup(cell_queue_entry_t *q)
1531 cell_queue_entry_t *rv = NULL;
1533 tor_assert(q);
1535 rv = tor_malloc(sizeof(*rv));
1536 memcpy(rv, q, sizeof(*rv));
1538 return rv;
1542 * Free a cell_queue_entry_t; the handed_off parameter indicates whether
1543 * the contents were passed to the lower layer (it is responsible for
1544 * them) or not (we should free).
1547 static void
1548 cell_queue_entry_free(cell_queue_entry_t *q, int handed_off)
1550 if (!q) return;
1552 if (!handed_off) {
1554 * If we handed it off, the recipient becomes responsible (or
1555 * with packed cells the channel_t subclass calls packed_cell
1556 * free after writing out its contents; see, e.g.,
1557 * channel_tls_write_packed_cell_method(). Otherwise, we have
1558 * to take care of it here if possible.
1560 switch (q->type) {
1561 case CELL_QUEUE_FIXED:
1562 if (q->u.fixed.cell) {
1564 * There doesn't seem to be a cell_free() function anywhere in the
1565 * pre-channel code; just use tor_free()
1567 tor_free(q->u.fixed.cell);
1569 break;
1570 case CELL_QUEUE_PACKED:
1571 if (q->u.packed.packed_cell) {
1572 packed_cell_free(q->u.packed.packed_cell);
1574 break;
1575 case CELL_QUEUE_VAR:
1576 if (q->u.var.var_cell) {
1578 * This one's in connection_or.c; it'd be nice to figure out the
1579 * whole flow of cells from one end to the other and factor the
1580 * cell memory management functions like this out of the specific
1581 * TLS lower layer.
1583 var_cell_free(q->u.var.var_cell);
1585 break;
1586 default:
1588 * Nothing we can do if we don't know the type; this will
1589 * have been warned about elsewhere.
1591 break;
1594 tor_free(q);
1598 * Check whether a cell queue entry is padding; this is a helper function
1599 * for channel_write_cell_queue_entry()
1602 static int
1603 cell_queue_entry_is_padding(cell_queue_entry_t *q)
1605 tor_assert(q);
1607 if (q->type == CELL_QUEUE_FIXED) {
1608 if (q->u.fixed.cell) {
1609 if (q->u.fixed.cell->command == CELL_PADDING ||
1610 q->u.fixed.cell->command == CELL_VPADDING) {
1611 return 1;
1614 } else if (q->type == CELL_QUEUE_VAR) {
1615 if (q->u.var.var_cell) {
1616 if (q->u.var.var_cell->command == CELL_PADDING ||
1617 q->u.var.var_cell->command == CELL_VPADDING) {
1618 return 1;
1623 return 0;
1627 * Allocate a new cell queue entry for a fixed-size cell
1630 static cell_queue_entry_t *
1631 cell_queue_entry_new_fixed(cell_t *cell)
1633 cell_queue_entry_t *q = NULL;
1635 tor_assert(cell);
1637 q = tor_malloc(sizeof(*q));
1638 q->type = CELL_QUEUE_FIXED;
1639 q->u.fixed.cell = cell;
1641 return q;
1645 * Allocate a new cell queue entry for a variable-size cell
1648 static cell_queue_entry_t *
1649 cell_queue_entry_new_var(var_cell_t *var_cell)
1651 cell_queue_entry_t *q = NULL;
1653 tor_assert(var_cell);
1655 q = tor_malloc(sizeof(*q));
1656 q->type = CELL_QUEUE_VAR;
1657 q->u.var.var_cell = var_cell;
1659 return q;
1663 * Write to a channel based on a cell_queue_entry_t
1665 * Given a cell_queue_entry_t filled out by the caller, try to send the cell
1666 * and queue it if we can't.
1669 static void
1670 channel_write_cell_queue_entry(channel_t *chan, cell_queue_entry_t *q)
1672 int result = 0, sent = 0;
1673 cell_queue_entry_t *tmp = NULL;
1675 tor_assert(chan);
1676 tor_assert(q);
1678 /* Assert that the state makes sense for a cell write */
1679 tor_assert(chan->state == CHANNEL_STATE_OPENING ||
1680 chan->state == CHANNEL_STATE_OPEN ||
1681 chan->state == CHANNEL_STATE_MAINT);
1683 /* Increment the timestamp unless it's padding */
1684 if (!cell_queue_entry_is_padding(q)) {
1685 chan->timestamp_last_added_nonpadding = approx_time();
1688 /* Can we send it right out? If so, try */
1689 if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue) &&
1690 chan->state == CHANNEL_STATE_OPEN) {
1691 /* Pick the right write function for this cell type and save the result */
1692 switch (q->type) {
1693 case CELL_QUEUE_FIXED:
1694 tor_assert(chan->write_cell);
1695 tor_assert(q->u.fixed.cell);
1696 result = chan->write_cell(chan, q->u.fixed.cell);
1697 break;
1698 case CELL_QUEUE_PACKED:
1699 tor_assert(chan->write_packed_cell);
1700 tor_assert(q->u.packed.packed_cell);
1701 result = chan->write_packed_cell(chan, q->u.packed.packed_cell);
1702 break;
1703 case CELL_QUEUE_VAR:
1704 tor_assert(chan->write_var_cell);
1705 tor_assert(q->u.var.var_cell);
1706 result = chan->write_var_cell(chan, q->u.var.var_cell);
1707 break;
1708 default:
1709 tor_assert(1);
1712 /* Check if we got it out */
1713 if (result > 0) {
1714 sent = 1;
1715 /* Timestamp for transmission */
1716 channel_timestamp_xmit(chan);
1717 /* If we're here the queue is empty, so it's drained too */
1718 channel_timestamp_drained(chan);
1719 /* Update the counter */
1720 ++(chan->n_cells_xmitted);
1724 if (!sent) {
1725 /* Not sent, queue it */
1727 * We have to copy the queue entry passed in, since the caller probably
1728 * used the stack.
1730 tmp = cell_queue_entry_dup(q);
1731 TOR_SIMPLEQ_INSERT_TAIL(&chan->outgoing_queue, tmp, next);
1732 /* Try to process the queue? */
1733 if (chan->state == CHANNEL_STATE_OPEN) channel_flush_cells(chan);
1738 * Write a cell to a channel
1740 * Write a fixed-length cell to a channel using the write_cell() method.
1741 * This is equivalent to the pre-channels connection_or_write_cell_to_buf();
1742 * it is called by the transport-independent code to deliver a cell to a
1743 * channel for transmission.
1746 void
1747 channel_write_cell(channel_t *chan, cell_t *cell)
1749 cell_queue_entry_t q;
1751 tor_assert(chan);
1752 tor_assert(cell);
1754 if (chan->state == CHANNEL_STATE_CLOSING) {
1755 log_debug(LD_CHANNEL, "Discarding cell_t %p on closing channel %p with "
1756 "global ID "U64_FORMAT, cell, chan,
1757 U64_PRINTF_ARG(chan->global_identifier));
1758 tor_free(cell);
1759 return;
1762 log_debug(LD_CHANNEL,
1763 "Writing cell_t %p to channel %p with global ID "
1764 U64_FORMAT,
1765 cell, chan, U64_PRINTF_ARG(chan->global_identifier));
1767 q.type = CELL_QUEUE_FIXED;
1768 q.u.fixed.cell = cell;
1769 channel_write_cell_queue_entry(chan, &q);
1773 * Write a packed cell to a channel
1775 * Write a packed cell to a channel using the write_cell() method. This is
1776 * called by the transport-independent code to deliver a packed cell to a
1777 * channel for transmission.
1780 void
1781 channel_write_packed_cell(channel_t *chan, packed_cell_t *packed_cell)
1783 cell_queue_entry_t q;
1785 tor_assert(chan);
1786 tor_assert(packed_cell);
1788 if (chan->state == CHANNEL_STATE_CLOSING) {
1789 log_debug(LD_CHANNEL, "Discarding packed_cell_t %p on closing channel %p "
1790 "with global ID "U64_FORMAT, packed_cell, chan,
1791 U64_PRINTF_ARG(chan->global_identifier));
1792 packed_cell_free(packed_cell);
1793 return;
1796 log_debug(LD_CHANNEL,
1797 "Writing packed_cell_t %p to channel %p with global ID "
1798 U64_FORMAT,
1799 packed_cell, chan,
1800 U64_PRINTF_ARG(chan->global_identifier));
1802 q.type = CELL_QUEUE_PACKED;
1803 q.u.packed.packed_cell = packed_cell;
1804 channel_write_cell_queue_entry(chan, &q);
1808 * Write a variable-length cell to a channel
1810 * Write a variable-length cell to a channel using the write_cell() method.
1811 * This is equivalent to the pre-channels
1812 * connection_or_write_var_cell_to_buf(); it's called by the transport-
1813 * independent code to deliver a var_cell to a channel for transmission.
1816 void
1817 channel_write_var_cell(channel_t *chan, var_cell_t *var_cell)
1819 cell_queue_entry_t q;
1821 tor_assert(chan);
1822 tor_assert(var_cell);
1824 if (chan->state == CHANNEL_STATE_CLOSING) {
1825 log_debug(LD_CHANNEL, "Discarding var_cell_t %p on closing channel %p "
1826 "with global ID "U64_FORMAT, var_cell, chan,
1827 U64_PRINTF_ARG(chan->global_identifier));
1828 var_cell_free(var_cell);
1829 return;
1832 log_debug(LD_CHANNEL,
1833 "Writing var_cell_t %p to channel %p with global ID "
1834 U64_FORMAT,
1835 var_cell, chan,
1836 U64_PRINTF_ARG(chan->global_identifier));
1838 q.type = CELL_QUEUE_VAR;
1839 q.u.var.var_cell = var_cell;
1840 channel_write_cell_queue_entry(chan, &q);
1844 * Change channel state
1846 * This internal and subclass use only function is used to change channel
1847 * state, performing all transition validity checks and whatever actions
1848 * are appropriate to the state transition in question.
1851 void
1852 channel_change_state(channel_t *chan, channel_state_t to_state)
1854 channel_state_t from_state;
1855 unsigned char was_active, is_active;
1856 unsigned char was_in_id_map, is_in_id_map;
1858 tor_assert(chan);
1859 from_state = chan->state;
1861 tor_assert(channel_state_is_valid(from_state));
1862 tor_assert(channel_state_is_valid(to_state));
1863 tor_assert(channel_state_can_transition(chan->state, to_state));
1865 /* Check for no-op transitions */
1866 if (from_state == to_state) {
1867 log_debug(LD_CHANNEL,
1868 "Got no-op transition from \"%s\" to itself on channel %p"
1869 "(global ID " U64_FORMAT ")",
1870 channel_state_to_string(to_state),
1871 chan, U64_PRINTF_ARG(chan->global_identifier));
1872 return;
1875 /* If we're going to a closing or closed state, we must have a reason set */
1876 if (to_state == CHANNEL_STATE_CLOSING ||
1877 to_state == CHANNEL_STATE_CLOSED ||
1878 to_state == CHANNEL_STATE_ERROR) {
1879 tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
1883 * We need to maintain the queues here for some transitions:
1884 * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
1885 * we may have a backlog of cells to transmit, so drain the queues in
1886 * that case, and when going to CHANNEL_STATE_CLOSED the subclass
1887 * should have made sure to finish sending things (or gone to
1888 * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
1891 log_debug(LD_CHANNEL,
1892 "Changing state of channel %p (global ID " U64_FORMAT
1893 ") from \"%s\" to \"%s\"",
1894 chan,
1895 U64_PRINTF_ARG(chan->global_identifier),
1896 channel_state_to_string(chan->state),
1897 channel_state_to_string(to_state));
1899 chan->state = to_state;
1901 /* Need to add to the right lists if the channel is registered */
1902 if (chan->registered) {
1903 was_active = !(from_state == CHANNEL_STATE_CLOSED ||
1904 from_state == CHANNEL_STATE_ERROR);
1905 is_active = !(to_state == CHANNEL_STATE_CLOSED ||
1906 to_state == CHANNEL_STATE_ERROR);
1908 /* Need to take off active list and put on finished list? */
1909 if (was_active && !is_active) {
1910 if (active_channels) smartlist_remove(active_channels, chan);
1911 if (!finished_channels) finished_channels = smartlist_new();
1912 smartlist_add(finished_channels, chan);
1914 /* Need to put on active list? */
1915 else if (!was_active && is_active) {
1916 if (finished_channels) smartlist_remove(finished_channels, chan);
1917 if (!active_channels) active_channels = smartlist_new();
1918 smartlist_add(active_channels, chan);
1921 if (!tor_digest_is_zero(chan->identity_digest)) {
1922 /* Now we need to handle the identity map */
1923 was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
1924 from_state == CHANNEL_STATE_CLOSED ||
1925 from_state == CHANNEL_STATE_ERROR);
1926 is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
1927 to_state == CHANNEL_STATE_CLOSED ||
1928 to_state == CHANNEL_STATE_ERROR);
1930 if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
1931 else if (was_in_id_map && !is_in_id_map)
1932 channel_remove_from_digest_map(chan);
1936 /* Tell circuits if we opened and stuff */
1937 if (to_state == CHANNEL_STATE_OPEN) {
1938 channel_do_open_actions(chan);
1940 /* Check for queued cells to process */
1941 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
1942 channel_process_cells(chan);
1943 if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue))
1944 channel_flush_cells(chan);
1945 } else if (to_state == CHANNEL_STATE_CLOSED ||
1946 to_state == CHANNEL_STATE_ERROR) {
1947 /* Assert that all queues are empty */
1948 tor_assert(TOR_SIMPLEQ_EMPTY(&chan->incoming_queue));
1949 tor_assert(TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue));
1954 * Change channel listener state
1956 * This internal and subclass use only function is used to change channel
1957 * listener state, performing all transition validity checks and whatever
1958 * actions are appropriate to the state transition in question.
1961 void
1962 channel_listener_change_state(channel_listener_t *chan_l,
1963 channel_listener_state_t to_state)
1965 channel_listener_state_t from_state;
1966 unsigned char was_active, is_active;
1968 tor_assert(chan_l);
1969 from_state = chan_l->state;
1971 tor_assert(channel_listener_state_is_valid(from_state));
1972 tor_assert(channel_listener_state_is_valid(to_state));
1973 tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
1975 /* Check for no-op transitions */
1976 if (from_state == to_state) {
1977 log_debug(LD_CHANNEL,
1978 "Got no-op transition from \"%s\" to itself on channel "
1979 "listener %p (global ID " U64_FORMAT ")",
1980 channel_listener_state_to_string(to_state),
1981 chan_l, U64_PRINTF_ARG(chan_l->global_identifier));
1982 return;
1985 /* If we're going to a closing or closed state, we must have a reason set */
1986 if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
1987 to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1988 to_state == CHANNEL_LISTENER_STATE_ERROR) {
1989 tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
1993 * We need to maintain the queues here for some transitions:
1994 * when we enter CHANNEL_STATE_OPEN (especially from CHANNEL_STATE_MAINT)
1995 * we may have a backlog of cells to transmit, so drain the queues in
1996 * that case, and when going to CHANNEL_STATE_CLOSED the subclass
1997 * should have made sure to finish sending things (or gone to
1998 * CHANNEL_STATE_ERROR if not possible), so we assert for that here.
2001 log_debug(LD_CHANNEL,
2002 "Changing state of channel listener %p (global ID " U64_FORMAT
2003 "from \"%s\" to \"%s\"",
2004 chan_l, U64_PRINTF_ARG(chan_l->global_identifier),
2005 channel_listener_state_to_string(chan_l->state),
2006 channel_listener_state_to_string(to_state));
2008 chan_l->state = to_state;
2010 /* Need to add to the right lists if the channel listener is registered */
2011 if (chan_l->registered) {
2012 was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
2013 from_state == CHANNEL_LISTENER_STATE_ERROR);
2014 is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2015 to_state == CHANNEL_LISTENER_STATE_ERROR);
2017 /* Need to take off active list and put on finished list? */
2018 if (was_active && !is_active) {
2019 if (active_listeners) smartlist_remove(active_listeners, chan_l);
2020 if (!finished_listeners) finished_listeners = smartlist_new();
2021 smartlist_add(finished_listeners, chan_l);
2023 /* Need to put on active list? */
2024 else if (!was_active && is_active) {
2025 if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
2026 if (!active_listeners) active_listeners = smartlist_new();
2027 smartlist_add(active_listeners, chan_l);
2031 if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
2032 to_state == CHANNEL_LISTENER_STATE_ERROR) {
2033 /* Assert that the queue is empty */
2034 tor_assert(!(chan_l->incoming_list) ||
2035 smartlist_len(chan_l->incoming_list) == 0);
2040 * Try to flush cells to the lower layer
2042 * this is called by the lower layer to indicate that it wants more cells;
2043 * it will try to write up to num_cells cells from the channel's cell queue or
2044 * from circuits active on that channel, or as many as it has available if
2045 * num_cells == -1.
2048 #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
2050 ssize_t
2051 channel_flush_some_cells(channel_t *chan, ssize_t num_cells)
2053 unsigned int unlimited = 0;
2054 ssize_t flushed = 0;
2055 int num_cells_from_circs, clamped_num_cells;
2057 tor_assert(chan);
2059 if (num_cells < 0) unlimited = 1;
2060 if (!unlimited && num_cells <= flushed) goto done;
2062 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
2063 if (chan->state == CHANNEL_STATE_OPEN) {
2064 /* Try to flush as much as we can that's already queued */
2065 flushed += channel_flush_some_cells_from_outgoing_queue(chan,
2066 (unlimited ? -1 : num_cells - flushed));
2067 if (!unlimited && num_cells <= flushed) goto done;
2069 if (circuitmux_num_cells(chan->cmux) > 0) {
2070 /* Calculate number of cells, including clamp */
2071 if (unlimited) {
2072 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
2073 } else {
2074 if (num_cells - flushed >
2075 MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
2076 clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
2077 } else {
2078 clamped_num_cells = (int)(num_cells - flushed);
2081 /* Try to get more cells from any active circuits */
2082 num_cells_from_circs = channel_flush_from_first_active_circuit(
2083 chan, clamped_num_cells);
2085 /* If it claims we got some, process the queue again */
2086 if (num_cells_from_circs > 0) {
2087 flushed += channel_flush_some_cells_from_outgoing_queue(chan,
2088 (unlimited ? -1 : num_cells - flushed));
2093 done:
2094 return flushed;
2098 * Flush cells from just the channel's outgoing cell queue
2100 * This gets called from channel_flush_some_cells() above to flush cells
2101 * just from the queue without trying for active_circuits.
2104 static ssize_t
2105 channel_flush_some_cells_from_outgoing_queue(channel_t *chan,
2106 ssize_t num_cells)
2108 unsigned int unlimited = 0;
2109 ssize_t flushed = 0;
2110 cell_queue_entry_t *q = NULL;
2112 tor_assert(chan);
2113 tor_assert(chan->write_cell);
2114 tor_assert(chan->write_packed_cell);
2115 tor_assert(chan->write_var_cell);
2117 if (num_cells < 0) unlimited = 1;
2118 if (!unlimited && num_cells <= flushed) return 0;
2120 /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
2121 if (chan->state == CHANNEL_STATE_OPEN) {
2122 while ((unlimited || num_cells > flushed) &&
2123 NULL != (q = TOR_SIMPLEQ_FIRST(&chan->outgoing_queue))) {
2125 if (1) {
2127 * Okay, we have a good queue entry, try to give it to the lower
2128 * layer.
2130 switch (q->type) {
2131 case CELL_QUEUE_FIXED:
2132 if (q->u.fixed.cell) {
2133 if (chan->write_cell(chan,
2134 q->u.fixed.cell)) {
2135 ++flushed;
2136 channel_timestamp_xmit(chan);
2137 ++(chan->n_cells_xmitted);
2138 cell_queue_entry_free(q, 1);
2139 q = NULL;
2141 /* Else couldn't write it; leave it on the queue */
2142 } else {
2143 /* This shouldn't happen */
2144 log_info(LD_CHANNEL,
2145 "Saw broken cell queue entry of type CELL_QUEUE_FIXED "
2146 "with no cell on channel %p "
2147 "(global ID " U64_FORMAT ").",
2148 chan, U64_PRINTF_ARG(chan->global_identifier));
2149 /* Throw it away */
2150 cell_queue_entry_free(q, 0);
2151 q = NULL;
2153 break;
2154 case CELL_QUEUE_PACKED:
2155 if (q->u.packed.packed_cell) {
2156 if (chan->write_packed_cell(chan,
2157 q->u.packed.packed_cell)) {
2158 ++flushed;
2159 channel_timestamp_xmit(chan);
2160 ++(chan->n_cells_xmitted);
2161 cell_queue_entry_free(q, 1);
2162 q = NULL;
2164 /* Else couldn't write it; leave it on the queue */
2165 } else {
2166 /* This shouldn't happen */
2167 log_info(LD_CHANNEL,
2168 "Saw broken cell queue entry of type CELL_QUEUE_PACKED "
2169 "with no cell on channel %p "
2170 "(global ID " U64_FORMAT ").",
2171 chan, U64_PRINTF_ARG(chan->global_identifier));
2172 /* Throw it away */
2173 cell_queue_entry_free(q, 0);
2174 q = NULL;
2176 break;
2177 case CELL_QUEUE_VAR:
2178 if (q->u.var.var_cell) {
2179 if (chan->write_var_cell(chan,
2180 q->u.var.var_cell)) {
2181 ++flushed;
2182 channel_timestamp_xmit(chan);
2183 ++(chan->n_cells_xmitted);
2184 cell_queue_entry_free(q, 1);
2185 q = NULL;
2187 /* Else couldn't write it; leave it on the queue */
2188 } else {
2189 /* This shouldn't happen */
2190 log_info(LD_CHANNEL,
2191 "Saw broken cell queue entry of type CELL_QUEUE_VAR "
2192 "with no cell on channel %p "
2193 "(global ID " U64_FORMAT ").",
2194 chan, U64_PRINTF_ARG(chan->global_identifier));
2195 /* Throw it away */
2196 cell_queue_entry_free(q, 0);
2197 q = NULL;
2199 break;
2200 default:
2201 /* Unknown type, log and free it */
2202 log_info(LD_CHANNEL,
2203 "Saw an unknown cell queue entry type %d on channel %p "
2204 "(global ID " U64_FORMAT "; ignoring it."
2205 " Someone should fix this.",
2206 q->type, chan, U64_PRINTF_ARG(chan->global_identifier));
2207 cell_queue_entry_free(q, 0);
2208 q = NULL;
2211 /* if q got NULLed out, we used it and should remove the queue entry */
2212 if (!q) TOR_SIMPLEQ_REMOVE_HEAD(&chan->outgoing_queue, next);
2213 /* No cell removed from list, so we can't go on any further */
2214 else break;
2219 /* Did we drain the queue? */
2220 if (TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
2221 channel_timestamp_drained(chan);
2224 return flushed;
2228 * Flush as many cells as we possibly can from the queue
2230 * This tries to flush as many cells from the queue as the lower layer
2231 * will take. It just calls channel_flush_some_cells_from_outgoing_queue()
2232 * in unlimited mode.
2235 void
2236 channel_flush_cells(channel_t *chan)
2238 channel_flush_some_cells_from_outgoing_queue(chan, -1);
2242 * Check if any cells are available
2244 * This gets used from the lower layer to check if any more cells are
2245 * available.
2249 channel_more_to_flush(channel_t *chan)
2251 tor_assert(chan);
2253 /* Check if we have any queued */
2254 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2255 return 1;
2257 /* Check if any circuits would like to queue some */
2258 if (circuitmux_num_cells(chan->cmux) > 0) return 1;
2260 /* Else no */
2261 return 0;
2265 * Notify the channel we're done flushing the output in the lower layer
2267 * Connection.c will call this when we've flushed the output; there's some
2268 * dirreq-related maintenance to do.
2271 void
2272 channel_notify_flushed(channel_t *chan)
2274 tor_assert(chan);
2276 if (chan->dirreq_id != 0)
2277 geoip_change_dirreq_state(chan->dirreq_id,
2278 DIRREQ_TUNNELED,
2279 DIRREQ_CHANNEL_BUFFER_FLUSHED);
2283 * Process the queue of incoming channels on a listener
2285 * Use a listener's registered callback to process as many entries in the
2286 * queue of incoming channels as possible.
2289 void
2290 channel_listener_process_incoming(channel_listener_t *listener)
2292 tor_assert(listener);
2295 * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
2296 * while closing a listener.
2298 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
2299 listener->state == CHANNEL_LISTENER_STATE_CLOSING);
2300 tor_assert(listener->listener);
2302 log_debug(LD_CHANNEL,
2303 "Processing queue of incoming connections for channel "
2304 "listener %p (global ID " U64_FORMAT ")",
2305 listener, U64_PRINTF_ARG(listener->global_identifier));
2307 if (!(listener->incoming_list)) return;
2309 SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
2310 channel_t *, chan) {
2311 tor_assert(chan);
2313 log_debug(LD_CHANNEL,
2314 "Handling incoming channel %p (" U64_FORMAT ") "
2315 "for listener %p (" U64_FORMAT ")",
2316 chan,
2317 U64_PRINTF_ARG(chan->global_identifier),
2318 listener,
2319 U64_PRINTF_ARG(listener->global_identifier));
2320 /* Make sure this is set correctly */
2321 channel_mark_incoming(chan);
2322 listener->listener(listener, chan);
2323 } SMARTLIST_FOREACH_END(chan);
2325 smartlist_free(listener->incoming_list);
2326 listener->incoming_list = NULL;
2330 * Take actions required when a channel becomes open
2332 * Handle actions we should do when we know a channel is open; a lot of
2333 * this comes from the old connection_or_set_state_open() of connection_or.c.
2335 * Because of this mechanism, future channel_t subclasses should take care
2336 * not to change a channel to from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
2337 * until there is positive confirmation that the network is operational.
2338 * In particular, anything UDP-based should not make this transition until a
2339 * packet is received from the other side.
2342 void
2343 channel_do_open_actions(channel_t *chan)
2345 tor_addr_t remote_addr;
2346 int started_here, not_using = 0;
2347 time_t now = time(NULL);
2349 tor_assert(chan);
2351 started_here = channel_is_outgoing(chan);
2353 if (started_here) {
2354 circuit_build_times_network_is_live(&circ_times);
2355 rep_hist_note_connect_succeeded(chan->identity_digest, now);
2356 if (entry_guard_register_connect_status(
2357 chan->identity_digest, 1, 0, now) < 0) {
2358 /* Close any circuits pending on this channel. We leave it in state
2359 * 'open' though, because it didn't actually *fail* -- we just
2360 * chose not to use it. */
2361 log_debug(LD_OR,
2362 "New entry guard was reachable, but closing this "
2363 "connection so we can retry the earlier entry guards.");
2364 circuit_n_chan_done(chan, 0);
2365 not_using = 1;
2367 router_set_status(chan->identity_digest, 1);
2368 } else {
2369 /* only report it to the geoip module if it's not a known router */
2370 if (!router_get_by_id_digest(chan->identity_digest)) {
2371 if (channel_get_addr_if_possible(chan, &remote_addr)) {
2372 geoip_note_client_seen(GEOIP_CLIENT_CONNECT, &remote_addr,
2373 now);
2375 /* Otherwise the underlying transport can't tell us this, so skip it */
2379 if (!not_using) circuit_n_chan_done(chan, 1);
2383 * Queue an incoming channel on a listener
2385 * Internal and subclass use only function to queue an incoming channel from
2386 * a listener. A subclass of channel_listener_t should call this when a new
2387 * incoming channel is created.
2390 void
2391 channel_listener_queue_incoming(channel_listener_t *listener,
2392 channel_t *incoming)
2394 int need_to_queue = 0;
2396 tor_assert(listener);
2397 tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
2398 tor_assert(incoming);
2400 log_debug(LD_CHANNEL,
2401 "Queueing incoming channel %p (global ID " U64_FORMAT ") on "
2402 "channel listener %p (global ID " U64_FORMAT ")",
2403 incoming, U64_PRINTF_ARG(incoming->global_identifier),
2404 listener, U64_PRINTF_ARG(listener->global_identifier));
2406 /* Do we need to queue it, or can we just call the listener right away? */
2407 if (!(listener->listener)) need_to_queue = 1;
2408 if (listener->incoming_list &&
2409 (smartlist_len(listener->incoming_list) > 0))
2410 need_to_queue = 1;
2412 /* If we need to queue and have no queue, create one */
2413 if (need_to_queue && !(listener->incoming_list)) {
2414 listener->incoming_list = smartlist_new();
2417 /* Bump the counter and timestamp it */
2418 channel_listener_timestamp_active(listener);
2419 channel_listener_timestamp_accepted(listener);
2420 ++(listener->n_accepted);
2422 /* If we don't need to queue, process it right away */
2423 if (!need_to_queue) {
2424 tor_assert(listener->listener);
2425 listener->listener(listener, incoming);
2428 * Otherwise, we need to queue; queue and then process the queue if
2429 * we can.
2431 else {
2432 tor_assert(listener->incoming_list);
2433 smartlist_add(listener->incoming_list, incoming);
2434 if (listener->listener) channel_listener_process_incoming(listener);
2439 * Process queued incoming cells
2441 * Process as many queued cells as we can from the incoming
2442 * cell queue.
2445 void
2446 channel_process_cells(channel_t *chan)
2448 cell_queue_entry_t *q;
2449 tor_assert(chan);
2450 tor_assert(chan->state == CHANNEL_STATE_CLOSING ||
2451 chan->state == CHANNEL_STATE_MAINT ||
2452 chan->state == CHANNEL_STATE_OPEN);
2454 log_debug(LD_CHANNEL,
2455 "Processing as many incoming cells as we can for channel %p",
2456 chan);
2458 /* Nothing we can do if we have no registered cell handlers */
2459 if (!(chan->cell_handler ||
2460 chan->var_cell_handler)) return;
2461 /* Nothing we can do if we have no cells */
2462 if (TOR_SIMPLEQ_EMPTY(&chan->incoming_queue)) return;
2465 * Process cells until we're done or find one we have no current handler
2466 * for.
2468 while (NULL != (q = TOR_SIMPLEQ_FIRST(&chan->incoming_queue))) {
2469 tor_assert(q);
2470 tor_assert(q->type == CELL_QUEUE_FIXED ||
2471 q->type == CELL_QUEUE_VAR);
2473 if (q->type == CELL_QUEUE_FIXED &&
2474 chan->cell_handler) {
2475 /* Handle a fixed-length cell */
2476 TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
2477 tor_assert(q->u.fixed.cell);
2478 log_debug(LD_CHANNEL,
2479 "Processing incoming cell_t %p for channel %p (global ID "
2480 U64_FORMAT ")",
2481 q->u.fixed.cell, chan,
2482 U64_PRINTF_ARG(chan->global_identifier));
2483 chan->cell_handler(chan, q->u.fixed.cell);
2484 tor_free(q);
2485 } else if (q->type == CELL_QUEUE_VAR &&
2486 chan->var_cell_handler) {
2487 /* Handle a variable-length cell */
2488 TOR_SIMPLEQ_REMOVE_HEAD(&chan->incoming_queue, next);
2489 tor_assert(q->u.var.var_cell);
2490 log_debug(LD_CHANNEL,
2491 "Processing incoming var_cell_t %p for channel %p (global ID "
2492 U64_FORMAT ")",
2493 q->u.var.var_cell, chan,
2494 U64_PRINTF_ARG(chan->global_identifier));
2495 chan->var_cell_handler(chan, q->u.var.var_cell);
2496 tor_free(q);
2497 } else {
2498 /* Can't handle this one */
2499 break;
2505 * Queue incoming cell
2507 * This should be called by a channel_t subclass to queue an incoming fixed-
2508 * length cell for processing, and process it if possible.
2511 void
2512 channel_queue_cell(channel_t *chan, cell_t *cell)
2514 int need_to_queue = 0;
2515 cell_queue_entry_t *q;
2517 tor_assert(chan);
2518 tor_assert(cell);
2519 tor_assert(chan->state == CHANNEL_STATE_OPEN);
2521 /* Do we need to queue it, or can we just call the handler right away? */
2522 if (!(chan->cell_handler)) need_to_queue = 1;
2523 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2524 need_to_queue = 1;
2526 /* Timestamp for receiving */
2527 channel_timestamp_recv(chan);
2529 /* Update the counter */
2530 ++(chan->n_cells_recved);
2532 /* If we don't need to queue we can just call cell_handler */
2533 if (!need_to_queue) {
2534 tor_assert(chan->cell_handler);
2535 log_debug(LD_CHANNEL,
2536 "Directly handling incoming cell_t %p for channel %p "
2537 "(global ID " U64_FORMAT ")",
2538 cell, chan,
2539 U64_PRINTF_ARG(chan->global_identifier));
2540 chan->cell_handler(chan, cell);
2541 } else {
2542 /* Otherwise queue it and then process the queue if possible. */
2543 q = cell_queue_entry_new_fixed(cell);
2544 log_debug(LD_CHANNEL,
2545 "Queueing incoming cell_t %p for channel %p "
2546 "(global ID " U64_FORMAT ")",
2547 cell, chan,
2548 U64_PRINTF_ARG(chan->global_identifier));
2549 TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
2550 if (chan->cell_handler ||
2551 chan->var_cell_handler) {
2552 channel_process_cells(chan);
2558 * Queue incoming variable-length cell
2560 * This should be called by a channel_t subclass to queue an incoming
2561 * variable-length cell for processing, and process it if possible.
2564 void
2565 channel_queue_var_cell(channel_t *chan, var_cell_t *var_cell)
2567 int need_to_queue = 0;
2568 cell_queue_entry_t *q;
2570 tor_assert(chan);
2571 tor_assert(var_cell);
2572 tor_assert(chan->state == CHANNEL_STATE_OPEN);
2574 /* Do we need to queue it, or can we just call the handler right away? */
2575 if (!(chan->var_cell_handler)) need_to_queue = 1;
2576 if (! TOR_SIMPLEQ_EMPTY(&chan->incoming_queue))
2577 need_to_queue = 1;
2579 /* Timestamp for receiving */
2580 channel_timestamp_recv(chan);
2582 /* Update the counter */
2583 ++(chan->n_cells_recved);
2585 /* If we don't need to queue we can just call cell_handler */
2586 if (!need_to_queue) {
2587 tor_assert(chan->var_cell_handler);
2588 log_debug(LD_CHANNEL,
2589 "Directly handling incoming var_cell_t %p for channel %p "
2590 "(global ID " U64_FORMAT ")",
2591 var_cell, chan,
2592 U64_PRINTF_ARG(chan->global_identifier));
2593 chan->var_cell_handler(chan, var_cell);
2594 } else {
2595 /* Otherwise queue it and then process the queue if possible. */
2596 q = cell_queue_entry_new_var(var_cell);
2597 log_debug(LD_CHANNEL,
2598 "Queueing incoming var_cell_t %p for channel %p "
2599 "(global ID " U64_FORMAT ")",
2600 var_cell, chan,
2601 U64_PRINTF_ARG(chan->global_identifier));
2602 TOR_SIMPLEQ_INSERT_TAIL(&chan->incoming_queue, q, next);
2603 if (chan->cell_handler ||
2604 chan->var_cell_handler) {
2605 channel_process_cells(chan);
2611 * Send destroy cell on a channel
2613 * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
2614 * onto channel <b>chan</b>. Don't perform range-checking on reason:
2615 * we may want to propagate reasons from other cells.
2619 channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
2621 cell_t cell;
2623 tor_assert(chan);
2625 /* Check to make sure we can send on this channel first */
2626 if (!(chan->state == CHANNEL_STATE_CLOSING ||
2627 chan->state == CHANNEL_STATE_CLOSED ||
2628 chan->state == CHANNEL_STATE_ERROR)) {
2629 memset(&cell, 0, sizeof(cell_t));
2630 cell.circ_id = circ_id;
2631 cell.command = CELL_DESTROY;
2632 cell.payload[0] = (uint8_t) reason;
2633 log_debug(LD_OR,
2634 "Sending destroy (circID %u) on channel %p "
2635 "(global ID " U64_FORMAT ")",
2636 (unsigned)circ_id, chan,
2637 U64_PRINTF_ARG(chan->global_identifier));
2639 channel_write_cell(chan, &cell);
2640 } else {
2641 log_warn(LD_BUG,
2642 "Someone called channel_send_destroy() for circID %u "
2643 "on a channel " U64_FORMAT " at %p in state %s (%d)",
2644 (unsigned)circ_id, U64_PRINTF_ARG(chan->global_identifier),
2645 chan, channel_state_to_string(chan->state),
2646 chan->state);
2649 return 0;
2653 * Dump channel statistics to the log
2655 * This is called from dumpstats() in main.c and spams the log with
2656 * statistics on channels.
2659 void
2660 channel_dumpstats(int severity)
2662 if (all_channels && smartlist_len(all_channels) > 0) {
2663 tor_log(severity, LD_GENERAL,
2664 "Dumping statistics about %d channels:",
2665 smartlist_len(all_channels));
2666 tor_log(severity, LD_GENERAL,
2667 "%d are active, and %d are done and waiting for cleanup",
2668 (active_channels != NULL) ?
2669 smartlist_len(active_channels) : 0,
2670 (finished_channels != NULL) ?
2671 smartlist_len(finished_channels) : 0);
2673 SMARTLIST_FOREACH(all_channels, channel_t *, chan,
2674 channel_dump_statistics(chan, severity));
2676 tor_log(severity, LD_GENERAL,
2677 "Done spamming about channels now");
2678 } else {
2679 tor_log(severity, LD_GENERAL,
2680 "No channels to dump");
2685 * Dump channel listener statistics to the log
2687 * This is called from dumpstats() in main.c and spams the log with
2688 * statistics on channel listeners.
2691 void
2692 channel_listener_dumpstats(int severity)
2694 if (all_listeners && smartlist_len(all_listeners) > 0) {
2695 tor_log(severity, LD_GENERAL,
2696 "Dumping statistics about %d channel listeners:",
2697 smartlist_len(all_listeners));
2698 tor_log(severity, LD_GENERAL,
2699 "%d are active and %d are done and waiting for cleanup",
2700 (active_listeners != NULL) ?
2701 smartlist_len(active_listeners) : 0,
2702 (finished_listeners != NULL) ?
2703 smartlist_len(finished_listeners) : 0);
2705 SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
2706 channel_listener_dump_statistics(chan_l, severity));
2708 tor_log(severity, LD_GENERAL,
2709 "Done spamming about channel listeners now");
2710 } else {
2711 tor_log(severity, LD_GENERAL,
2712 "No channel listeners to dump");
2717 * Set the cmux policy on all active channels
2720 void
2721 channel_set_cmux_policy_everywhere(circuitmux_policy_t *pol)
2723 if (!active_channels) return;
2725 SMARTLIST_FOREACH_BEGIN(active_channels, channel_t *, curr) {
2726 if (curr->cmux) {
2727 circuitmux_set_policy(curr->cmux, pol);
2729 } SMARTLIST_FOREACH_END(curr);
2733 * Clean up channels
2735 * This gets called periodically from run_scheduled_events() in main.c;
2736 * it cleans up after closed channels.
2739 void
2740 channel_run_cleanup(void)
2742 channel_t *tmp = NULL;
2744 /* Check if we need to do anything */
2745 if (!finished_channels || smartlist_len(finished_channels) == 0) return;
2747 /* Iterate through finished_channels and get rid of them */
2748 SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
2749 tmp = curr;
2750 /* Remove it from the list */
2751 SMARTLIST_DEL_CURRENT(finished_channels, curr);
2752 /* Also unregister it */
2753 channel_unregister(tmp);
2754 /* ... and free it */
2755 channel_free(tmp);
2756 } SMARTLIST_FOREACH_END(curr);
2760 * Clean up channel listeners
2762 * This gets called periodically from run_scheduled_events() in main.c;
2763 * it cleans up after closed channel listeners.
2766 void
2767 channel_listener_run_cleanup(void)
2769 channel_listener_t *tmp = NULL;
2771 /* Check if we need to do anything */
2772 if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
2774 /* Iterate through finished_channels and get rid of them */
2775 SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
2776 tmp = curr;
2777 /* Remove it from the list */
2778 SMARTLIST_DEL_CURRENT(finished_listeners, curr);
2779 /* Also unregister it */
2780 channel_listener_unregister(tmp);
2781 /* ... and free it */
2782 channel_listener_free(tmp);
2783 } SMARTLIST_FOREACH_END(curr);
2787 * Free a list of channels for channel_free_all()
2790 static void
2791 channel_free_list(smartlist_t *channels, int mark_for_close)
2793 if (!channels) return;
2795 SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
2796 /* Deregister and free it */
2797 tor_assert(curr);
2798 log_debug(LD_CHANNEL,
2799 "Cleaning up channel %p (global ID " U64_FORMAT ") "
2800 "in state %s (%d)",
2801 curr, U64_PRINTF_ARG(curr->global_identifier),
2802 channel_state_to_string(curr->state), curr->state);
2803 /* Detach circuits early so they can find the channel */
2804 if (curr->cmux) {
2805 circuitmux_detach_all_circuits(curr->cmux);
2807 channel_unregister(curr);
2808 if (mark_for_close) {
2809 if (!(curr->state == CHANNEL_STATE_CLOSING ||
2810 curr->state == CHANNEL_STATE_CLOSED ||
2811 curr->state == CHANNEL_STATE_ERROR)) {
2812 channel_mark_for_close(curr);
2814 channel_force_free(curr);
2815 } else channel_free(curr);
2816 } SMARTLIST_FOREACH_END(curr);
2820 * Free a list of channel listeners for channel_free_all()
2823 static void
2824 channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
2826 if (!listeners) return;
2828 SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
2829 /* Deregister and free it */
2830 tor_assert(curr);
2831 log_debug(LD_CHANNEL,
2832 "Cleaning up channel listener %p (global ID " U64_FORMAT ") "
2833 "in state %s (%d)",
2834 curr, U64_PRINTF_ARG(curr->global_identifier),
2835 channel_listener_state_to_string(curr->state), curr->state);
2836 channel_listener_unregister(curr);
2837 if (mark_for_close) {
2838 if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
2839 curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
2840 curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
2841 channel_listener_mark_for_close(curr);
2843 channel_listener_force_free(curr);
2844 } else channel_listener_free(curr);
2845 } SMARTLIST_FOREACH_END(curr);
2849 * Close all channels and free everything
2851 * This gets called from tor_free_all() in main.c to clean up on exit.
2852 * It will close all registered channels and free associated storage,
2853 * then free the all_channels, active_channels, listening_channels and
2854 * finished_channels lists and also channel_identity_map.
2857 void
2858 channel_free_all(void)
2860 log_debug(LD_CHANNEL,
2861 "Shutting down channels...");
2863 /* First, let's go for finished channels */
2864 if (finished_channels) {
2865 channel_free_list(finished_channels, 0);
2866 smartlist_free(finished_channels);
2867 finished_channels = NULL;
2870 /* Now the finished listeners */
2871 if (finished_listeners) {
2872 channel_listener_free_list(finished_listeners, 0);
2873 smartlist_free(finished_listeners);
2874 finished_listeners = NULL;
2877 /* Now all active channels */
2878 if (active_channels) {
2879 channel_free_list(active_channels, 1);
2880 smartlist_free(active_channels);
2881 active_channels = NULL;
2884 /* Now all active listeners */
2885 if (active_listeners) {
2886 channel_listener_free_list(active_listeners, 1);
2887 smartlist_free(active_listeners);
2888 active_listeners = NULL;
2891 /* Now all channels, in case any are left over */
2892 if (all_channels) {
2893 channel_free_list(all_channels, 1);
2894 smartlist_free(all_channels);
2895 all_channels = NULL;
2898 /* Now all listeners, in case any are left over */
2899 if (all_listeners) {
2900 channel_listener_free_list(all_listeners, 1);
2901 smartlist_free(all_listeners);
2902 all_listeners = NULL;
2905 /* Now free channel_identity_map */
2906 log_debug(LD_CHANNEL,
2907 "Freeing channel_identity_map");
2908 /* Geez, anything still left over just won't die ... let it leak then */
2909 HT_CLEAR(channel_idmap, &channel_identity_map);
2911 log_debug(LD_CHANNEL,
2912 "Done cleaning up after channels");
2916 * Connect to a given addr/port/digest
2918 * This sets up a new outgoing channel; in the future if multiple
2919 * channel_t subclasses are available, this is where the selection policy
2920 * should go. It may also be desirable to fold port into tor_addr_t
2921 * or make a new type including a tor_addr_t and port, so we have a
2922 * single abstract object encapsulating all the protocol details of
2923 * how to contact an OR.
2926 channel_t *
2927 channel_connect(const tor_addr_t *addr, uint16_t port,
2928 const char *id_digest)
2930 return channel_tls_connect(addr, port, id_digest);
2934 * Decide which of two channels to prefer for extending a circuit
2936 * This function is called while extending a circuit and returns true iff
2937 * a is 'better' than b. The most important criterion here is that a
2938 * canonical channel is always better than a non-canonical one, but the
2939 * number of circuits and the age are used as tie-breakers.
2941 * This is based on the former connection_or_is_better() of connection_or.c
2945 channel_is_better(time_t now, channel_t *a, channel_t *b,
2946 int forgive_new_connections)
2948 int a_grace, b_grace;
2949 int a_is_canonical, b_is_canonical;
2950 int a_has_circs, b_has_circs;
2953 * Do not definitively deprecate a new channel with no circuits on it
2954 * until this much time has passed.
2956 #define NEW_CHAN_GRACE_PERIOD (15*60)
2958 tor_assert(a);
2959 tor_assert(b);
2961 /* Check if one is canonical and the other isn't first */
2962 a_is_canonical = channel_is_canonical(a);
2963 b_is_canonical = channel_is_canonical(b);
2965 if (a_is_canonical && !b_is_canonical) return 1;
2966 if (!a_is_canonical && b_is_canonical) return 0;
2969 * Okay, if we're here they tied on canonicity. Next we check if
2970 * they have any circuits, and if one does and the other doesn't,
2971 * we prefer the one that does, unless we are forgiving and the
2972 * one that has no circuits is in its grace period.
2975 a_has_circs = (channel_num_circuits(a) > 0);
2976 b_has_circs = (channel_num_circuits(b) > 0);
2977 a_grace = (forgive_new_connections &&
2978 (now < channel_when_created(a) + NEW_CHAN_GRACE_PERIOD));
2979 b_grace = (forgive_new_connections &&
2980 (now < channel_when_created(b) + NEW_CHAN_GRACE_PERIOD));
2982 if (a_has_circs && !b_has_circs && !b_grace) return 1;
2983 if (!a_has_circs && b_has_circs && !a_grace) return 0;
2985 /* They tied on circuits too; just prefer whichever is newer */
2987 if (channel_when_created(a) > channel_when_created(b)) return 1;
2988 else return 0;
2992 * Get a channel to extend a circuit
2994 * Pick a suitable channel to extend a circuit to given the desired digest
2995 * the address we believe is correct for that digest; this tries to see
2996 * if we already have one for the requested endpoint, but if there is no good
2997 * channel, set *msg_out to a message describing the channel's state
2998 * and our next action, and set *launch_out to a boolean indicated whether
2999 * the caller should try to launch a new channel with channel_connect().
3002 channel_t *
3003 channel_get_for_extend(const char *digest,
3004 const tor_addr_t *target_addr,
3005 const char **msg_out,
3006 int *launch_out)
3008 channel_t *chan, *best = NULL;
3009 int n_inprogress_goodaddr = 0, n_old = 0;
3010 int n_noncanonical = 0, n_possible = 0;
3011 time_t now = approx_time();
3013 tor_assert(msg_out);
3014 tor_assert(launch_out);
3016 chan = channel_find_by_remote_digest(digest);
3018 /* Walk the list, unrefing the old one and refing the new at each
3019 * iteration.
3021 for (; chan; chan = channel_next_with_digest(chan)) {
3022 tor_assert(tor_memeq(chan->identity_digest,
3023 digest, DIGEST_LEN));
3025 if (chan->state == CHANNEL_STATE_CLOSING ||
3026 chan->state == CHANNEL_STATE_CLOSED ||
3027 chan->state == CHANNEL_STATE_ERROR)
3028 continue;
3030 /* Never return a channel on which the other end appears to be
3031 * a client. */
3032 if (channel_is_client(chan)) {
3033 continue;
3036 /* Never return a non-open connection. */
3037 if (chan->state != CHANNEL_STATE_OPEN) {
3038 /* If the address matches, don't launch a new connection for this
3039 * circuit. */
3040 if (!channel_matches_target_addr_for_extend(chan, target_addr))
3041 ++n_inprogress_goodaddr;
3042 continue;
3045 /* Never return a connection that shouldn't be used for circs. */
3046 if (channel_is_bad_for_new_circs(chan)) {
3047 ++n_old;
3048 continue;
3051 /* Never return a non-canonical connection using a recent link protocol
3052 * if the address is not what we wanted.
3054 * The channel_is_canonical_is_reliable() function asks the lower layer
3055 * if we should trust channel_is_canonical(). The below is from the
3056 * comments of the old circuit_or_get_for_extend() and applies when
3057 * the lower-layer transport is channel_tls_t.
3059 * (For old link protocols, we can't rely on is_canonical getting
3060 * set properly if we're talking to the right address, since we might
3061 * have an out-of-date descriptor, and we will get no NETINFO cell to
3062 * tell us about the right address.)
3064 if (!channel_is_canonical(chan) &&
3065 channel_is_canonical_is_reliable(chan) &&
3066 !channel_matches_target_addr_for_extend(chan, target_addr)) {
3067 ++n_noncanonical;
3068 continue;
3071 ++n_possible;
3073 if (!best) {
3074 best = chan; /* If we have no 'best' so far, this one is good enough. */
3075 continue;
3078 if (channel_is_better(now, chan, best, 0))
3079 best = chan;
3082 if (best) {
3083 *msg_out = "Connection is fine; using it.";
3084 *launch_out = 0;
3085 return best;
3086 } else if (n_inprogress_goodaddr) {
3087 *msg_out = "Connection in progress; waiting.";
3088 *launch_out = 0;
3089 return NULL;
3090 } else if (n_old || n_noncanonical) {
3091 *msg_out = "Connections all too old, or too non-canonical. "
3092 " Launching a new one.";
3093 *launch_out = 1;
3094 return NULL;
3095 } else {
3096 *msg_out = "Not connected. Connecting.";
3097 *launch_out = 1;
3098 return NULL;
3103 * Describe the transport subclass for a channel
3105 * Invoke a method to get a string description of the lower-layer
3106 * transport for this channel.
3109 const char *
3110 channel_describe_transport(channel_t *chan)
3112 tor_assert(chan);
3113 tor_assert(chan->describe_transport);
3115 return chan->describe_transport(chan);
3119 * Describe the transport subclass for a channel listener
3121 * Invoke a method to get a string description of the lower-layer
3122 * transport for this channel listener.
3125 const char *
3126 channel_listener_describe_transport(channel_listener_t *chan_l)
3128 tor_assert(chan_l);
3129 tor_assert(chan_l->describe_transport);
3131 return chan_l->describe_transport(chan_l);
3135 * Return the number of entries in <b>queue</b>
3137 static int
3138 chan_cell_queue_len(const chan_cell_queue_t *queue)
3140 int r = 0;
3141 cell_queue_entry_t *cell;
3142 TOR_SIMPLEQ_FOREACH(cell, queue, next)
3143 ++r;
3144 return r;
3148 * Dump channel statistics
3150 * Dump statistics for one channel to the log
3153 void
3154 channel_dump_statistics(channel_t *chan, int severity)
3156 double avg, interval, age;
3157 time_t now = time(NULL);
3158 tor_addr_t remote_addr;
3159 int have_remote_addr;
3160 char *remote_addr_str;
3162 tor_assert(chan);
3164 age = (double)(now - chan->timestamp_created);
3166 tor_log(severity, LD_GENERAL,
3167 "Channel " U64_FORMAT " (at %p) with transport %s is in state "
3168 "%s (%d)",
3169 U64_PRINTF_ARG(chan->global_identifier), chan,
3170 channel_describe_transport(chan),
3171 channel_state_to_string(chan->state), chan->state);
3172 tor_log(severity, LD_GENERAL,
3173 " * Channel " U64_FORMAT " was created at " U64_FORMAT
3174 " (" U64_FORMAT " seconds ago) "
3175 "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3176 U64_PRINTF_ARG(chan->global_identifier),
3177 U64_PRINTF_ARG(chan->timestamp_created),
3178 U64_PRINTF_ARG(now - chan->timestamp_created),
3179 U64_PRINTF_ARG(chan->timestamp_active),
3180 U64_PRINTF_ARG(now - chan->timestamp_active));
3182 /* Handle digest and nickname */
3183 if (!tor_digest_is_zero(chan->identity_digest)) {
3184 if (chan->nickname) {
3185 tor_log(severity, LD_GENERAL,
3186 " * Channel " U64_FORMAT " says it is connected "
3187 "to an OR with digest %s and nickname %s",
3188 U64_PRINTF_ARG(chan->global_identifier),
3189 hex_str(chan->identity_digest, DIGEST_LEN),
3190 chan->nickname);
3191 } else {
3192 tor_log(severity, LD_GENERAL,
3193 " * Channel " U64_FORMAT " says it is connected "
3194 "to an OR with digest %s and no known nickname",
3195 U64_PRINTF_ARG(chan->global_identifier),
3196 hex_str(chan->identity_digest, DIGEST_LEN));
3198 } else {
3199 if (chan->nickname) {
3200 tor_log(severity, LD_GENERAL,
3201 " * Channel " U64_FORMAT " does not know the digest"
3202 " of the OR it is connected to, but reports its nickname is %s",
3203 U64_PRINTF_ARG(chan->global_identifier),
3204 chan->nickname);
3205 } else {
3206 tor_log(severity, LD_GENERAL,
3207 " * Channel " U64_FORMAT " does not know the digest"
3208 " or the nickname of the OR it is connected to",
3209 U64_PRINTF_ARG(chan->global_identifier));
3213 /* Handle remote address and descriptions */
3214 have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
3215 if (have_remote_addr) {
3216 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
3217 remote_addr_str = tor_dup_addr(&remote_addr);
3218 tor_log(severity, LD_GENERAL,
3219 " * Channel " U64_FORMAT " says its remote address"
3220 " is %s, and gives a canonical description of \"%s\" and an "
3221 "actual description of \"%s\"",
3222 U64_PRINTF_ARG(chan->global_identifier),
3223 remote_addr_str,
3224 channel_get_canonical_remote_descr(chan),
3225 actual);
3226 tor_free(remote_addr_str);
3227 tor_free(actual);
3228 } else {
3229 char *actual = tor_strdup(channel_get_actual_remote_descr(chan));
3230 tor_log(severity, LD_GENERAL,
3231 " * Channel " U64_FORMAT " does not know its remote "
3232 "address, but gives a canonical description of \"%s\" and an "
3233 "actual description of \"%s\"",
3234 U64_PRINTF_ARG(chan->global_identifier),
3235 channel_get_canonical_remote_descr(chan),
3236 actual);
3237 tor_free(actual);
3240 /* Handle marks */
3241 tor_log(severity, LD_GENERAL,
3242 " * Channel " U64_FORMAT " has these marks: %s %s %s "
3243 "%s %s %s",
3244 U64_PRINTF_ARG(chan->global_identifier),
3245 channel_is_bad_for_new_circs(chan) ?
3246 "bad_for_new_circs" : "!bad_for_new_circs",
3247 channel_is_canonical(chan) ?
3248 "canonical" : "!canonical",
3249 channel_is_canonical_is_reliable(chan) ?
3250 "is_canonical_is_reliable" :
3251 "!is_canonical_is_reliable",
3252 channel_is_client(chan) ?
3253 "client" : "!client",
3254 channel_is_local(chan) ?
3255 "local" : "!local",
3256 channel_is_incoming(chan) ?
3257 "incoming" : "outgoing");
3259 /* Describe queues */
3260 tor_log(severity, LD_GENERAL,
3261 " * Channel " U64_FORMAT " has %d queued incoming cells"
3262 " and %d queued outgoing cells",
3263 U64_PRINTF_ARG(chan->global_identifier),
3264 chan_cell_queue_len(&chan->incoming_queue),
3265 chan_cell_queue_len(&chan->outgoing_queue));
3267 /* Describe circuits */
3268 tor_log(severity, LD_GENERAL,
3269 " * Channel " U64_FORMAT " has %d active circuits out of"
3270 " %d in total",
3271 U64_PRINTF_ARG(chan->global_identifier),
3272 (chan->cmux != NULL) ?
3273 circuitmux_num_active_circuits(chan->cmux) : 0,
3274 (chan->cmux != NULL) ?
3275 circuitmux_num_circuits(chan->cmux) : 0);
3277 /* Describe timestamps */
3278 tor_log(severity, LD_GENERAL,
3279 " * Channel " U64_FORMAT " was last used by a "
3280 "client at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3281 U64_PRINTF_ARG(chan->global_identifier),
3282 U64_PRINTF_ARG(chan->timestamp_client),
3283 U64_PRINTF_ARG(now - chan->timestamp_client));
3284 tor_log(severity, LD_GENERAL,
3285 " * Channel " U64_FORMAT " was last drained at "
3286 U64_FORMAT " (" U64_FORMAT " seconds ago)",
3287 U64_PRINTF_ARG(chan->global_identifier),
3288 U64_PRINTF_ARG(chan->timestamp_drained),
3289 U64_PRINTF_ARG(now - chan->timestamp_drained));
3290 tor_log(severity, LD_GENERAL,
3291 " * Channel " U64_FORMAT " last received a cell "
3292 "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3293 U64_PRINTF_ARG(chan->global_identifier),
3294 U64_PRINTF_ARG(chan->timestamp_recv),
3295 U64_PRINTF_ARG(now - chan->timestamp_recv));
3296 tor_log(severity, LD_GENERAL,
3297 " * Channel " U64_FORMAT " last trasmitted a cell "
3298 "at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3299 U64_PRINTF_ARG(chan->global_identifier),
3300 U64_PRINTF_ARG(chan->timestamp_xmit),
3301 U64_PRINTF_ARG(now - chan->timestamp_xmit));
3303 /* Describe counters and rates */
3304 tor_log(severity, LD_GENERAL,
3305 " * Channel " U64_FORMAT " has received "
3306 U64_FORMAT " cells and transmitted " U64_FORMAT,
3307 U64_PRINTF_ARG(chan->global_identifier),
3308 U64_PRINTF_ARG(chan->n_cells_recved),
3309 U64_PRINTF_ARG(chan->n_cells_xmitted));
3310 if (now > chan->timestamp_created &&
3311 chan->timestamp_created > 0) {
3312 if (chan->n_cells_recved > 0) {
3313 avg = (double)(chan->n_cells_recved) / age;
3314 if (avg >= 1.0) {
3315 tor_log(severity, LD_GENERAL,
3316 " * Channel " U64_FORMAT " has averaged %f "
3317 "cells received per second",
3318 U64_PRINTF_ARG(chan->global_identifier), avg);
3319 } else if (avg >= 0.0) {
3320 interval = 1.0 / avg;
3321 tor_log(severity, LD_GENERAL,
3322 " * Channel " U64_FORMAT " has averaged %f "
3323 "seconds between received cells",
3324 U64_PRINTF_ARG(chan->global_identifier), interval);
3327 if (chan->n_cells_xmitted > 0) {
3328 avg = (double)(chan->n_cells_xmitted) / age;
3329 if (avg >= 1.0) {
3330 tor_log(severity, LD_GENERAL,
3331 " * Channel " U64_FORMAT " has averaged %f "
3332 "cells transmitted per second",
3333 U64_PRINTF_ARG(chan->global_identifier), avg);
3334 } else if (avg >= 0.0) {
3335 interval = 1.0 / avg;
3336 tor_log(severity, LD_GENERAL,
3337 " * Channel " U64_FORMAT " has averaged %f "
3338 "seconds between transmitted cells",
3339 U64_PRINTF_ARG(chan->global_identifier), interval);
3344 /* Dump anything the lower layer has to say */
3345 channel_dump_transport_statistics(chan, severity);
3349 * Dump channel listener statistics
3351 * Dump statistics for one channel listener to the log
3354 void
3355 channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
3357 double avg, interval, age;
3358 time_t now = time(NULL);
3360 tor_assert(chan_l);
3362 age = (double)(now - chan_l->timestamp_created);
3364 tor_log(severity, LD_GENERAL,
3365 "Channel listener " U64_FORMAT " (at %p) with transport %s is in "
3366 "state %s (%d)",
3367 U64_PRINTF_ARG(chan_l->global_identifier), chan_l,
3368 channel_listener_describe_transport(chan_l),
3369 channel_listener_state_to_string(chan_l->state), chan_l->state);
3370 tor_log(severity, LD_GENERAL,
3371 " * Channel listener " U64_FORMAT " was created at " U64_FORMAT
3372 " (" U64_FORMAT " seconds ago) "
3373 "and last active at " U64_FORMAT " (" U64_FORMAT " seconds ago)",
3374 U64_PRINTF_ARG(chan_l->global_identifier),
3375 U64_PRINTF_ARG(chan_l->timestamp_created),
3376 U64_PRINTF_ARG(now - chan_l->timestamp_created),
3377 U64_PRINTF_ARG(chan_l->timestamp_active),
3378 U64_PRINTF_ARG(now - chan_l->timestamp_active));
3380 tor_log(severity, LD_GENERAL,
3381 " * Channel listener " U64_FORMAT " last accepted an incoming "
3382 "channel at " U64_FORMAT " (" U64_FORMAT " seconds ago) "
3383 "and has accepted " U64_FORMAT " channels in total",
3384 U64_PRINTF_ARG(chan_l->global_identifier),
3385 U64_PRINTF_ARG(chan_l->timestamp_accepted),
3386 U64_PRINTF_ARG(now - chan_l->timestamp_accepted),
3387 U64_PRINTF_ARG(chan_l->n_accepted));
3390 * If it's sensible to do so, get the rate of incoming channels on this
3391 * listener
3393 if (now > chan_l->timestamp_created &&
3394 chan_l->timestamp_created > 0 &&
3395 chan_l->n_accepted > 0) {
3396 avg = (double)(chan_l->n_accepted) / age;
3397 if (avg >= 1.0) {
3398 tor_log(severity, LD_GENERAL,
3399 " * Channel listener " U64_FORMAT " has averaged %f incoming "
3400 "channels per second",
3401 U64_PRINTF_ARG(chan_l->global_identifier), avg);
3402 } else if (avg >= 0.0) {
3403 interval = 1.0 / avg;
3404 tor_log(severity, LD_GENERAL,
3405 " * Channel listener " U64_FORMAT " has averaged %f seconds "
3406 "between incoming channels",
3407 U64_PRINTF_ARG(chan_l->global_identifier), interval);
3411 /* Dump anything the lower layer has to say */
3412 channel_listener_dump_transport_statistics(chan_l, severity);
3416 * Invoke transport-specific stats dump for channel
3418 * If there is a lower-layer statistics dump method, invoke it
3421 void
3422 channel_dump_transport_statistics(channel_t *chan, int severity)
3424 tor_assert(chan);
3426 if (chan->dumpstats) chan->dumpstats(chan, severity);
3430 * Invoke transport-specific stats dump for channel listener
3432 * If there is a lower-layer statistics dump method, invoke it
3435 void
3436 channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
3437 int severity)
3439 tor_assert(chan_l);
3441 if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
3445 * Return text description of the remote endpoint
3447 * This function return a test provided by the lower layer of the remote
3448 * endpoint for this channel; it should specify the actual address connected
3449 * to/from.
3451 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3452 * may invalidate the return value from this function.
3454 const char *
3455 channel_get_actual_remote_descr(channel_t *chan)
3457 tor_assert(chan);
3458 tor_assert(chan->get_remote_descr);
3460 /* Param 1 indicates the actual description */
3461 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL);
3465 * Return the text address of the remote endpoint.
3467 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3468 * may invalidate the return value from this function.
3470 const char *
3471 channel_get_actual_remote_address(channel_t *chan)
3473 /* Param 1 indicates the actual description */
3474 return chan->get_remote_descr(chan, GRD_FLAG_ORIGINAL|GRD_FLAG_ADDR_ONLY);
3478 * Return text description of the remote endpoint canonical address
3480 * This function return a test provided by the lower layer of the remote
3481 * endpoint for this channel; it should use the known canonical address for
3482 * this OR's identity digest if possible.
3484 * Subsequent calls to channel_get_{actual,canonical}_remote_{address,descr}
3485 * may invalidate the return value from this function.
3487 const char *
3488 channel_get_canonical_remote_descr(channel_t *chan)
3490 tor_assert(chan);
3491 tor_assert(chan->get_remote_descr);
3493 /* Param 0 indicates the canonicalized description */
3494 return chan->get_remote_descr(chan, 0);
3498 * Get remote address if possible.
3500 * Write the remote address out to a tor_addr_t if the underlying transport
3501 * supports this operation, and return 1. Return 0 if the underlying transport
3502 * doesn't let us do this.
3505 channel_get_addr_if_possible(channel_t *chan, tor_addr_t *addr_out)
3507 tor_assert(chan);
3508 tor_assert(addr_out);
3510 if (chan->get_remote_addr)
3511 return chan->get_remote_addr(chan, addr_out);
3512 /* Else no support, method not implemented */
3513 else return 0;
3517 * Check if there are outgoing queue writes on this channel
3519 * Indicate if either we have queued cells, or if not, whether the underlying
3520 * lower-layer transport thinks it has an output queue.
3524 channel_has_queued_writes(channel_t *chan)
3526 int has_writes = 0;
3528 tor_assert(chan);
3529 tor_assert(chan->has_queued_writes);
3531 if (! TOR_SIMPLEQ_EMPTY(&chan->outgoing_queue)) {
3532 has_writes = 1;
3533 } else {
3534 /* Check with the lower layer */
3535 has_writes = chan->has_queued_writes(chan);
3538 return has_writes;
3542 * Check the is_bad_for_new_circs flag
3544 * This function returns the is_bad_for_new_circs flag of the specified
3545 * channel.
3549 channel_is_bad_for_new_circs(channel_t *chan)
3551 tor_assert(chan);
3553 return chan->is_bad_for_new_circs;
3557 * Mark a channel as bad for new circuits
3559 * Set the is_bad_for_new_circs_flag on chan.
3562 void
3563 channel_mark_bad_for_new_circs(channel_t *chan)
3565 tor_assert(chan);
3567 chan->is_bad_for_new_circs = 1;
3571 * Get the client flag
3573 * This returns the client flag of a channel, which will be set if
3574 * command_process_create_cell() in command.c thinks this is a connection
3575 * from a client.
3579 channel_is_client(channel_t *chan)
3581 tor_assert(chan);
3583 return chan->is_client;
3587 * Set the client flag
3589 * Mark a channel as being from a client
3592 void
3593 channel_mark_client(channel_t *chan)
3595 tor_assert(chan);
3597 chan->is_client = 1;
3601 * Get the canonical flag for a channel
3603 * This returns the is_canonical for a channel; this flag is determined by
3604 * the lower layer and can't be set in a transport-independent way.
3608 channel_is_canonical(channel_t *chan)
3610 tor_assert(chan);
3611 tor_assert(chan->is_canonical);
3613 return chan->is_canonical(chan, 0);
3617 * Test if the canonical flag is reliable
3619 * This function asks if the lower layer thinks it's safe to trust the
3620 * result of channel_is_canonical()
3624 channel_is_canonical_is_reliable(channel_t *chan)
3626 tor_assert(chan);
3627 tor_assert(chan->is_canonical);
3629 return chan->is_canonical(chan, 1);
3633 * Test incoming flag
3635 * This function gets the incoming flag; this is set when a listener spawns
3636 * a channel. If this returns true the channel was remotely initiated.
3640 channel_is_incoming(channel_t *chan)
3642 tor_assert(chan);
3644 return chan->is_incoming;
3648 * Set the incoming flag
3650 * This function is called when a channel arrives on a listening channel
3651 * to mark it as incoming.
3654 void
3655 channel_mark_incoming(channel_t *chan)
3657 tor_assert(chan);
3659 chan->is_incoming = 1;
3663 * Test local flag
3665 * This function gets the local flag; the lower layer should set this when
3666 * setting up the channel if is_local_addr() is true for all of the
3667 * destinations it will communicate with on behalf of this channel. It's
3668 * used to decide whether to declare the network reachable when seeing incoming
3669 * traffic on the channel.
3673 channel_is_local(channel_t *chan)
3675 tor_assert(chan);
3677 return chan->is_local;
3681 * Set the local flag
3683 * This internal-only function should be called by the lower layer if the
3684 * channel is to a local address. See channel_is_local() above or the
3685 * description of the is_local bit in channel.h
3688 void
3689 channel_mark_local(channel_t *chan)
3691 tor_assert(chan);
3693 chan->is_local = 1;
3697 * Test outgoing flag
3699 * This function gets the outgoing flag; this is the inverse of the incoming
3700 * bit set when a listener spawns a channel. If this returns true the channel
3701 * was locally initiated.
3705 channel_is_outgoing(channel_t *chan)
3707 tor_assert(chan);
3709 return !(chan->is_incoming);
3713 * Mark a channel as outgoing
3715 * This function clears the incoming flag and thus marks a channel as
3716 * outgoing.
3719 void
3720 channel_mark_outgoing(channel_t *chan)
3722 tor_assert(chan);
3724 chan->is_incoming = 0;
3727 /*********************
3728 * Timestamp updates *
3729 ********************/
3732 * Update the created timestamp for a channel
3734 * This updates the channel's created timestamp and should only be called
3735 * from channel_init().
3738 void
3739 channel_timestamp_created(channel_t *chan)
3741 time_t now = time(NULL);
3743 tor_assert(chan);
3745 chan->timestamp_created = now;
3749 * Update the created timestamp for a channel listener
3751 * This updates the channel listener's created timestamp and should only be
3752 * called from channel_init_listener().
3755 void
3756 channel_listener_timestamp_created(channel_listener_t *chan_l)
3758 time_t now = time(NULL);
3760 tor_assert(chan_l);
3762 chan_l->timestamp_created = now;
3766 * Update the last active timestamp for a channel
3768 * This function updates the channel's last active timestamp; it should be
3769 * called by the lower layer whenever there is activity on the channel which
3770 * does not lead to a cell being transmitted or received; the active timestamp
3771 * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
3772 * but it should be updated for things like the v3 handshake and stuff that
3773 * produce activity only visible to the lower layer.
3776 void
3777 channel_timestamp_active(channel_t *chan)
3779 time_t now = time(NULL);
3781 tor_assert(chan);
3783 chan->timestamp_active = now;
3787 * Update the last active timestamp for a channel listener
3790 void
3791 channel_listener_timestamp_active(channel_listener_t *chan_l)
3793 time_t now = time(NULL);
3795 tor_assert(chan_l);
3797 chan_l->timestamp_active = now;
3801 * Update the last accepted timestamp.
3803 * This function updates the channel listener's last accepted timestamp; it
3804 * should be called whenever a new incoming channel is accepted on a
3805 * listener.
3808 void
3809 channel_listener_timestamp_accepted(channel_listener_t *chan_l)
3811 time_t now = time(NULL);
3813 tor_assert(chan_l);
3815 chan_l->timestamp_active = now;
3816 chan_l->timestamp_accepted = now;
3820 * Update client timestamp
3822 * This function is called by relay.c to timestamp a channel that appears to
3823 * be used as a client.
3826 void
3827 channel_timestamp_client(channel_t *chan)
3829 time_t now = time(NULL);
3831 tor_assert(chan);
3833 chan->timestamp_client = now;
3837 * Update the last drained timestamp
3839 * This is called whenever we transmit a cell which leaves the outgoing cell
3840 * queue completely empty. It also updates the xmit time and the active time.
3843 void
3844 channel_timestamp_drained(channel_t *chan)
3846 time_t now = time(NULL);
3848 tor_assert(chan);
3850 chan->timestamp_active = now;
3851 chan->timestamp_drained = now;
3852 chan->timestamp_xmit = now;
3856 * Update the recv timestamp
3858 * This is called whenever we get an incoming cell from the lower layer.
3859 * This also updates the active timestamp.
3862 void
3863 channel_timestamp_recv(channel_t *chan)
3865 time_t now = time(NULL);
3867 tor_assert(chan);
3869 chan->timestamp_active = now;
3870 chan->timestamp_recv = now;
3874 * Update the xmit timestamp
3875 * This is called whenever we pass an outgoing cell to the lower layer. This
3876 * also updates the active timestamp.
3879 void
3880 channel_timestamp_xmit(channel_t *chan)
3882 time_t now = time(NULL);
3884 tor_assert(chan);
3886 chan->timestamp_active = now;
3887 chan->timestamp_xmit = now;
3890 /***************************************************************
3891 * Timestamp queries - see above for definitions of timestamps *
3892 **************************************************************/
3895 * Query created timestamp for a channel
3898 time_t
3899 channel_when_created(channel_t *chan)
3901 tor_assert(chan);
3903 return chan->timestamp_created;
3907 * Query created timestamp for a channel listener
3910 time_t
3911 channel_listener_when_created(channel_listener_t *chan_l)
3913 tor_assert(chan_l);
3915 return chan_l->timestamp_created;
3919 * Query last active timestamp for a channel
3922 time_t
3923 channel_when_last_active(channel_t *chan)
3925 tor_assert(chan);
3927 return chan->timestamp_active;
3931 * Query last active timestamp for a channel listener
3934 time_t
3935 channel_listener_when_last_active(channel_listener_t *chan_l)
3937 tor_assert(chan_l);
3939 return chan_l->timestamp_active;
3943 * Query last accepted timestamp for a channel listener
3946 time_t
3947 channel_listener_when_last_accepted(channel_listener_t *chan_l)
3949 tor_assert(chan_l);
3951 return chan_l->timestamp_accepted;
3955 * Query client timestamp
3958 time_t
3959 channel_when_last_client(channel_t *chan)
3961 tor_assert(chan);
3963 return chan->timestamp_client;
3967 * Query drained timestamp
3970 time_t
3971 channel_when_last_drained(channel_t *chan)
3973 tor_assert(chan);
3975 return chan->timestamp_drained;
3979 * Query recv timestamp
3982 time_t
3983 channel_when_last_recv(channel_t *chan)
3985 tor_assert(chan);
3987 return chan->timestamp_recv;
3991 * Query xmit timestamp
3994 time_t
3995 channel_when_last_xmit(channel_t *chan)
3997 tor_assert(chan);
3999 return chan->timestamp_xmit;
4003 * Query accepted counter
4006 uint64_t
4007 channel_listener_count_accepted(channel_listener_t *chan_l)
4009 tor_assert(chan_l);
4011 return chan_l->n_accepted;
4015 * Query received cell counter
4018 uint64_t
4019 channel_count_recved(channel_t *chan)
4021 tor_assert(chan);
4023 return chan->n_cells_recved;
4027 * Query transmitted cell counter
4030 uint64_t
4031 channel_count_xmitted(channel_t *chan)
4033 tor_assert(chan);
4035 return chan->n_cells_xmitted;
4039 * Check if a channel matches an extend_info_t
4041 * This function calls the lower layer and asks if this channel matches a
4042 * given extend_info_t.
4046 channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
4048 tor_assert(chan);
4049 tor_assert(chan->matches_extend_info);
4050 tor_assert(extend_info);
4052 return chan->matches_extend_info(chan, extend_info);
4056 * Check if a channel matches a given target address
4058 * This function calls into the lower layer and asks if this channel thinks
4059 * it matches a given target address for circuit extension purposes.
4063 channel_matches_target_addr_for_extend(channel_t *chan,
4064 const tor_addr_t *target)
4066 tor_assert(chan);
4067 tor_assert(chan->matches_target);
4068 tor_assert(target);
4070 return chan->matches_target(chan, target);
4074 * Return the total number of circuits used by a channel
4076 * @param chan Channel to query
4077 * @return Number of circuits using this as n_chan or p_chan
4080 unsigned int
4081 channel_num_circuits(channel_t *chan)
4083 tor_assert(chan);
4085 return chan->num_n_circuits +
4086 chan->num_p_circuits;
4090 * Set up circuit ID generation
4092 * This is called when setting up a channel and replaces the old
4093 * connection_or_set_circid_type()
4095 void
4096 channel_set_circid_type(channel_t *chan,
4097 crypto_pk_t *identity_rcvd,
4098 int consider_identity)
4100 int started_here;
4101 crypto_pk_t *our_identity;
4103 tor_assert(chan);
4105 started_here = channel_is_outgoing(chan);
4107 if (! consider_identity) {
4108 if (started_here)
4109 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
4110 else
4111 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
4112 return;
4115 our_identity = started_here ?
4116 get_tlsclient_identity_key() : get_server_identity_key();
4118 if (identity_rcvd) {
4119 if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
4120 chan->circ_id_type = CIRC_ID_TYPE_LOWER;
4121 } else {
4122 chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
4124 } else {
4125 chan->circ_id_type = CIRC_ID_TYPE_NEITHER;