1
//! Code for talking directly (over a TLS connection) to a Tor client or relay.
2
//!
3
//! Channels form the basis of the rest of the Tor protocol: they are
4
//! the only way for two Tor instances to talk.
5
//!
6
//! Channels are not useful directly for application requests: after
7
//! making a channel, it needs to get used to build circuits, and the
8
//! circuits are used to anonymize streams.  The streams are the
9
//! objects corresponding to directory requests.
10
//!
11
//! In general, you shouldn't try to manage channels on your own;
12
//! use the `tor-chanmgr` crate instead.
13
//!
14
//! To launch a channel:
15
//!
16
//!  * Create a TLS connection as an object that implements AsyncRead +
17
//!    AsyncWrite + StreamOps, and pass it to a channel builder. This will
18
//!    yield an [crate::client::channel::handshake::ClientInitiatorHandshake] that represents
19
//!    the state of the handshake.
20
//!  * Call [crate::client::channel::handshake::ClientInitiatorHandshake::connect] on the result
21
//!    to negotiate the rest of the handshake.  This will verify
22
//!    syntactic correctness of the handshake, but not its cryptographic
23
//!    integrity.
24
//!  * Call handshake::UnverifiedChannel::check on the result.  This
25
//!    finishes the cryptographic checks.
26
//!  * Call handshake::VerifiedChannel::finish on the result. This
27
//!    completes the handshake and produces an open channel and Reactor.
28
//!  * Launch an asynchronous task to call the reactor's run() method.
29
//!
30
//! One you have a running channel, you can create circuits on it with
31
//! its [Channel::new_tunnel] method.  See
32
//! [crate::client::circuit::PendingClientTunnel] for information on how to
33
//! proceed from there.
34
//!
35
//! # Design
36
//!
37
//! For now, this code splits the channel into two pieces: a "Channel"
38
//! object that can be used by circuits to write cells onto the
39
//! channel, and a "Reactor" object that runs as a task in the
40
//! background, to read channel cells and pass them to circuits as
41
//! appropriate.
42
//!
43
//! I'm not at all sure that's the best way to do that, but it's what
44
//! I could think of.
45
//!
46
//! # Limitations
47
//!
48
//! TODO: There is no rate limiting or fairness.
49

            
50
/// The size of the channel buffer for communication between `Channel` and its reactor.
51
pub const CHANNEL_BUFFER_SIZE: usize = 128;
52

            
53
mod circmap;
54
mod handler;
55
pub(crate) mod handshake;
56
pub mod kist;
57
mod msg;
58
pub mod padding;
59
pub mod params;
60
mod reactor;
61
mod unique_id;
62

            
63
pub use crate::channel::params::*;
64
pub(crate) use crate::channel::reactor::Reactor;
65
use crate::channel::reactor::{BoxedChannelSink, BoxedChannelStream};
66
pub use crate::channel::unique_id::UniqId;
67
use crate::client::circuit::PendingClientTunnel;
68
use crate::client::circuit::padding::{PaddingController, QueuedCellPaddingInfo};
69
use crate::memquota::{ChannelAccount, CircuitAccount, SpecificAccount as _};
70
use crate::peer::PeerInfo;
71
use crate::util::err::ChannelClosed;
72
use crate::util::oneshot_broadcast;
73
use crate::util::timeout::TimeoutEstimator;
74
use crate::util::ts::AtomicOptTimestamp;
75
use crate::{ClockSkew, client};
76
use crate::{Error, Result};
77
use cfg_if::cfg_if;
78
use reactor::BoxedChannelStreamOps;
79
use safelog::{MaybeSensitive, sensitive as sv};
80
use std::future::{Future, IntoFuture};
81
use std::net::IpAddr;
82
use std::pin::Pin;
83
use std::sync::{Mutex, MutexGuard};
84
use std::time::Duration;
85
use tor_cell::chancell::ChanMsg;
86
use tor_cell::chancell::{AnyChanCell, CircId, msg::Netinfo, msg::PaddingNegotiate};
87
use tor_error::internal;
88
use tor_linkspec::{HasRelayIds, OwnedChanTarget};
89
use tor_memquota::mq_queue::{self, ChannelSpec as _, MpscSpec};
90
use tor_rtcompat::{CoarseTimeProvider, DynTimeProvider, SleepProvider};
91

            
92
#[cfg(feature = "circ-padding")]
93
use tor_async_utils::counting_streams::{self, CountingSink, CountingStream};
94

            
95
#[cfg(feature = "relay")]
96
use crate::circuit::CircuitRxReceiver;
97

            
98
/// Imports that are re-exported pub if feature `testing` is enabled
99
///
100
/// Putting them together in a little module like this allows us to select the
101
/// visibility for all of these things together.
102
mod testing_exports {
103
    #![allow(unreachable_pub)]
104
    pub use super::reactor::CtrlMsg;
105
    pub use crate::circuit::celltypes::CreateResponse;
106
}
107
#[cfg(feature = "testing")]
108
pub use testing_exports::*;
109
#[cfg(not(feature = "testing"))]
110
use testing_exports::*;
111

            
112
use asynchronous_codec;
113
use futures::channel::mpsc;
114
use futures::io::{AsyncRead, AsyncWrite};
115
use oneshot_fused_workaround as oneshot;
116

            
117
use educe::Educe;
118
use futures::{FutureExt as _, Sink};
119
use std::result::Result as StdResult;
120
use std::sync::Arc;
121
use std::task::{Context, Poll};
122

            
123
use tracing::{instrument, trace};
124

            
125
// reexport
126
pub use super::client::channel::handshake::ClientInitiatorHandshake;
127
#[cfg(feature = "relay")]
128
pub use super::relay::channel::handshake::RelayInitiatorHandshake;
129
use crate::channel::unique_id::CircUniqIdContext;
130

            
131
use kist::KistParams;
132

            
133
/// This indicate what type of channel it is. It allows us to decide for the correct channel cell
134
/// state machines and authentication process (if any).
135
///
136
/// It is created when a channel is requested for creation which means the subsystem wanting to
137
/// open a channel needs to know what type it wants.
138
#[derive(Clone, Copy, Debug, derive_more::Display)]
139
#[non_exhaustive]
140
pub enum ChannelType {
141
    /// Client: Initiated from a client to a relay. Client is unauthenticated and relay is
142
    /// authenticated.
143
    ClientInitiator,
144
    /// Relay: Initiating as a relay to a relay. Both sides are authenticated.
145
    RelayInitiator,
146
    /// Relay: Responding as a relay to a relay or client. Authenticated or Unauthenticated.
147
    RelayResponder {
148
        /// Indicate if the channel is authenticated. Responding as a relay can be either from a
149
        /// Relay (authenticated) or a Client/Bridge (Unauthenticated). We only know this
150
        /// information once the handshake is completed.
151
        ///
152
        /// This side is always authenticated, the other side can be if a relay or not if
153
        /// bridge/client. This is set to false unless we end up authenticating the other side
154
        /// meaning a relay.
155
        authenticated: bool,
156
    },
157
}
158

            
159
impl ChannelType {
160
    /// Set that this channel type is now authenticated. This only applies to RelayResponder.
161
    pub(crate) fn set_authenticated(&mut self) {
162
        if let Self::RelayResponder { authenticated } = self {
163
            *authenticated = true;
164
        }
165
    }
166
}
167

            
168
/// A channel cell frame used for sending and receiving cells on a channel. The handler takes care
169
/// of the cell codec transition depending in which state the channel is.
170
///
171
/// ChannelFrame is used to basically handle all in and outbound cells on a channel for its entire
172
/// lifetime.
173
pub(crate) type ChannelFrame<T> = asynchronous_codec::Framed<T, handler::ChannelCellHandler>;
174

            
175
/// An entry in a channel's queue of cells to be flushed.
176
pub(crate) type ChanCellQueueEntry = (AnyChanCell, Option<QueuedCellPaddingInfo>);
177

            
178
/// Helper: Return a new channel frame [ChannelFrame] from an object implementing AsyncRead + AsyncWrite. In the
179
/// tor context, it is always a TLS stream.
180
///
181
/// The ty (type) argument needs to be able to transform into a [handler::ChannelCellHandler] which would
182
/// generally be a [ChannelType].
183
72
pub(crate) fn new_frame<T, I>(tls: T, ty: I) -> ChannelFrame<T>
184
72
where
185
72
    T: AsyncRead + AsyncWrite,
