1
//! Abstract implementation of a channel manager
2

            
3
use crate::factory::BootstrapReporter;
4
use crate::mgr::state::{ChannelForTarget, PendingChannelHandle};
5
use crate::{ChanProvenance, ChannelConfig, ChannelUsage, Dormancy, Error, Result};
6

            
7
use async_trait::async_trait;
8
use futures::future::Shared;
9
use oneshot_fused_workaround as oneshot;
10
use std::result::Result as StdResult;
11
use std::sync::Arc;
12
use std::time::Duration;
13
use tor_error::{error_report, internal};
14
use tor_linkspec::{ChannelMethod, HasChanMethod, HasRelayIds};
15
use tor_netdir::params::NetParameters;
16
use tor_proto::channel::kist::KistParams;
17
use tor_proto::channel::params::ChannelPaddingInstructionsUpdates;
18
use tor_proto::memquota::{ChannelAccount, SpecificAccount as _, ToplevelAccount};
19
use tracing::{instrument, trace};
20

            
21
#[cfg(feature = "relay")]
22
use {
23
    safelog::Sensitive, std::net::SocketAddr, std::num::NonZero,
24
    tor_async_utils::bw_pool::BandwidthPool,
25
    tor_async_utils::global_rate_limit::GlobalRateLimitedConn, tor_proto::RelayChannelAuthMaterial,
26
};
27

            
28
mod select;
29
mod state;
30

            
31
/// Trait to describe as much of a
32
/// [`Channel`](tor_proto::channel::Channel) as `AbstractChanMgr`
33
/// needs to use.
34
pub(crate) trait AbstractChannel: HasRelayIds {
35
    /// Return true iff this channel is considered canonical by us.
36
    fn is_canonical(&self) -> bool;
37
    /// Return true if we think the peer considers this channel as canonical.
38
    fn is_canonical_to_peer(&self) -> bool;
39
    /// Return true iff the IP address of this channel's peer matches the given method.
40
    fn peer_matches_chan_method(&self, method: &ChannelMethod) -> bool;
41
    /// Return the amount of time that has passed since this channel became open.
42
    fn age(&self) -> Duration;
43
    /// Return true if this channel is usable.
44
    ///
45
    /// A channel might be unusable because it is closed, because it has
46
    /// hit a bug, or for some other reason.  We don't return unusable
47
    /// channels back to the user.
48
    fn is_usable(&self) -> bool;
49
    /// Return the amount of time a channel has not been in use.
50
    /// Return None if the channel is currently in use.
51
    fn duration_unused(&self) -> Option<Duration>;
52

            
53
    /// Reparameterize this channel according to the provided `ChannelPaddingInstructionsUpdates`
54
    ///
55
    /// The changed parameters may not be implemented "immediately",
56
    /// but this will be done "reasonably soon".
57
    fn reparameterize(
58
        &self,
59
        updates: Arc<ChannelPaddingInstructionsUpdates>,
60
    ) -> tor_proto::Result<()>;
61

            
62
    /// Update the KIST parameters.
63
    ///
64
    /// The changed parameters may not be implemented "immediately",
65
    /// but this will be done "reasonably soon".
66
    fn reparameterize_kist(&self, kist_params: KistParams) -> tor_proto::Result<()>;
67

            
68
    /// Specify that this channel should do activities related to channel padding
69
    ///
70
    /// See [`Channel::engage_padding_activities`]
71
    ///
72
    /// [`Channel::engage_padding_activities`]: tor_proto::channel::Channel::engage_padding_activities
73
    fn engage_padding_activities(&self);
74
}
75

            
76
/// Trait to describe how channels-like objects are created.
77
///
78
/// This differs from [`ChannelFactory`](crate::factory::ChannelFactory) in that
79
/// it's a purely crate-internal type that we use to decouple the
80
/// AbstractChanMgr code from actual "what is a channel" concerns.
81
#[async_trait]
82
pub(crate) trait AbstractChannelFactory {
83
    /// The type of channel that this factory can build.
84
    type Channel: AbstractChannel;
85
    /// Type that explains how to build an outgoing channel.
86
    type BuildSpec: HasRelayIds + HasChanMethod;
87
    /// The type of byte stream that's required to build channels for incoming connections.
88
    type Stream;
89

            
90
    /// Construct a new channel to the destination described at `target`.
91
    ///
92
    /// This function must take care of all timeouts, error detection,
93
    /// and so on.
94
    ///
95
    /// It should not retry; that is handled at a higher level.
96
    async fn build_channel(
97
        &self,
98
        target: &Self::BuildSpec,
99
        reporter: BootstrapReporter,
100
        memquota: ChannelAccount,
101
    ) -> Result<Arc<Self::Channel>>;
102

            
103
    /// Construct a new channel for an incoming connection.
104
    #[cfg(feature = "relay")]
105
    async fn build_channel_using_incoming(
106
        &self,
107
        peer: Sensitive<std::net::SocketAddr>,
108
        stream: Self::Stream,
109
        memquota: ChannelAccount,
110
    ) -> Result<Arc<Self::Channel>>;
111
}
112

            
113
/// This is the configuration for a [`ChanMgr`](crate::ChanMgr) given to the constructor.
114
#[derive(Default)]
115
pub struct ChanMgrConfig {
116
    /// Channel configuration which usually comes from a configuration file.
117
    pub(crate) cfg: ChannelConfig,
118
    /// Relay authentication key material for relay channels.
119
    #[cfg(feature = "relay")]
120
    pub(crate) auth_material: Option<Arc<RelayChannelAuthMaterial>>,
121
    /// Our address(es). When building outgoing channel, we need our addresses in order to send
122
    /// them in the NETINFO cell. It will also be used to validate initiator channel target.
123
    #[cfg(feature = "relay")]
124
    pub(crate) my_addrs: Vec<SocketAddr>,
125
    /// Bandwidth pools shared by all channels for global rate limiting.
126
    #[cfg(feature = "relay")]
127
    pub(crate) bw_pools: Option<ChannelBandwidthPools>,
128
    /// Allow outgoing relay channels to all addresses, including local and private
129
    /// addresses.
130
    #[cfg(feature = "relay")]
131
    pub(crate) allow_any_addrs: bool,
132
    // TODO: Would be good to add more things such as NetParameters and Dormancy maybe?
133
}
134

            
135
impl ChanMgrConfig {
136
    /// Constructor.
137
    pub fn new(cfg: ChannelConfig) -> Self {
138
        Self {
139
            cfg,
140
            #[cfg(feature = "relay")]
141
            auth_material: None,
142
            #[cfg(feature = "relay")]
143
            my_addrs: Vec::new(),
144
            #[cfg(feature = "relay")]
145
            bw_pools: None,
146
            #[cfg(feature = "relay")]
147
            allow_any_addrs: false,
148
        }
149
    }
150

            
151
    /// Set whether outgoing relay channels may connect to all addresses, including local
152
    /// and private addresses.
153
    ///
154
    /// This is should only be used in a testing network.
155
    #[cfg(feature = "relay")]
156
    pub fn allow_any_addrs(mut self, allow_any_addrs: bool) -> Self {
157
        self.allow_any_addrs = allow_any_addrs;
158
        self
159
    }
160

            
161
    /// Set the relay channel authentication key material and return itself.
162
    #[cfg(feature = "relay")]
163
    pub fn with_auth_material(mut self, auth_material: Arc<RelayChannelAuthMaterial>) -> Self {
164
        self.auth_material = Some(auth_material);
165
        self
166
    }
167

            
168
    /// Set our addresses that we advertise to the world.
169
    #[cfg(feature = "relay")]
170
    pub fn with_my_addrs(mut self, my_addrs: Vec<SocketAddr>) -> Self {
171
        self.my_addrs = my_addrs;
172
        self
173
    }
174

            
175
    /// Set the read and write bandwidth pools shared by all channels.
176
    #[cfg(feature = "relay")]
177
    pub fn with_bandwidth_pools(mut self, read: BandwidthPool, write: BandwidthPool) -> Self {
178
        self.bw_pools = Some(ChannelBandwidthPools { read, write });
179
        self
180
    }
181
}
182

            
183
/// Maximum number of bytes a single channel requests from the bandwidth pool.
184
///
185
/// This is the maximum TLS record plaintext size of 16KiB. See:
186
/// [RFC 8446 section 5.1](https://www.rfc-editor.org/rfc/rfc8446#section-5.1) (TLS 1.3) and
187
/// [RFC 5246 section 6.2.1](https://www.rfc-editor.org/rfc/rfc5246#section-6.2.1) (TLS 1.2).
188
#[cfg(feature = "relay")]
189
const BW_MAX_CHUNK: NonZero<usize> = NonZero::new(16 * 1024).expect("bandwidth max chunk is zero");
190

            
191
/// Global read and write bandwidth pools shared by all channels.
192
#[cfg(feature = "relay")]
193
pub(crate) struct ChannelBandwidthPools {
194
    /// Pool for bytes read from channels.
195
    pub(crate) read: BandwidthPool,
196
    /// Pool for bytes written to channels.
197
    pub(crate) write: BandwidthPool,
198
}
199

            
200
#[cfg(feature = "relay")]
201
impl ChannelBandwidthPools {
202
    /// Return another [`ChannelBandwidthPools`] sharing the same pools.
203
    pub(crate) fn share(&self) -> Self {
204
        Self {
205
            read: self.read.share(),
206
            write: self.write.share(),
207
        }
208
    }
209

            
210
    /// Return `stream` rate limited by these pools.
211
    pub(crate) fn rate_limit<S>(&self, stream: S) -> GlobalRateLimitedConn<S> {
212
        GlobalRateLimitedConn::new(
213
            stream,
214
            self.read.new_acquirer(),
215
            self.write.new_acquirer(),
216
            BW_MAX_CHUNK,
217
        )
218
    }
219
}
220

            
221
/// A type- and network-agnostic implementation for [`ChanMgr`](crate::ChanMgr).
222
///
223
/// This type does the work of keeping track of open channels and pending
224
/// channel requests, launching requests as needed, waiting for pending
225
/// requests, and so forth.
226
///
227
/// The actual job of launching connections is deferred to an
228
/// `AbstractChannelFactory` type.
229
pub(crate) struct AbstractChanMgr<CF: AbstractChannelFactory> {
230
    /// All internal state held by this channel manager.
231
    ///
232
    /// The most important part is the map from relay identity to channel, or
233
    /// to pending channel status.
234
    pub(crate) channels: state::MgrState<CF>,
235

            
236
    /// A bootstrap reporter to give out when building channels.
237
    pub(crate) reporter: BootstrapReporter,
238

            
239
    /// The memory quota account that every channel will be a child of
240
    pub(crate) memquota: ToplevelAccount,
241

            
242
    /// Metrics counters / gauges / histograms.
243
    #[cfg(feature = "metrics")]
244
    pub(crate) metrics: ChanMgrMetrics,
245
}
246

            
247
/// Struct to hold all the metrics counters / gauges / histograms we use.
248
///
249
/// We create these and store them in the [`AbstractChanMgr`] in order to avoid
250
/// the performance hit associated with re-registering counters.
251
#[cfg(feature = "metrics")]
252
pub(crate) struct ChanMgrMetrics {
253
    /// Number of inbound channels successfully built.
254
    pub(crate) inbound_channels_built_success: metrics::Counter,
255
    /// Number of inbound channels that we tried to build but had an [`Error::UnusableTarget`] error.
256
    pub(crate) inbound_channels_built_failure_unusable_target: metrics::Counter,
257
    /// Number of inbound channels that we tried to build but had an [`Error::PendingFailed`] error.
258
    pub(crate) inbound_channels_built_failure_pending_failed: metrics::Counter,
259
    /// Number of inbound channels that we tried to build but had an [`Error::ChanTimeout`] error.
260
    pub(crate) inbound_channels_built_failure_chan_timeout: metrics::Counter,
261
    /// Number of inbound channels that we tried to build but had an [`Error::Proto`] error.
262
    pub(crate) inbound_channels_built_failure_proto: metrics::Counter,
263
    /// Number of inbound channels that we tried to build but had an [`Error::Io`] error.
264
    pub(crate) inbound_channels_built_failure_io: metrics::Counter,
265
    /// Number of inbound channels that we tried to build but had an [`Error::Connect`] error.
266
    pub(crate) inbound_channels_built_failure_connect: metrics::Counter,
267
    /// Number of inbound channels that we tried to build but had an [`Error::Spawn`] error.
268
    pub(crate) inbound_channels_built_failure_spawn: metrics::Counter,
269
    /// Number of inbound channels that we tried to build but had an [`Error::MissingId`] error.
270
    pub(crate) inbound_channels_built_failure_missing_id: metrics::Counter,
271
    /// Number of inbound channels that we tried to build but had an [`Error::IdentityConflict`] error.
272
    pub(crate) inbound_channels_built_failure_identity_conflict: metrics::Counter,
273
    /// Number of inbound channels that we tried to build but had an [`Error::NoSuchTransport`] error.
274
    pub(crate) inbound_channels_built_failure_no_such_transport: metrics::Counter,
275
    /// Number of inbound channels that we tried to build but had an [`Error::RequestCancelled`] error.
276
    pub(crate) inbound_channels_built_failure_request_cancelled: metrics::Counter,
277
    /// Number of inbound channels that we tried to build but had an [`Error::Pt`] error.
278
    pub(crate) inbound_channels_built_failure_pt: metrics::Counter,
279
    /// Number of inbound channels that we tried to build but had an [`Error::Memquota`] error.
280
    pub(crate) inbound_channels_built_failure_memquota: metrics::Counter,
281
    /// Number of inbound channels that we tried to build but had an [`Error::Internal`] error.
282
    pub(crate) inbound_channels_built_failure_internal: metrics::Counter,
283
}
284

            
285
#[cfg(feature = "metrics")]
286
impl ChanMgrMetrics {
287
    /// Create a new instance of [`ChanMgrMetrics`].
288
823
    pub(crate) fn new() -> Self {
289
823
        ChanMgrMetrics {
290
823
            inbound_channels_built_success: metrics::counter!(
291
823
                description: "Total number of channels built",
292
823
                unit: metrics::Unit::Count,
293
823
                "arti_chanmgr_channels_built",
294
823
                "result" => "success",
295
823
                "direction" => "inbound",
296
823
            ),
297
823
            inbound_channels_built_failure_unusable_target: metrics::counter!(
298
823
                description: "Total number of channels built",
299
823
                unit: metrics::Unit::Count,
300
823
                "arti_chanmgr_channels_built",
301
823
                "result" => "failure",
302
823
                "direction" => "inbound",
303
823
                "error" => "unusable_target",
304
823
            ),
305
823
            inbound_channels_built_failure_pending_failed: metrics::counter!(
306
823
                description: "Total number of channels built",
307
823
                unit: metrics::Unit::Count,
308
823
                "arti_chanmgr_channels_built",
309
823
                "result" => "failure",
310
823
                "direction" => "inbound",
311
823
                "error" => "pending_failed",
312
823
            ),
313
823
            inbound_channels_built_failure_chan_timeout: metrics::counter!(
314
823
                description: "Total number of channels built",
315
823
                unit: metrics::Unit::Count,
316
823
                "arti_chanmgr_channels_built",
317
823
                "result" => "failure",
318
823
                "direction" => "inbound",
319
823
                "error" => "chan_timeout",
320
823
            ),
321
823
            inbound_channels_built_failure_proto: metrics::counter!(
322
823
                description: "Total number of channels built",
323
823
                unit: metrics::Unit::Count,
324
823
                "arti_chanmgr_channels_built",
325
823
                "result" => "failure",
326
823
                "direction" => "inbound",
327
823
                "error" => "proto",
328
823
            ),
329
823
            inbound_channels_built_failure_io: metrics::counter!(
330
823
                description: "Total number of channels built",
331
823
                unit: metrics::Unit::Count,
332
823
                "arti_chanmgr_channels_built",
333
823
                "result" => "failure",
334
823
                "direction" => "inbound",
335
823
                "error" => "io",
336
823
            ),
337
823
            inbound_channels_built_failure_connect: metrics::counter!(
338
823
                description: "Total number of channels built",
339
823
                unit: metrics::Unit::Count,
340
823
                "arti_chanmgr_channels_built",
341
823
                "result" => "failure",
342
823
                "direction" => "inbound",
343
823
                "error" => "connect",
344
823
            ),
345
823
            inbound_channels_built_failure_spawn: metrics::counter!(
346
823
                description: "Total number of channels built",
347
823
                unit: metrics::Unit::Count,
348
823
                "arti_chanmgr_channels_built",
349
823
                "result" => "failure",
350
823
                "direction" => "inbound",
351
823
                "error" => "spawn",
352
823
            ),
353
823
            inbound_channels_built_failure_missing_id: metrics::counter!(
354
823
                description: "Total number of channels built",
355
823
                unit: metrics::Unit::Count,
356
823
                "arti_chanmgr_channels_built",
357
823
                "result" => "failure",
358
823
                "direction" => "inbound",
359
823
                "error" => "missing_id",
360
823
            ),
361
823
            inbound_channels_built_failure_identity_conflict: metrics::counter!(
362
823
                description: "Total number of channels built",
363
823
                unit: metrics::Unit::Count,
364
823
                "arti_chanmgr_channels_built",
365
823
                "result" => "failure",
366
823
                "direction" => "inbound",
367
823
                "error" => "identity_conflict",
368
823
            ),
369
823
            inbound_channels_built_failure_no_such_transport: metrics::counter!(
370
823
                description: "Total number of channels built",
371
823
                unit: metrics::Unit::Count,
372
823
                "arti_chanmgr_channels_built",
373
823
                "result" => "failure",
374
823
                "direction" => "inbound",
375
823
                "error" => "no_such_transport",
376
823
            ),
377
823
            inbound_channels_built_failure_request_cancelled: metrics::counter!(
378
823
                description: "Total number of channels built",
379
823
                unit: metrics::Unit::Count,
380
823
                "arti_chanmgr_channels_built",
381
823
                "result" => "failure",
382
823
                "direction" => "inbound",
383
823
                "error" => "request_cancelled",
384
823
            ),
385
823
            inbound_channels_built_failure_pt: metrics::counter!(
386
823
                description: "Total number of channels built",
387
823
                unit: metrics::Unit::Count,
388
823
                "arti_chanmgr_channels_built",
389
823
                "result" => "failure",
390
823
                "direction" => "inbound",
391
823
                "error" => "pt",
392
823
            ),
393
823
            inbound_channels_built_failure_memquota: metrics::counter!(
394
823
                description: "Total number of channels built",
395
823
                unit: metrics::Unit::Count,
396
823
                "arti_chanmgr_channels_built",
397
823
                "result" => "failure",
398
823
                "direction" => "inbound",
399
823
                "error" => "memquota",
400
823
            ),
401
823
            inbound_channels_built_failure_internal: metrics::counter!(
402
823
                description: "Total number of channels built",
403
823
                unit: metrics::Unit::Count,
404
823
                "arti_chanmgr_channels_built",
405
823
                "result" => "failure",
406
823
                "direction" => "inbound",
407
823
                "error" => "internal",
408
823
            ),
409
823
        }
410
823
    }
411

            
412
    /// Increment the correct inbound_channels_built counter for the given result.
413
    pub(crate) fn increment_inbound_channels_built<R>(&self, result: &Result<R>) {
414
        match result {
415
            Ok(_) => self.inbound_channels_built_success.increment(1),
416
            Err(Error::UnusableTarget(_)) => self
417
                .inbound_channels_built_failure_unusable_target
418
                .increment(1),
419
            Err(Error::PendingFailed { .. }) => self
420
                .inbound_channels_built_failure_pending_failed
421
                .increment(1),
422
            Err(Error::ChanTimeout { .. }) => self
423
                .inbound_channels_built_failure_chan_timeout
424
                .increment(1),
425
            Err(Error::Proto { .. }) => self.inbound_channels_built_failure_proto.increment(1),
426
            Err(Error::Io { .. }) => self.inbound_channels_built_failure_io.increment(1),
427
            Err(Error::Connect { .. }) => self.inbound_channels_built_failure_connect.increment(1),
428
            Err(Error::Spawn { .. }) => self.inbound_channels_built_failure_spawn.increment(1),
429
            Err(Error::MissingId) => self.inbound_channels_built_failure_missing_id.increment(1),
430
            Err(Error::IdentityConflict) => self
431
                .inbound_channels_built_failure_identity_conflict
432
                .increment(1),
433
            Err(Error::NoSuchTransport(_)) => self
434
                .inbound_channels_built_failure_no_such_transport
435
                .increment(1),
436
            Err(Error::RequestCancelled) => self
437
                .inbound_channels_built_failure_request_cancelled
438
                .increment(1),
439
            Err(Error::Pt(_)) => self.inbound_channels_built_failure_pt.increment(1),
440
            Err(Error::Memquota(_)) => self.inbound_channels_built_failure_memquota.increment(1),
441
            Err(Error::Internal(_)) => self.inbound_channels_built_failure_internal.increment(1),
442
        }
443
    }
444
}
445

            
446
/// Type alias for a future that we wait on to see when a pending
447
/// channel is done or failed.
448
type Pending = Shared<oneshot::Receiver<Result<()>>>;
449

            
450
/// Type alias for the sender we notify when we complete a channel (or fail to
451
/// complete it).
452
type Sending = oneshot::Sender<Result<()>>;
453

            
454
/// Keeps a pending launch entry and its waiters in sync.
455
///
456
/// Every exit path from a launch attempt must either remove the pending entry
457
/// or upgrade it to an open channel, and must notify all waiters with the
458
/// outcome. This guard makes cancellation and early returns follow the same
459
/// cleanup path as ordinary failures.
460
struct PendingLaunchGuard<'a, CF: AbstractChannelFactory> {
461
    /// Channel state used to remove or upgrade the pending entry.
