Line data Source code
1 : /* * Copyright (c) 2012-2021, The Tor Project, Inc. */
2 : /* See LICENSE for licensing information */
3 :
4 : /**
5 : * \file channel.c
6 : *
7 : * \brief OR/OP-to-OR channel abstraction layer. A channel's job is to
8 : * transfer cells from Tor instance to Tor instance. Currently, there is only
9 : * one implementation of the channel abstraction: in channeltls.c.
10 : *
11 : * Channels are a higher-level abstraction than or_connection_t: In general,
12 : * any means that two Tor relays use to exchange cells, or any means that a
13 : * relay and a client use to exchange cells, is a channel.
14 : *
15 : * Channels differ from pluggable transports in that they do not wrap an
16 : * underlying protocol over which cells are transmitted: they <em>are</em> the
17 : * underlying protocol.
18 : *
19 : * This module defines the generic parts of the channel_t interface, and
20 : * provides the machinery necessary for specialized implementations to be
21 : * created. At present, there is one specialized implementation in
22 : * channeltls.c, which uses connection_or.c to send cells over a TLS
23 : * connection.
24 : *
25 : * Every channel implementation is responsible for being able to transmit
26 : * cells that are passed to it
27 : *
28 : * For *inbound* cells, the entry point is: channel_process_cell(). It takes a
29 : * cell and will pass it to the cell handler set by
30 : * channel_set_cell_handlers(). Currently, this is passed back to the command
31 : * subsystem which is command_process_cell().
32 : *
33 : * NOTE: For now, the separation between channels and specialized channels
34 : * (like channeltls) is not that well defined. So the channeltls layer calls
35 : * channel_process_cell() which originally comes from the connection subsystem.
36 : * This should be hopefully be fixed with #23993.
37 : *
38 : * For *outbound* cells, the entry point is: channel_write_packed_cell().
39 : * Only packed cells are dequeued from the circuit queue by the scheduler
40 : * which uses channel_flush_from_first_active_circuit() to decide which cells
41 : * to flush from which circuit on the channel. They are then passed down to
42 : * the channel subsystem. This calls the low layer with the function pointer
43 : * .write_packed_cell().
44 : *
45 : * Each specialized channel (currently only channeltls_t) MUST implement a
46 : * series of function found in channel_t. See channel.h for more
47 : * documentation.
48 : **/
49 :
50 : /*
51 : * Define this so channel.h gives us things only channel_t subclasses
52 : * should touch.
53 : */
54 : #define CHANNEL_OBJECT_PRIVATE
55 :
56 : /* This one's for stuff only channel.c and the test suite should see */
57 : #define CHANNEL_FILE_PRIVATE
58 :
59 : #include "core/or/or.h"
60 : #include "app/config/config.h"
61 : #include "core/mainloop/mainloop.h"
62 : #include "core/or/channel.h"
63 : #include "core/or/channelpadding.h"
64 : #include "core/or/channeltls.h"
65 : #include "core/or/circuitbuild.h"
66 : #include "core/or/circuitlist.h"
67 : #include "core/or/circuitmux.h"
68 : #include "core/or/circuitstats.h"
69 : #include "core/or/connection_or.h" /* For var_cell_free() */
70 : #include "core/or/dos.h"
71 : #include "core/or/relay.h"
72 : #include "core/or/scheduler.h"
73 : #include "feature/client/entrynodes.h"
74 : #include "feature/hs/hs_service.h"
75 : #include "feature/nodelist/dirlist.h"
76 : #include "feature/nodelist/networkstatus.h"
77 : #include "feature/nodelist/nodelist.h"
78 : #include "feature/nodelist/routerlist.h"
79 : #include "feature/relay/router.h"
80 : #include "feature/stats/geoip_stats.h"
81 : #include "feature/stats/rephist.h"
82 : #include "lib/evloop/timers.h"
83 : #include "lib/time/compat_time.h"
84 :
85 : #include "core/or/cell_queue_st.h"
86 :
87 : /* Global lists of channels */
88 :
89 : /* All channel_t instances */
90 : static smartlist_t *all_channels = NULL;
91 :
92 : /* All channel_t instances not in ERROR or CLOSED states */
93 : static smartlist_t *active_channels = NULL;
94 :
95 : /* All channel_t instances in ERROR or CLOSED states */
96 : static smartlist_t *finished_channels = NULL;
97 :
98 : /* All channel_listener_t instances */
99 : static smartlist_t *all_listeners = NULL;
100 :
101 : /* All channel_listener_t instances in LISTENING state */
102 : static smartlist_t *active_listeners = NULL;
103 :
104 : /* All channel_listener_t instances in LISTENING state */
105 : static smartlist_t *finished_listeners = NULL;
106 :
107 : /** Map from channel->global_identifier to channel. Contains the same
108 : * elements as all_channels. */
109 : static HT_HEAD(channel_gid_map, channel_t) channel_gid_map = HT_INITIALIZER();
110 :
111 : static unsigned
112 290 : channel_id_hash(const channel_t *chan)
113 : {
114 290 : return (unsigned) chan->global_identifier;
115 : }
116 : static int
117 140 : channel_id_eq(const channel_t *a, const channel_t *b)
118 : {
119 140 : return a->global_identifier == b->global_identifier;
120 : }
121 830 : HT_PROTOTYPE(channel_gid_map, channel_t, gidmap_node,
122 : channel_id_hash, channel_id_eq);
123 514 : HT_GENERATE2(channel_gid_map, channel_t, gidmap_node,
124 : channel_id_hash, channel_id_eq,
125 : 0.6, tor_reallocarray_, tor_free_);
126 :
127 581 : HANDLE_IMPL(channel, channel_t,)
128 :
129 : /* Counter for ID numbers */
130 : static uint64_t n_channels_allocated = 0;
131 :
132 : /* Digest->channel map
133 : *
134 : * Similar to the one used in connection_or.c, this maps from the identity
135 : * digest of a remote endpoint to a channel_t to that endpoint. Channels
136 : * should be placed here when registered and removed when they close or error.
137 : * If more than one channel exists, follow the next_with_same_id pointer
138 : * as a linked list.
139 : */
140 : static HT_HEAD(channel_idmap, channel_idmap_entry_t) channel_identity_map =
141 : HT_INITIALIZER();
142 :
143 : typedef struct channel_idmap_entry_t {
144 : HT_ENTRY(channel_idmap_entry_t) node;
145 : uint8_t digest[DIGEST_LEN];
146 : TOR_LIST_HEAD(channel_list_t, channel_t) channel_list;
147 : } channel_idmap_entry_t;
148 :
149 : static inline unsigned
150 79 : channel_idmap_hash(const channel_idmap_entry_t *ent)
151 : {
152 79 : return (unsigned) siphash24g(ent->digest, DIGEST_LEN);
153 : }
154 :
155 : static inline int
156 54 : channel_idmap_eq(const channel_idmap_entry_t *a,
157 : const channel_idmap_entry_t *b)
158 : {
159 54 : return tor_memeq(a->digest, b->digest, DIGEST_LEN);
160 : }
161 :
162 613 : HT_PROTOTYPE(channel_idmap, channel_idmap_entry_t, node, channel_idmap_hash,
163 : channel_idmap_eq);
164 255 : HT_GENERATE2(channel_idmap, channel_idmap_entry_t, node, channel_idmap_hash,
165 : channel_idmap_eq, 0.5, tor_reallocarray_, tor_free_);
166 :
167 : /* Functions to maintain the digest map */
168 : static void channel_remove_from_digest_map(channel_t *chan);
169 :
170 : static void channel_force_xfree(channel_t *chan);
171 : static void channel_free_list(smartlist_t *channels,
172 : int mark_for_close);
173 : static void channel_listener_free_list(smartlist_t *channels,
174 : int mark_for_close);
175 : static void channel_listener_force_xfree(channel_listener_t *chan_l);
176 :
177 : /***********************************
178 : * Channel state utility functions *
179 : **********************************/
180 :
181 : /**
182 : * Indicate whether a given channel state is valid.
183 : */
184 : int
185 180 : channel_state_is_valid(channel_state_t state)
186 : {
187 180 : int is_valid;
188 :
189 180 : switch (state) {
190 : case CHANNEL_STATE_CLOSED:
191 : case CHANNEL_STATE_CLOSING:
192 : case CHANNEL_STATE_ERROR:
193 : case CHANNEL_STATE_MAINT:
194 : case CHANNEL_STATE_OPENING:
195 : case CHANNEL_STATE_OPEN:
196 : is_valid = 1;
197 : break;
198 2 : case CHANNEL_STATE_LAST:
199 : default:
200 2 : is_valid = 0;
201 : }
202 :
203 180 : return is_valid;
204 : }
205 :
206 : /**
207 : * Indicate whether a given channel listener state is valid.
208 : */
209 : int
210 10 : channel_listener_state_is_valid(channel_listener_state_t state)
211 : {
212 10 : int is_valid;
213 :
214 10 : switch (state) {
215 : case CHANNEL_LISTENER_STATE_CLOSED:
216 : case CHANNEL_LISTENER_STATE_LISTENING:
217 : case CHANNEL_LISTENER_STATE_CLOSING:
218 : case CHANNEL_LISTENER_STATE_ERROR:
219 : is_valid = 1;
220 : break;
221 2 : case CHANNEL_LISTENER_STATE_LAST:
222 : default:
223 2 : is_valid = 0;
224 : }
225 :
226 10 : return is_valid;
227 : }
228 :
229 : /**
230 : * Indicate whether a channel state transition is valid.
231 : *
232 : * This function takes two channel states and indicates whether a
233 : * transition between them is permitted (see the state definitions and
234 : * transition table in or.h at the channel_state_t typedef).
235 : */
236 : int
237 104 : channel_state_can_transition(channel_state_t from, channel_state_t to)
238 : {
239 104 : int is_valid;
240 :
241 104 : switch (from) {
242 2 : case CHANNEL_STATE_CLOSED:
243 2 : is_valid = (to == CHANNEL_STATE_OPENING);
244 2 : break;
245 22 : case CHANNEL_STATE_CLOSING:
246 22 : is_valid = (to == CHANNEL_STATE_CLOSED ||
247 22 : to == CHANNEL_STATE_ERROR);
248 22 : break;
249 : case CHANNEL_STATE_ERROR:
250 : is_valid = 0;
251 : break;
252 8 : case CHANNEL_STATE_MAINT:
253 8 : is_valid = (to == CHANNEL_STATE_CLOSING ||
254 8 : to == CHANNEL_STATE_ERROR ||
255 8 : to == CHANNEL_STATE_OPEN);
256 8 : break;
257 49 : case CHANNEL_STATE_OPENING:
258 49 : is_valid = (to == CHANNEL_STATE_CLOSING ||
259 49 : to == CHANNEL_STATE_ERROR ||
260 49 : to == CHANNEL_STATE_OPEN);
261 49 : break;
262 21 : case CHANNEL_STATE_OPEN:
263 21 : is_valid = (to == CHANNEL_STATE_CLOSING ||
264 21 : to == CHANNEL_STATE_ERROR ||
265 : to == CHANNEL_STATE_MAINT);
266 21 : break;
267 : case CHANNEL_STATE_LAST:
268 : default:
269 : is_valid = 0;
270 : }
271 :
272 104 : return is_valid;
273 : }
274 :
275 : /**
276 : * Indicate whether a channel listener state transition is valid.
277 : *
278 : * This function takes two channel listener states and indicates whether a
279 : * transition between them is permitted (see the state definitions and
280 : * transition table in or.h at the channel_listener_state_t typedef).
281 : */
282 : int
283 10 : channel_listener_state_can_transition(channel_listener_state_t from,
284 : channel_listener_state_t to)
285 : {
286 10 : int is_valid;
287 :
288 10 : switch (from) {
289 2 : case CHANNEL_LISTENER_STATE_CLOSED:
290 2 : is_valid = (to == CHANNEL_LISTENER_STATE_LISTENING);
291 2 : break;
292 3 : case CHANNEL_LISTENER_STATE_CLOSING:
293 3 : is_valid = (to == CHANNEL_LISTENER_STATE_CLOSED ||
294 3 : to == CHANNEL_LISTENER_STATE_ERROR);
295 3 : break;
296 : case CHANNEL_LISTENER_STATE_ERROR:
297 : is_valid = 0;
298 : break;
299 3 : case CHANNEL_LISTENER_STATE_LISTENING:
300 3 : is_valid = (to == CHANNEL_LISTENER_STATE_CLOSING ||
301 : to == CHANNEL_LISTENER_STATE_ERROR);
302 3 : break;
303 : case CHANNEL_LISTENER_STATE_LAST:
304 : default:
305 : is_valid = 0;
306 : }
307 :
308 10 : return is_valid;
309 : }
310 :
311 : /**
312 : * Return a human-readable description for a channel state.
313 : */
314 : const char *
315 512 : channel_state_to_string(channel_state_t state)
316 : {
317 512 : const char *descr;
318 :
319 512 : switch (state) {
320 : case CHANNEL_STATE_CLOSED:
321 : descr = "closed";
322 : break;
323 71 : case CHANNEL_STATE_CLOSING:
324 71 : descr = "closing";
325 71 : break;
326 3 : case CHANNEL_STATE_ERROR:
327 3 : descr = "channel error";
328 3 : break;
329 9 : case CHANNEL_STATE_MAINT:
330 9 : descr = "temporarily suspended for maintenance";
331 9 : break;
332 89 : case CHANNEL_STATE_OPENING:
333 89 : descr = "opening";
334 89 : break;
335 312 : case CHANNEL_STATE_OPEN:
336 312 : descr = "open";
337 312 : break;
338 2 : case CHANNEL_STATE_LAST:
339 : default:
340 2 : descr = "unknown or invalid channel state";
341 : }
342 :
343 512 : return descr;
344 : }
345 :
346 : /**
347 : * Return a human-readable description for a channel listener state.
348 : */
349 : const char *
350 12 : channel_listener_state_to_string(channel_listener_state_t state)
351 : {
352 12 : const char *descr;
353 :
354 12 : switch (state) {
355 : case CHANNEL_LISTENER_STATE_CLOSED:
356 : descr = "closed";
357 : break;
358 3 : case CHANNEL_LISTENER_STATE_CLOSING:
359 3 : descr = "closing";
360 3 : break;
361 1 : case CHANNEL_LISTENER_STATE_ERROR:
362 1 : descr = "channel listener error";
363 1 : break;
364 3 : case CHANNEL_LISTENER_STATE_LISTENING:
365 3 : descr = "listening";
366 3 : break;
367 2 : case CHANNEL_LISTENER_STATE_LAST:
368 : default:
369 2 : descr = "unknown or invalid channel listener state";
370 : }
371 :
372 12 : return descr;
373 : }
374 :
375 : /***************************************
376 : * Channel registration/unregistration *
377 : ***************************************/
378 :
379 : /**
380 : * Register a channel.
381 : *
382 : * This function registers a newly created channel in the global lists/maps
383 : * of active channels.
384 : */
385 : void
386 149 : channel_register(channel_t *chan)
387 : {
388 149 : tor_assert(chan);
389 149 : tor_assert(chan->global_identifier);
390 :
391 : /* No-op if already registered */
392 149 : if (chan->registered) return;
393 :
394 149 : log_debug(LD_CHANNEL,
395 : "Registering channel %p (ID %"PRIu64 ") "
396 : "in state %s (%d) with digest %s",
397 : chan, (chan->global_identifier),
398 : channel_state_to_string(chan->state), chan->state,
399 : hex_str(chan->identity_digest, DIGEST_LEN));
400 :
401 : /* Make sure we have all_channels, then add it */
402 149 : if (!all_channels) all_channels = smartlist_new();
403 149 : smartlist_add(all_channels, chan);
404 149 : channel_t *oldval = HT_REPLACE(channel_gid_map, &channel_gid_map, chan);
405 149 : tor_assert(! oldval);
406 :
407 : /* Is it finished? */
408 149 : if (CHANNEL_FINISHED(chan)) {
409 : /* Put it in the finished list, creating it if necessary */
410 0 : if (!finished_channels) finished_channels = smartlist_new();
411 0 : smartlist_add(finished_channels, chan);
412 0 : mainloop_schedule_postloop_cleanup();
413 : } else {
414 : /* Put it in the active list, creating it if necessary */
415 149 : if (!active_channels) active_channels = smartlist_new();
416 149 : smartlist_add(active_channels, chan);
417 :
418 149 : if (!CHANNEL_IS_CLOSING(chan)) {
419 : /* It should have a digest set */
420 149 : if (!tor_digest_is_zero(chan->identity_digest)) {
421 : /* Yeah, we're good, add it to the map */
422 6 : channel_add_to_digest_map(chan);
423 : } else {
424 143 : log_info(LD_CHANNEL,
425 : "Channel %p (global ID %"PRIu64 ") "
426 : "in state %s (%d) registered with no identity digest",
427 : chan, (chan->global_identifier),
428 : channel_state_to_string(chan->state), chan->state);
429 : }
430 : }
431 : }
432 :
433 : /* Mark it as registered */
434 149 : chan->registered = 1;
435 : }
436 :
437 : /**
438 : * Unregister a channel.
439 : *
440 : * This function removes a channel from the global lists and maps and is used
441 : * when freeing a closed/errored channel.
442 : */
443 : void
444 135 : channel_unregister(channel_t *chan)
445 : {
446 135 : tor_assert(chan);
447 :
448 : /* No-op if not registered */
449 135 : if (!(chan->registered)) return;
450 :
451 : /* Is it finished? */
452 135 : if (CHANNEL_FINISHED(chan)) {
453 : /* Get it out of the finished list */
454 16 : if (finished_channels) smartlist_remove(finished_channels, chan);
455 : } else {
456 : /* Get it out of the active list */
457 119 : if (active_channels) smartlist_remove(active_channels, chan);
458 : }
459 :
460 : /* Get it out of all_channels */
461 135 : if (all_channels) smartlist_remove(all_channels, chan);
462 135 : channel_t *oldval = HT_REMOVE(channel_gid_map, &channel_gid_map, chan);
463 135 : tor_assert(oldval == NULL || oldval == chan);
464 :
465 : /* Mark it as unregistered */
466 135 : chan->registered = 0;
467 :
468 : /* Should it be in the digest map? */
469 135 : if (!tor_digest_is_zero(chan->identity_digest) &&
470 6 : !(CHANNEL_CONDEMNED(chan))) {
471 : /* Remove it */
472 6 : channel_remove_from_digest_map(chan);
473 : }
474 : }
475 :
476 : /**
477 : * Register a channel listener.
478 : *
479 : * This function registers a newly created channel listener in the global
480 : * lists/maps of active channel listeners.
481 : */
482 : void
483 2 : channel_listener_register(channel_listener_t *chan_l)
484 : {
485 2 : tor_assert(chan_l);
486 :
487 : /* No-op if already registered */
488 2 : if (chan_l->registered) return;
489 :
490 2 : log_debug(LD_CHANNEL,
491 : "Registering channel listener %p (ID %"PRIu64 ") "
492 : "in state %s (%d)",
493 : chan_l, (chan_l->global_identifier),
494 : channel_listener_state_to_string(chan_l->state),
495 : chan_l->state);
496 :
497 : /* Make sure we have all_listeners, then add it */
498 2 : if (!all_listeners) all_listeners = smartlist_new();
499 2 : smartlist_add(all_listeners, chan_l);
500 :
501 : /* Is it finished? */
502 2 : if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
503 : chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
504 : /* Put it in the finished list, creating it if necessary */
505 1 : if (!finished_listeners) finished_listeners = smartlist_new();
506 1 : smartlist_add(finished_listeners, chan_l);
507 : } else {
508 : /* Put it in the active list, creating it if necessary */
509 1 : if (!active_listeners) active_listeners = smartlist_new();
510 1 : smartlist_add(active_listeners, chan_l);
511 : }
512 :
513 : /* Mark it as registered */
514 2 : chan_l->registered = 1;
515 : }
516 :
517 : /**
518 : * Unregister a channel listener.
519 : *
520 : * This function removes a channel listener from the global lists and maps
521 : * and is used when freeing a closed/errored channel listener.
522 : */
523 : void
524 2 : channel_listener_unregister(channel_listener_t *chan_l)
525 : {
526 2 : tor_assert(chan_l);
527 :
528 : /* No-op if not registered */
529 2 : if (!(chan_l->registered)) return;
530 :
531 : /* Is it finished? */
532 2 : if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
533 : chan_l->state == CHANNEL_LISTENER_STATE_ERROR) {
534 : /* Get it out of the finished list */
535 2 : if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
536 : } else {
537 : /* Get it out of the active list */
538 0 : if (active_listeners) smartlist_remove(active_listeners, chan_l);
539 : }
540 :
541 : /* Get it out of all_listeners */
542 2 : if (all_listeners) smartlist_remove(all_listeners, chan_l);
543 :
544 : /* Mark it as unregistered */
545 2 : chan_l->registered = 0;
546 : }
547 :
548 : /*********************************
549 : * Channel digest map maintenance
550 : *********************************/
551 :
552 : /**
553 : * Add a channel to the digest map.
554 : *
555 : * This function adds a channel to the digest map and inserts it into the
556 : * correct linked list if channels with that remote endpoint identity digest
557 : * already exist.
558 : */
559 : STATIC void
560 15 : channel_add_to_digest_map(channel_t *chan)
561 : {
562 15 : channel_idmap_entry_t *ent, search;
563 :
564 15 : tor_assert(chan);
565 :
566 : /* Assert that the state makes sense */
567 15 : tor_assert(!CHANNEL_CONDEMNED(chan));
568 :
569 : /* Assert that there is a digest */
570 15 : tor_assert(!tor_digest_is_zero(chan->identity_digest));
571 :
572 15 : memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
573 15 : ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
574 15 : if (! ent) {
575 12 : ent = tor_malloc(sizeof(channel_idmap_entry_t));
576 12 : memcpy(ent->digest, chan->identity_digest, DIGEST_LEN);
577 12 : TOR_LIST_INIT(&ent->channel_list);
578 12 : HT_INSERT(channel_idmap, &channel_identity_map, ent);
579 : }
580 15 : TOR_LIST_INSERT_HEAD(&ent->channel_list, chan, next_with_same_id);
581 :
582 15 : log_debug(LD_CHANNEL,
583 : "Added channel %p (global ID %"PRIu64 ") "
584 : "to identity map in state %s (%d) with digest %s",
585 : chan, (chan->global_identifier),
586 : channel_state_to_string(chan->state), chan->state,
587 : hex_str(chan->identity_digest, DIGEST_LEN));
588 15 : }
589 :
590 : /**
591 : * Remove a channel from the digest map.
592 : *
593 : * This function removes a channel from the digest map and the linked list of
594 : * channels for that digest if more than one exists.
595 : */
596 : static void
597 12 : channel_remove_from_digest_map(channel_t *chan)
598 : {
599 12 : channel_idmap_entry_t *ent, search;
600 :
601 12 : tor_assert(chan);
602 :
603 : /* Assert that there is a digest */
604 12 : tor_assert(!tor_digest_is_zero(chan->identity_digest));
605 :
606 : /* Pull it out of its list, wherever that list is */
607 12 : TOR_LIST_REMOVE(chan, next_with_same_id);
608 :
609 12 : memcpy(search.digest, chan->identity_digest, DIGEST_LEN);
610 12 : ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
611 :
612 : /* Look for it in the map */
613 12 : if (ent) {
614 : /* Okay, it's here */
615 :
616 12 : if (TOR_LIST_EMPTY(&ent->channel_list)) {
617 10 : HT_REMOVE(channel_idmap, &channel_identity_map, ent);
618 10 : tor_free(ent);
619 : }
620 :
621 12 : log_debug(LD_CHANNEL,
622 : "Removed channel %p (global ID %"PRIu64 ") from "
623 : "identity map in state %s (%d) with digest %s",
624 : chan, (chan->global_identifier),
625 : channel_state_to_string(chan->state), chan->state,
626 : hex_str(chan->identity_digest, DIGEST_LEN));
627 : } else {
628 : /* Shouldn't happen */
629 0 : log_warn(LD_BUG,
630 : "Trying to remove channel %p (global ID %"PRIu64 ") with "
631 : "digest %s from identity map, but couldn't find any with "
632 : "that digest",
633 : chan, (chan->global_identifier),
634 : hex_str(chan->identity_digest, DIGEST_LEN));
635 : }
636 12 : }
637 :
638 : /****************************
639 : * Channel lookup functions *
640 : ***************************/
641 :
642 : /**
643 : * Find channel by global ID.
644 : *
645 : * This function searches for a channel by the global_identifier assigned
646 : * at initialization time. This identifier is unique for the lifetime of the
647 : * Tor process.
648 : */
649 : channel_t *
650 6 : channel_find_by_global_id(uint64_t global_identifier)
651 : {
652 6 : channel_t lookup;
653 6 : channel_t *rv = NULL;
654 :
655 6 : lookup.global_identifier = global_identifier;
656 6 : rv = HT_FIND(channel_gid_map, &channel_gid_map, &lookup);
657 6 : if (rv) {
658 5 : tor_assert(rv->global_identifier == global_identifier);
659 : }
660 :
661 6 : return rv;
662 : }
663 :
664 : /** Return true iff <b>chan</b> matches <b>rsa_id_digest</b> and <b>ed_id</b>.
665 : * as its identity keys. If either is NULL, do not check for a match. */
666 : int
667 52 : channel_remote_identity_matches(const channel_t *chan,
668 : const char *rsa_id_digest,
669 : const ed25519_public_key_t *ed_id)
670 : {
671 52 : if (BUG(!chan))
672 0 : return 0;
673 52 : if (rsa_id_digest) {
674 52 : if (tor_memneq(rsa_id_digest, chan->identity_digest, DIGEST_LEN))
675 : return 0;
676 : }
677 52 : if (ed_id) {
678 40 : if (tor_memneq(ed_id->pubkey, chan->ed25519_identity.pubkey,
679 : ED25519_PUBKEY_LEN))
680 10 : return 0;
681 : }
682 : return 1;
683 : }
684 :
685 : /**
686 : * Find channel by RSA/Ed25519 identity of of the remote endpoint.
687 : *
688 : * This function looks up a channel by the digest of its remote endpoint's RSA
689 : * identity key. If <b>ed_id</b> is provided and nonzero, only a channel
690 : * matching the <b>ed_id</b> will be returned.
691 : *
692 : * It's possible that more than one channel to a given endpoint exists. Use
693 : * channel_next_with_rsa_identity() to walk the list of channels; make sure
694 : * to test for Ed25519 identity match too (as appropriate)
695 : */
696 : channel_t *
697 30 : channel_find_by_remote_identity(const char *rsa_id_digest,
698 : const ed25519_public_key_t *ed_id)
699 : {
700 30 : channel_t *rv = NULL;
701 30 : channel_idmap_entry_t *ent, search;
702 :
703 30 : tor_assert(rsa_id_digest); /* For now, we require that every channel have
704 : * an RSA identity, and that every lookup
705 : * contain an RSA identity */
706 30 : if (ed_id && ed25519_public_key_is_zero(ed_id)) {
707 : /* Treat zero as meaning "We don't care about the presence or absence of
708 : * an Ed key", not "There must be no Ed key". */
709 5 : ed_id = NULL;
710 : }
711 :
712 30 : memcpy(search.digest, rsa_id_digest, DIGEST_LEN);
713 30 : ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
714 30 : if (ent) {
715 29 : rv = TOR_LIST_FIRST(&ent->channel_list);
716 : }
717 38 : while (rv && ! channel_remote_identity_matches(rv, rsa_id_digest, ed_id)) {
718 8 : rv = channel_next_with_rsa_identity(rv);
719 : }
720 :
721 30 : return rv;
722 : }
723 :
724 : /**
725 : * Get next channel with digest.
726 : *
727 : * This function takes a channel and finds the next channel in the list
728 : * with the same digest.
729 : */
730 : channel_t *
731 37 : channel_next_with_rsa_identity(channel_t *chan)
732 : {
733 37 : tor_assert(chan);
734 :
735 37 : return TOR_LIST_NEXT(chan, next_with_same_id);
736 : }
737 :
738 : /**
739 : * Relays run this once an hour to look over our list of channels to other
740 : * relays. It prints out some statistics if there are multiple connections
741 : * to many relays.
742 : *
743 : * This function is similar to connection_or_set_bad_connections(),
744 : * and probably could be adapted to replace it, if it was modified to actually
745 : * take action on any of these connections.
746 : */
747 : void
748 5 : channel_check_for_duplicates(void)
749 : {
750 5 : channel_idmap_entry_t **iter;
751 5 : channel_t *chan;
752 5 : int total_dirauth_connections = 0, total_dirauths = 0;
753 5 : int total_relay_connections = 0, total_relays = 0, total_canonical = 0;
754 5 : int total_half_canonical = 0;
755 5 : int total_gt_one_connection = 0, total_gt_two_connections = 0;
756 5 : int total_gt_four_connections = 0;
757 :
758 9 : HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
759 4 : int connections_to_relay = 0;
760 4 : const char *id_digest = (char *) (*iter)->digest;
761 :
762 : /* Only consider relay connections */
763 4 : if (!connection_or_digest_is_known_relay(id_digest))
764 1 : continue;
765 :
766 3 : total_relays++;
767 :
768 3 : const bool is_dirauth = router_digest_is_trusted_dir(id_digest);
769 3 : if (is_dirauth)
770 0 : total_dirauths++;
771 :
772 6 : for (chan = TOR_LIST_FIRST(&(*iter)->channel_list); chan;
773 3 : chan = channel_next_with_rsa_identity(chan)) {
774 :
775 3 : if (CHANNEL_CONDEMNED(chan) || !CHANNEL_IS_OPEN(chan))
776 1 : continue;
777 :
778 2 : connections_to_relay++;
779 2 : total_relay_connections++;
780 2 : if (is_dirauth)
781 : total_dirauth_connections++;
782 :
783 2 : if (chan->is_canonical(chan)) total_canonical++;
784 :
785 2 : if (!chan->is_canonical_to_peer && chan->is_canonical(chan)) {
786 1 : total_half_canonical++;
787 : }
788 : }
789 :
790 3 : if (connections_to_relay > 1) total_gt_one_connection++;
791 3 : if (connections_to_relay > 2) total_gt_two_connections++;
792 3 : if (connections_to_relay > 4) total_gt_four_connections++;
793 : }
794 :
795 : /* Don't bother warning about excessive connections unless we have
796 : * at least this many connections, total.
797 : */
798 : #define MIN_RELAY_CONNECTIONS_TO_WARN 25
799 : /* If the average number of connections for a regular relay is more than
800 : * this, that's too high.
801 : */
802 : #define MAX_AVG_RELAY_CONNECTIONS 1.5
803 : /* If the average number of connections for a dirauth is more than
804 : * this, that's too high.
805 : */
806 : #define MAX_AVG_DIRAUTH_CONNECTIONS 4
807 :
808 : /* How many connections total would be okay, given the number of
809 : * relays and dirauths that we have connections to? */
810 5 : const int max_tolerable_connections = (int)(
811 5 : (total_relays-total_dirauths) * MAX_AVG_RELAY_CONNECTIONS +
812 5 : total_dirauths * MAX_AVG_DIRAUTH_CONNECTIONS);
813 :
814 : /* If we average 1.5 or more connections per relay, something is wrong */
815 5 : if (total_relays > MIN_RELAY_CONNECTIONS_TO_WARN &&
816 5 : total_relay_connections > max_tolerable_connections) {
817 0 : log_notice(LD_OR,
818 : "Your relay has a very large number of connections to other relays. "
819 : "Is your outbound address the same as your relay address? "
820 : "Found %d connections to %d relays. Found %d current canonical "
821 : "connections, in %d of which we were a non-canonical peer. "
822 : "%d relays had more than 1 connection, %d had more than 2, and "
823 : "%d had more than 4 connections.",
824 : total_relay_connections, total_relays, total_canonical,
825 : total_half_canonical, total_gt_one_connection,
826 : total_gt_two_connections, total_gt_four_connections);
827 : } else {
828 5 : log_info(LD_OR, "Performed connection pruning. "
829 : "Found %d connections to %d relays. Found %d current canonical "
830 : "connections, in %d of which we were a non-canonical peer. "
831 : "%d relays had more than 1 connection, %d had more than 2, and "
832 : "%d had more than 4 connections.",
833 : total_relay_connections, total_relays, total_canonical,
834 : total_half_canonical, total_gt_one_connection,
835 : total_gt_two_connections, total_gt_four_connections);
836 : }
837 5 : }
838 :
839 : /**
840 : * Initialize a channel.
841 : *
842 : * This function should be called by subclasses to set up some per-channel
843 : * variables. I.e., this is the superclass constructor. Before this, the
844 : * channel should be allocated with tor_malloc_zero().
845 : */
846 : void
847 192 : channel_init(channel_t *chan)
848 : {
849 192 : tor_assert(chan);
850 :
851 : /* Assign an ID and bump the counter */
852 192 : chan->global_identifier = ++n_channels_allocated;
853 :
854 : /* Init timestamp */
855 192 : chan->timestamp_last_had_circuits = time(NULL);
856 :
857 : /* Warn about exhausted circuit IDs no more than hourly. */
858 192 : chan->last_warned_circ_ids_exhausted.rate = 3600;
859 :
860 : /* Initialize list entries. */
861 192 : memset(&chan->next_with_same_id, 0, sizeof(chan->next_with_same_id));
862 :
863 : /* Timestamp it */
864 192 : channel_timestamp_created(chan);
865 :
866 : /* It hasn't been open yet. */
867 192 : chan->has_been_open = 0;
868 :
869 : /* Scheduler state is idle */
870 192 : chan->scheduler_state = SCHED_CHAN_IDLE;
871 :
872 : /* Channel is not in the scheduler heap. */
873 192 : chan->sched_heap_idx = -1;
874 :
875 192 : tor_addr_make_unspec(&chan->addr_according_to_peer);
876 192 : }
877 :
878 : /**
879 : * Initialize a channel listener.
880 : *
881 : * This function should be called by subclasses to set up some per-channel
882 : * variables. I.e., this is the superclass constructor. Before this, the
883 : * channel listener should be allocated with tor_malloc_zero().
884 : */
885 : void
886 1 : channel_init_listener(channel_listener_t *chan_l)
887 : {
888 1 : tor_assert(chan_l);
889 :
890 : /* Assign an ID and bump the counter */
891 1 : chan_l->global_identifier = ++n_channels_allocated;
892 :
893 : /* Timestamp it */
894 1 : channel_listener_timestamp_created(chan_l);
895 1 : }
896 :
897 : /**
898 : * Free a channel; nothing outside of channel.c and subclasses should call
899 : * this - it frees channels after they have closed and been unregistered.
900 : */
901 : void
902 21 : channel_free_(channel_t *chan)
903 : {
904 21 : if (!chan) return;
905 :
906 : /* It must be closed or errored */
907 21 : tor_assert(CHANNEL_FINISHED(chan));
908 :
909 : /* It must be deregistered */
910 21 : tor_assert(!(chan->registered));
911 :
912 21 : log_debug(LD_CHANNEL,
913 : "Freeing channel %"PRIu64 " at %p",
914 : (chan->global_identifier), chan);
915 :
916 : /* Get this one out of the scheduler */
917 21 : scheduler_release_channel(chan);
918 :
919 : /*
920 : * Get rid of cmux policy before we do anything, so cmux policies don't
921 : * see channels in weird half-freed states.
922 : */
923 21 : if (chan->cmux) {
924 21 : circuitmux_set_policy(chan->cmux, NULL);
925 : }
926 :
927 : /* Remove all timers and associated handle entries now */
928 21 : timer_free(chan->padding_timer);
929 21 : channel_handle_free(chan->timer_handle);
930 21 : channel_handles_clear(chan);
931 :
932 : /* Call a free method if there is one */
933 21 : if (chan->free_fn) chan->free_fn(chan);
934 :
935 21 : channel_clear_remote_end(chan);
936 :
937 : /* Get rid of cmux */
938 21 : if (chan->cmux) {
939 21 : circuitmux_detach_all_circuits(chan->cmux, NULL);
940 21 : circuitmux_mark_destroyed_circids_usable(chan->cmux, chan);
941 21 : circuitmux_free(chan->cmux);
942 21 : chan->cmux = NULL;
943 : }
944 :
945 21 : tor_free(chan);
946 : }
947 :
948 : /**
949 : * Free a channel listener; nothing outside of channel.c and subclasses
950 : * should call this - it frees channel listeners after they have closed and
951 : * been unregistered.
952 : */
953 : void
954 0 : channel_listener_free_(channel_listener_t *chan_l)
955 : {
956 0 : if (!chan_l) return;
957 :
958 0 : log_debug(LD_CHANNEL,
959 : "Freeing channel_listener_t %"PRIu64 " at %p",
960 : (chan_l->global_identifier),
961 : chan_l);
962 :
963 : /* It must be closed or errored */
964 0 : tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
965 : chan_l->state == CHANNEL_LISTENER_STATE_ERROR);
966 : /* It must be deregistered */
967 0 : tor_assert(!(chan_l->registered));
968 :
969 : /* Call a free method if there is one */
970 0 : if (chan_l->free_fn) chan_l->free_fn(chan_l);
971 :
972 0 : tor_free(chan_l);
973 : }
974 :
975 : /**
976 : * Free a channel and skip the state/registration asserts; this internal-
977 : * use-only function should be called only from channel_free_all() when
978 : * shutting down the Tor process.
979 : */
980 : static void
981 3 : channel_force_xfree(channel_t *chan)
982 : {
983 3 : tor_assert(chan);
984 :
985 3 : log_debug(LD_CHANNEL,
986 : "Force-freeing channel %"PRIu64 " at %p",
987 : (chan->global_identifier), chan);
988 :
989 : /* Get this one out of the scheduler */
990 3 : scheduler_release_channel(chan);
991 :
992 : /*
993 : * Get rid of cmux policy before we do anything, so cmux policies don't
994 : * see channels in weird half-freed states.
995 : */
996 3 : if (chan->cmux) {
997 3 : circuitmux_set_policy(chan->cmux, NULL);
998 : }
999 :
1000 : /* Remove all timers and associated handle entries now */
1001 3 : timer_free(chan->padding_timer);
1002 3 : channel_handle_free(chan->timer_handle);
1003 3 : channel_handles_clear(chan);
1004 :
1005 : /* Call a free method if there is one */
1006 3 : if (chan->free_fn) chan->free_fn(chan);
1007 :
1008 3 : channel_clear_remote_end(chan);
1009 :
1010 : /* Get rid of cmux */
1011 3 : if (chan->cmux) {
1012 3 : circuitmux_free(chan->cmux);
1013 3 : chan->cmux = NULL;
1014 : }
1015 :
1016 3 : tor_free(chan);
1017 3 : }
1018 :
1019 : /**
1020 : * Free a channel listener and skip the state/registration asserts; this
1021 : * internal-use-only function should be called only from channel_free_all()
1022 : * when shutting down the Tor process.
1023 : */
1024 : static void
1025 0 : channel_listener_force_xfree(channel_listener_t *chan_l)
1026 : {
1027 0 : tor_assert(chan_l);
1028 :
1029 0 : log_debug(LD_CHANNEL,
1030 : "Force-freeing channel_listener_t %"PRIu64 " at %p",
1031 : (chan_l->global_identifier),
1032 : chan_l);
1033 :
1034 : /* Call a free method if there is one */
1035 0 : if (chan_l->free_fn) chan_l->free_fn(chan_l);
1036 :
1037 : /*
1038 : * The incoming list just gets emptied and freed; we request close on
1039 : * any channels we find there, but since we got called while shutting
1040 : * down they will get deregistered and freed elsewhere anyway.
1041 : */
1042 0 : if (chan_l->incoming_list) {
1043 0 : SMARTLIST_FOREACH_BEGIN(chan_l->incoming_list,
1044 : channel_t *, qchan) {
1045 0 : channel_mark_for_close(qchan);
1046 0 : } SMARTLIST_FOREACH_END(qchan);
1047 :
1048 0 : smartlist_free(chan_l->incoming_list);
1049 0 : chan_l->incoming_list = NULL;
1050 : }
1051 :
1052 0 : tor_free(chan_l);
1053 0 : }
1054 :
1055 : /**
1056 : * Set the listener for a channel listener.
1057 : *
1058 : * This function sets the handler for new incoming channels on a channel
1059 : * listener.
1060 : */
1061 : void
1062 1 : channel_listener_set_listener_fn(channel_listener_t *chan_l,
1063 : channel_listener_fn_ptr listener)
1064 : {
1065 1 : tor_assert(chan_l);
1066 1 : tor_assert(chan_l->state == CHANNEL_LISTENER_STATE_LISTENING);
1067 :
1068 1 : log_debug(LD_CHANNEL,
1069 : "Setting listener callback for channel listener %p "
1070 : "(global ID %"PRIu64 ") to %p",
1071 : chan_l, (chan_l->global_identifier),
1072 : listener);
1073 :
1074 1 : chan_l->listener = listener;
1075 1 : if (chan_l->listener) channel_listener_process_incoming(chan_l);
1076 1 : }
1077 :
1078 : /**
1079 : * Return the fixed-length cell handler for a channel.
1080 : *
1081 : * This function gets the handler for incoming fixed-length cells installed
1082 : * on a channel.
1083 : */
1084 : channel_cell_handler_fn_ptr
1085 1 : channel_get_cell_handler(channel_t *chan)
1086 : {
1087 1 : tor_assert(chan);
1088 :
1089 1 : if (CHANNEL_CAN_HANDLE_CELLS(chan))
1090 1 : return chan->cell_handler;
1091 :
1092 : return NULL;
1093 : }
1094 :
1095 : /**
1096 : * Set both cell handlers for a channel.
1097 : *
1098 : * This function sets both the fixed-length and variable length cell handlers
1099 : * for a channel.
1100 : */
1101 : void
1102 2 : channel_set_cell_handlers(channel_t *chan,
1103 : channel_cell_handler_fn_ptr cell_handler)
1104 : {
1105 2 : tor_assert(chan);
1106 2 : tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1107 :
1108 2 : log_debug(LD_CHANNEL,
1109 : "Setting cell_handler callback for channel %p to %p",
1110 : chan, cell_handler);
1111 :
1112 : /* Change them */
1113 2 : chan->cell_handler = cell_handler;
1114 2 : }
1115 :
1116 : /*
1117 : * On closing channels
1118 : *
1119 : * There are three functions that close channels, for use in
1120 : * different circumstances:
1121 : *
1122 : * - Use channel_mark_for_close() for most cases
1123 : * - Use channel_close_from_lower_layer() if you are connection_or.c
1124 : * and the other end closes the underlying connection.
1125 : * - Use channel_close_for_error() if you are connection_or.c and
1126 : * some sort of error has occurred.
1127 : */
1128 :
1129 : /**
1130 : * Mark a channel for closure.
1131 : *
1132 : * This function tries to close a channel_t; it will go into the CLOSING
1133 : * state, and eventually the lower layer should put it into the CLOSED or
1134 : * ERROR state. Then, channel_run_cleanup() will eventually free it.
1135 : */
1136 : void
1137 23 : channel_mark_for_close(channel_t *chan)
1138 : {
1139 23 : tor_assert(chan != NULL);
1140 23 : tor_assert(chan->close != NULL);
1141 :
1142 : /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1143 23 : if (CHANNEL_CONDEMNED(chan))
1144 : return;
1145 :
1146 23 : log_debug(LD_CHANNEL,
1147 : "Closing channel %p (global ID %"PRIu64 ") "
1148 : "by request",
1149 : chan, (chan->global_identifier));
1150 :
1151 : /* Note closing by request from above */
1152 23 : chan->reason_for_closing = CHANNEL_CLOSE_REQUESTED;
1153 :
1154 : /* Change state to CLOSING */
1155 23 : channel_change_state(chan, CHANNEL_STATE_CLOSING);
1156 :
1157 : /* Tell the lower layer */
1158 23 : chan->close(chan);
1159 :
1160 : /*
1161 : * It's up to the lower layer to change state to CLOSED or ERROR when we're
1162 : * ready; we'll try to free channels that are in the finished list from
1163 : * channel_run_cleanup(). The lower layer should do this by calling
1164 : * channel_closed().
1165 : */
1166 : }
1167 :
1168 : /**
1169 : * Mark a channel listener for closure.
1170 : *
1171 : * This function tries to close a channel_listener_t; it will go into the
1172 : * CLOSING state, and eventually the lower layer should put it into the CLOSED
1173 : * or ERROR state. Then, channel_run_cleanup() will eventually free it.
1174 : */
1175 : void
1176 1 : channel_listener_mark_for_close(channel_listener_t *chan_l)
1177 : {
1178 1 : tor_assert(chan_l != NULL);
1179 1 : tor_assert(chan_l->close != NULL);
1180 :
1181 : /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1182 1 : if (chan_l->state == CHANNEL_LISTENER_STATE_CLOSING ||
1183 1 : chan_l->state == CHANNEL_LISTENER_STATE_CLOSED ||
1184 : chan_l->state == CHANNEL_LISTENER_STATE_ERROR) return;
1185 :
1186 1 : log_debug(LD_CHANNEL,
1187 : "Closing channel listener %p (global ID %"PRIu64 ") "
1188 : "by request",
1189 : chan_l, (chan_l->global_identifier));
1190 :
1191 : /* Note closing by request from above */
1192 1 : chan_l->reason_for_closing = CHANNEL_LISTENER_CLOSE_REQUESTED;
1193 :
1194 : /* Change state to CLOSING */
1195 1 : channel_listener_change_state(chan_l, CHANNEL_LISTENER_STATE_CLOSING);
1196 :
1197 : /* Tell the lower layer */
1198 1 : chan_l->close(chan_l);
1199 :
1200 : /*
1201 : * It's up to the lower layer to change state to CLOSED or ERROR when we're
1202 : * ready; we'll try to free channels that are in the finished list from
1203 : * channel_run_cleanup(). The lower layer should do this by calling
1204 : * channel_listener_closed().
1205 : */
1206 : }
1207 :
1208 : /**
1209 : * Close a channel from the lower layer.
1210 : *
1211 : * Notify the channel code that the channel is being closed due to a non-error
1212 : * condition in the lower layer. This does not call the close() method, since
1213 : * the lower layer already knows.
1214 : */
1215 : void
1216 1 : channel_close_from_lower_layer(channel_t *chan)
1217 : {
1218 1 : tor_assert(chan != NULL);
1219 :
1220 : /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1221 1 : if (CHANNEL_CONDEMNED(chan))
1222 : return;
1223 :
1224 1 : log_debug(LD_CHANNEL,
1225 : "Closing channel %p (global ID %"PRIu64 ") "
1226 : "due to lower-layer event",
1227 : chan, (chan->global_identifier));
1228 :
1229 : /* Note closing by event from below */
1230 1 : chan->reason_for_closing = CHANNEL_CLOSE_FROM_BELOW;
1231 :
1232 : /* Change state to CLOSING */
1233 1 : channel_change_state(chan, CHANNEL_STATE_CLOSING);
1234 : }
1235 :
1236 : /**
1237 : * Notify that the channel is being closed due to an error condition.
1238 : *
1239 : * This function is called by the lower layer implementing the transport
1240 : * when a channel must be closed due to an error condition. This does not
1241 : * call the channel's close method, since the lower layer already knows.
1242 : */
1243 : void
1244 26 : channel_close_for_error(channel_t *chan)
1245 : {
1246 26 : tor_assert(chan != NULL);
1247 :
1248 : /* If it's already in CLOSING, CLOSED or ERROR, this is a no-op */
1249 26 : if (CHANNEL_CONDEMNED(chan))
1250 : return;
1251 :
1252 26 : log_debug(LD_CHANNEL,
1253 : "Closing channel %p due to lower-layer error",
1254 : chan);
1255 :
1256 : /* Note closing by event from below */
1257 26 : chan->reason_for_closing = CHANNEL_CLOSE_FOR_ERROR;
1258 :
1259 : /* Change state to CLOSING */
1260 26 : channel_change_state(chan, CHANNEL_STATE_CLOSING);
1261 : }
1262 :
1263 : /**
1264 : * Notify that the lower layer is finished closing the channel.
1265 : *
1266 : * This function should be called by the lower layer when a channel
1267 : * is finished closing and it should be regarded as inactive and
1268 : * freed by the channel code.
1269 : */
1270 : void
1271 19 : channel_closed(channel_t *chan)
1272 : {
1273 19 : tor_assert(chan);
1274 19 : tor_assert(CHANNEL_CONDEMNED(chan));
1275 :
1276 : /* No-op if already inactive */
1277 19 : if (CHANNEL_FINISHED(chan))
1278 : return;
1279 :
1280 : /* Inform any pending (not attached) circs that they should
1281 : * give up. */
1282 19 : if (! chan->has_been_open)
1283 12 : circuit_n_chan_done(chan, 0, 0);
1284 :
1285 : /* Now close all the attached circuits on it. */
1286 19 : circuit_unlink_all_from_channel(chan, END_CIRC_REASON_CHANNEL_CLOSED);
1287 :
1288 19 : if (chan->reason_for_closing != CHANNEL_CLOSE_FOR_ERROR) {
1289 17 : channel_change_state(chan, CHANNEL_STATE_CLOSED);
1290 : } else {
1291 2 : channel_change_state(chan, CHANNEL_STATE_ERROR);
1292 : }
1293 : }
1294 :
1295 : /**
1296 : * Clear the identity_digest of a channel.
1297 : *
1298 : * This function clears the identity digest of the remote endpoint for a
1299 : * channel; this is intended for use by the lower layer.
1300 : */
1301 : void
1302 6 : channel_clear_identity_digest(channel_t *chan)
1303 : {
1304 6 : int state_not_in_map;
1305 :
1306 6 : tor_assert(chan);
1307 :
1308 6 : log_debug(LD_CHANNEL,
1309 : "Clearing remote endpoint digest on channel %p with "
1310 : "global ID %"PRIu64,
1311 : chan, (chan->global_identifier));
1312 :
1313 6 : state_not_in_map = CHANNEL_CONDEMNED(chan);
1314 :
1315 12 : if (!state_not_in_map && chan->registered &&
1316 6 : !tor_digest_is_zero(chan->identity_digest))
1317 : /* if it's registered get it out of the digest map */
1318 6 : channel_remove_from_digest_map(chan);
1319 :
1320 6 : memset(chan->identity_digest, 0,
1321 : sizeof(chan->identity_digest));
1322 6 : }
1323 :
1324 : /**
1325 : * Set the identity_digest of a channel.
1326 : *
1327 : * This function sets the identity digest of the remote endpoint for a
1328 : * channel; this is intended for use by the lower layer.
1329 : */
1330 : void
1331 13 : channel_set_identity_digest(channel_t *chan,
1332 : const char *identity_digest,
1333 : const ed25519_public_key_t *ed_identity)
1334 : {
1335 13 : int was_in_digest_map, should_be_in_digest_map, state_not_in_map;
1336 :
1337 13 : tor_assert(chan);
1338 :
1339 13 : log_debug(LD_CHANNEL,
1340 : "Setting remote endpoint digest on channel %p with "
1341 : "global ID %"PRIu64 " to digest %s",
1342 : chan, (chan->global_identifier),
1343 : identity_digest ?
1344 : hex_str(identity_digest, DIGEST_LEN) : "(null)");
1345 :
1346 13 : state_not_in_map = CHANNEL_CONDEMNED(chan);
1347 :
1348 23 : was_in_digest_map =
1349 10 : !state_not_in_map &&
1350 8 : chan->registered &&
1351 8 : !tor_digest_is_zero(chan->identity_digest);
1352 26 : should_be_in_digest_map =
1353 10 : !state_not_in_map &&
1354 21 : chan->registered &&
1355 8 : (identity_digest &&
1356 8 : !tor_digest_is_zero(identity_digest));
1357 :
1358 13 : if (was_in_digest_map)
1359 : /* We should always remove it; we'll add it back if we're writing
1360 : * in a new digest.
1361 : */
1362 0 : channel_remove_from_digest_map(chan);
1363 :
1364 13 : if (identity_digest) {
1365 13 : memcpy(chan->identity_digest,
1366 : identity_digest,
1367 : sizeof(chan->identity_digest));
1368 : } else {
1369 0 : memset(chan->identity_digest, 0,
1370 : sizeof(chan->identity_digest));
1371 : }
1372 13 : if (ed_identity) {
1373 9 : memcpy(&chan->ed25519_identity, ed_identity, sizeof(*ed_identity));
1374 : } else {
1375 4 : memset(&chan->ed25519_identity, 0, sizeof(*ed_identity));
1376 : }
1377 :
1378 : /* Put it in the digest map if we should */
1379 13 : if (should_be_in_digest_map)
1380 8 : channel_add_to_digest_map(chan);
1381 13 : }
1382 :
1383 : /**
1384 : * Clear the remote end metadata (identity_digest) of a channel.
1385 : *
1386 : * This function clears all the remote end info from a channel; this is
1387 : * intended for use by the lower layer.
1388 : */
1389 : void
1390 24 : channel_clear_remote_end(channel_t *chan)
1391 : {
1392 24 : int state_not_in_map;
1393 :
1394 24 : tor_assert(chan);
1395 :
1396 24 : log_debug(LD_CHANNEL,
1397 : "Clearing remote endpoint identity on channel %p with "
1398 : "global ID %"PRIu64,
1399 : chan, (chan->global_identifier));
1400 :
1401 24 : state_not_in_map = CHANNEL_CONDEMNED(chan);
1402 :
1403 0 : if (!state_not_in_map && chan->registered &&
1404 0 : !tor_digest_is_zero(chan->identity_digest))
1405 : /* if it's registered get it out of the digest map */
1406 0 : channel_remove_from_digest_map(chan);
1407 :
1408 24 : memset(chan->identity_digest, 0,
1409 : sizeof(chan->identity_digest));
1410 24 : }
1411 :
1412 : /**
1413 : * Write to a channel the given packed cell.
1414 : *
1415 : * Two possible errors can happen. Either the channel is not opened or the
1416 : * lower layer (specialized channel) failed to write it. In both cases, it is
1417 : * the caller responsibility to free the cell.
1418 : */
1419 : static int
1420 4 : write_packed_cell(channel_t *chan, packed_cell_t *cell)
1421 : {
1422 4 : int ret = -1;
1423 4 : size_t cell_bytes;
1424 4 : uint8_t command = packed_cell_get_command(cell, chan->wide_circ_ids);
1425 :
1426 4 : tor_assert(chan);
1427 4 : tor_assert(cell);
1428 :
1429 : /* Assert that the state makes sense for a cell write */
1430 4 : tor_assert(CHANNEL_CAN_HANDLE_CELLS(chan));
1431 :
1432 : {
1433 4 : circid_t circ_id;
1434 4 : if (packed_cell_is_destroy(chan, cell, &circ_id)) {
1435 0 : channel_note_destroy_not_pending(chan, circ_id);
1436 : }
1437 : }
1438 :
1439 : /* For statistical purposes, figure out how big this cell is */
1440 4 : cell_bytes = get_cell_network_size(chan->wide_circ_ids);
1441 :
1442 : /* Can we send it right out? If so, try */
1443 4 : if (!CHANNEL_IS_OPEN(chan)) {
1444 1 : goto done;
1445 : }
1446 :
1447 : /* Write the cell on the connection's outbuf. */
1448 3 : if (chan->write_packed_cell(chan, cell) < 0) {
1449 0 : goto done;
1450 : }
1451 : /* Timestamp for transmission */
1452 3 : channel_timestamp_xmit(chan);
1453 : /* Update the counter */
1454 3 : ++(chan->n_cells_xmitted);
1455 3 : chan->n_bytes_xmitted += cell_bytes;
1456 : /* Successfully sent the cell. */
1457 3 : ret = 0;
1458 :
1459 : /* Update padding statistics for the packed codepath.. */
1460 3 : rep_hist_padding_count_write(PADDING_TYPE_TOTAL);
1461 3 : if (command == CELL_PADDING)
1462 3 : rep_hist_padding_count_write(PADDING_TYPE_CELL);
1463 3 : if (chan->padding_enabled) {
1464 0 : rep_hist_padding_count_write(PADDING_TYPE_ENABLED_TOTAL);
1465 0 : if (command == CELL_PADDING)
1466 0 : rep_hist_padding_count_write(PADDING_TYPE_ENABLED_CELL);
1467 : }
1468 :
1469 3 : done:
1470 4 : return ret;
1471 : }
1472 :
1473 : /**
1474 : * Write a packed cell to a channel.
1475 : *
1476 : * Write a packed cell to a channel using the write_cell() method. This is
1477 : * called by the transport-independent code to deliver a packed cell to a
1478 : * channel for transmission.
1479 : *
1480 : * Return 0 on success else a negative value. In both cases, the caller should
1481 : * not access the cell anymore, it is freed both on success and error.
1482 : */
1483 : int
1484 4 : channel_write_packed_cell(channel_t *chan, packed_cell_t *cell)
1485 : {
1486 4 : int ret = -1;
1487 :
1488 4 : tor_assert(chan);
1489 4 : tor_assert(cell);
1490 :
1491 4 : if (CHANNEL_IS_CLOSING(chan)) {
1492 0 : log_debug(LD_CHANNEL, "Discarding %p on closing channel %p with "
1493 : "global ID %"PRIu64, cell, chan,
1494 : (chan->global_identifier));
1495 0 : goto end;
1496 : }
1497 4 : log_debug(LD_CHANNEL,
1498 : "Writing %p to channel %p with global ID "
1499 : "%"PRIu64, cell, chan, (chan->global_identifier));
1500 :
1501 4 : ret = write_packed_cell(chan, cell);
1502 :
1503 4 : end:
1504 : /* Whatever happens, we free the cell. Either an error occurred or the cell
1505 : * was put on the connection outbuf, both cases we have ownership of the
1506 : * cell and we free it. */
1507 4 : packed_cell_free(cell);
1508 4 : return ret;
1509 : }
1510 :
1511 : /**
1512 : * Change channel state.
1513 : *
1514 : * This internal and subclass use only function is used to change channel
1515 : * state, performing all transition validity checks and whatever actions
1516 : * are appropriate to the state transition in question.
1517 : */
1518 : static void
1519 86 : channel_change_state_(channel_t *chan, channel_state_t to_state)
1520 : {
1521 86 : channel_state_t from_state;
1522 86 : unsigned char was_active, is_active;
1523 86 : unsigned char was_in_id_map, is_in_id_map;
1524 :
1525 86 : tor_assert(chan);
1526 86 : from_state = chan->state;
1527 :
1528 86 : tor_assert(channel_state_is_valid(from_state));
1529 86 : tor_assert(channel_state_is_valid(to_state));
1530 86 : tor_assert(channel_state_can_transition(chan->state, to_state));
1531 :
1532 : /* Check for no-op transitions */
1533 86 : if (from_state == to_state) {
1534 0 : log_debug(LD_CHANNEL,
1535 : "Got no-op transition from \"%s\" to itself on channel %p"
1536 : "(global ID %"PRIu64 ")",
1537 : channel_state_to_string(to_state),
1538 : chan, (chan->global_identifier));
1539 0 : return;
1540 : }
1541 :
1542 : /* If we're going to a closing or closed state, we must have a reason set */
1543 86 : if (to_state == CHANNEL_STATE_CLOSING ||
1544 86 : to_state == CHANNEL_STATE_CLOSED ||
1545 : to_state == CHANNEL_STATE_ERROR) {
1546 69 : tor_assert(chan->reason_for_closing != CHANNEL_NOT_CLOSING);
1547 : }
1548 :
1549 86 : log_debug(LD_CHANNEL,
1550 : "Changing state of channel %p (global ID %"PRIu64
1551 : ") from \"%s\" to \"%s\"",
1552 : chan,
1553 : (chan->global_identifier),
1554 : channel_state_to_string(chan->state),
1555 : channel_state_to_string(to_state));
1556 :
1557 86 : chan->state = to_state;
1558 :
1559 : /* Need to add to the right lists if the channel is registered */
1560 86 : if (chan->registered) {
1561 55 : was_active = !(from_state == CHANNEL_STATE_CLOSED ||
1562 55 : from_state == CHANNEL_STATE_ERROR);
1563 55 : is_active = !(to_state == CHANNEL_STATE_CLOSED ||
1564 55 : to_state == CHANNEL_STATE_ERROR);
1565 :
1566 : /* Need to take off active list and put on finished list? */
1567 55 : if (was_active && !is_active) {
1568 19 : if (active_channels) smartlist_remove(active_channels, chan);
1569 19 : if (!finished_channels) finished_channels = smartlist_new();
1570 19 : smartlist_add(finished_channels, chan);
1571 19 : mainloop_schedule_postloop_cleanup();
1572 : }
1573 : /* Need to put on active list? */
1574 36 : else if (!was_active && is_active) {
1575 0 : if (finished_channels) smartlist_remove(finished_channels, chan);
1576 0 : if (!active_channels) active_channels = smartlist_new();
1577 0 : smartlist_add(active_channels, chan);
1578 : }
1579 :
1580 55 : if (!tor_digest_is_zero(chan->identity_digest)) {
1581 : /* Now we need to handle the identity map */
1582 0 : was_in_id_map = !(from_state == CHANNEL_STATE_CLOSING ||
1583 : from_state == CHANNEL_STATE_CLOSED ||
1584 : from_state == CHANNEL_STATE_ERROR);
1585 0 : is_in_id_map = !(to_state == CHANNEL_STATE_CLOSING ||
1586 : to_state == CHANNEL_STATE_CLOSED ||
1587 : to_state == CHANNEL_STATE_ERROR);
1588 :
1589 0 : if (!was_in_id_map && is_in_id_map) channel_add_to_digest_map(chan);
1590 0 : else if (was_in_id_map && !is_in_id_map)
1591 0 : channel_remove_from_digest_map(chan);
1592 : }
1593 : }
1594 :
1595 : /*
1596 : * If we're going to a closed/closing state, we don't need scheduling any
1597 : * more; in CHANNEL_STATE_MAINT we can't accept writes.
1598 : */
1599 86 : if (to_state == CHANNEL_STATE_CLOSING ||
1600 19 : to_state == CHANNEL_STATE_CLOSED ||
1601 : to_state == CHANNEL_STATE_ERROR) {
1602 69 : scheduler_release_channel(chan);
1603 17 : } else if (to_state == CHANNEL_STATE_MAINT) {
1604 4 : scheduler_channel_doesnt_want_writes(chan);
1605 : }
1606 : }
1607 :
1608 : /**
1609 : * As channel_change_state_, but change the state to any state but open.
1610 : */
1611 : void
1612 73 : channel_change_state(channel_t *chan, channel_state_t to_state)
1613 : {
1614 73 : tor_assert(to_state != CHANNEL_STATE_OPEN);
1615 73 : channel_change_state_(chan, to_state);
1616 73 : }
1617 :
1618 : /**
1619 : * As channel_change_state, but change the state to open.
1620 : */
1621 : void
1622 13 : channel_change_state_open(channel_t *chan)
1623 : {
1624 13 : channel_change_state_(chan, CHANNEL_STATE_OPEN);
1625 :
1626 : /* Tell circuits if we opened and stuff */
1627 13 : channel_do_open_actions(chan);
1628 13 : chan->has_been_open = 1;
1629 13 : }
1630 :
1631 : /**
1632 : * Change channel listener state.
1633 : *
1634 : * This internal and subclass use only function is used to change channel
1635 : * listener state, performing all transition validity checks and whatever
1636 : * actions are appropriate to the state transition in question.
1637 : */
1638 : void
1639 2 : channel_listener_change_state(channel_listener_t *chan_l,
1640 : channel_listener_state_t to_state)
1641 : {
1642 2 : channel_listener_state_t from_state;
1643 2 : unsigned char was_active, is_active;
1644 :
1645 2 : tor_assert(chan_l);
1646 2 : from_state = chan_l->state;
1647 :
1648 2 : tor_assert(channel_listener_state_is_valid(from_state));
1649 2 : tor_assert(channel_listener_state_is_valid(to_state));
1650 2 : tor_assert(channel_listener_state_can_transition(chan_l->state, to_state));
1651 :
1652 : /* Check for no-op transitions */
1653 2 : if (from_state == to_state) {
1654 0 : log_debug(LD_CHANNEL,
1655 : "Got no-op transition from \"%s\" to itself on channel "
1656 : "listener %p (global ID %"PRIu64 ")",
1657 : channel_listener_state_to_string(to_state),
1658 : chan_l, (chan_l->global_identifier));
1659 0 : return;
1660 : }
1661 :
1662 : /* If we're going to a closing or closed state, we must have a reason set */
1663 2 : if (to_state == CHANNEL_LISTENER_STATE_CLOSING ||
1664 2 : to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1665 : to_state == CHANNEL_LISTENER_STATE_ERROR) {
1666 2 : tor_assert(chan_l->reason_for_closing != CHANNEL_LISTENER_NOT_CLOSING);
1667 : }
1668 :
1669 2 : log_debug(LD_CHANNEL,
1670 : "Changing state of channel listener %p (global ID %"PRIu64
1671 : "from \"%s\" to \"%s\"",
1672 : chan_l, (chan_l->global_identifier),
1673 : channel_listener_state_to_string(chan_l->state),
1674 : channel_listener_state_to_string(to_state));
1675 :
1676 2 : chan_l->state = to_state;
1677 :
1678 : /* Need to add to the right lists if the channel listener is registered */
1679 2 : if (chan_l->registered) {
1680 2 : was_active = !(from_state == CHANNEL_LISTENER_STATE_CLOSED ||
1681 2 : from_state == CHANNEL_LISTENER_STATE_ERROR);
1682 2 : is_active = !(to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1683 2 : to_state == CHANNEL_LISTENER_STATE_ERROR);
1684 :
1685 : /* Need to take off active list and put on finished list? */
1686 2 : if (was_active && !is_active) {
1687 1 : if (active_listeners) smartlist_remove(active_listeners, chan_l);
1688 1 : if (!finished_listeners) finished_listeners = smartlist_new();
1689 1 : smartlist_add(finished_listeners, chan_l);
1690 1 : mainloop_schedule_postloop_cleanup();
1691 : }
1692 : /* Need to put on active list? */
1693 1 : else if (!was_active && is_active) {
1694 0 : if (finished_listeners) smartlist_remove(finished_listeners, chan_l);
1695 0 : if (!active_listeners) active_listeners = smartlist_new();
1696 0 : smartlist_add(active_listeners, chan_l);
1697 : }
1698 : }
1699 :
1700 2 : if (to_state == CHANNEL_LISTENER_STATE_CLOSED ||
1701 2 : to_state == CHANNEL_LISTENER_STATE_ERROR) {
1702 1 : tor_assert(!(chan_l->incoming_list) ||
1703 : smartlist_len(chan_l->incoming_list) == 0);
1704 : }
1705 : }
1706 :
1707 : /* Maximum number of cells that is allowed to flush at once within
1708 : * channel_flush_some_cells(). */
1709 : #define MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED 256
1710 :
1711 : /**
1712 : * Try to flush cells of the given channel chan up to a maximum of num_cells.
1713 : *
1714 : * This is called by the scheduler when it wants to flush cells from the
1715 : * channel's circuit queue(s) to the connection outbuf (not yet on the wire).
1716 : *
1717 : * If the channel is not in state CHANNEL_STATE_OPEN, this does nothing and
1718 : * will return 0 meaning no cells were flushed.
1719 : *
1720 : * If num_cells is -1, we'll try to flush up to the maximum cells allowed
1721 : * defined in MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED.
1722 : *
1723 : * On success, the number of flushed cells are returned and it can never be
1724 : * above num_cells. If 0 is returned, no cells were flushed either because the
1725 : * channel was not opened or we had no cells on the channel. A negative number
1726 : * can NOT be sent back.
1727 : *
1728 : * This function is part of the fast path. */
1729 4 : MOCK_IMPL(ssize_t,
1730 : channel_flush_some_cells, (channel_t *chan, ssize_t num_cells))
1731 : {
1732 4 : unsigned int unlimited = 0;
1733 4 : ssize_t flushed = 0;
1734 4 : int clamped_num_cells;
1735 :
1736 4 : tor_assert(chan);
1737 :
1738 4 : if (num_cells < 0) unlimited = 1;
1739 4 : if (!unlimited && num_cells <= flushed) goto done;
1740 :
1741 : /* If we aren't in CHANNEL_STATE_OPEN, nothing goes through */
1742 4 : if (CHANNEL_IS_OPEN(chan)) {
1743 4 : if (circuitmux_num_cells(chan->cmux) > 0) {
1744 : /* Calculate number of cells, including clamp */
1745 2 : if (unlimited) {
1746 : clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
1747 : } else {
1748 2 : if (num_cells - flushed >
1749 : MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED) {
1750 : clamped_num_cells = MAX_CELLS_TO_GET_FROM_CIRCUITS_FOR_UNLIMITED;
1751 : } else {
1752 2 : clamped_num_cells = (int)(num_cells - flushed);
1753 : }
1754 : }
1755 :
1756 : /* Try to get more cells from any active circuits */
1757 2 : flushed = channel_flush_from_first_active_circuit(
1758 : chan, clamped_num_cells);
1759 : }
1760 : }
1761 :
1762 2 : done:
1763 4 : return flushed;
1764 : }
1765 :
1766 : /**
1767 : * Check if any cells are available.
1768 : *
1769 : * This is used by the scheduler to know if the channel has more to flush
1770 : * after a scheduling round.
1771 : */
1772 4 : MOCK_IMPL(int,
1773 : channel_more_to_flush, (channel_t *chan))
1774 : {
1775 4 : tor_assert(chan);
1776 :
1777 4 : if (circuitmux_num_cells(chan->cmux) > 0) return 1;
1778 :
1779 : /* Else no */
1780 : return 0;
1781 : }
1782 :
1783 : /**
1784 : * Notify the channel we're done flushing the output in the lower layer.
1785 : *
1786 : * Connection.c will call this when we've flushed the output; there's some
1787 : * dirreq-related maintenance to do.
1788 : */
1789 : void
1790 0 : channel_notify_flushed(channel_t *chan)
1791 : {
1792 0 : tor_assert(chan);
1793 :
1794 0 : if (chan->dirreq_id != 0)
1795 0 : geoip_change_dirreq_state(chan->dirreq_id,
1796 : DIRREQ_TUNNELED,
1797 : DIRREQ_CHANNEL_BUFFER_FLUSHED);
1798 0 : }
1799 :
1800 : /**
1801 : * Process the queue of incoming channels on a listener.
1802 : *
1803 : * Use a listener's registered callback to process as many entries in the
1804 : * queue of incoming channels as possible.
1805 : */
1806 : void
1807 1 : channel_listener_process_incoming(channel_listener_t *listener)
1808 : {
1809 1 : tor_assert(listener);
1810 :
1811 : /*
1812 : * CHANNEL_LISTENER_STATE_CLOSING permitted because we drain the queue
1813 : * while closing a listener.
1814 : */
1815 1 : tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING ||
1816 : listener->state == CHANNEL_LISTENER_STATE_CLOSING);
1817 1 : tor_assert(listener->listener);
1818 :
1819 1 : log_debug(LD_CHANNEL,
1820 : "Processing queue of incoming connections for channel "
1821 : "listener %p (global ID %"PRIu64 ")",
1822 : listener, (listener->global_identifier));
1823 :
1824 1 : if (!(listener->incoming_list)) return;
1825 :
1826 0 : SMARTLIST_FOREACH_BEGIN(listener->incoming_list,
1827 : channel_t *, chan) {
1828 0 : tor_assert(chan);
1829 :
1830 0 : log_debug(LD_CHANNEL,
1831 : "Handling incoming channel %p (%"PRIu64 ") "
1832 : "for listener %p (%"PRIu64 ")",
1833 : chan,
1834 : (chan->global_identifier),
1835 : listener,
1836 : (listener->global_identifier));
1837 : /* Make sure this is set correctly */
1838 0 : channel_mark_incoming(chan);
1839 0 : listener->listener(listener, chan);
1840 0 : } SMARTLIST_FOREACH_END(chan);
1841 :
1842 0 : smartlist_free(listener->incoming_list);
1843 0 : listener->incoming_list = NULL;
1844 : }
1845 :
1846 : /**
1847 : * Take actions required when a channel becomes open.
1848 : *
1849 : * Handle actions we should do when we know a channel is open; a lot of
1850 : * this comes from the old connection_or_set_state_open() of connection_or.c.
1851 : *
1852 : * Because of this mechanism, future channel_t subclasses should take care
1853 : * not to change a channel from CHANNEL_STATE_OPENING to CHANNEL_STATE_OPEN
1854 : * until there is positive confirmation that the network is operational.
1855 : * In particular, anything UDP-based should not make this transition until a
1856 : * packet is received from the other side.
1857 : */
1858 : void
1859 21 : channel_do_open_actions(channel_t *chan)
1860 : {
1861 21 : tor_addr_t remote_addr;
1862 21 : int started_here;
1863 21 : time_t now = time(NULL);
1864 21 : int close_origin_circuits = 0;
1865 :
1866 21 : tor_assert(chan);
1867 :
1868 21 : started_here = channel_is_outgoing(chan);
1869 :
1870 21 : if (started_here) {
1871 21 : circuit_build_times_network_is_live(get_circuit_build_times_mutable());
1872 21 : router_set_status(chan->identity_digest, 1);
1873 : } else {
1874 : /* only report it to the geoip module if it's a client */
1875 0 : if (channel_is_client(chan)) {
1876 0 : if (channel_get_addr_if_possible(chan, &remote_addr)) {
1877 0 : char *transport_name = NULL;
1878 0 : channel_tls_t *tlschan = BASE_CHAN_TO_TLS(chan);
1879 0 : if (chan->get_transport_name(chan, &transport_name) < 0)
1880 0 : transport_name = NULL;
1881 :
1882 0 : geoip_note_client_seen(GEOIP_CLIENT_CONNECT,
1883 : &remote_addr, transport_name,
1884 : now);
1885 : /* Notify the DoS subsystem of a new client. */
1886 0 : if (tlschan && tlschan->conn) {
1887 0 : dos_new_client_conn(tlschan->conn, transport_name);
1888 : }
1889 0 : tor_free(transport_name);
1890 : }
1891 : /* Otherwise the underlying transport can't tell us this, so skip it */
1892 : }
1893 : }
1894 :
1895 : /* Disable or reduce padding according to user prefs. */
1896 21 : if (chan->padding_enabled || get_options()->ConnectionPadding == 1) {
1897 8 : if (!get_options()->ConnectionPadding) {
1898 : /* Disable if torrc disabled */
1899 0 : channelpadding_disable_padding_on_channel(chan);
1900 8 : } else if (hs_service_allow_non_anonymous_connection(get_options()) &&
1901 0 : !networkstatus_get_param(NULL,
1902 : CHANNELPADDING_SOS_PARAM,
1903 : CHANNELPADDING_SOS_DEFAULT, 0, 1)) {
1904 : /* Disable if we're using RSOS and the consensus disabled padding
1905 : * for RSOS */
1906 0 : channelpadding_disable_padding_on_channel(chan);
1907 8 : } else if (get_options()->ReducedConnectionPadding) {
1908 : /* Padding can be forced and/or reduced by clients, regardless of if
1909 : * the channel supports it */
1910 0 : channelpadding_reduce_padding_on_channel(chan);
1911 : }
1912 : }
1913 :
1914 21 : circuit_n_chan_done(chan, 1, close_origin_circuits);
1915 21 : }
1916 :
1917 : /**
1918 : * Queue an incoming channel on a listener.
1919 : *
1920 : * Internal and subclass use only function to queue an incoming channel from
1921 : * a listener. A subclass of channel_listener_t should call this when a new
1922 : * incoming channel is created.
1923 : */
1924 : void
1925 1 : channel_listener_queue_incoming(channel_listener_t *listener,
1926 : channel_t *incoming)
1927 : {
1928 1 : int need_to_queue = 0;
1929 :
1930 1 : tor_assert(listener);
1931 1 : tor_assert(listener->state == CHANNEL_LISTENER_STATE_LISTENING);
1932 1 : tor_assert(incoming);
1933 :
1934 1 : log_debug(LD_CHANNEL,
1935 : "Queueing incoming channel %p (global ID %"PRIu64 ") on "
1936 : "channel listener %p (global ID %"PRIu64 ")",
1937 : incoming, (incoming->global_identifier),
1938 : listener, (listener->global_identifier));
1939 :
1940 : /* Do we need to queue it, or can we just call the listener right away? */
1941 1 : if (!(listener->listener)) need_to_queue = 1;
1942 1 : if (listener->incoming_list &&
1943 0 : (smartlist_len(listener->incoming_list) > 0))
1944 : need_to_queue = 1;
1945 :
1946 : /* If we need to queue and have no queue, create one */
1947 1 : if (need_to_queue && !(listener->incoming_list)) {
1948 0 : listener->incoming_list = smartlist_new();
1949 : }
1950 :
1951 : /* Bump the counter and timestamp it */
1952 1 : channel_listener_timestamp_active(listener);
1953 1 : channel_listener_timestamp_accepted(listener);
1954 1 : ++(listener->n_accepted);
1955 :
1956 : /* If we don't need to queue, process it right away */
1957 1 : if (!need_to_queue) {
1958 1 : tor_assert(listener->listener);
1959 1 : listener->listener(listener, incoming);
1960 : }
1961 : /*
1962 : * Otherwise, we need to queue; queue and then process the queue if
1963 : * we can.
1964 : */
1965 : else {
1966 0 : tor_assert(listener->incoming_list);
1967 0 : smartlist_add(listener->incoming_list, incoming);
1968 0 : if (listener->listener) channel_listener_process_incoming(listener);
1969 : }
1970 1 : }
1971 :
1972 : /**
1973 : * Process a cell from the given channel.
1974 : */
1975 : void
1976 3 : channel_process_cell(channel_t *chan, cell_t *cell)
1977 : {
1978 3 : tor_assert(chan);
1979 3 : tor_assert(CHANNEL_IS_CLOSING(chan) || CHANNEL_IS_MAINT(chan) ||
1980 : CHANNEL_IS_OPEN(chan));
1981 3 : tor_assert(cell);
1982 :
1983 : /* Nothing we can do if we have no registered cell handlers */
1984 3 : if (!chan->cell_handler)
1985 : return;
1986 :
1987 : /* Timestamp for receiving */
1988 2 : channel_timestamp_recv(chan);
1989 : /* Update received counter. */
1990 2 : ++(chan->n_cells_recved);
1991 2 : chan->n_bytes_recved += get_cell_network_size(chan->wide_circ_ids);
1992 :
1993 2 : log_debug(LD_CHANNEL,
1994 : "Processing incoming cell_t %p for channel %p (global ID "
1995 : "%"PRIu64 ")", cell, chan,
1996 : (chan->global_identifier));
1997 2 : chan->cell_handler(chan, cell);
1998 : }
1999 :
2000 : /** If <b>packed_cell</b> on <b>chan</b> is a destroy cell, then set
2001 : * *<b>circid_out</b> to its circuit ID, and return true. Otherwise, return
2002 : * false. */
2003 : /* XXXX Move this function. */
2004 : int
2005 8 : packed_cell_is_destroy(channel_t *chan,
2006 : const packed_cell_t *packed_cell,
2007 : circid_t *circid_out)
2008 : {
2009 8 : if (chan->wide_circ_ids) {
2010 2 : if (packed_cell->body[4] == CELL_DESTROY) {
2011 1 : *circid_out = ntohl(get_uint32(packed_cell->body));
2012 1 : return 1;
2013 : }
2014 : } else {
2015 6 : if (packed_cell->body[2] == CELL_DESTROY) {
2016 1 : *circid_out = ntohs(get_uint16(packed_cell->body));
2017 1 : return 1;
2018 : }
2019 : }
2020 : return 0;
2021 : }
2022 :
2023 : /**
2024 : * Send destroy cell on a channel.
2025 : *
2026 : * Write a destroy cell with circ ID <b>circ_id</b> and reason <b>reason</b>
2027 : * onto channel <b>chan</b>. Don't perform range-checking on reason:
2028 : * we may want to propagate reasons from other cells.
2029 : */
2030 : int
2031 0 : channel_send_destroy(circid_t circ_id, channel_t *chan, int reason)
2032 : {
2033 0 : tor_assert(chan);
2034 0 : if (circ_id == 0) {
2035 0 : log_warn(LD_BUG, "Attempted to send a destroy cell for circID 0 "
2036 : "on a channel %"PRIu64 " at %p in state %s (%d)",
2037 : (chan->global_identifier),
2038 : chan, channel_state_to_string(chan->state),
2039 : chan->state);
2040 0 : return 0;
2041 : }
2042 :
2043 : /* Check to make sure we can send on this channel first */
2044 0 : if (!CHANNEL_CONDEMNED(chan) && chan->cmux) {
2045 0 : channel_note_destroy_pending(chan, circ_id);
2046 0 : circuitmux_append_destroy_cell(chan, chan->cmux, circ_id, reason);
2047 0 : log_debug(LD_OR,
2048 : "Sending destroy (circID %u) on channel %p "
2049 : "(global ID %"PRIu64 ")",
2050 : (unsigned)circ_id, chan,
2051 : (chan->global_identifier));
2052 : } else {
2053 0 : log_warn(LD_BUG,
2054 : "Someone called channel_send_destroy() for circID %u "
2055 : "on a channel %"PRIu64 " at %p in state %s (%d)",
2056 : (unsigned)circ_id, (chan->global_identifier),
2057 : chan, channel_state_to_string(chan->state),
2058 : chan->state);
2059 : }
2060 :
2061 : return 0;
2062 : }
2063 :
2064 : /**
2065 : * Dump channel statistics to the log.
2066 : *
2067 : * This is called from dumpstats() in main.c and spams the log with
2068 : * statistics on channels.
2069 : */
2070 : void
2071 3 : channel_dumpstats(int severity)
2072 : {
2073 3 : if (all_channels && smartlist_len(all_channels) > 0) {
2074 2 : tor_log(severity, LD_GENERAL,
2075 : "Dumping statistics about %d channels:",
2076 : smartlist_len(all_channels));
2077 3 : tor_log(severity, LD_GENERAL,
2078 : "%d are active, and %d are done and waiting for cleanup",
2079 2 : (active_channels != NULL) ?
2080 : smartlist_len(active_channels) : 0,
2081 2 : (finished_channels != NULL) ?
2082 : smartlist_len(finished_channels) : 0);
2083 :
2084 4 : SMARTLIST_FOREACH(all_channels, channel_t *, chan,
2085 : channel_dump_statistics(chan, severity));
2086 :
2087 2 : tor_log(severity, LD_GENERAL,
2088 : "Done spamming about channels now");
2089 : } else {
2090 1 : tor_log(severity, LD_GENERAL,
2091 : "No channels to dump");
2092 : }
2093 3 : }
2094 :
2095 : /**
2096 : * Dump channel listener statistics to the log.
2097 : *
2098 : * This is called from dumpstats() in main.c and spams the log with
2099 : * statistics on channel listeners.
2100 : */
2101 : void
2102 0 : channel_listener_dumpstats(int severity)
2103 : {
2104 0 : if (all_listeners && smartlist_len(all_listeners) > 0) {
2105 0 : tor_log(severity, LD_GENERAL,
2106 : "Dumping statistics about %d channel listeners:",
2107 : smartlist_len(all_listeners));
2108 0 : tor_log(severity, LD_GENERAL,
2109 : "%d are active and %d are done and waiting for cleanup",
2110 0 : (active_listeners != NULL) ?
2111 : smartlist_len(active_listeners) : 0,
2112 0 : (finished_listeners != NULL) ?
2113 : smartlist_len(finished_listeners) : 0);
2114 :
2115 0 : SMARTLIST_FOREACH(all_listeners, channel_listener_t *, chan_l,
2116 : channel_listener_dump_statistics(chan_l, severity));
2117 :
2118 0 : tor_log(severity, LD_GENERAL,
2119 : "Done spamming about channel listeners now");
2120 : } else {
2121 0 : tor_log(severity, LD_GENERAL,
2122 : "No channel listeners to dump");
2123 : }
2124 0 : }
2125 :
2126 : /**
2127 : * Clean up channels.
2128 : *
2129 : * This gets called periodically from run_scheduled_events() in main.c;
2130 : * it cleans up after closed channels.
2131 : */
2132 : void
2133 8 : channel_run_cleanup(void)
2134 : {
2135 8 : channel_t *tmp = NULL;
2136 :
2137 : /* Check if we need to do anything */
2138 8 : if (!finished_channels || smartlist_len(finished_channels) == 0) return;
2139 :
2140 : /* Iterate through finished_channels and get rid of them */
2141 16 : SMARTLIST_FOREACH_BEGIN(finished_channels, channel_t *, curr) {
2142 8 : tmp = curr;
2143 : /* Remove it from the list */
2144 8 : SMARTLIST_DEL_CURRENT(finished_channels, curr);
2145 : /* Also unregister it */
2146 8 : channel_unregister(tmp);
2147 : /* ... and free it */
2148 8 : channel_free(tmp);
2149 8 : } SMARTLIST_FOREACH_END(curr);
2150 : }
2151 :
2152 : /**
2153 : * Clean up channel listeners.
2154 : *
2155 : * This gets called periodically from run_scheduled_events() in main.c;
2156 : * it cleans up after closed channel listeners.
2157 : */
2158 : void
2159 0 : channel_listener_run_cleanup(void)
2160 : {
2161 0 : channel_listener_t *tmp = NULL;
2162 :
2163 : /* Check if we need to do anything */
2164 0 : if (!finished_listeners || smartlist_len(finished_listeners) == 0) return;
2165 :
2166 : /* Iterate through finished_channels and get rid of them */
2167 0 : SMARTLIST_FOREACH_BEGIN(finished_listeners, channel_listener_t *, curr) {
2168 0 : tmp = curr;
2169 : /* Remove it from the list */
2170 0 : SMARTLIST_DEL_CURRENT(finished_listeners, curr);
2171 : /* Also unregister it */
2172 0 : channel_listener_unregister(tmp);
2173 : /* ... and free it */
2174 0 : channel_listener_free(tmp);
2175 0 : } SMARTLIST_FOREACH_END(curr);
2176 : }
2177 :
2178 : /**
2179 : * Free a list of channels for channel_free_all().
2180 : */
2181 : static void
2182 29 : channel_free_list(smartlist_t *channels, int mark_for_close)
2183 : {
2184 29 : if (!channels) return;
2185 :
2186 29 : SMARTLIST_FOREACH_BEGIN(channels, channel_t *, curr) {
2187 : /* Deregister and free it */
2188 11 : tor_assert(curr);
2189 11 : log_debug(LD_CHANNEL,
2190 : "Cleaning up channel %p (global ID %"PRIu64 ") "
2191 : "in state %s (%d)",
2192 : curr, (curr->global_identifier),
2193 : channel_state_to_string(curr->state), curr->state);
2194 : /* Detach circuits early so they can find the channel */
2195 11 : if (curr->cmux) {
2196 11 : circuitmux_detach_all_circuits(curr->cmux, NULL);
2197 : }
2198 11 : SMARTLIST_DEL_CURRENT(channels, curr);
2199 11 : channel_unregister(curr);
2200 11 : if (mark_for_close) {
2201 3 : if (!CHANNEL_CONDEMNED(curr)) {
2202 2 : channel_mark_for_close(curr);
2203 : }
2204 3 : channel_force_xfree(curr);
2205 8 : } else channel_free(curr);
2206 40 : } SMARTLIST_FOREACH_END(curr);
2207 : }
2208 :
2209 : /**
2210 : * Free a list of channel listeners for channel_free_all().
2211 : */
2212 : static void
2213 3 : channel_listener_free_list(smartlist_t *listeners, int mark_for_close)
2214 : {
2215 3 : if (!listeners) return;
2216 :
2217 3 : SMARTLIST_FOREACH_BEGIN(listeners, channel_listener_t *, curr) {
2218 : /* Deregister and free it */
2219 0 : tor_assert(curr);
2220 0 : log_debug(LD_CHANNEL,
2221 : "Cleaning up channel listener %p (global ID %"PRIu64 ") "
2222 : "in state %s (%d)",
2223 : curr, (curr->global_identifier),
2224 : channel_listener_state_to_string(curr->state), curr->state);
2225 0 : channel_listener_unregister(curr);
2226 0 : if (mark_for_close) {
2227 0 : if (!(curr->state == CHANNEL_LISTENER_STATE_CLOSING ||
2228 : curr->state == CHANNEL_LISTENER_STATE_CLOSED ||
2229 : curr->state == CHANNEL_LISTENER_STATE_ERROR)) {
2230 0 : channel_listener_mark_for_close(curr);
2231 : }
2232 0 : channel_listener_force_xfree(curr);
2233 0 : } else channel_listener_free(curr);
2234 0 : } SMARTLIST_FOREACH_END(curr);
2235 : }
2236 :
2237 : /**
2238 : * Close all channels and free everything.
2239 : *
2240 : * This gets called from tor_free_all() in main.c to clean up on exit.
2241 : * It will close all registered channels and free associated storage,
2242 : * then free the all_channels, active_channels, listening_channels and
2243 : * finished_channels lists and also channel_identity_map.
2244 : */
2245 : void
2246 250 : channel_free_all(void)
2247 : {
2248 250 : log_debug(LD_CHANNEL,
2249 : "Shutting down channels...");
2250 :
2251 : /* First, let's go for finished channels */
2252 250 : if (finished_channels) {
2253 5 : channel_free_list(finished_channels, 0);
2254 5 : smartlist_free(finished_channels);
2255 5 : finished_channels = NULL;
2256 : }
2257 :
2258 : /* Now the finished listeners */
2259 250 : if (finished_listeners) {
2260 1 : channel_listener_free_list(finished_listeners, 0);
2261 1 : smartlist_free(finished_listeners);
2262 1 : finished_listeners = NULL;
2263 : }
2264 :
2265 : /* Now all active channels */
2266 250 : if (active_channels) {
2267 12 : channel_free_list(active_channels, 1);
2268 12 : smartlist_free(active_channels);
2269 12 : active_channels = NULL;
2270 : }
2271 :
2272 : /* Now all active listeners */
2273 250 : if (active_listeners) {
2274 1 : channel_listener_free_list(active_listeners, 1);
2275 1 : smartlist_free(active_listeners);
2276 1 : active_listeners = NULL;
2277 : }
2278 :
2279 : /* Now all channels, in case any are left over */
2280 250 : if (all_channels) {
2281 12 : channel_free_list(all_channels, 1);
2282 12 : smartlist_free(all_channels);
2283 12 : all_channels = NULL;
2284 : }
2285 :
2286 : /* Now all listeners, in case any are left over */
2287 250 : if (all_listeners) {
2288 1 : channel_listener_free_list(all_listeners, 1);
2289 1 : smartlist_free(all_listeners);
2290 1 : all_listeners = NULL;
2291 : }
2292 :
2293 : /* Now free channel_identity_map */
2294 250 : log_debug(LD_CHANNEL,
2295 : "Freeing channel_identity_map");
2296 : /* Geez, anything still left over just won't die ... let it leak then */
2297 250 : HT_CLEAR(channel_idmap, &channel_identity_map);
2298 :
2299 : /* Same with channel_gid_map */
2300 250 : log_debug(LD_CHANNEL,
2301 : "Freeing channel_gid_map");
2302 250 : HT_CLEAR(channel_gid_map, &channel_gid_map);
2303 :
2304 250 : log_debug(LD_CHANNEL,
2305 : "Done cleaning up after channels");
2306 250 : }
2307 :
2308 : /**
2309 : * Connect to a given addr/port/digest.
2310 : *
2311 : * This sets up a new outgoing channel; in the future if multiple
2312 : * channel_t subclasses are available, this is where the selection policy
2313 : * should go. It may also be desirable to fold port into tor_addr_t
2314 : * or make a new type including a tor_addr_t and port, so we have a
2315 : * single abstract object encapsulating all the protocol details of
2316 : * how to contact an OR.
2317 : */
2318 : channel_t *
2319 0 : channel_connect(const tor_addr_t *addr, uint16_t port,
2320 : const char *id_digest,
2321 : const ed25519_public_key_t *ed_id)
2322 : {
2323 0 : return channel_tls_connect(addr, port, id_digest, ed_id);
2324 : }
2325 :
2326 : /**
2327 : * Decide which of two channels to prefer for extending a circuit.
2328 : *
2329 : * This function is called while extending a circuit and returns true iff
2330 : * a is 'better' than b. The most important criterion here is that a
2331 : * canonical channel is always better than a non-canonical one, but the
2332 : * number of circuits and the age are used as tie-breakers.
2333 : *
2334 : * This is based on the former connection_or_is_better() of connection_or.c
2335 : */
2336 : int
2337 3 : channel_is_better(channel_t *a, channel_t *b)
2338 : {
2339 3 : int a_is_canonical, b_is_canonical;
2340 :
2341 3 : tor_assert(a);
2342 3 : tor_assert(b);
2343 :
2344 : /* If one channel is bad for new circuits, and the other isn't,
2345 : * use the one that is still good. */
2346 3 : if (!channel_is_bad_for_new_circs(a) && channel_is_bad_for_new_circs(b))
2347 : return 1;
2348 3 : if (channel_is_bad_for_new_circs(a) && !channel_is_bad_for_new_circs(b))
2349 : return 0;
2350 :
2351 : /* Check if one is canonical and the other isn't first */
2352 3 : a_is_canonical = channel_is_canonical(a);
2353 3 : b_is_canonical = channel_is_canonical(b);
2354 :
2355 3 : if (a_is_canonical && !b_is_canonical) return 1;
2356 3 : if (!a_is_canonical && b_is_canonical) return 0;
2357 :
2358 : /* Check if we suspect that one of the channels will be preferred
2359 : * by the peer */
2360 3 : if (a->is_canonical_to_peer && !b->is_canonical_to_peer) return 1;
2361 3 : if (!a->is_canonical_to_peer && b->is_canonical_to_peer) return 0;
2362 :
2363 : /*
2364 : * Okay, if we're here they tied on canonicity. Prefer the older
2365 : * connection, so that the adversary can't create a new connection
2366 : * and try to switch us over to it (which will leak information
2367 : * about long-lived circuits). Additionally, switching connections
2368 : * too often makes us more vulnerable to attacks like Torscan and
2369 : * passive netflow-based equivalents.
2370 : *
2371 : * Connections will still only live for at most a week, due to
2372 : * the check in connection_or_group_set_badness() against
2373 : * TIME_BEFORE_OR_CONN_IS_TOO_OLD, which marks old connections as
2374 : * unusable for new circuits after 1 week. That check sets
2375 : * is_bad_for_new_circs, which is checked in channel_get_for_extend().
2376 : *
2377 : * We check channel_is_bad_for_new_circs() above here anyway, for safety.
2378 : */
2379 3 : if (channel_when_created(a) < channel_when_created(b)) return 1;
2380 2 : else if (channel_when_created(a) > channel_when_created(b)) return 0;
2381 :
2382 1 : if (channel_num_circuits(a) > channel_num_circuits(b)) return 1;
2383 1 : else return 0;
2384 : }
2385 :
2386 : /**
2387 : * Get a channel to extend a circuit.
2388 : *
2389 : * Given the desired relay identity, pick a suitable channel to extend a
2390 : * circuit to the target IPv4 or IPv6 address requested by the client. Search
2391 : * for an existing channel for the requested endpoint. Make sure the channel
2392 : * is usable for new circuits, and matches one of the target addresses.
2393 : *
2394 : * Try to return the best channel. But if there is no good channel, set
2395 : * *msg_out to a message describing the channel's state and our next action,
2396 : * and set *launch_out to a boolean indicated whether the caller should try to
2397 : * launch a new channel with channel_connect().
2398 : *
2399 : * If `for_origin_circ` is set, mark the channel as interesting for origin
2400 : * circuits, and therefore interesting for our bootstrapping reports.
2401 : */
2402 10 : MOCK_IMPL(channel_t *,
2403 : channel_get_for_extend,(const char *rsa_id_digest,
2404 : const ed25519_public_key_t *ed_id,
2405 : const tor_addr_t *target_ipv4_addr,
2406 : const tor_addr_t *target_ipv6_addr,
2407 : bool for_origin_circ,
2408 : const char **msg_out,
2409 : int *launch_out))
2410 : {
2411 10 : channel_t *chan, *best = NULL;
2412 10 : int n_inprogress_goodaddr = 0, n_old = 0;
2413 10 : int n_noncanonical = 0;
2414 :
2415 10 : tor_assert(msg_out);
2416 10 : tor_assert(launch_out);
2417 :
2418 10 : chan = channel_find_by_remote_identity(rsa_id_digest, ed_id);
2419 :
2420 : /* Walk the list of channels */
2421 40 : for (; chan; chan = channel_next_with_rsa_identity(chan)) {
2422 20 : tor_assert(tor_memeq(chan->identity_digest,
2423 : rsa_id_digest, DIGEST_LEN));
2424 :
2425 20 : if (CHANNEL_CONDEMNED(chan))
2426 1 : continue;
2427 :
2428 : /* Never return a channel on which the other end appears to be
2429 : * a client. */
2430 19 : if (channel_is_client(chan)) {
2431 1 : continue;
2432 : }
2433 :
2434 : /* The Ed25519 key has to match too */
2435 18 : if (!channel_remote_identity_matches(chan, rsa_id_digest, ed_id)) {
2436 2 : continue;
2437 : }
2438 :
2439 16 : const bool matches_target =
2440 16 : channel_matches_target_addr_for_extend(chan,
2441 : target_ipv4_addr,
2442 : target_ipv6_addr);
2443 : /* Never return a non-open connection. */
2444 16 : if (!CHANNEL_IS_OPEN(chan)) {
2445 : /* If the address matches, don't launch a new connection for this
2446 : * circuit. */
2447 2 : if (matches_target) {
2448 2 : ++n_inprogress_goodaddr;
2449 2 : if (for_origin_circ) {
2450 : /* We were looking for a connection for an origin circuit; this one
2451 : * matches, so we'll note that we decided to use it for an origin
2452 : * circuit. */
2453 0 : channel_mark_as_used_for_origin_circuit(chan);
2454 : }
2455 : }
2456 2 : continue;
2457 : }
2458 :
2459 : /* Never return a connection that shouldn't be used for circs. */
2460 14 : if (channel_is_bad_for_new_circs(chan)) {
2461 3 : ++n_old;
2462 3 : continue;
2463 : }
2464 :
2465 : /* Only return canonical connections or connections where the address
2466 : * is the address we wanted. */
2467 11 : if (!channel_is_canonical(chan) && !matches_target) {
2468 2 : ++n_noncanonical;
2469 2 : continue;
2470 : }
2471 :
2472 9 : if (!best) {
2473 6 : best = chan; /* If we have no 'best' so far, this one is good enough. */
2474 6 : continue;
2475 : }
2476 :
2477 3 : if (channel_is_better(chan, best))
2478 1 : best = chan;
2479 : }
2480 :
2481 10 : if (best) {
2482 6 : *msg_out = "Connection is fine; using it.";
2483 6 : *launch_out = 0;
2484 6 : return best;
2485 4 : } else if (n_inprogress_goodaddr) {
2486 1 : *msg_out = "Connection in progress; waiting.";
2487 1 : *launch_out = 0;
2488 1 : return NULL;
2489 3 : } else if (n_old || n_noncanonical) {
2490 2 : *msg_out = "Connections all too old, or too non-canonical. "
2491 : " Launching a new one.";
2492 2 : *launch_out = 1;
2493 2 : return NULL;
2494 : } else {
2495 1 : *msg_out = "Not connected. Connecting.";
2496 1 : *launch_out = 1;
2497 1 : return NULL;
2498 : }
2499 : }
2500 :
2501 : /**
2502 : * Describe the transport subclass for a channel.
2503 : *
2504 : * Invoke a method to get a string description of the lower-layer
2505 : * transport for this channel.
2506 : */
2507 : const char *
2508 1 : channel_describe_transport(channel_t *chan)
2509 : {
2510 1 : tor_assert(chan);
2511 1 : tor_assert(chan->describe_transport);
2512 :
2513 1 : return chan->describe_transport(chan);
2514 : }
2515 :
2516 : /**
2517 : * Describe the transport subclass for a channel listener.
2518 : *
2519 : * Invoke a method to get a string description of the lower-layer
2520 : * transport for this channel listener.
2521 : */
2522 : const char *
2523 1 : channel_listener_describe_transport(channel_listener_t *chan_l)
2524 : {
2525 1 : tor_assert(chan_l);
2526 1 : tor_assert(chan_l->describe_transport);
2527 :
2528 1 : return chan_l->describe_transport(chan_l);
2529 : }
2530 :
2531 : /**
2532 : * Dump channel statistics.
2533 : *
2534 : * Dump statistics for one channel to the log.
2535 : */
2536 1 : MOCK_IMPL(void,
2537 : channel_dump_statistics, (channel_t *chan, int severity))
2538 : {
2539 1 : double avg, interval, age;
2540 1 : time_t now = time(NULL);
2541 1 : tor_addr_t remote_addr;
2542 1 : int have_remote_addr;
2543 1 : char *remote_addr_str;
2544 :
2545 1 : tor_assert(chan);
2546 :
2547 1 : age = (double)(now - chan->timestamp_created);
2548 :
2549 1 : tor_log(severity, LD_GENERAL,
2550 : "Channel %"PRIu64 " (at %p) with transport %s is in state "
2551 : "%s (%d)",
2552 : (chan->global_identifier), chan,
2553 : channel_describe_transport(chan),
2554 1 : channel_state_to_string(chan->state), chan->state);
2555 1 : tor_log(severity, LD_GENERAL,
2556 : " * Channel %"PRIu64 " was created at %"PRIu64
2557 : " (%"PRIu64 " seconds ago) "
2558 : "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
2559 : (chan->global_identifier),
2560 : (uint64_t)(chan->timestamp_created),
2561 1 : (uint64_t)(now - chan->timestamp_created),
2562 : (uint64_t)(chan->timestamp_active),
2563 1 : (uint64_t)(now - chan->timestamp_active));
2564 :
2565 : /* Handle digest. */
2566 1 : if (!tor_digest_is_zero(chan->identity_digest)) {
2567 0 : tor_log(severity, LD_GENERAL,
2568 : " * Channel %"PRIu64 " says it is connected "
2569 : "to an OR with digest %s",
2570 : (chan->global_identifier),
2571 : hex_str(chan->identity_digest, DIGEST_LEN));
2572 : } else {
2573 1 : tor_log(severity, LD_GENERAL,
2574 : " * Channel %"PRIu64 " does not know the digest"
2575 : " of the OR it is connected to",
2576 : (chan->global_identifier));
2577 : }
2578 :
2579 : /* Handle remote address and descriptions */
2580 1 : have_remote_addr = channel_get_addr_if_possible(chan, &remote_addr);
2581 1 : if (have_remote_addr) {
2582 1 : char *actual = tor_strdup(channel_describe_peer(chan));
2583 1 : remote_addr_str = tor_addr_to_str_dup(&remote_addr);
2584 1 : tor_log(severity, LD_GENERAL,
2585 : " * Channel %"PRIu64 " says its remote address"
2586 : " is %s, and gives a canonical description of \"%s\" and an "
2587 : "actual description of \"%s\"",
2588 : (chan->global_identifier),
2589 : safe_str(remote_addr_str),
2590 : safe_str(channel_describe_peer(chan)),
2591 : safe_str(actual));
2592 1 : tor_free(remote_addr_str);
2593 1 : tor_free(actual);
2594 : } else {
2595 0 : char *actual = tor_strdup(channel_describe_peer(chan));
2596 0 : tor_log(severity, LD_GENERAL,
2597 : " * Channel %"PRIu64 " does not know its remote "
2598 : "address, but gives a canonical description of \"%s\" and an "
2599 : "actual description of \"%s\"",
2600 : (chan->global_identifier),
2601 : channel_describe_peer(chan),
2602 : actual);
2603 0 : tor_free(actual);
2604 : }
2605 :
2606 : /* Handle marks */
2607 6 : tor_log(severity, LD_GENERAL,
2608 : " * Channel %"PRIu64 " has these marks: %s %s %s %s %s",
2609 : (chan->global_identifier),
2610 1 : channel_is_bad_for_new_circs(chan) ?
2611 : "bad_for_new_circs" : "!bad_for_new_circs",
2612 1 : channel_is_canonical(chan) ?
2613 : "canonical" : "!canonical",
2614 1 : channel_is_client(chan) ?
2615 : "client" : "!client",
2616 1 : channel_is_local(chan) ?
2617 : "local" : "!local",
2618 1 : channel_is_incoming(chan) ?
2619 : "incoming" : "outgoing");
2620 :
2621 : /* Describe circuits */
2622 1 : tor_log(severity, LD_GENERAL,
2623 : " * Channel %"PRIu64 " has %d active circuits out of"
2624 : " %d in total",
2625 : (chan->global_identifier),
2626 1 : (chan->cmux != NULL) ?
2627 1 : circuitmux_num_active_circuits(chan->cmux) : 0,
2628 1 : (chan->cmux != NULL) ?
2629 1 : circuitmux_num_circuits(chan->cmux) : 0);
2630 :
2631 : /* Describe timestamps */
2632 1 : tor_log(severity, LD_GENERAL,
2633 : " * Channel %"PRIu64 " was last used by a "
2634 : "client at %"PRIu64 " (%"PRIu64 " seconds ago)",
2635 : (chan->global_identifier),
2636 : (uint64_t)(chan->timestamp_client),
2637 1 : (uint64_t)(now - chan->timestamp_client));
2638 1 : tor_log(severity, LD_GENERAL,
2639 : " * Channel %"PRIu64 " last received a cell "
2640 : "at %"PRIu64 " (%"PRIu64 " seconds ago)",
2641 : (chan->global_identifier),
2642 : (uint64_t)(chan->timestamp_recv),
2643 1 : (uint64_t)(now - chan->timestamp_recv));
2644 1 : tor_log(severity, LD_GENERAL,
2645 : " * Channel %"PRIu64 " last transmitted a cell "
2646 : "at %"PRIu64 " (%"PRIu64 " seconds ago)",
2647 : (chan->global_identifier),
2648 : (uint64_t)(chan->timestamp_xmit),
2649 1 : (uint64_t)(now - chan->timestamp_xmit));
2650 :
2651 : /* Describe counters and rates */
2652 1 : tor_log(severity, LD_GENERAL,
2653 : " * Channel %"PRIu64 " has received "
2654 : "%"PRIu64 " bytes in %"PRIu64 " cells and transmitted "
2655 : "%"PRIu64 " bytes in %"PRIu64 " cells",
2656 : (chan->global_identifier),
2657 : (chan->n_bytes_recved),
2658 : (chan->n_cells_recved),
2659 : (chan->n_bytes_xmitted),
2660 : (chan->n_cells_xmitted));
2661 1 : if (now > chan->timestamp_created &&
2662 : chan->timestamp_created > 0) {
2663 1 : if (chan->n_bytes_recved > 0) {
2664 1 : avg = (double)(chan->n_bytes_recved) / age;
2665 1 : tor_log(severity, LD_GENERAL,
2666 : " * Channel %"PRIu64 " has averaged %f "
2667 : "bytes received per second",
2668 : (chan->global_identifier), avg);
2669 : }
2670 1 : if (chan->n_cells_recved > 0) {
2671 1 : avg = (double)(chan->n_cells_recved) / age;
2672 1 : if (avg >= 1.0) {
2673 0 : tor_log(severity, LD_GENERAL,
2674 : " * Channel %"PRIu64 " has averaged %f "
2675 : "cells received per second",
2676 : (chan->global_identifier), avg);
2677 1 : } else if (avg >= 0.0) {
2678 1 : interval = 1.0 / avg;
2679 1 : tor_log(severity, LD_GENERAL,
2680 : " * Channel %"PRIu64 " has averaged %f "
2681 : "seconds between received cells",
2682 : (chan->global_identifier), interval);
2683 : }
2684 : }
2685 1 : if (chan->n_bytes_xmitted > 0) {
2686 1 : avg = (double)(chan->n_bytes_xmitted) / age;
2687 1 : tor_log(severity, LD_GENERAL,
2688 : " * Channel %"PRIu64 " has averaged %f "
2689 : "bytes transmitted per second",
2690 : (chan->global_identifier), avg);
2691 : }
2692 1 : if (chan->n_cells_xmitted > 0) {
2693 1 : avg = (double)(chan->n_cells_xmitted) / age;
2694 1 : if (avg >= 1.0) {
2695 0 : tor_log(severity, LD_GENERAL,
2696 : " * Channel %"PRIu64 " has averaged %f "
2697 : "cells transmitted per second",
2698 : (chan->global_identifier), avg);
2699 1 : } else if (avg >= 0.0) {
2700 1 : interval = 1.0 / avg;
2701 1 : tor_log(severity, LD_GENERAL,
2702 : " * Channel %"PRIu64 " has averaged %f "
2703 : "seconds between transmitted cells",
2704 : (chan->global_identifier), interval);
2705 : }
2706 : }
2707 : }
2708 :
2709 : /* Dump anything the lower layer has to say */
2710 1 : channel_dump_transport_statistics(chan, severity);
2711 1 : }
2712 :
2713 : /**
2714 : * Dump channel listener statistics.
2715 : *
2716 : * Dump statistics for one channel listener to the log.
2717 : */
2718 : void
2719 1 : channel_listener_dump_statistics(channel_listener_t *chan_l, int severity)
2720 : {
2721 1 : double avg, interval, age;
2722 1 : time_t now = time(NULL);
2723 :
2724 1 : tor_assert(chan_l);
2725 :
2726 1 : age = (double)(now - chan_l->timestamp_created);
2727 :
2728 1 : tor_log(severity, LD_GENERAL,
2729 : "Channel listener %"PRIu64 " (at %p) with transport %s is in "
2730 : "state %s (%d)",
2731 : (chan_l->global_identifier), chan_l,
2732 : channel_listener_describe_transport(chan_l),
2733 1 : channel_listener_state_to_string(chan_l->state), chan_l->state);
2734 1 : tor_log(severity, LD_GENERAL,
2735 : " * Channel listener %"PRIu64 " was created at %"PRIu64
2736 : " (%"PRIu64 " seconds ago) "
2737 : "and last active at %"PRIu64 " (%"PRIu64 " seconds ago)",
2738 : (chan_l->global_identifier),
2739 : (uint64_t)(chan_l->timestamp_created),
2740 1 : (uint64_t)(now - chan_l->timestamp_created),
2741 : (uint64_t)(chan_l->timestamp_active),
2742 1 : (uint64_t)(now - chan_l->timestamp_active));
2743 :
2744 1 : tor_log(severity, LD_GENERAL,
2745 : " * Channel listener %"PRIu64 " last accepted an incoming "
2746 : "channel at %"PRIu64 " (%"PRIu64 " seconds ago) "
2747 : "and has accepted %"PRIu64 " channels in total",
2748 : (chan_l->global_identifier),
2749 : (uint64_t)(chan_l->timestamp_accepted),
2750 1 : (uint64_t)(now - chan_l->timestamp_accepted),
2751 1 : (uint64_t)(chan_l->n_accepted));
2752 :
2753 : /*
2754 : * If it's sensible to do so, get the rate of incoming channels on this
2755 : * listener
2756 : */
2757 1 : if (now > chan_l->timestamp_created &&
2758 1 : chan_l->timestamp_created > 0 &&
2759 1 : chan_l->n_accepted > 0) {
2760 1 : avg = (double)(chan_l->n_accepted) / age;
2761 1 : if (avg >= 1.0) {
2762 0 : tor_log(severity, LD_GENERAL,
2763 : " * Channel listener %"PRIu64 " has averaged %f incoming "
2764 : "channels per second",
2765 : (chan_l->global_identifier), avg);
2766 1 : } else if (avg >= 0.0) {
2767 1 : interval = 1.0 / avg;
2768 1 : tor_log(severity, LD_GENERAL,
2769 : " * Channel listener %"PRIu64 " has averaged %f seconds "
2770 : "between incoming channels",
2771 : (chan_l->global_identifier), interval);
2772 : }
2773 : }
2774 :
2775 : /* Dump anything the lower layer has to say */
2776 1 : channel_listener_dump_transport_statistics(chan_l, severity);
2777 1 : }
2778 :
2779 : /**
2780 : * Invoke transport-specific stats dump for channel.
2781 : *
2782 : * If there is a lower-layer statistics dump method, invoke it.
2783 : */
2784 : void
2785 1 : channel_dump_transport_statistics(channel_t *chan, int severity)
2786 : {
2787 1 : tor_assert(chan);
2788 :
2789 1 : if (chan->dumpstats) chan->dumpstats(chan, severity);
2790 1 : }
2791 :
2792 : /**
2793 : * Invoke transport-specific stats dump for channel listener.
2794 : *
2795 : * If there is a lower-layer statistics dump method, invoke it.
2796 : */
2797 : void
2798 1 : channel_listener_dump_transport_statistics(channel_listener_t *chan_l,
2799 : int severity)
2800 : {
2801 1 : tor_assert(chan_l);
2802 :
2803 1 : if (chan_l->dumpstats) chan_l->dumpstats(chan_l, severity);
2804 1 : }
2805 :
2806 : /**
2807 : * Return text description of the remote endpoint canonical address.
2808 : *
2809 : * This function returns a human-readable string for logging; nothing
2810 : * should parse it or rely on a particular format.
2811 : *
2812 : * Subsequent calls to this function may invalidate its return value.
2813 : */
2814 246 : MOCK_IMPL(const char *,
2815 : channel_describe_peer,(channel_t *chan))
2816 : {
2817 246 : tor_assert(chan);
2818 246 : tor_assert(chan->describe_peer);
2819 :
2820 246 : return chan->describe_peer(chan);
2821 : }
2822 :
2823 : /**
2824 : * Get the remote address for this channel, if possible.
2825 : *
2826 : * Write the remote address out to a tor_addr_t if the underlying transport
2827 : * supports this operation, and return 1. Return 0 if the underlying transport
2828 : * doesn't let us do this.
2829 : *
2830 : * Always returns the "real" address of the peer -- the one we're connected to
2831 : * on the internet.
2832 : */
2833 3 : MOCK_IMPL(int,
2834 : channel_get_addr_if_possible,(const channel_t *chan,
2835 : tor_addr_t *addr_out))
2836 : {
2837 3 : tor_assert(chan);
2838 3 : tor_assert(addr_out);
2839 3 : tor_assert(chan->get_remote_addr);
2840 :
2841 3 : return chan->get_remote_addr(chan, addr_out);
2842 : }
2843 :
2844 : /**
2845 : * Return true iff the channel has any cells on the connection outbuf waiting
2846 : * to be sent onto the network.
2847 : */
2848 : int
2849 4 : channel_has_queued_writes(channel_t *chan)
2850 : {
2851 4 : tor_assert(chan);
2852 4 : tor_assert(chan->has_queued_writes);
2853 :
2854 : /* Check with the lower layer */
2855 4 : return chan->has_queued_writes(chan);
2856 : }
2857 :
2858 : /**
2859 : * Check the is_bad_for_new_circs flag.
2860 : *
2861 : * This function returns the is_bad_for_new_circs flag of the specified
2862 : * channel.
2863 : */
2864 : int
2865 24 : channel_is_bad_for_new_circs(channel_t *chan)
2866 : {
2867 24 : tor_assert(chan);
2868 :
2869 24 : return chan->is_bad_for_new_circs;
2870 : }
2871 :
2872 : /**
2873 : * Mark a channel as bad for new circuits.
2874 : *
2875 : * Set the is_bad_for_new_circs_flag on chan.
2876 : */
2877 : void
2878 3 : channel_mark_bad_for_new_circs(channel_t *chan)
2879 : {
2880 3 : tor_assert(chan);
2881 :
2882 3 : chan->is_bad_for_new_circs = 1;
2883 3 : }
2884 :
2885 : /**
2886 : * Get the client flag.
2887 : *
2888 : * This returns the client flag of a channel, which will be set if
2889 : * command_process_create_cell() in command.c thinks this is a connection
2890 : * from a client.
2891 : */
2892 : int
2893 856 : channel_is_client(const channel_t *chan)
2894 : {
2895 856 : tor_assert(chan);
2896 :
2897 856 : return chan->is_client;
2898 : }
2899 :
2900 : /**
2901 : * Set the client flag.
2902 : *
2903 : * Mark a channel as being from a client.
2904 : */
2905 : void
2906 1 : channel_mark_client(channel_t *chan)
2907 : {
2908 1 : tor_assert(chan);
2909 :
2910 1 : chan->is_client = 1;
2911 1 : }
2912 :
2913 : /**
2914 : * Clear the client flag.
2915 : *
2916 : * Mark a channel as being _not_ from a client.
2917 : */
2918 : void
2919 1 : channel_clear_client(channel_t *chan)
2920 : {
2921 1 : tor_assert(chan);
2922 :
2923 1 : chan->is_client = 0;
2924 1 : }
2925 :
2926 : /**
2927 : * Get the canonical flag for a channel.
2928 : *
2929 : * This returns the is_canonical for a channel; this flag is determined by
2930 : * the lower layer and can't be set in a transport-independent way.
2931 : */
2932 : int
2933 18 : channel_is_canonical(channel_t *chan)
2934 : {
2935 18 : tor_assert(chan);
2936 18 : tor_assert(chan->is_canonical);
2937 :
2938 18 : return chan->is_canonical(chan);
2939 : }
2940 :
2941 : /**
2942 : * Test incoming flag.
2943 : *
2944 : * This function gets the incoming flag; this is set when a listener spawns
2945 : * a channel. If this returns true the channel was remotely initiated.
2946 : */
2947 : int
2948 1 : channel_is_incoming(channel_t *chan)
2949 : {
2950 1 : tor_assert(chan);
2951 :
2952 1 : return chan->is_incoming;
2953 : }
2954 :
2955 : /**
2956 : * Set the incoming flag.
2957 : *
2958 : * This function is called when a channel arrives on a listening channel
2959 : * to mark it as incoming.
2960 : */
2961 : void
2962 0 : channel_mark_incoming(channel_t *chan)
2963 : {
2964 0 : tor_assert(chan);
2965 :
2966 0 : chan->is_incoming = 1;
2967 0 : }
2968 :
2969 : /**
2970 : * Test local flag.
2971 : *
2972 : * This function gets the local flag; the lower layer should set this when
2973 : * setting up the channel if is_local_addr() is true for all of the
2974 : * destinations it will communicate with on behalf of this channel. It's
2975 : * used to decide whether to declare the network reachable when seeing incoming
2976 : * traffic on the channel.
2977 : */
2978 : int
2979 7 : channel_is_local(channel_t *chan)
2980 : {
2981 7 : tor_assert(chan);
2982 :
2983 7 : return chan->is_local;
2984 : }
2985 :
2986 : /**
2987 : * Set the local flag.
2988 : *
2989 : * This internal-only function should be called by the lower layer if the
2990 : * channel is to a local address. See channel_is_local() above or the
2991 : * description of the is_local bit in channel.h.
2992 : */
2993 : void
2994 1 : channel_mark_local(channel_t *chan)
2995 : {
2996 1 : tor_assert(chan);
2997 :
2998 1 : chan->is_local = 1;
2999 1 : }
3000 :
3001 : /**
3002 : * Mark a channel as remote.
3003 : *
3004 : * This internal-only function should be called by the lower layer if the
3005 : * channel is not to a local address but has previously been marked local.
3006 : * See channel_is_local() above or the description of the is_local bit in
3007 : * channel.h
3008 : */
3009 : void
3010 3 : channel_mark_remote(channel_t *chan)
3011 : {
3012 3 : tor_assert(chan);
3013 :
3014 3 : chan->is_local = 0;
3015 3 : }
3016 :
3017 : /**
3018 : * Test outgoing flag.
3019 : *
3020 : * This function gets the outgoing flag; this is the inverse of the incoming
3021 : * bit set when a listener spawns a channel. If this returns true the channel
3022 : * was locally initiated.
3023 : */
3024 : int
3025 26 : channel_is_outgoing(channel_t *chan)
3026 : {
3027 26 : tor_assert(chan);
3028 :
3029 26 : return !(chan->is_incoming);
3030 : }
3031 :
3032 : /**
3033 : * Mark a channel as outgoing.
3034 : *
3035 : * This function clears the incoming flag and thus marks a channel as
3036 : * outgoing.
3037 : */
3038 : void
3039 4 : channel_mark_outgoing(channel_t *chan)
3040 : {
3041 4 : tor_assert(chan);
3042 :
3043 4 : chan->is_incoming = 0;
3044 4 : }
3045 :
3046 : /************************
3047 : * Flow control queries *
3048 : ***********************/
3049 :
3050 : /**
3051 : * Estimate the number of writeable cells.
3052 : *
3053 : * Ask the lower layer for an estimate of how many cells it can accept.
3054 : */
3055 : int
3056 5 : channel_num_cells_writeable(channel_t *chan)
3057 : {
3058 5 : int result;
3059 :
3060 5 : tor_assert(chan);
3061 5 : tor_assert(chan->num_cells_writeable);
3062 :
3063 5 : if (chan->state == CHANNEL_STATE_OPEN) {
3064 : /* Query lower layer */
3065 4 : result = chan->num_cells_writeable(chan);
3066 4 : if (result < 0) result = 0;
3067 : } else {
3068 : /* No cells are writeable in any other state */
3069 : result = 0;
3070 : }
3071 :
3072 5 : return result;
3073 : }
3074 :
3075 : /*********************
3076 : * Timestamp updates *
3077 : ********************/
3078 :
3079 : /**
3080 : * Update the created timestamp for a channel.
3081 : *
3082 : * This updates the channel's created timestamp and should only be called
3083 : * from channel_init().
3084 : */
3085 : void
3086 192 : channel_timestamp_created(channel_t *chan)
3087 : {
3088 192 : time_t now = time(NULL);
3089 :
3090 192 : tor_assert(chan);
3091 :
3092 192 : chan->timestamp_created = now;
3093 192 : }
3094 :
3095 : /**
3096 : * Update the created timestamp for a channel listener.
3097 : *
3098 : * This updates the channel listener's created timestamp and should only be
3099 : * called from channel_init_listener().
3100 : */
3101 : void
3102 1 : channel_listener_timestamp_created(channel_listener_t *chan_l)
3103 : {
3104 1 : time_t now = time(NULL);
3105 :
3106 1 : tor_assert(chan_l);
3107 :
3108 1 : chan_l->timestamp_created = now;
3109 1 : }
3110 :
3111 : /**
3112 : * Update the last active timestamp for a channel.
3113 : *
3114 : * This function updates the channel's last active timestamp; it should be
3115 : * called by the lower layer whenever there is activity on the channel which
3116 : * does not lead to a cell being transmitted or received; the active timestamp
3117 : * is also updated from channel_timestamp_recv() and channel_timestamp_xmit(),
3118 : * but it should be updated for things like the v3 handshake and stuff that
3119 : * produce activity only visible to the lower layer.
3120 : */
3121 : void
3122 111 : channel_timestamp_active(channel_t *chan)
3123 : {
3124 111 : time_t now = time(NULL);
3125 :
3126 111 : tor_assert(chan);
3127 111 : monotime_coarse_get(&chan->timestamp_xfer);
3128 :
3129 111 : chan->timestamp_active = now;
3130 :
3131 : /* Clear any potential netflow padding timer. We're active */
3132 111 : monotime_coarse_zero(&chan->next_padding_time);
3133 111 : }
3134 :
3135 : /**
3136 : * Update the last active timestamp for a channel listener.
3137 : */
3138 : void
3139 1 : channel_listener_timestamp_active(channel_listener_t *chan_l)
3140 : {
3141 1 : time_t now = time(NULL);
3142 :
3143 1 : tor_assert(chan_l);
3144 :
3145 1 : chan_l->timestamp_active = now;
3146 1 : }
3147 :
3148 : /**
3149 : * Update the last accepted timestamp.
3150 : *
3151 : * This function updates the channel listener's last accepted timestamp; it
3152 : * should be called whenever a new incoming channel is accepted on a
3153 : * listener.
3154 : */
3155 : void
3156 1 : channel_listener_timestamp_accepted(channel_listener_t *chan_l)
3157 : {
3158 1 : time_t now = time(NULL);
3159 :
3160 1 : tor_assert(chan_l);
3161 :
3162 1 : chan_l->timestamp_active = now;
3163 1 : chan_l->timestamp_accepted = now;
3164 1 : }
3165 :
3166 : /**
3167 : * Update client timestamp.
3168 : *
3169 : * This function is called by relay.c to timestamp a channel that appears to
3170 : * be used as a client.
3171 : */
3172 : void
3173 0 : channel_timestamp_client(channel_t *chan)
3174 : {
3175 0 : time_t now = time(NULL);
3176 :
3177 0 : tor_assert(chan);
3178 :
3179 0 : chan->timestamp_client = now;
3180 0 : }
3181 :
3182 : /**
3183 : * Update the recv timestamp.
3184 : *
3185 : * This is called whenever we get an incoming cell from the lower layer.
3186 : * This also updates the active timestamp.
3187 : */
3188 : void
3189 2 : channel_timestamp_recv(channel_t *chan)
3190 : {
3191 2 : time_t now = time(NULL);
3192 2 : tor_assert(chan);
3193 2 : monotime_coarse_get(&chan->timestamp_xfer);
3194 :
3195 2 : chan->timestamp_active = now;
3196 2 : chan->timestamp_recv = now;
3197 :
3198 : /* Clear any potential netflow padding timer. We're active */
3199 2 : monotime_coarse_zero(&chan->next_padding_time);
3200 2 : }
3201 :
3202 : /**
3203 : * Update the xmit timestamp.
3204 : *
3205 : * This is called whenever we pass an outgoing cell to the lower layer. This
3206 : * also updates the active timestamp.
3207 : */
3208 : void
3209 3 : channel_timestamp_xmit(channel_t *chan)
3210 : {
3211 3 : time_t now = time(NULL);
3212 3 : tor_assert(chan);
3213 :
3214 3 : monotime_coarse_get(&chan->timestamp_xfer);
3215 :
3216 3 : chan->timestamp_active = now;
3217 3 : chan->timestamp_xmit = now;
3218 :
3219 : /* Clear any potential netflow padding timer. We're active */
3220 3 : monotime_coarse_zero(&chan->next_padding_time);
3221 3 : }
3222 :
3223 : /***************************************************************
3224 : * Timestamp queries - see above for definitions of timestamps *
3225 : **************************************************************/
3226 :
3227 : /**
3228 : * Query created timestamp for a channel.
3229 : */
3230 : time_t
3231 10 : channel_when_created(channel_t *chan)
3232 : {
3233 10 : tor_assert(chan);
3234 :
3235 10 : return chan->timestamp_created;
3236 : }
3237 :
3238 : /**
3239 : * Query client timestamp.
3240 : */
3241 : time_t
3242 0 : channel_when_last_client(channel_t *chan)
3243 : {
3244 0 : tor_assert(chan);
3245 :
3246 0 : return chan->timestamp_client;
3247 : }
3248 :
3249 : /**
3250 : * Query xmit timestamp.
3251 : */
3252 : time_t
3253 0 : channel_when_last_xmit(channel_t *chan)
3254 : {
3255 0 : tor_assert(chan);
3256 :
3257 0 : return chan->timestamp_xmit;
3258 : }
3259 :
3260 : /**
3261 : * Check if a channel matches an extend_info_t.
3262 : *
3263 : * This function calls the lower layer and asks if this channel matches a
3264 : * given extend_info_t.
3265 : *
3266 : * NOTE that this function only checks for an address/port match, and should
3267 : * be used only when no identity is available.
3268 : */
3269 : int
3270 0 : channel_matches_extend_info(channel_t *chan, extend_info_t *extend_info)
3271 : {
3272 0 : tor_assert(chan);
3273 0 : tor_assert(chan->matches_extend_info);
3274 0 : tor_assert(extend_info);
3275 :
3276 0 : return chan->matches_extend_info(chan, extend_info);
3277 : }
3278 :
3279 : /**
3280 : * Check if a channel matches the given target IPv4 or IPv6 addresses.
3281 : * If either address matches, return true. If neither address matches,
3282 : * return false.
3283 : *
3284 : * Both addresses can't be NULL.
3285 : *
3286 : * This function calls into the lower layer and asks if this channel thinks
3287 : * it matches the target addresses for circuit extension purposes.
3288 : */
3289 : STATIC bool
3290 20 : channel_matches_target_addr_for_extend(channel_t *chan,
3291 : const tor_addr_t *target_ipv4_addr,
3292 : const tor_addr_t *target_ipv6_addr)
3293 : {
3294 20 : tor_assert(chan);
3295 20 : tor_assert(chan->matches_target);
3296 :
3297 20 : IF_BUG_ONCE(!target_ipv4_addr && !target_ipv6_addr)
3298 : return false;
3299 :
3300 20 : if (target_ipv4_addr && chan->matches_target(chan, target_ipv4_addr))
3301 : return true;
3302 :
3303 13 : if (target_ipv6_addr && chan->matches_target(chan, target_ipv6_addr))
3304 1 : return true;
3305 :
3306 : return false;
3307 : }
3308 :
3309 : /**
3310 : * Return the total number of circuits used by a channel.
3311 : *
3312 : * @param chan Channel to query
3313 : * @return Number of circuits using this as n_chan or p_chan
3314 : */
3315 : unsigned int
3316 3 : channel_num_circuits(channel_t *chan)
3317 : {
3318 3 : tor_assert(chan);
3319 :
3320 3 : return chan->num_n_circuits +
3321 3 : chan->num_p_circuits;
3322 : }
3323 :
3324 : /**
3325 : * Set up circuit ID generation.
3326 : *
3327 : * This is called when setting up a channel and replaces the old
3328 : * connection_or_set_circid_type().
3329 : */
3330 5 : MOCK_IMPL(void,
3331 : channel_set_circid_type,(channel_t *chan,
3332 : crypto_pk_t *identity_rcvd,
3333 : int consider_identity))
3334 : {
3335 5 : int started_here;
3336 5 : crypto_pk_t *our_identity;
3337 :
3338 5 : tor_assert(chan);
3339 :
3340 5 : started_here = channel_is_outgoing(chan);
3341 :
3342 5 : if (! consider_identity) {
3343 5 : if (started_here)
3344 5 : chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
3345 : else
3346 0 : chan->circ_id_type = CIRC_ID_TYPE_LOWER;
3347 5 : return;
3348 : }
3349 :
3350 0 : our_identity = started_here ?
3351 0 : get_tlsclient_identity_key() : get_server_identity_key();
3352 :
3353 0 : if (identity_rcvd) {
3354 0 : if (crypto_pk_cmp_keys(our_identity, identity_rcvd) < 0) {
3355 0 : chan->circ_id_type = CIRC_ID_TYPE_LOWER;
3356 : } else {
3357 0 : chan->circ_id_type = CIRC_ID_TYPE_HIGHER;
3358 : }
3359 : } else {
3360 0 : chan->circ_id_type = CIRC_ID_TYPE_NEITHER;
3361 : }
3362 : }
3363 :
3364 : static int
3365 0 : channel_sort_by_ed25519_identity(const void **a_, const void **b_)
3366 : {
3367 0 : const channel_t *a = *a_,
3368 0 : *b = *b_;
3369 0 : return fast_memcmp(&a->ed25519_identity.pubkey,
3370 : &b->ed25519_identity.pubkey,
3371 : sizeof(a->ed25519_identity.pubkey));
3372 : }
3373 :
3374 : /** Helper for channel_update_bad_for_new_circs(): Perform the
3375 : * channel_update_bad_for_new_circs operation on all channels in <b>lst</b>,
3376 : * all of which MUST have the same RSA ID. (They MAY have different
3377 : * Ed25519 IDs.) */
3378 : static void
3379 0 : channel_rsa_id_group_set_badness(struct channel_list_t *lst, int force)
3380 : {
3381 : /*XXXX This function should really be about channels. 15056 */
3382 0 : channel_t *chan = TOR_LIST_FIRST(lst);
3383 :
3384 0 : if (!chan)
3385 0 : return;
3386 :
3387 : /* if there is only one channel, don't bother looping */
3388 0 : if (PREDICT_LIKELY(!TOR_LIST_NEXT(chan, next_with_same_id))) {
3389 0 : connection_or_single_set_badness_(
3390 0 : time(NULL), BASE_CHAN_TO_TLS(chan)->conn, force);
3391 0 : return;
3392 : }
3393 :
3394 0 : smartlist_t *channels = smartlist_new();
3395 :
3396 0 : TOR_LIST_FOREACH(chan, lst, next_with_same_id) {
3397 0 : if (BASE_CHAN_TO_TLS(chan)->conn) {
3398 0 : smartlist_add(channels, chan);
3399 : }
3400 : }
3401 :
3402 0 : smartlist_sort(channels, channel_sort_by_ed25519_identity);
3403 :
3404 0 : const ed25519_public_key_t *common_ed25519_identity = NULL;
3405 : /* it would be more efficient to do a slice, but this case is rare */
3406 0 : smartlist_t *or_conns = smartlist_new();
3407 0 : SMARTLIST_FOREACH_BEGIN(channels, channel_t *, channel) {
3408 0 : tor_assert(channel); // Suppresses some compiler warnings.
3409 :
3410 0 : if (!common_ed25519_identity)
3411 0 : common_ed25519_identity = &channel->ed25519_identity;
3412 :
3413 0 : if (! ed25519_pubkey_eq(&channel->ed25519_identity,
3414 : common_ed25519_identity)) {
3415 0 : connection_or_group_set_badness_(or_conns, force);
3416 0 : smartlist_clear(or_conns);
3417 0 : common_ed25519_identity = &channel->ed25519_identity;
3418 : }
3419 :
3420 0 : smartlist_add(or_conns, BASE_CHAN_TO_TLS(channel)->conn);
3421 0 : } SMARTLIST_FOREACH_END(channel);
3422 :
3423 0 : connection_or_group_set_badness_(or_conns, force);
3424 :
3425 : /* XXXX 15056 we may want to do something special with connections that have
3426 : * no set Ed25519 identity! */
3427 :
3428 0 : smartlist_free(or_conns);
3429 0 : smartlist_free(channels);
3430 : }
3431 :
3432 : /** Go through all the channels (or if <b>digest</b> is non-NULL, just
3433 : * the OR connections with that digest), and set the is_bad_for_new_circs
3434 : * flag based on the rules in connection_or_group_set_badness() (or just
3435 : * always set it if <b>force</b> is true).
3436 : */
3437 : void
3438 0 : channel_update_bad_for_new_circs(const char *digest, int force)
3439 : {
3440 0 : if (digest) {
3441 0 : channel_idmap_entry_t *ent;
3442 0 : channel_idmap_entry_t search;
3443 0 : memset(&search, 0, sizeof(search));
3444 0 : memcpy(search.digest, digest, DIGEST_LEN);
3445 0 : ent = HT_FIND(channel_idmap, &channel_identity_map, &search);
3446 0 : if (ent) {
3447 0 : channel_rsa_id_group_set_badness(&ent->channel_list, force);
3448 : }
3449 0 : return;
3450 : }
3451 :
3452 : /* no digest; just look at everything. */
3453 0 : channel_idmap_entry_t **iter;
3454 0 : HT_FOREACH(iter, channel_idmap, &channel_identity_map) {
3455 0 : channel_rsa_id_group_set_badness(&(*iter)->channel_list, force);
3456 : }
3457 : }
|