186
72
    I: Into<handler::ChannelCellHandler>,
187
{
188
72
    let mut framed = asynchronous_codec::Framed::new(tls, ty.into());
189
72
    framed.set_send_high_water_mark(32 * 1024);
190
72
    framed
191
72
}
192

            
193
/// Canonical state between this channel and its peer. This is inferred from the [`Netinfo`]
194
/// received during the channel handshake.
195
///
196
/// A connection is "canonical" if the TCP connection's peer IP address matches an address
197
/// that the relay itself claims in its [`Netinfo`] cell.
198
#[derive(Debug)]
199
pub(crate) struct Canonicity {
200
    /// The peer has proven this connection is canonical for its address: at least one NETINFO "my
201
    /// address" matches the observed TCP peer address.
202
    pub(crate) peer_is_canonical: bool,
203
    /// We appear canonical from the peer's perspective: its NETINFO "other address" matches our
204
    /// advertised relay address.
205
    pub(crate) canonical_to_peer: bool,
206
}
207

            
208
impl Canonicity {
209
    /// Using a [`Netinfo`], build the canonicity object with the given addresses.
210
    ///
211
    /// The `my_addrs` are the advertised address of this relay or empty if a client/bridge as they
212
    /// do not advertise or expose a reachable address.
213
    ///
214
    /// The `peer_addr` is the IP address we believe the peer has. In other words, it is either the
215
    /// IP we used to connect to or the address we see in the accept() phase of the connection.
216
    ///
217
    /// It can be None if we used a non-IP address to connect to the peer (PT).
218
50
    pub(crate) fn from_netinfo(
219
50
        netinfo: &Netinfo,
220
50
        my_addrs: &[IpAddr],
221
50
        peer_addr: Option<IpAddr>,
222
50
    ) -> Self {
223
        Self {
224
            // The "other addr" (our address as seen by the peer) matches the one we advertised.
225
50
            canonical_to_peer: netinfo
226
50
                .their_addr()
227
52
                .is_some_and(|a: &IpAddr| my_addrs.contains(a)),
228
            // The "my addresses" (the peer addresses that it claims to have) matches the one we
229
            // see on the connection or that we attempted to connect to.
230
50
            peer_is_canonical: peer_addr
231
52
                .map(|a| netinfo.my_addrs().contains(&a))
232
50
                .unwrap_or_default(),
233
        }
234
50
    }
235

            
236
    /// Construct a fully canonical object.
237
    #[cfg(any(test, feature = "testing"))]
238
1644
    pub(crate) fn new_canonical() -> Self {
239
1644
        Self {
240
1644
            peer_is_canonical: true,
241
1644
            canonical_to_peer: true,
242
1644
        }
243
1644
    }
244
}
245

            
246
/// An open client channel, ready to send and receive Tor cells.
247
///
248
/// A channel is a direct connection to a Tor relay, implemented using TLS.
249
///
250
/// This struct is a frontend that can be used to send cells
251
/// and otherwise control the channel.  The main state is
252
/// in the Reactor object.
253
///
254
/// (Users need a mutable reference because of the types in `Sink`, and
255
/// ultimately because `cell_tx: mpsc::Sender` doesn't work without mut.
256
///
257
/// # Channel life cycle
258
///
259
/// Channels can be created directly here through a channel builder (client or relay) API.
260
/// For a higher-level API (with better support for TLS, pluggable transports,
261
/// and channel reuse) see the `tor-chanmgr` crate.
262
///
263
/// After a channel is created, it will persist until it is closed in one of
264
/// four ways:
265
///    1. A remote error occurs.
266
///    2. The other side of the channel closes the channel.
267
///    3. Someone calls [`Channel::terminate`] on the channel.
268
///    4. The last reference to the `Channel` is dropped. (Note that every circuit
269
///       on a `Channel` keeps a reference to it, which will in turn keep the
270
///       channel from closing until all those circuits have gone away.)
271
///
272
/// Note that in cases 1-3, the [`Channel`] object itself will still exist: it
273
/// will just be unusable for most purposes.  Most operations on it will fail
274
/// with an error.
275
pub struct Channel {
276
    /// The channel type.
277
    #[expect(unused)] // TODO: Remove once used.
278
    channel_type: ChannelType,
279
    /// A channel used to send control messages to the Reactor.
280
    control: mpsc::UnboundedSender<CtrlMsg>,
281
    /// A channel used to send cells to the Reactor.
282
    cell_tx: CellTx,
283

            
284
    /// A receiver that indicates whether the channel is closed.
285
    ///
286
    /// Awaiting will return a `CancelledError` event when the reactor is dropped.
287
    /// Read to decide if operations may succeed, and is returned by `wait_for_close`.
288
    reactor_closed_rx: oneshot_broadcast::Receiver<Result<CloseInfo>>,
289

            
290
    /// Padding controller, used to report when data is queued for this channel.
291
    padding_ctrl: PaddingController,
292

            
293
    /// A unique identifier for this channel.
294
    unique_id: UniqId,
295
    /// Target identity and address information for this peer.
296
    peer_id: OwnedChanTarget,
297
    /// Validated information for this peer.
298
    #[expect(unused)] // TODO(relay) Remove once used un choose_channel()
299
    peer: MaybeSensitive<PeerInfo>,
300
    /// The declared clock skew on this channel, at the time when this channel was
301
    /// created.
302
    clock_skew: ClockSkew,
303
    /// The time when this channel was successfully completed
304
    opened_at: coarsetime::Instant,
305
    /// Mutable state used by the `Channel.
306
    mutable: Mutex<MutableDetails>,
307
    /// Information shared with the reactor
308
    details: Arc<ChannelDetails>,
309
    /// Canonicity of this channel.
310
    canonicity: Canonicity,
311
}
312

            
313
/// This is information shared between the reactor and the frontend (`Channel` object).
314
///
315
/// `control` can't be here because we rely on it getting dropped when the last user goes away.
316
#[derive(Debug)]
317
pub(crate) struct ChannelDetails {
318
    /// Since when the channel became unused.
319
    ///
320
    /// If calling `time_since_update` returns None,
321
    /// this channel is still in use by at least one circuit.
322
    ///
323
    /// Set by reactor when a circuit is added or removed.
324
    /// Read from `Channel::duration_unused`.
325
    unused_since: AtomicOptTimestamp,
326
    /// Memory quota account
327
    ///
328
    /// This is here partly because we need to ensure it lives as long as the channel,
329
    /// as otherwise the memquota system will tear the account down.
330
    #[allow(dead_code)]
331
    memquota: ChannelAccount,
332
}
333

            
334
/// Mutable details (state) used by the `Channel` (frontend)
335
#[derive(Debug, Default)]
336
struct MutableDetails {
337
    /// State used to control padding
338
    padding: PaddingControlState,
339
}
340

            
341
/// State used to control padding
342
///
343
/// We store this here because:
344
///
345
///  1. It must be per-channel, because it depends on channel usage.  So it can't be in
346
///     (for example) `ChannelPaddingInstructionsUpdate`.
347
///
348
///  2. It could be in the channel manager's per-channel state but (for code flow reasons
349
///     there, really) at the point at which the channel manager concludes for a pending
350
///     channel that it ought to update the usage, it has relinquished the lock on its own data
351
///     structure.
352
///     And there is actually no need for this to be global: a per-channel lock is better than
353
///     reacquiring the global one.
354
///
355
///  3. It doesn't want to be in the channel reactor since that's super hot.
356
///
357
/// See also the overview at [`tor_proto::channel::padding`](padding)
358
#[derive(Debug, Educe)]
359
#[educe(Default)]
360
enum PaddingControlState {
361
    /// No usage of this channel, so far, implies sending or negotiating channel padding.
362
    ///
363
    /// This means we do not send (have not sent) any `ChannelPaddingInstructionsUpdates` to the reactor,
364
    /// with the following consequences:
365
    ///
366
    ///  * We don't enable our own padding.
367
    ///  * We don't do any work to change the timeout distribution in the padding timer,
368
    ///    (which is fine since this timer is not enabled).
369
    ///  * We don't send any PADDING_NEGOTIATE cells.  The peer is supposed to come to the
370
    ///    same conclusions as us, based on channel usage: it should also not send padding.
371
    #[educe(Default)]
372
    UsageDoesNotImplyPadding {
373
        /// The last padding parameters (from reparameterize)
374
        ///
375
        /// We keep this so that we can send it if and when
376
        /// this channel starts to be used in a way that implies (possibly) sending padding.
377
        padding_params: ChannelPaddingInstructionsUpdates,
378
    },
379

            
380
    /// Some usage of this channel implies possibly sending channel padding
381
    ///
382
    /// The required padding timer, negotiation cell, etc.,
383
    /// have been communicated to the reactor via a `CtrlMsg::ConfigUpdate`.
384
    ///
385
    /// Once we have set this variant, it remains this way forever for this channel,
386
    /// (the spec speaks of channels "only used for" certain purposes not getting padding).
387
    PaddingConfigured,
388
}
389

            
390
use PaddingControlState as PCS;
391

            
392
cfg_if! {
393
    if #[cfg(feature="circ-padding")] {
394
        /// Implementation type for a ChannelSender.
395
        type CellTx = CountingSink<mq_queue::Sender<ChanCellQueueEntry, mq_queue::MpscSpec>>;
396

            
397
        /// Implementation type for a cell queue held by a reactor.
398
        type CellRx = CountingStream<mq_queue::Receiver<ChanCellQueueEntry, mq_queue::MpscSpec>>;
399
    } else {
400
        /// Implementation type for a ChannelSender.
401
        type CellTx = mq_queue::Sender<ChanCellQueueEntry, mq_queue::MpscSpec>;
402

            
403
        /// Implementation type for a cell queue held by a reactor.
404
        type CellRx = mq_queue::Receiver<ChanCellQueueEntry, mq_queue::MpscSpec>;
405
    }