462
    channels: &'a state::MgrState<CF>,
463
    /// Handle to the pending entry, if it has not yet been removed.
464
    handle: Option<PendingChannelHandle>,
465
    /// Sender used to notify tasks waiting on this launch.
466
    send: Option<Sending>,
467
    /// Result to report to the waiters if the launch ends here.
468
    result: Result<()>,
469
}
470

            
471
impl<'a, CF: AbstractChannelFactory> PendingLaunchGuard<'a, CF> {
472
    /// Create a new guard for a pending launch.
473
42
    fn new(channels: &'a state::MgrState<CF>, handle: PendingChannelHandle, send: Sending) -> Self {
474
42
        Self {
475
42
            channels,
476
42
            handle: Some(handle),
477
42
            send: Some(send),
478
42
            result: Err(Error::RequestCancelled),
479
42
        }
480
42
    }
481

            
482
    /// Record the result that should be reported to any waiters.
483
40
    fn note_result(&mut self, result: Result<()>) {
484
40
        self.result = result;
485
40
    }
486

            
487
    /// Replace the pending channel with an open one.
488
36
    fn upgrade_pending_channel_to_open(&mut self, channel: Arc<CF::Channel>) -> Result<()> {
489
36
        let handle = self
490
36
            .handle
491
36
            .take()
492
36
            .expect("pending launch guard lost its handle before upgrade");
493
36
        self.channels
494
36
            .upgrade_pending_channel_to_open(handle, channel)
495
36
    }
496
}
497

            
498
impl<'a, CF: AbstractChannelFactory> Drop for PendingLaunchGuard<'a, CF> {
499
42
    fn drop(&mut self) {
500
42
        if let Some(handle) = self.handle.take() {
501
6
            if let Err(e) = self.channels.remove_pending_channel(handle) {
502
                // Just log an error if we're unable to remove it, since there's
503
                // nothing else we can do here, and returning the error would
504
                // hide the actual error that we care about (the channel build
505
                // failure).
506
                #[allow(clippy::missing_docs_in_private_items)]
507
                const MSG: &str = "Unable to remove the pending channel";
508
                error_report!(internal!("{e}"), "{}", MSG);
509
6
            }
510
36
        }
511

            
512
42
        if let Some(send) = self.send.take() {
513
            // It's okay if all the receivers went away:
514
            // that means that nobody was waiting for this channel.
515
42
            let _ignore_err = send.send(self.result.clone());
516
        }
517
42
    }
518
}
519

            
520
impl<CF: AbstractChannelFactory + Clone> AbstractChanMgr<CF> {
521
    /// Make a new empty channel manager.
522
49
    pub(crate) fn new(
523
49
        connector: CF,
524
49
        config: ChannelConfig,
525
49
        dormancy: Dormancy,
526
49
        netparams: &NetParameters,
527
49
        reporter: BootstrapReporter,
528
49
        memquota: ToplevelAccount,
529
49
    ) -> Self {
530
49
        AbstractChanMgr {
531
49
            channels: state::MgrState::new(connector, config, dormancy, netparams),
532
49
            reporter,
533
49
            memquota,
534
49
            #[cfg(feature = "metrics")]
535
49
            metrics: ChanMgrMetrics::new(),
536
49
        }
537
49
    }
538

            
539
    /// Run a function to modify the channel builder in this object.
540
    #[allow(unused)]
541
    pub(crate) fn with_mut_builder<F>(&self, func: F)
542
    where
543
        F: FnOnce(&mut CF),
544
    {
545
        self.channels.with_mut_builder(func);
546
    }
547

            
548
    /// Remove every unusable entry from this channel manager.
549
    #[cfg(test)]
550
1
    pub(crate) fn remove_unusable_entries(&self) -> Result<()> {
551
1
        self.channels.remove_unusable()
552
1
    }
553

            
554
    /// Build a channel for an incoming stream. See
555
    /// [`ChanMgr::handle_incoming`](crate::ChanMgr::handle_incoming).
556
    #[cfg(feature = "relay")]
557
    pub(crate) async fn handle_incoming(
558
        &self,
559
        src: Sensitive<std::net::SocketAddr>,
560
        stream: CF::Stream,
561
    ) -> Result<Arc<CF::Channel>> {
562
        let chan_builder = self.channels.builder();
563
        let memquota = ChannelAccount::new(&self.memquota)?;
564
        let channel = chan_builder
565
            .build_channel_using_incoming(src, stream, memquota)
566
            .await?;
567
        // Add it to our list.
568
        self.channels.add_open(channel.clone())?;
569
        Ok(channel)
570
    }
571

            
572
    /// Get a channel corresponding to the identities of `target`.
573
    ///
574
    /// If a usable channel exists with that identity, return it.
575
    ///
576
    /// If no such channel exists already, and none is in progress,
577
    /// launch a new request using `target`.
578
    ///
579
    /// If no such channel exists already, but we have one that's in
580
    /// progress, wait for it to succeed or fail.
581
    #[instrument(skip_all, level = "trace")]
582
46
    pub(crate) async fn get_or_launch(
583
46
        &self,
584
46
        target: CF::BuildSpec,
585
46
        usage: ChannelUsage,
586
46
    ) -> Result<(Arc<CF::Channel>, ChanProvenance)> {
587
        use ChannelUsage as CU;
588

            
589
        let chan = self.get_or_launch_internal(target).await?;
590

            
591
        match usage {
592
            CU::Dir | CU::UselessCircuit => {}
593
            CU::UserTraffic => chan.0.engage_padding_activities(),
594
        }
595

            
596
        Ok(chan)
597
44
    }
598

            
599
    /// Get a channel whose identity is `ident` - internal implementation
600
    #[instrument(skip_all, level = "trace")]
601
46
    async fn get_or_launch_internal(
602
46
        &self,
603
46
        target: CF::BuildSpec,
604
46
    ) -> Result<(Arc<CF::Channel>, ChanProvenance)> {
605
        /// How many times do we try?
606
        const N_ATTEMPTS: usize = 2;
607
        let mut attempts_so_far = 0;
608
        let mut final_attempt = false;
609
        let mut provenance = ChanProvenance::Preexisting;
610

            
611
        // TODO(nickm): It would be neat to use tor_retry instead.
612
        let mut last_err = None;
613

            
614
        while attempts_so_far < N_ATTEMPTS || final_attempt {
615
            attempts_so_far += 1;
616

            
617
            // For each attempt, we _first_ look at the state of the channel map
618
            // to decide on an `Action`, and _then_ we execute that action.
619

            
620
            // First, see what state we're in, and what we should do about it.
621
            let action = self.choose_action(&target, final_attempt)?;
622

            
623
            // We are done deciding on our Action! It's time act based on the
624
            // Action that we chose.
625
            match action {
626
                // If this happens, we were trying to make one final check of our state, but
627
                // we would have had to make additional attempts.
628
                None => {
629
                    if !final_attempt {
630
                        return Err(Error::Internal(internal!(
631
                            "No action returned while not on final attempt"
632
                        )));
633
                    }
634
                    break;
635
                }
636
                // Easy case: we have an error or a channel to return.
637
                Some(Action::Return(v)) => {
638
                    trace!("Returning existing channel");
639
4
                    return v.map(|chan| (chan, provenance));
640
                }
641
                // There's an in-progress channel.  Wait for it.
642
                Some(Action::Wait(pend)) => {
643
                    trace!("Waiting for in-progress channel");
644
                    match pend.await {
645
                        Ok(Ok(())) => {
646
                            // We were waiting for a channel, and it succeeded, or it
647
                            // got cancelled.  But it might have gotten more
648
                            // identities while negotiating than it had when it was
649
                            // launched, or it might have failed to get all the
650
                            // identities we want. Check for this.
651
                            final_attempt = true;
652
                            provenance = ChanProvenance::NewlyCreated;
653
                            last_err.get_or_insert(Error::RequestCancelled);
654
                        }
655
                        Ok(Err(e)) => {
656
                            last_err = Some(e);
657
                        }
658
                        Err(_) => {
659
                            last_err =
660
                                Some(Error::Internal(internal!("channel build task disappeared")));
661
                        }
662
                    }
663
                }
664
                // We need to launch a channel.
665
                Some(Action::Launch((handle, send))) => {
666
                    trace!("Launching channel");
667
                    let connector = self.channels.builder();
668
                    let mut launch = PendingLaunchGuard::new(&self.channels, handle, send);
669
                    let memquota = match ChannelAccount::new(&self.memquota) {
670
                        Ok(memquota) => memquota,
671
                        Err(e) => {
672
                            let e: Error = e.into();
673
                            launch.note_result(Err(e.clone()));
674
                            return Err(e);
675
                        }
676
                    };
677

            
678
                    let outcome = connector
679
                        .build_channel(&target, self.reporter.clone(), memquota)
680
                        .await;
681

            
682
                    match outcome {
683
                        Ok(ref chan) => {
684
                            // Replace the pending channel with the newly built channel.
685
                            match launch.upgrade_pending_channel_to_open(Arc::clone(chan)) {
686
                                Ok(()) => launch.note_result(Ok(())),
687
                                Err(e) => {
688
                                    launch.note_result(Err(e.clone()));
689
                                    return Err(e);
690
                                }
691
                            }
692
                        }
693
                        Err(_) => {
694
                            launch.note_result(outcome.clone().map(|_| ()));
695
                        }
696
                    }
697

            
698
                    match outcome {
699
                        Ok(chan) => {
700
                            return Ok((chan, ChanProvenance::NewlyCreated));
701
                        }
702
                        Err(e) => last_err = Some(e),
703
                    }
704
                }
705
            }
706

            
707
            // End of this attempt. We will try again...
708
        }
709

            
710
        Err(last_err.unwrap_or_else(|| Error::Internal(internal!("no error was set!?"))))
711
44
    }
712

            
713
    /// Helper: based on our internal state, decide which action to take when
714
    /// asked for a channel, and update our internal state accordingly.
715
    ///
716
    /// If `final_attempt` is true, then we will not pick any action that does
717
    /// not result in an immediate result. If we would pick such an action, we
718
    /// instead return `Ok(None)`.  (We could instead have the caller detect
719
    /// such actions, but it's less efficient to construct them, insert them,
720
    /// and immediately revert them.)
721
    #[instrument(skip_all, level = "trace")]
722
53
    fn choose_action(
723
53
        &self,
724
53
        target: &CF::BuildSpec,
725
53
        final_attempt: bool,
726
53
    ) -> Result<Option<Action<CF::Channel>>> {
727
        // don't create new channels on the final attempt
728
53
        let response = self.channels.request_channel(
729
53
            target,
730
53
            /* add_new_entry_if_not_found= */ !final_attempt,
731
53
        );
732

            
733
53
        match response {
734
4
            Ok(Some(ChannelForTarget::Open(channel))) => Ok(Some(Action::Return(Ok(channel)))),
735
            Ok(Some(ChannelForTarget::Pending(pending))) => {
736
7
                if !final_attempt {
737
7
                    Ok(Some(Action::Wait(pending)))
738
                } else {
739
                    // don't return a pending channel on the final attempt
740
                    Ok(None)
741
                }
742
            }
743
            Ok(Some(ChannelForTarget::NewEntry((handle, send)))) => {
744
                // do not drop the handle if refactoring; see `PendingChannelHandle` for details
745
42
                Ok(Some(Action::Launch((handle, send))))
746
            }
747
            Ok(None) => Ok(None),
748
            Err(e @ Error::IdentityConflict) => Ok(Some(Action::Return(Err(e)))),
749
            Err(e) => Err(e),
750
        }
751
53
    }
752

            
753
    /// Update the netdir
754
12
    pub(crate) fn update_netparams(
755
12
        &self,
756
12
        netparams: Arc<dyn AsRef<NetParameters>>,
757
12
    ) -> StdResult<(), tor_error::Bug> {
758
12
        self.channels.reconfigure_general(None, None, netparams)
759
12
    }
760

            
761
    /// Notifies the chanmgr to be dormant like dormancy
762
12
    pub(crate) fn set_dormancy(
763
12
        &self,
764
12
        dormancy: Dormancy,
765
12
        netparams: Arc<dyn AsRef<NetParameters>>,
766
12
    ) -> StdResult<(), tor_error::Bug> {
767
12
        self.channels
768
12
            .reconfigure_general(None, Some(dormancy), netparams)
769
12
    }
770

            
771
    /// Reconfigure all channels
772
12
    pub(crate) fn reconfigure(
773
12
        &self,
774
12
        config: &ChannelConfig,
775
12
        netparams: Arc<dyn AsRef<NetParameters>>,
776
12
    ) -> StdResult<(), tor_error::Bug> {
777
12
        self.channels
778
12
            .reconfigure_general(Some(config), None, netparams)
779
12
    }
780

            
781
    /// Expire any channels that have been unused longer than
782
    /// their maximum unused duration assigned during creation.
783
    ///
784
    /// Return a duration from now until next channel expires.
785
    ///
786
    /// If all channels are in use or there are no open channels,
787
    /// return 180 seconds which is the minimum value of
788
    /// max_unused_duration.
789
    pub(crate) fn expire_channels(&self) -> Duration {
790
        self.channels.expire_channels()
791
    }
792

            
793
    /// Test only: return the open usable channels with a given `ident`.
794
    #[cfg(test)]
795
7
    pub(crate) fn get_nowait<'a, T>(&self, ident: T) -> Vec<Arc<CF::Channel>>
796
7
    where
797
7
        T: Into<tor_linkspec::RelayIdRef<'a>>,
798
    {
799
        use state::ChannelState::*;
800
7
        self.channels
801
7
            .with_channels(|channel_map| {
802
7
                channel_map
803
7
                    .by_id(ident)
804
4
                    .filter_map(|entry| match entry {
805
4
                        Open(ent) if ent.channel.is_usable() => Some(Arc::clone(&ent.channel)),
806
                        _ => None,
807
4
                    })
808
                    .collect()
809
7
            })
810
7
            .expect("Poisoned lock")
811
7
    }
812
}
813

            
814
/// Possible actions that we'll decide to take when asked for a channel.
815
#[allow(clippy::large_enum_variant)]
816
enum Action<C: AbstractChannel> {
817
    /// We found no channel.  We're going to launch a new one,
818
    /// then tell everybody about it.
819
    Launch((PendingChannelHandle, Sending)),
820
    /// We found an in-progress attempt at making a channel.
821
    /// We're going to wait for it to finish.
822
    Wait(Pending),
823
    /// We found a usable channel.  We're going to return it.
824
    Return(Result<Arc<C>>),
825
}
826

            
827
#[cfg(test)]
828
mod test {
829
    // @@ begin test lint list maintained by maint/add_warning @@
830
    #![allow(clippy::bool_assert_comparison)]
831
    #![allow(clippy::clone_on_copy)]
832
    #![allow(clippy::dbg_macro)]
833
    #![allow(clippy::mixed_attributes_style)]
834
    #![allow(clippy::print_stderr)]
835
    #![allow(clippy::print_stdout)]
836
    #![allow(clippy::single_char_pattern)]
837
    #![allow(clippy::unwrap_used)]
838
    #![allow(clippy::unchecked_time_subtraction)]
839
    #![allow(clippy::useless_vec)]
840
    #![allow(clippy::needless_pass_by_value)]
841
    #![allow(clippy::string_slice)] // See arti#2571
842
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
843
    use super::*;
844
    use crate::Error;
845

            
846
    use futures::{join, poll};
847
    use std::error::Error as StdError;
848
    use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
849
    use std::sync::Arc;
850
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
851
    use std::time::Duration;
852
    use tor_error::bad_api_usage;
853
    use tor_linkspec::ChannelMethod;
854
    use tor_llcrypto::pk::ed25519::Ed25519Identity;
855
    use tor_memquota::ArcMemoryQuotaTrackerExt as _;
856

            
857
    use crate::ChannelUsage as CU;
858
    use tor_rtcompat::{Runtime, task::yield_now, test_with_one_runtime};
859

            
860
    // Two distinct addresses we can use in tests.
861
    const ADDR_A: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(1, 1, 1, 1), 443));