406
}
407

            
408
/// A handle to a [`Channel`]` that can be used, by circuits, to send channel cells.
409
#[derive(Debug)]
410
pub(crate) struct ChannelSender {
411
    /// MPSC sender to send cells.
412
    cell_tx: CellTx,
413
    /// A receiver used to check if the channel is closed.
414
    reactor_closed_rx: oneshot_broadcast::Receiver<Result<CloseInfo>>,
415
    /// Unique ID for this channel. For logging.
416
    unique_id: UniqId,
417
    /// Padding controller for this channel:
418
    /// used to report when we queue data that will eventually wind up on the channel.
419
    padding_ctrl: PaddingController,
420
}
421

            
422
impl ChannelSender {
423
    /// Check whether a cell type is permissible to be _sent_ on an
424
    /// open client channel.
425
4674
    fn check_cell(&self, cell: &AnyChanCell) -> Result<()> {
426
        use tor_cell::chancell::msg::AnyChanMsg::*;
427
4674
        let msg = cell.msg();
428
4674
        match msg {
429
12
            Created(_) | Created2(_) | CreatedFast(_) => Err(Error::from(internal!(
430
12
                "Can't send {} cell on client channel",
431
12
                msg.cmd()
432
12
            ))),
433
            Certs(_) | Versions(_) | Authenticate(_) | AuthChallenge(_) | Netinfo(_) => {
434
12
                Err(Error::from(internal!(
435
12
                    "Can't send {} cell after handshake is done",
436
12
                    msg.cmd()
437
12
                )))
438
            }
439
4650
            _ => Ok(()),
440
        }
441
4674
    }
442

            
443
    /// Obtain a reference to the `ChannelSender`'s [`DynTimeProvider`]
444
    ///
445
    /// (This can sometimes be used to avoid having to keep
446
    /// a separate clone of the time provider.)
447
72
    pub(crate) fn time_provider(&self) -> &DynTimeProvider {
448
        cfg_if! {
449
            if #[cfg(feature="circ-padding")] {
450
72
                self.cell_tx.inner().time_provider()
451
            } else {
452
                self.cell_tx.time_provider()
453
            }
454
        }
455
72
    }
456

            
457
    /// Return an approximate count of the number of outbound cells queued for this channel.
458
    ///
459
    /// This count is necessarily approximate,
460
    /// because the underlying count can be modified by other senders and receivers
461
    /// between when this method is called and when its return value is used.
462
    ///
463
    /// Does not include cells that have already been passed to the TLS connection.
464
    ///
465
    /// Circuit padding uses this count to determine
466
    /// when messages are already outbound for the first hop of a circuit.
467
    #[cfg(feature = "circ-padding")]
468
    pub(crate) fn approx_count(&self) -> usize {
469
        self.cell_tx.approx_count()
470
    }
471

            
472
    /// Note that a cell has been queued that will eventually be placed onto this sender.
473
    ///
474
    /// We use this as an input for padding machines.
475
4638
    pub(crate) fn note_cell_queued(&self) {
476
4638
        self.padding_ctrl.queued_data(crate::HopNum::from(0));
477
4638
    }
478
}
479

            
480
impl Sink<ChanCellQueueEntry> for ChannelSender {
481
    type Error = Error;
482

            
483
18842
    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
484
18842
        let this = self.get_mut();
485
18842
        Pin::new(&mut this.cell_tx)
486
18842
            .poll_ready(cx)
487
18850
            .map_err(|_| ChannelClosed.into())
488
18842
    }
489

            
490
4638
    fn start_send(self: Pin<&mut Self>, cell: ChanCellQueueEntry) -> Result<()> {
491
4638
        let this = self.get_mut();
492
4638
        if this.reactor_closed_rx.is_ready() {
493
            return Err(ChannelClosed.into());
494
4638
        }
495
4638
        this.check_cell(&cell.0)?;
496
        {
497
            use tor_cell::chancell::msg::AnyChanMsg::*;
498
4638
            match cell.0.msg() {
499
4518
                Relay(_) | Padding(_) | Vpadding(_) => {} // too frequent to log.
500
120
                _ => trace!(
501
                    channel_id = %this.unique_id,
502
                    "Sending {} for {}",
503
                    cell.0.msg().cmd(),
504
                    CircId::get_or_zero(cell.0.circid())
505
                ),
506
            }
507
        }
508

            
509
4638
        Pin::new(&mut this.cell_tx)
510
4638
            .start_send(cell)
511
4638
            .map_err(|_| ChannelClosed.into())
512
4638
    }
513

            
514
48
    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
515
48
        let this = self.get_mut();
516
48
        Pin::new(&mut this.cell_tx)
517
48
            .poll_flush(cx)
518
48
            .map_err(|_| ChannelClosed.into())
519
48
    }
520

            
521
    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
522
        let this = self.get_mut();
523
        Pin::new(&mut this.cell_tx)
524
            .poll_close(cx)
525
            .map_err(|_| ChannelClosed.into())
526
    }
527
}
528

            
529
impl Channel {
530
    /// Construct a channel and reactor.
531
    ///
532
    /// Internal method, called to finalize the channel when we've
533
    /// sent our netinfo cell, received the peer's netinfo cell, and
534
    /// we're finally ready to create circuits.
535
    ///
536
    /// Quick note on the allow clippy. This is has one call site so for now, it is fine that we
537
    /// bust the mighty 7 arguments.
538
    #[allow(clippy::too_many_arguments)] // TODO consider if we want a builder
539
476
    fn new<S>(
540
476
        channel_type: ChannelType,
541
476
        link_protocol: u16,
542
476
        sink: BoxedChannelSink,
543
476
        stream: BoxedChannelStream,
544
476
        streamops: BoxedChannelStreamOps,
545
476
        unique_id: UniqId,
546
476
        peer_id: OwnedChanTarget,
547
476
        peer: MaybeSensitive<PeerInfo>,
548
476
        clock_skew: ClockSkew,
549
476
        sleep_prov: S,
550
476
        memquota: ChannelAccount,
551
476
        canonicity: Canonicity,
552
476
    ) -> Result<(Arc<Self>, reactor::Reactor<S>)>
553
476
    where
554
476
        S: CoarseTimeProvider + SleepProvider,
555
    {
556
        use circmap::{CircIdRange, CircMap};
557
476
        let circid_range = match channel_type {
558
            ChannelType::RelayResponder { .. } => CircIdRange::Low,
559
476
            ChannelType::ClientInitiator | ChannelType::RelayInitiator => CircIdRange::High,
560
        };
561
476
        let circmap = CircMap::new(circid_range);
562
476
        let dyn_time = DynTimeProvider::new(sleep_prov.clone());
563

            
564
476
        let (control_tx, control_rx) = mpsc::unbounded();
565
476
        let (cell_tx, cell_rx) = mq_queue::MpscSpec::new(CHANNEL_BUFFER_SIZE)
566
476
            .new_mq(dyn_time.clone(), memquota.as_raw_account())?;
567
        #[cfg(feature = "circ-padding")]
568
476
        let (cell_tx, cell_rx) = counting_streams::channel(cell_tx, cell_rx);
569
476
        let unused_since = AtomicOptTimestamp::new();
570
476
        unused_since.update();
571

            
572
476
        let mutable = MutableDetails::default();
573
476
        let (reactor_closed_tx, reactor_closed_rx) = oneshot_broadcast::channel();
574

            
575
476
        let details = ChannelDetails {
576
476
            unused_since,
577
476
            memquota,
578
476
        };
579
476
        let details = Arc::new(details);
580

            
581
        // We might be using experimental maybenot padding; this creates the padding framework for that.
582
        //
583
        // TODO: This backend is currently optimized for circuit padding,
584
        // so it might allocate a bit more than necessary to account for multiple hops.
585
        // We should tune it when we deploy padding in production.
586
476
        let (padding_ctrl, padding_event_stream) =
587
476
            client::circuit::padding::new_padding(DynTimeProvider::new(sleep_prov.clone()));
588

            
589
476
        let channel = Arc::new(Channel {
590
476
            channel_type,
591
476
            control: control_tx,
592
476
            cell_tx,
593
476
            reactor_closed_rx,
594
476
            padding_ctrl: padding_ctrl.clone(),
595
476
            unique_id,
596
476
            peer_id,
597
476
            peer,
598
476
            clock_skew,
599
476
            opened_at: coarsetime::Instant::now(),
600
476
            mutable: Mutex::new(mutable),
601
476
            details: Arc::clone(&details),
602
476
            canonicity,
603
476
        });
604

            
605
        // We start disabled; the channel manager will `reconfigure` us soon after creation.
606
476
        let padding_timer = Box::pin(padding::Timer::new_disabled(sleep_prov.clone(), None)?);
607

            
608
        cfg_if! {
609
            if #[cfg(feature = "circ-padding")] {
610
                use crate::util::sink_blocker::{SinkBlocker,CountingPolicy};
611
476
                let sink = SinkBlocker::new(sink, CountingPolicy::new_unlimited());
612
            }
613
        }
614

            
615
476
        let reactor = Reactor {
616
476
            runtime: sleep_prov,
617
476
            control: control_rx,
618
476
            cells: cell_rx,
619
476
            reactor_closed_tx,
620
476
            input: futures::StreamExt::fuse(stream),
621
476
            output: sink,
622
476
            streamops,
623
476
            circs: circmap,
624
476
            circ_unique_id_ctx: CircUniqIdContext::new(),
625
476
            link_protocol,
626
476
            unique_id,
627
476
            details,
628
476
            padding_timer,
629
476
            padding_ctrl,
630
476
            padding_event_stream,
631
476
            padding_blocker: None,
632
476
            special_outgoing: Default::default(),
633
476
        };
634

            
635
476
        Ok((channel, reactor))
636
476
    }