862
    const ADDR_B: SocketAddr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(2, 2, 2, 2), 443));
863

            
864
    #[derive(Clone)]
865
    struct FakeChannelFactory<RT> {
866
        runtime: RT,
867
        build_attempts: Arc<AtomicUsize>,
868
    }
869

            
870
    #[derive(Clone, Debug)]
871
    struct FakeChannel {
872
        ed_ident: Ed25519Identity,
873
        mood: char,
874
        closing: Arc<AtomicBool>,
875
        detect_reuse: Arc<char>,
876
        // last_params: Option<ChannelPaddingInstructionsUpdates>,
877
    }
878

            
879
    impl PartialEq for FakeChannel {
880
        fn eq(&self, other: &Self) -> bool {
881
            Arc::ptr_eq(&self.detect_reuse, &other.detect_reuse)
882
        }
883
    }
884

            
885
    impl AbstractChannel for FakeChannel {
886
        fn is_canonical(&self) -> bool {
887
            true
888
        }
889
        fn is_canonical_to_peer(&self) -> bool {
890
            unimplemented!()
891
        }
892
        fn peer_matches_chan_method(&self, _method: &ChannelMethod) -> bool {
893
            unimplemented!()
894
        }
895
        fn age(&self) -> Duration {
896
            unimplemented!()
897
        }
898
        fn is_usable(&self) -> bool {
899
            !self.closing.load(Ordering::SeqCst)
900
        }
901
        fn duration_unused(&self) -> Option<Duration> {
902
            None
903
        }
904
        fn reparameterize(
905
            &self,
906
            _updates: Arc<ChannelPaddingInstructionsUpdates>,
907
        ) -> tor_proto::Result<()> {
908
            // *self.last_params.lock().unwrap() = Some((*updates).clone());
909
            match self.mood {
910
                // Build succeeds, but installing the channel into the manager fails.
911
                'r' => Err(tor_proto::Error::ChanProto(
912
                    "synthetic reparameterize failure".into(),
913
                )),
914
                _ => Ok(()),
915
            }
916
        }
917
        fn reparameterize_kist(&self, _kist_params: KistParams) -> tor_proto::Result<()> {
918
            Ok(())
919
        }
920
        fn engage_padding_activities(&self) {}
921
    }