637

            
638
    /// Return a process-unique identifier for this channel.
639
4
    pub fn unique_id(&self) -> UniqId {
640
4
        self.unique_id
641
4
    }
642

            
643
    /// Return a reference to the memory tracking account for this Channel
644
    pub fn mq_account(&self) -> &ChannelAccount {
645
        &self.details.memquota
646
    }
647

            
648
    /// Obtain a reference to the `Channel`'s [`DynTimeProvider`]
649
    ///
650
    /// (This can sometimes be used to avoid having to keep
651
    /// a separate clone of the time provider.)
652
388
    pub fn time_provider(&self) -> &DynTimeProvider {
653
        cfg_if! {
654
            if #[cfg(feature="circ-padding")] {
655
388
                self.cell_tx.inner().time_provider()
656
            } else {
657
                self.cell_tx.time_provider()
658
            }
659
        }
660
388
    }
661

            
662
    /// Return an OwnedChanTarget representing the actual handshake used to
663
    /// create this channel.
664
1200
    pub fn target(&self) -> &OwnedChanTarget {
665
1200
        &self.peer_id
666
1200
    }
667

            
668
    /// Return the amount of time that has passed since this channel became open.
669
    pub fn age(&self) -> Duration {
670
        self.opened_at.elapsed().into()
671
    }
672

            
673
    /// Return a ClockSkew declaring how much clock skew the other side of this channel
674
    /// claimed that we had when we negotiated the connection.
675
    pub fn clock_skew(&self) -> ClockSkew {
676
        self.clock_skew
677
    }
678

            
679
    /// Send a control message
680
    #[instrument(level = "trace", skip_all)]
681
2964
    fn send_control(&self, msg: CtrlMsg) -> StdResult<(), ChannelClosed> {
682
2964
        self.control
683
2964
            .unbounded_send(msg)
684
2964
            .map_err(|_| ChannelClosed)?;
685
2862
        Ok(())
686
2964
    }
687

            
688
    /// Acquire the lock on `mutable` (and handle any poison error)
689
1152
    fn mutable(&self) -> MutexGuard<MutableDetails> {
690
1152
        self.mutable.lock().expect("channel details poisoned")
691
1152
    }
692

            
693
    /// Specify that this channel should do activities related to channel padding
694
    ///
695
    /// Initially, the channel does nothing related to channel padding:
696
    /// it neither sends any padding, nor sends any PADDING_NEGOTIATE cells.
697
    ///
698
    /// After this function has been called, it will do both,
699
    /// according to the parameters specified through `reparameterize`.
700
    /// Note that this might include *disabling* padding
701
    /// (for example, by sending a `PADDING_NEGOTIATE`).
702
    ///
703
    /// Idempotent.
704
    ///
705
    /// There is no way to undo the effect of this call.
706
    #[instrument(level = "trace", skip_all)]
707
1152
    pub fn engage_padding_activities(&self) {
708
1152
        let mut mutable = self.mutable();
709

            
710
1152
        match &mutable.padding {
711
            PCS::UsageDoesNotImplyPadding {
712
1152
                padding_params: params,
713
            } => {
714
                // Well, apparently the channel usage *does* imply padding now,
715
                // so we need to (belatedly) enable the timer,
716
                // send the padding negotiation cell, etc.
717
1152
                let mut params = params.clone();
718

            
719
                // Except, maybe the padding we would be requesting is precisely default,
720
                // so we wouldn't actually want to send that cell.
721
1152
                if params.padding_negotiate == Some(PaddingNegotiate::start_default()) {
722
                    params.padding_negotiate = None;
723
1152
                }
724

            
725
1152
                match self.send_control(CtrlMsg::ConfigUpdate(Arc::new(params))) {
726
1152
                    Ok(()) => {}
727
                    Err(ChannelClosed) => return,
728
                }
729

            
730
1152
                mutable.padding = PCS::PaddingConfigured;
731
            }
732

            
733
            PCS::PaddingConfigured => {
734
                // OK, nothing to do
735
            }
736
        }
737

            
738
1152
        drop(mutable); // release the lock now: lock span covers the send, ensuring ordering
739
1152
    }
740

            
741
    /// Reparameterise (update parameters; reconfigure)
742
    ///
743
    /// Returns `Err` if the channel was closed earlier