922

            
923
    impl HasRelayIds for FakeChannel {
924
        fn identity(
925
            &self,
926
            key_type: tor_linkspec::RelayIdType,
927
        ) -> Option<tor_linkspec::RelayIdRef<'_>> {
928
            match key_type {
929
                tor_linkspec::RelayIdType::Ed25519 => Some((&self.ed_ident).into()),
930
                _ => None,
931
            }
932
        }
933
    }
934

            
935
    impl FakeChannel {
936
        fn start_closing(&self) {
937
            self.closing.store(true, Ordering::SeqCst);
938
        }
939
    }
940

            
941
    impl<RT: Runtime> FakeChannelFactory<RT> {
942
        fn new(runtime: RT, build_attempts: Arc<AtomicUsize>) -> Self {
943
            FakeChannelFactory {
944
                runtime,
945
                build_attempts,
946
            }
947
        }
948
    }
949

            
950
    fn new_test_abstract_chanmgr<R: Runtime>(runtime: R) -> AbstractChanMgr<FakeChannelFactory<R>> {
951
        new_test_abstract_chanmgr_and_build_attempts(runtime).0
952
    }
953

            
954
    fn new_test_abstract_chanmgr_and_build_attempts<R: Runtime>(
955
        runtime: R,
956
    ) -> (AbstractChanMgr<FakeChannelFactory<R>>, Arc<AtomicUsize>) {
957
        let build_attempts = Arc::new(AtomicUsize::new(0));
958
        let cf = FakeChannelFactory::new(runtime, Arc::clone(&build_attempts));
959
        let mgr = AbstractChanMgr::new(
960
            cf,
961
            Default::default(),
962
            Default::default(),
963
            &Default::default(),
964
            BootstrapReporter::fake(),
965
            ToplevelAccount::new_noop(),
966
        );
967
        (mgr, build_attempts)
968
    }