744
    #[instrument(level = "trace", skip_all)]
745
2592
    pub fn reparameterize(&self, params: Arc<ChannelPaddingInstructionsUpdates>) -> Result<()> {
746
2592
        let mut mutable = self
747
2592
            .mutable
748
2592
            .lock()
749
2592
            .map_err(|_| internal!("channel details poisoned"))?;
750

            
751
2592
        match &mut mutable.padding {
752
            PCS::PaddingConfigured => {
753
1440
                self.send_control(CtrlMsg::ConfigUpdate(params))?;
754
            }
755
1152
            PCS::UsageDoesNotImplyPadding { padding_params } => {
756
1152
                padding_params.combine(&params);
757
1152
            }
758
        }
759

            
760
2592
        drop(mutable); // release the lock now: lock span covers the send, ensuring ordering
761
2592
        Ok(())
762
2592
    }
763

            
764
    /// Update the KIST parameters.
765
    ///
766
    /// Returns `Err` if the channel is closed.
767
    #[instrument(level = "trace", skip_all)]
768
    pub fn reparameterize_kist(&self, kist_params: KistParams) -> Result<()> {
769
        Ok(self.send_control(CtrlMsg::KistConfigUpdate(kist_params))?)
770
    }
771

            
772
    /// Return an error if this channel is somehow mismatched with the
773
    /// given target.
774
42
    pub fn check_match<T: HasRelayIds + ?Sized>(&self, target: &T) -> Result<()> {
775
42
        check_id_match_helper(&self.peer_id, target)
776
42
    }
777

            
778
    /// Return true if this channel is closed and therefore unusable.
779
120
    pub fn is_closing(&self) -> bool {
780
120
        self.reactor_closed_rx.is_ready()
781
120
    }
782

            
783
    /// Return true iff this channel is considered canonical by us.
784
    pub fn is_canonical(&self) -> bool {
785
        self.canonicity.peer_is_canonical
786
    }
787

            
788
    /// Return true if we think the peer considers this channel as canonical.
789
    pub fn is_canonical_to_peer(&self) -> bool {
790
        self.canonicity.canonical_to_peer
791
    }
792

            
793
    /// If the channel is not in use, return the amount of time
794
    /// it has had with no circuits.
795
    ///
796
    /// Return `None` if the channel is currently in use.
797
182
    pub fn duration_unused(&self) -> Option<std::time::Duration> {
798
182
        self.details
799
182
            .unused_since
800
182
            .time_since_update()
801
182
            .map(Into::into)
802
182
    }
803

            
804
    /// Return a new [`ChannelSender`] to transmit cells on this channel.
805
412
    pub(crate) fn sender(&self) -> ChannelSender {
806
412
        ChannelSender {
807
412
            cell_tx: self.cell_tx.clone(),
808
412
            reactor_closed_rx: self.reactor_closed_rx.clone(),
809
412
            unique_id: self.unique_id,
810
412
            padding_ctrl: self.padding_ctrl.clone(),
811
412
        }
812
412
    }
813

            
814
    /// Return a newly allocated PendingClientTunnel object with
815
    /// a corresponding tunnel reactor. A circuit ID is allocated, but no
816
    /// messages are sent, and no cryptography is done.
817
    ///
818
    /// To use the results of this method, call Reactor::run() in a
819
    /// new task, then use the methods of
820
    /// [crate::client::circuit::PendingClientTunnel] to build the circuit.
821
    #[instrument(level = "trace", skip_all)]
822
12
    pub async fn new_tunnel(
823
12
        self: &Arc<Self>,
824
12
        timeouts: Arc<dyn TimeoutEstimator>,
825
18
    ) -> Result<(PendingClientTunnel, client::reactor::Reactor)> {
826
        if self.is_closing() {
827
            return Err(ChannelClosed.into());
828
        }
829

            
830
        let time_prov = self.time_provider().clone();
831
        let memquota = CircuitAccount::new(&self.details.memquota)?;
832

            
833
        // TODO: blocking is risky, but so is unbounded.
834
        let (sender, receiver) =
835
            MpscSpec::new(128).new_mq(time_prov.clone(), memquota.as_raw_account())?;
836
        let (createdsender, createdreceiver) = oneshot::channel::<CreateResponse>();
837

            
838
        let (tx, rx) = oneshot::channel();
839
        self.send_control(CtrlMsg::AllocateCircuit {
840
            created_sender: createdsender,
841
            sender,
842
            tx,
843
        })?;
844
        let (id, circ_unique_id, padding_ctrl, padding_stream) =
845
            rx.await.map_err(|_| ChannelClosed)??;
846

            
847
        trace!("{}: Allocated CircId {}", circ_unique_id, id);
848

            
849
        Ok(PendingClientTunnel::new(
850
            id,
851
            self.clone(),
852
            createdreceiver,
853
            receiver,
854
            circ_unique_id,
855
            time_prov,
856
            memquota,
857
            padding_ctrl,
858
            padding_stream,
859
            timeouts,
860
        ))
861
12
    }
862

            
863
    /// Return a newly allocated outbound relay circuit with.
864
    ///
865
    /// A circuit ID is allocated, but no messages are sent, and no cryptography is done.
866
    ///
867
    // TODO(relay): this duplicates much of new_tunnel above, but I expect
868
    // the implementations to diverge once we introduce a new CtrlMsg for
869
    // allocating relay circuits.
870
    #[cfg(feature = "relay")]
871
    pub(crate) async fn new_outbound_circ(
872
        self: &Arc<Self>,
873
    ) -> Result<(CircId, CircuitRxReceiver, oneshot::Receiver<CreateResponse>)> {
874
        if self.is_closing() {
875
            return Err(ChannelClosed.into());
876
        }
877

            
878
        let time_prov = self.time_provider().clone();
879
        let memquota = CircuitAccount::new(&self.details.memquota)?;
880

            
881
        // TODO: blocking is risky, but so is unbounded.
882
        let (sender, receiver) =
883
            MpscSpec::new(128).new_mq(time_prov.clone(), memquota.as_raw_account())?;
884
        let (createdsender, createdreceiver) = oneshot::channel::<CreateResponse>();
885

            
886
        let (tx, rx) = oneshot::channel();
887

            
888
        self.send_control(CtrlMsg::AllocateCircuit {
889
            created_sender: createdsender,
890
            sender,
891
            tx,
892
        })?;
893

            
894
        // TODO(relay): I don't think we need circuit-level padding on this side of the circuit.
895
        // This just drops the padding controller and corresponding event stream,
896
        // but maybe it would be better to just not set it up in the first place?
897
        // This suggests we might need a different control command for allocating
898
        // the outbound relay circuits...
899
        let (id, circ_unique_id, _padding_ctrl, _padding_stream) =
900
            rx.await.map_err(|_| ChannelClosed)??;
901

            
902
        trace!("{}: Allocated CircId {}", circ_unique_id, id);
903

            
904
        Ok((id, receiver, createdreceiver))
905
    }
906

            
907
    /// Shut down this channel immediately, along with all circuits that
908
    /// are using it.
909
    ///
910
    /// Note that other references to this channel may exist.  If they
911
    /// do, they will stop working after you call this function.
912
    ///
913
    /// It's not necessary to call this method if you're just done
914
    /// with a channel: the channel should close on its own once nothing
915
    /// is using it any more.
916
    #[instrument(level = "trace", skip_all)]
917
36
    pub fn terminate(&self) {
918
36
        let _ = self.send_control(CtrlMsg::Shutdown);
919
36
    }
920

            
921
    /// Tell the reactor that the circuit with the given ID has gone away.
922
    #[instrument(level = "trace", skip_all)]
923
324
    pub fn close_circuit(&self, circid: CircId) -> Result<()> {
924
324
        self.send_control(CtrlMsg::CloseCircuit(circid))?;
925
222
        Ok(())
926
324
    }
927

            
928
    /// Return a future that will resolve once this channel has closed.
929
    ///
930
    /// Note that this method does not _cause_ the channel to shut down on its own.
931
36
    pub fn wait_for_close(
932
36
        &self,
933
36
    ) -> impl Future<Output = StdResult<CloseInfo, ClosedUnexpectedly>> + Send + Sync + 'static + use<>
934
    {
935
36
        self.reactor_closed_rx
936
36
            .clone()
937
36
            .into_future()
938
48
            .map(|recv| match recv {
939
12
                Ok(Ok(info)) => Ok(info),
940
12
                Ok(Err(e)) => Err(ClosedUnexpectedly::ReactorError(e)),
941
12
                Err(oneshot_broadcast::SenderDropped) => Err(ClosedUnexpectedly::ReactorDropped),
942
36
            })
943
36
    }
944

            
945
    /// Install a [`CircuitPadder`](client::CircuitPadder) for this channel.
946
    ///
947
    /// Replaces any previous padder installed.
948
    #[cfg(feature = "circ-padding-manual")]
949
    pub async fn start_padding(self: &Arc<Self>, padder: client::CircuitPadder) -> Result<()> {
950
        self.set_padder_impl(Some(padder)).await
951
    }
952

            
953
    /// Remove any [`CircuitPadder`](client::CircuitPadder) installed for this channel.
954
    ///
955
    /// Does nothing if there was not a padder installed there.
956
    #[cfg(feature = "circ-padding-manual")]
957
    pub async fn stop_padding(self: &Arc<Self>) -> Result<()> {
958
        self.set_padder_impl(None).await
959
    }
960

            
961
    /// Replace the [`CircuitPadder`](client::CircuitPadder) installed for this channel with `padder`.
962
    #[cfg(feature = "circ-padding-manual")]
963
    async fn set_padder_impl(
964
        self: &Arc<Self>,
965
        padder: Option<client::CircuitPadder>,
966
    ) -> Result<()> {
967
        let (tx, rx) = oneshot::channel();
968
        let msg = CtrlMsg::SetChannelPadder { padder, sender: tx };
969
        self.control
970
            .unbounded_send(msg)
971
            .map_err(|_| Error::ChannelClosed(ChannelClosed))?;
972
        rx.await.map_err(|_| Error::ChannelClosed(ChannelClosed))?
973
    }
974

            
975
    /// Make a new fake reactor-less channel.  For testing only, obviously.
976
    ///
977
    /// Returns the receiver end of the control message mpsc.
978
    ///
979
    /// Suitable for external callers who want to test behaviour
980
    /// of layers including the logic in the channel frontend
981
    /// (`Channel` object methods).
982
    //
983
    // This differs from test::fake_channel as follows:
984
    //  * It returns the mpsc Receiver
985
    //  * It does not require explicit specification of details
986
    #[cfg(feature = "testing")]
987
48
    pub fn new_fake(
988
48
        rt: impl SleepProvider + CoarseTimeProvider,
989
48
        channel_type: ChannelType,
990
48
    ) -> (Channel, mpsc::UnboundedReceiver<CtrlMsg>) {
991
48
        let (control, control_recv) = mpsc::unbounded();
992
48
        let details = fake_channel_details();
993

            
994
48
        let unique_id = UniqId::new();
995
48
        let peer_id = OwnedChanTarget::builder()
996
48
            .ed_identity([6_u8; 32].into())
997
48
            .rsa_identity([10_u8; 20].into())
998
48
            .build()
999
48
            .expect("Couldn't construct peer id");
        // This will make rx trigger immediately.
48
        let (_tx, rx) = oneshot_broadcast::channel();
48
        let (padding_ctrl, _) = client::circuit::padding::new_padding(DynTimeProvider::new(rt));
48
        let channel = Channel {
48
            channel_type,
48
            control,
48
            cell_tx: fake_mpsc().0,
48
            reactor_closed_rx: rx,
48
            padding_ctrl,
48
            unique_id,
48
            peer_id,
48
            peer: MaybeSensitive::not_sensitive(PeerInfo::EMPTY),
48
            clock_skew: ClockSkew::None,
48
            opened_at: coarsetime::Instant::now(),
48
            mutable: Default::default(),
48
            details,
48
            canonicity: Canonicity::new_canonical(),
48
        };
48
        (channel, control_recv)
48
    }
}
/// If there is any identity in `wanted_ident` that is not present in
/// `my_ident`, return a ChanMismatch error.
///
/// This is a helper for [`Channel::check_match`] and
/// UnverifiedChannel::check_internal.
50
fn check_id_match_helper<T, U>(my_ident: &T, wanted_ident: &U) -> Result<()>
50
where
50
    T: HasRelayIds + ?Sized,