969

            
970
    #[derive(Clone, Debug)]
971
    struct FakeBuildSpec(u32, char, Ed25519Identity, SocketAddr);
972

            
973
    impl HasRelayIds for FakeBuildSpec {
974
        fn identity(
975
            &self,
976
            key_type: tor_linkspec::RelayIdType,
977
        ) -> Option<tor_linkspec::RelayIdRef<'_>> {
978
            match key_type {
979
                tor_linkspec::RelayIdType::Ed25519 => Some((&self.2).into()),
980
                _ => None,
981
            }
982
        }
983
    }
984

            
985
    impl HasChanMethod for FakeBuildSpec {
986
        fn chan_method(&self) -> ChannelMethod {
987
            ChannelMethod::Direct(vec![self.3.clone()])
988
        }
989
    }
990

            
991
    /// Helper to make a fake Ed identity from a u32.
992
    fn u32_to_ed(n: u32) -> Ed25519Identity {
993
        let mut bytes = [0; 32];
994
        bytes[0..4].copy_from_slice(&n.to_be_bytes());
995
        bytes.into()
996
    }
997

            
998
    /// Return true if `needle` appears anywhere in `err`'s error chain.
999
    fn error_contains(err: &Error, needle: &str) -> bool {
        let mut source: Option<&(dyn StdError + 'static)> = Some(err);
        while let Some(err) = source {
            if err.to_string().contains(needle) || format!("{err:?}").contains(needle) {
                return true;
            }
            source = err.source();
        }
        false
    }
    #[async_trait]
    impl<RT: Runtime> AbstractChannelFactory for FakeChannelFactory<RT> {
        type Channel = FakeChannel;
        type BuildSpec = FakeBuildSpec;
        type Stream = ();
        async fn build_channel(
            &self,
            target: &Self::BuildSpec,
            _reporter: BootstrapReporter,
            _memquota: ChannelAccount,
        ) -> Result<Arc<FakeChannel>> {
            self.build_attempts.fetch_add(1, Ordering::SeqCst);
            yield_now().await;
            let FakeBuildSpec(ident, mood, id, _addr) = *target;
            let ed_ident = u32_to_ed(ident);
            assert_eq!(ed_ident, id);
            match mood {
                // "X" means never connect.
                '❌' | '🔥' => return Err(Error::UnusableTarget(bad_api_usage!("emoji"))),
                // "zzz" means wait for 15 seconds then succeed.
                '💤' => {
                    self.runtime.sleep(Duration::new(15, 0)).await;
                }
                _ => {}
            }
            Ok(Arc::new(FakeChannel {
                ed_ident,
                mood,
                closing: Arc::new(AtomicBool::new(false)),
                detect_reuse: Default::default(),
                // last_params: None,
            }))
        }
        #[cfg(feature = "relay")]
        async fn build_channel_using_incoming(
            &self,
            _peer: Sensitive<std::net::SocketAddr>,
            _stream: Self::Stream,
            _memquota: ChannelAccount,
        ) -> Result<Arc<Self::Channel>> {
            unimplemented!()
        }
    }
    #[test]
    fn connect_one_ok() {
        test_with_one_runtime!(|runtime| async {
            let mgr = new_test_abstract_chanmgr(runtime);
            let target = FakeBuildSpec(413, '!', u32_to_ed(413), ADDR_A);
            let chan1 = mgr
                .get_or_launch(target.clone(), CU::UserTraffic)
                .await
                .unwrap()
                .0;
            let chan2 = mgr.get_or_launch(target, CU::UserTraffic).await.unwrap().0;
            assert_eq!(chan1, chan2);
            assert_eq!(mgr.get_nowait(&u32_to_ed(413)), vec![chan1]);
        });
    }
    #[test]
    fn connect_one_fail() {
        test_with_one_runtime!(|runtime| async {
            let mgr = new_test_abstract_chanmgr(runtime);
            // This is set up to always fail.
            let target = FakeBuildSpec(999, '❌', u32_to_ed(999), ADDR_A);
            let res1 = mgr.get_or_launch(target, CU::UserTraffic).await;
            assert!(matches!(res1, Err(Error::UnusableTarget(_))));
            assert!(mgr.get_nowait(&u32_to_ed(999)).is_empty());
        });
    }
    #[test]
    fn connect_different_address() {
        test_with_one_runtime!(|runtime| async {
            let mgr = new_test_abstract_chanmgr(runtime);
            // Two targets that have different addresses.
            let target1 = FakeBuildSpec(413, '!', u32_to_ed(413), ADDR_A);
            let mut target2 = target1.clone();
            target2.3 = ADDR_B;
            let chan1 = mgr.get_or_launch(target1, CU::UserTraffic).await.unwrap().0;
            let chan2 = mgr.get_or_launch(target2, CU::UserTraffic).await.unwrap().0;
            // Even with different addresses, the original channel is returned.
            assert_eq!(chan1, chan2);
            assert_eq!(mgr.get_nowait(&u32_to_ed(413)), vec![chan1]);
        });
    }
    #[test]
    fn test_concurrent() {
        test_with_one_runtime!(|runtime| async {
            let mgr = new_test_abstract_chanmgr(runtime);
            let usage = CU::UserTraffic;
            // TODO(nickm): figure out how to make these actually run
            // concurrently. Right now it seems that they don't actually
            // interact.
            let (ch3a, ch3b, ch44a, ch44b, ch50a, ch50b, ch86a, ch86b) = join!(
                mgr.get_or_launch(FakeBuildSpec(3, 'a', u32_to_ed(3), ADDR_A), usage),
                mgr.get_or_launch(FakeBuildSpec(3, 'b', u32_to_ed(3), ADDR_A), usage),
                mgr.get_or_launch(FakeBuildSpec(44, 'a', u32_to_ed(44), ADDR_A), usage),
                mgr.get_or_launch(FakeBuildSpec(44, 'b', u32_to_ed(44), ADDR_A), usage),
                mgr.get_or_launch(FakeBuildSpec(50, 'a', u32_to_ed(50), ADDR_A), usage),
                mgr.get_or_launch(FakeBuildSpec(50, 'b', u32_to_ed(50), ADDR_B), usage),
                mgr.get_or_launch(FakeBuildSpec(86, '❌', u32_to_ed(86), ADDR_A), usage),
                mgr.get_or_launch(FakeBuildSpec(86, '🔥', u32_to_ed(86), ADDR_A), usage),
            );
            let ch3a = ch3a.unwrap();
            let ch3b = ch3b.unwrap();
            let ch44a = ch44a.unwrap();
            let ch44b = ch44b.unwrap();
            let ch50a = ch50a.unwrap();
            let ch50b = ch50b.unwrap();
            let err_a = ch86a.unwrap_err();
            let err_b = ch86b.unwrap_err();
            assert_eq!(ch3a, ch3b);
            assert_eq!(ch44a, ch44b);
            assert_ne!(ch50a, ch50b);
            assert_ne!(ch44a, ch3a);
            assert!(matches!(err_a, Error::UnusableTarget(_)));
            assert!(matches!(err_b, Error::UnusableTarget(_)));
        });
    }
    #[test]
    fn dropped_launch_reports_request_cancelled_to_waiters() {
        test_with_one_runtime!(|runtime| async {
            let mgr = new_test_abstract_chanmgr(runtime);
            let target = FakeBuildSpec(777, '💤', u32_to_ed(777), ADDR_A);
            let usage = CU::UserTraffic;
            let mut owner1 = Box::pin(mgr.get_or_launch(target.clone(), usage));
            assert!(poll!(&mut owner1).is_pending());
            let mut waiter = Box::pin(mgr.get_or_launch(target.clone(), usage));
            assert!(poll!(&mut waiter).is_pending());
            drop(owner1);
            let mut owner2 = Box::pin(mgr.get_or_launch(target, usage));
            assert!(poll!(&mut owner2).is_pending());
            assert!(poll!(&mut waiter).is_pending());
            drop(owner2);
            let waiter = waiter.await;
            assert!(
                matches!(&waiter, Err(Error::RequestCancelled)),
                "{waiter:?}"
            );
            if let Err(ref err) = waiter {
                assert!(!error_contains(err, "channel build task disappeared"));
            }
        });
    }
    #[test]
    fn failed_upgrade_reports_original_error_without_owner_retry() {
        test_with_one_runtime!(|runtime| async {
            let (mgr, build_attempts) = new_test_abstract_chanmgr_and_build_attempts(runtime);
            let target = FakeBuildSpec(778, 'r', u32_to_ed(778), ADDR_A);
            let usage = CU::UserTraffic;
            let mut owner = Box::pin(mgr.get_or_launch(target.clone(), usage));
            assert!(poll!(&mut owner).is_pending());
            let mut waiter = Box::pin(mgr.get_or_launch(target.clone(), usage));
            assert!(poll!(&mut waiter).is_pending());
            let owner = owner.await;
            assert!(matches!(&owner, Err(Error::Internal(_))), "{owner:?}");
            if let Err(ref err) = owner {
                assert!(error_contains(err, "failure on new channel"));
                assert!(!error_contains(err, "channel build task disappeared"));
            }
            assert_eq!(build_attempts.load(Ordering::SeqCst), 1);
            assert!(mgr.get_nowait(&u32_to_ed(778)).is_empty());
            let waiter = waiter.await;
            assert!(matches!(&waiter, Err(Error::Internal(_))), "{waiter:?}");
            if let Err(ref err) = waiter {
                assert!(error_contains(err, "failure on new channel"));
                assert!(!error_contains(err, "channel build task disappeared"));
            }
        });
    }
    #[test]
    fn unusable_entries() {
        test_with_one_runtime!(|runtime| async {
            let mgr = new_test_abstract_chanmgr(runtime);
            let (ch3, ch4, ch5) = join!(
                mgr.get_or_launch(FakeBuildSpec(3, 'a', u32_to_ed(3), ADDR_A), CU::UserTraffic),
                mgr.get_or_launch(FakeBuildSpec(4, 'a', u32_to_ed(4), ADDR_A), CU::UserTraffic),
                mgr.get_or_launch(FakeBuildSpec(5, 'a', u32_to_ed(5), ADDR_A), CU::UserTraffic),
            );
            let ch3 = ch3.unwrap().0;
            let _ch4 = ch4.unwrap();
            let ch5 = ch5.unwrap().0;
            ch3.start_closing();
            ch5.start_closing();
            let ch3_new = mgr
                .get_or_launch(FakeBuildSpec(3, 'b', u32_to_ed(3), ADDR_A), CU::UserTraffic)
                .await
                .unwrap()
                .0;
            assert_ne!(ch3, ch3_new);
            assert_eq!(ch3_new.mood, 'b');
            mgr.remove_unusable_entries().unwrap();
            assert!(!mgr.get_nowait(&u32_to_ed(3)).is_empty());
            assert!(!mgr.get_nowait(&u32_to_ed(4)).is_empty());
            assert!(mgr.get_nowait(&u32_to_ed(5)).is_empty());
        });
    }
}