50
    U: HasRelayIds + ?Sized,
{
70
    for desired in wanted_ident.identities() {
70
        let id_type = desired.id_type();
70
        match my_ident.identity(id_type) {
70
            Some(actual) if actual == desired => {}
8
            Some(actual) => {
8
                return Err(Error::ChanMismatch(format!(
8
                    "Identity {} does not match target {}",
8
                    sv(actual),
8
                    sv(desired)
8
                )));
            }
            None => {
                return Err(Error::ChanMismatch(format!(
                    "Peer does not have {} identity",
                    id_type
                )));
            }
        }
    }
42
    Ok(())
50
}
impl HasRelayIds for Channel {
4656
    fn identity(
4656
        &self,
4656
        key_type: tor_linkspec::RelayIdType,
4656
    ) -> Option<tor_linkspec::RelayIdRef<'_>> {
4656
        self.peer_id.identity(key_type)
4656
    }
}
/// The status of a channel which was closed successfully.
///
/// **Note:** This doesn't have any associated data,
/// but may be expanded in the future.
// I can't think of any info we'd want to return to waiters,
// but this type leaves the possibility open without requiring any backwards-incompatible changes.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct CloseInfo;
/// The status of a channel which closed unexpectedly.
#[derive(Clone, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ClosedUnexpectedly {
    /// The channel reactor was dropped or panicked before completing.
    #[error("channel reactor was dropped or panicked before completing")]
    ReactorDropped,
    /// The channel reactor had an internal error.
    #[error("channel reactor had an internal error")]
    ReactorError(Error),
}
/// Make some fake channel details (for testing only!)
#[cfg(any(test, feature = "testing"))]
1174
fn fake_channel_details() -> Arc<ChannelDetails> {
1174
    let unused_since = AtomicOptTimestamp::new();
1174
    Arc::new(ChannelDetails {
1174
        unused_since,
1174
        memquota: crate::util::fake_mq(),
1174
    })
1174
}
/// Make an MPSC queue, of the type we use in Channels, but a fake one for testing
#[cfg(any(test, feature = "testing"))] // Used by Channel::new_fake which is also feature=testing
1172
pub(crate) fn fake_mpsc() -> (CellTx, CellRx) {
1172
    let (tx, rx) = crate::fake_mpsc(CHANNEL_BUFFER_SIZE);
    #[cfg(feature = "circ-padding")]
1172
    let (tx, rx) = counting_streams::channel(tx, rx);
1172
    (tx, rx)
1172
}
#[cfg(test)]
pub(crate) mod test {
    // Most of this module is tested via tests that also check on the
    // reactor code; there are just a few more cases to examine here.
    #![allow(clippy::unwrap_used)]
    use super::*;
    pub(crate) use crate::channel::reactor::test::{CodecResult, new_reactor};
    use tor_cell::chancell::msg::HandshakeType;
    use tor_cell::chancell::{AnyChanCell, msg};
    use tor_rtcompat::test_with_one_runtime;
    /// Make a new fake reactor-less channel.  For testing only, obviously.
    pub(crate) fn fake_channel(
        rt: impl SleepProvider + CoarseTimeProvider,
        channel_type: ChannelType,
    ) -> Channel {
        let unique_id = UniqId::new();
        let peer_id = OwnedChanTarget::builder()
            .ed_identity([6_u8; 32].into())
            .rsa_identity([10_u8; 20].into())
            .build()
            .expect("Couldn't construct peer id");
        // This will make rx trigger immediately.
        let (_tx, rx) = oneshot_broadcast::channel();
        let (padding_ctrl, _) = client::circuit::padding::new_padding(DynTimeProvider::new(rt));
        Channel {
            channel_type,
            control: mpsc::unbounded().0,
            cell_tx: fake_mpsc().0,
            reactor_closed_rx: rx,
            padding_ctrl,
            unique_id,
            peer_id,
            peer: MaybeSensitive::not_sensitive(PeerInfo::EMPTY),
            clock_skew: ClockSkew::None,
            opened_at: coarsetime::Instant::now(),
            mutable: Default::default(),
            details: fake_channel_details(),
            canonicity: Canonicity::new_canonical(),
        }
    }
    #[test]
    fn send_bad() {
        tor_rtcompat::test_with_all_runtimes!(|rt| async move {
            use std::error::Error;
            let chan = fake_channel(rt, ChannelType::ClientInitiator);
            let cell = AnyChanCell::new(CircId::new(7), msg::Created2::new(&b"hihi"[..]).into());
            let e = chan.sender().check_cell(&cell);
            assert!(e.is_err());
            assert!(
                format!("{}", e.unwrap_err().source().unwrap())
                    .contains("Can't send CREATED2 cell on client channel")
            );
            let cell = AnyChanCell::new(None, msg::Certs::new_empty().into());
            let e = chan.sender().check_cell(&cell);
            assert!(e.is_err());
            assert!(
                format!("{}", e.unwrap_err().source().unwrap())
                    .contains("Can't send CERTS cell after handshake is done")
            );
            let cell = AnyChanCell::new(
                CircId::new(5),
                msg::Create2::new(HandshakeType::NTOR, &b"abc"[..]).into(),
            );
            let e = chan.sender().check_cell(&cell);
            assert!(e.is_ok());
            // FIXME(eta): more difficult to test that sending works now that it has to go via reactor
            // let got = output.next().await.unwrap();
            // assert!(matches!(got.msg(), ChanMsg::Create2(_)));
        });
    }
    #[test]
    fn check_match() {
        test_with_one_runtime!(|rt| async move {
            let chan = fake_channel(rt, ChannelType::ClientInitiator);
            let t1 = OwnedChanTarget::builder()
                .ed_identity([6; 32].into())
                .rsa_identity([10; 20].into())
                .build()
                .unwrap();
            let t2 = OwnedChanTarget::builder()
                .ed_identity([1; 32].into())
                .rsa_identity([3; 20].into())
                .build()
                .unwrap();
            let t3 = OwnedChanTarget::builder()
                .ed_identity([3; 32].into())
                .rsa_identity([2; 20].into())
                .build()
                .unwrap();
            assert!(chan.check_match(&t1).is_ok());
            assert!(chan.check_match(&t2).is_err());
            assert!(chan.check_match(&t3).is_err());
        });
    }
    #[test]
    fn unique_id() {
        test_with_one_runtime!(|rt| async move {
            let ch1 = fake_channel(rt.clone(), ChannelType::ClientInitiator);
            let ch2 = fake_channel(rt, ChannelType::ClientInitiator);
            assert_ne!(ch1.unique_id(), ch2.unique_id());
        });
    }
    #[test]
    fn duration_unused_at() {
        test_with_one_runtime!(|rt| async move {
            let details = fake_channel_details();
            let mut ch = fake_channel(rt, ChannelType::ClientInitiator);
            ch.details = details.clone();
            details.unused_since.update();
            assert!(ch.duration_unused().is_some());
        });
    }
}