1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
pub mod builder;
52
mod config;
53
mod err;
54
mod event;
55
pub mod factory;
56
mod mgr;
57
#[cfg(test)]
58
mod testing;
59
pub mod transport;
60

            
61
use futures::StreamExt;
62
use futures::select_biased;
63
use std::result::Result as StdResult;
64
use std::sync::{Arc, Weak};
65
use std::time::Duration;
66
use tor_config::ReconfigureError;
67
use tor_error::error_report;
68
use tor_linkspec::{ChanTarget, OwnedChanTarget};
69
use tor_netdir::{NetDirProvider, params::NetParameters};
70
use tor_proto::channel::Channel;
71
#[cfg(feature = "experimental-api")]
72
use tor_proto::memquota::ChannelAccount;
73
use tor_proto::memquota::ToplevelAccount;
74
use tor_rtcompat::SpawnExt;
75
use tracing::debug;
76
use tracing::instrument;
77
use void::{ResultVoidErrExt, Void};
78

            
79
#[cfg(feature = "relay")]
80
use {
81
    async_trait::async_trait, safelog::Sensitive, tor_proto::relay::CreateRequestHandler,
82
    tor_proto::relay::channel_provider::ChannelProvider,
83
};
84

            
85
pub use err::Error;
86

            
87
pub use config::{ChannelConfig, ChannelConfigBuilder, ProxyProtocol};
88
pub use mgr::ChanMgrConfig;
89

            
90
use tor_rtcompat::Runtime;
91

            
92
/// A Result as returned by this crate.
93
pub type Result<T> = std::result::Result<T, Error>;
94

            
95
use crate::factory::BootstrapReporter;
96
pub use event::{ConnBlockage, ConnStatus, ConnStatusEvents};
97
use tor_rtcompat::scheduler::{TaskHandle, TaskSchedule};
98

            
99
/// An object that remembers a set of live channels, and launches new ones on
100
/// request.
101
///
102
/// Use the [`ChanMgr::get_or_launch`] function to create a new [`Channel`], or
103
/// get one if it exists.  (For a slightly lower-level API that does no caching,
104
/// see [`ChannelFactory`](factory::ChannelFactory) and its implementors.
105
///
106
/// Each channel is kept open as long as there is a reference to it, or
107
/// something else (such as the relay or a network error) kills the channel.
108
///
109
/// After a `ChanMgr` launches a channel, it keeps a reference to it until that
110
/// channel has been unused (that is, had no circuits attached to it) for a
111
/// certain amount of time. (Currently this interval is chosen randomly from
112
/// between 180-270 seconds, but this is an implementation detail that may change
113
/// in the future.)
114
pub struct ChanMgr<R: Runtime> {
115
    /// Internal channel manager object that does the actual work.
116
    ///
117
    /// ## How this is built
118
    ///
119
    /// This internal manager is parameterized over an
120
    /// [`mgr::AbstractChannelFactory`], which here is instantiated with a [`factory::CompoundFactory`].
121
    /// The `CompoundFactory` itself holds:
122
    ///   * A `dyn` [`factory::AbstractPtMgr`] that can provide a `dyn`
123
    ///     [`factory::ChannelFactory`] for each supported pluggable transport.
124
    ///     This starts out as `None`, but can be replaced with [`ChanMgr::set_pt_mgr`].
125
    ///     The `TorClient` code currently sets this using `tor_ptmgr::PtMgr`.
126
    ///     `PtMgr` currently returns `ChannelFactory` implementations that are
127
    ///     built using [`transport::proxied::ExternalProxyPlugin`], which implements
128
    ///     [`transport::TransportImplHelper`], which in turn is wrapped into a
129
    ///     `ChanBuilder` to implement `ChannelFactory`.
130
    ///   * A generic [`factory::ChannelFactory`] that it uses for everything else
131
    ///     We instantiate this with a
132
    ///     [`builder::ChanBuilder`] using a [`transport::default::DefaultTransport`].
133
    // This type is a bit long, but I think it's better to just state it here explicitly rather than
134
    // hiding parts of it behind a type alias to make it look nicer.
135
    mgr: mgr::AbstractChanMgr<
136
        factory::CompoundFactory<builder::ChanBuilder<R, transport::DefaultTransport<R>>>,
137
    >,
138

            
139
    /// Stream of [`ConnStatus`] events.
140
    bootstrap_status: event::ConnStatusEvents,
141

            
142
    /// The runtime. Needed to possibly spawn tasks.
143
    #[allow(unused)] // Relay use this, not client yet. Keep it here instead of gating.
144
    runtime: R,
145
}
146

            
147
/// Description of how we got a channel.
148
#[non_exhaustive]
149
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
150
pub enum ChanProvenance {
151
    /// This channel was newly launched, or was in progress and finished while
152
    /// we were waiting.
153
    NewlyCreated,
154
    /// This channel already existed when we asked for it.
155
    Preexisting,
156
}
157

            
158
/// Dormancy state, as far as the channel manager is concerned
159
///
160
/// This is usually derived in higher layers from `arti_client::DormantMode`.
161
#[non_exhaustive]
162
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
163
pub enum Dormancy {
164
    /// Not dormant
165
    ///
166
    /// Channels will operate normally.
167
    #[default]
168
    Active,
169
    /// Totally dormant
170
    ///
171
    /// Channels will not perform any spontaneous activity (eg, netflow padding)
172
    Dormant,
173
}
174

            
175
/// The usage that we have in mind when requesting a channel.
176
///
177
/// A channel may be used in multiple ways.  Each time a channel is requested
178
/// from `ChanMgr` a separate `ChannelUsage` is passed in to tell the `ChanMgr`
179
/// how the channel will be used this time.
180
///
181
/// To be clear, the `ChannelUsage` is aspect of a _request_ for a channel, and
182
/// is not an immutable property of the channel itself.
183
///
184
/// This type is obtained from a `tor_circmgr::usage::SupportedCircUsage` in
185
/// `tor_circmgr::usage`, and it has roughly the same set of variants.
186
#[derive(Clone, Debug, Copy, Eq, PartialEq)]
187
#[non_exhaustive]
188
pub enum ChannelUsage {
189
    /// Requesting a channel to use for BEGINDIR-based non-anonymous directory
190
    /// connections.
191
    Dir,
192

            
193
    /// Requesting a channel to transmit user traffic (including exit traffic)
194
    /// over the network.
195
    ///
196
    /// This includes the case where we are constructing a circuit preemptively,
197
    /// and _planning_ to use it for user traffic later on.
198
    UserTraffic,
199

            
200
    /// Requesting a channel that the caller does not plan to used at all, or
201
    /// which it plans to use only for testing circuits.
202
    UselessCircuit,
203
}
204

            
205
impl<R: Runtime> ChanMgr<R> {
206
    /// Construct a new channel manager.
207
    ///
208
    /// A new `ChannelAccount` will be made from `memquota`, for each Channel.
209
    ///
210
    /// The `ChannelAccount` is used for data associated with this channel.
211
    ///
212
    /// This does *not* (currently) include downstream outbound data
213
    /// (ie, data processed by the channel implementation here,
214
    /// awaiting TLS processing and actual transmission).
215
    /// In any case we try to keep those buffers small.
216
    ///
217
    /// The ChannelAccount *does* track upstream outbound data
218
    /// (ie, data processed by a circuit, but not yet by the channel),
219
    /// even though that data relates to a specific circuit.
220
    /// TODO #1652 use `CircuitAccount` for circuit->channel queue.
221
    ///
222
    /// # Usage note
223
    ///
224
    /// For the manager to work properly, you will need to call `ChanMgr::launch_background_tasks`.
225
    ///
226
    /// The `keymgr` is only needed for a relay which is used for authenticating its channel to
227
    /// other relays. Pass `None` for a client.
228
36
    pub fn new(
229
36
        runtime: R,
230
36
        config: ChanMgrConfig,
231
36
        dormancy: Dormancy,
232
36
        netparams: &NetParameters,
233
36
        memquota: ToplevelAccount,
234
36
    ) -> Result<Self>
235
36
    where
236
36
        R: 'static,
237
    {
238
36
        let (sender, receiver) = event::channel();
239
36
        let sender = Arc::new(std::sync::Mutex::new(sender));
240
36
        let reporter = BootstrapReporter(sender);
241
36
        let transport =
242
36
            transport::DefaultTransport::new(runtime.clone(), config.cfg.outbound_proxy.clone());
243
        cfg_if::cfg_if! {
244
            if #[cfg(feature = "relay")] {
245
36
                let builder = if let Some(auth_material) = &config.auth_material {
246
                    builder::ChanBuilder::new_relay(runtime.clone(), transport, auth_material.clone(), config.my_addrs, None)?
247
                } else {
248
                    // Yes, clients can have the "relay" feature enabled (unit tests).
249
36
                    builder::ChanBuilder::new_client(runtime.clone(), transport)
250
                };
251
            } else {
252
                let builder =  builder::ChanBuilder::new_client(runtime.clone(), transport);
253
            }
254
        };
255

            
256
36
        let factory = factory::CompoundFactory::new(
257
36
            Arc::new(builder),
258
            #[cfg(feature = "pt-client")]
259
36
            None,
260
        );
261

            
262
        // Warn if outbound_proxy is configured to a non-loopback address
263
36
        if let Some(ref proxy) = config.cfg.outbound_proxy {
264
            if !proxy.is_loopback() {
265
                tracing::warn!(
266
                    proxy_addr = %proxy,
267
                    "outbound_proxy is configured to a non-loopback address; \
268
                     this may expose Tor traffic to an untrusted intermediate"
269
                );
270
            }
271
36
        }
272

            
273
36
        let mgr =
274
36
            mgr::AbstractChanMgr::new(factory, config.cfg, dormancy, netparams, reporter, memquota);
275

            
276
36
        Ok(ChanMgr {
277
36
            mgr,
278
36
            bootstrap_status: receiver,
279
36
            runtime,
280
36
        })
281
36
    }
282

            
283
    /// Launch the periodic daemon tasks required by the manager to function properly.
284
    ///
285
    /// Returns a [`TaskHandle`] that can be used to manage
286
    /// those daemon tasks that poll periodically.
287
    #[instrument(level = "trace", skip_all)]
288
    pub fn launch_background_tasks(
289
        self: &Arc<Self>,
290
        runtime: &R,
291
        netdir: Arc<dyn NetDirProvider>,
292
    ) -> Result<Vec<TaskHandle>> {
293
        runtime
294
            .spawn(Self::continually_update_channels_config(
295
                Arc::downgrade(self),
296
                netdir,
297
            ))
298
            .map_err(|e| Error::from_spawn("channels config task", e))?;
299

            
300
        let (sched, handle) = TaskSchedule::new(runtime.clone());
301
        runtime
302
            .spawn(Self::continually_expire_channels(
303
                sched,
304
                Arc::downgrade(self),
305
            ))
306
            .map_err(|e| Error::from_spawn("channel expiration task", e))?;
307
        Ok(vec![handle])
308
    }
309

            
310
    /// Build a channel for an incoming stream.
311
    ///
312
    /// The `my_addrs` are the IP address(es) that are advertised by the relay in the consensus. We
313
    /// need to pass them so they can be sent in the NETINFO cell.
314
    ///
315
    /// The channel may or may not be authenticated. This method will wait until the channel is
316
    /// usable, and may return an error if we already have an existing channel to this peer.
317
    #[cfg(feature = "relay")]
318
    pub async fn handle_incoming(
319
        &self,
320
        src: Sensitive<std::net::SocketAddr>,
321
        stream: <R as tor_rtcompat::NetStreamProvider>::Stream,
322
    ) -> Result<Arc<Channel>> {
323
        let result = self.mgr.handle_incoming(src, stream).await;
324

            
325
        #[cfg(feature = "metrics")]
326
        self.mgr.metrics.increment_inbound_channels_built(&result);
327

            
328
        result
329
    }
330

            
331
    /// Try to get a suitable channel to the provided `target`,
332
    /// launching one if one does not exist.
333
    ///
334
    /// This function does not guarantee that the returned channel
335
    /// satisfies all of the properties of `target`. For example if an
336
    /// existing channel is returned, it might not be connected to any
337
    /// of the addresses specified in `target`.
338
    // ^ see https://gitlab.torproject.org/tpo/core/arti/-/issues/2344
339
    ///
340
    /// If there is already a channel launch attempt in progress, this
341
    /// function will wait until that launch is complete, and succeed
342
    /// or fail depending on its outcome.
343
    #[instrument(level = "trace", skip_all)]
344
    pub async fn get_or_launch<T: ChanTarget + ?Sized>(
345
        &self,
346
        target: &T,
347
        usage: ChannelUsage,
348
    ) -> Result<(Arc<Channel>, ChanProvenance)> {
349
        let targetinfo = OwnedChanTarget::from_chan_target(target);
350

            
351
        let (chan, provenance) = self.mgr.get_or_launch(targetinfo, usage).await?;
352
        // Double-check the match to make sure that the RSA identity is
353
        // what we wanted too.
354
        chan.check_match(target)
355
            .map_err(|e| Error::from_proto_no_skew(e, target))?;
356
        Ok((chan, provenance))
357
    }
358

            
359
    /// Return a stream of [`ConnStatus`] events to tell us about changes
360
    /// in our ability to connect to the internet.
361
    ///
362
    /// Note that this stream can be lossy: the caller will not necessarily
363
    /// observe every event on the stream
364
    pub fn bootstrap_events(&self) -> ConnStatusEvents {
365
        self.bootstrap_status.clone()
366
    }
367

            
368
    /// Expire all channels that have been unused for too long.
369
    ///
370
    /// Return the duration from now until next channel expires.
371
    pub fn expire_channels(&self) -> Duration {
372
        self.mgr.expire_channels()
373
    }
374

            
375
    /// Notifies the chanmgr to be dormant like dormancy
376
    pub fn set_dormancy(
377
        &self,
378
        dormancy: Dormancy,
379
        netparams: Arc<dyn AsRef<NetParameters>>,
380
    ) -> StdResult<(), tor_error::Bug> {
381
        self.mgr.set_dormancy(dormancy, netparams)
382
    }
383

            
384
    /// Reconfigure all channels
385
    pub fn reconfigure(
386
        &self,
387
        config: &ChannelConfig,
388
        how: tor_config::Reconfigure,
389
        netparams: Arc<dyn AsRef<NetParameters>>,
390
    ) -> StdResult<(), ReconfigureError> {
391
        if how == tor_config::Reconfigure::CheckAllOrNothing {
392
            // Since `self.mgr.reconfigure` returns an error type of `Bug` and not
393
            // `ReconfigureError` (see check below), the reconfigure should only fail due to bugs.
394
            // This means we can return `Ok` here since there should never be an error with the
395
            // provided `config` values.
396
            return Ok(());
397
        }
398

            
399
        let r = self.mgr.reconfigure(config, netparams);
400

            
401
        // Check that `self.mgr.reconfigure` returns an error type of `Bug` (see comment above).
402
        let _: Option<&tor_error::Bug> = r.as_ref().err();
403

            
404
        Ok(r?)
405
    }
406

            
407
    /// Replace the transport registry with one that may know about
408
    /// more transports.
409
    ///
410
    /// Note that the [`ChannelFactory`](factory::ChannelFactory) instances returned by `ptmgr` are
411
    /// required to time-out channels that take too long to build.  You'll get
412
    /// this behavior by default if the factories implement [`ChannelFactory`](factory::ChannelFactory) using
413
    /// [`transport::proxied::ExternalProxyPlugin`], which `tor-ptmgr` does.
414
    #[cfg(feature = "pt-client")]
415
    pub fn set_pt_mgr(&self, ptmgr: Arc<dyn factory::AbstractPtMgr + 'static>) {
416
        self.mgr.with_mut_builder(|f| f.replace_ptmgr(ptmgr));
417
    }
418

            
419
    /// Replace the relay auth material used for building new channels.
420
    ///
421
    /// This rebuilds the internal channel builder with the provided `auth_material`, which includes a
422
    /// new TLS cert and key. Existing channels are not affected, only newly created channels will
423
    /// use the new keys.
424
    #[cfg(feature = "relay")]
425
    pub fn set_relay_auth_material(
426
        &self,
427
        auth_material: Arc<tor_proto::RelayChannelAuthMaterial>,
428
    ) -> Result<()> {
429
        let mut result = Ok(());
430
        self.mgr.with_mut_builder(|f| {
431
            match f
432
                .default_factory()
433
                .rebuild_with_auth_material(auth_material)
434
            {
435
                Ok(b) => f.replace_default_factory(Arc::new(b)),
436
                Err(e) => result = Err(e),
437
            }
438
        });
439
        result
440
    }
441

            
442
    /// This will be used to handle CREATE* requests on channels.
443
    ///
444
    /// This handler will only be used for new channels, not existing channels.
445
    ///
446
    /// This will *not* be updated in any way by the channel manager,
447
    /// for example by a netdir update or when any keys change.
448
    /// The caller must handle this.
449
    /// The idea is that the channel manager shouldn't need to deal with circuit-specific stuff.
450
    ///
451
    /// It's expected to only ever call this once.
452
    /// Ideally it would be an `Option` in the constructor,
453
    /// but we don't want conditionally-compiled constructor arguments,
454
    /// and the [`CreateRequestHandler`] requires a [`dyn ChannelProvider`]
455
    /// which is typically this [`ChanMgr`] itself.
456
    #[cfg(feature = "relay")]
457
    pub fn set_create_request_handler(&self, handler: Arc<CreateRequestHandler>) -> Result<()> {
458
        let mut result = Ok(());
459
        self.mgr.with_mut_builder(|f| {
460
            match f
461
                .default_factory()
462
                .rebuild_with_create_request_handler(handler)
463
            {
464
                Ok(b) => f.replace_default_factory(Arc::new(b)),
465
                Err(e) => result = Err(e),
466
            }
467
        });
468
        result
469
    }
470

            
471
    /// Try to create a new, unmanaged channel to `target`.
472
    ///
473
    /// Unlike [`get_or_launch`](ChanMgr::get_or_launch), this function always
474
    /// creates a new channel, never retries transient failure, and does not
475
    /// register this channel with the `ChanMgr`.
476
    ///
477
    /// Generally you should not use this function; `get_or_launch` is usually a
478
    /// better choice.  This function is the right choice if, for whatever
479
    /// reason, you need to manage the lifetime of the channel you create, and
480
    /// make sure that no other code with access to this `ChanMgr` will be able
481
    /// to use the channel.
482
    #[cfg(feature = "experimental-api")]
483
    #[instrument(level = "trace", skip_all)]
484
    pub async fn build_unmanaged_channel(
485
        &self,
486
        target: impl tor_linkspec::IntoOwnedChanTarget,
487
        memquota: ChannelAccount,
488
    ) -> Result<Arc<Channel>> {
489
        use factory::ChannelFactory as _;
490
        let target = target.to_owned();
491

            
492
        self.mgr
493
            .channels
494
            .builder()
495
            .connect_via_transport(&target, self.mgr.reporter.clone(), memquota)
496
            .await
497
    }
498

            
499
    /// Watch for things that ought to change the configuration of all channels in the client
500
    ///
501
    /// Currently this handles enabling and disabling channel padding.
502
    ///
503
    /// This is a daemon task that runs indefinitely in the background,
504
    /// and exits when we find that `chanmgr` is dropped.
505
    #[instrument(level = "trace", skip_all)]
506
    async fn continually_update_channels_config(
507
        self_: Weak<Self>,
508
        netdir: Arc<dyn NetDirProvider>,
509
    ) {
510
        use tor_netdir::DirEvent as DE;
511
        let mut netdir_stream = netdir.events().fuse();
512
        let netdir = {
513
            let weak = Arc::downgrade(&netdir);
514
            drop(netdir);
515
            weak
516
        };
517
        let termination_reason: std::result::Result<Void, &str> = async move {
518
            loop {
519
                select_biased! {
520
                    direvent = netdir_stream.next() => {
521
                        let direvent = direvent.ok_or("EOF on netdir provider event stream")?;
522
                        if ! matches!(direvent, DE::NewConsensus) { continue };
523
                        let self_ = self_.upgrade().ok_or("channel manager gone away")?;
524
                        let netdir = netdir.upgrade().ok_or("netdir gone away")?;
525
                        let netparams = netdir.params();
526
                        self_.mgr.update_netparams(netparams).map_err(|e| {
527
                            error_report!(e, "continually_update_channels_config: failed to process!");
528
                            "error processing netdir"
529
                        })?;
530
                    }
531
                }
532
            }
533
        }
534
        .await;
535
        debug!(
536
            "continually_update_channels_config: shutting down: {}",
537
            termination_reason.void_unwrap_err()
538
        );
539
    }
540

            
541
    /// Periodically expire any channels that have been unused beyond
542
    /// the maximum duration allowed.
543
    ///
544
    /// Exist when we find that `chanmgr` is dropped
545
    ///
546
    /// This is a daemon task that runs indefinitely in the background
547
    #[instrument(level = "trace", skip_all)]
548
    async fn continually_expire_channels(mut sched: TaskSchedule<R>, chanmgr: Weak<Self>) {
549
        while sched.next().await.is_some() {
550
            let Some(cm) = Weak::upgrade(&chanmgr) else {
551
                // channel manager is closed.
552
                return;
553
            };
554
            let delay = cm.expire_channels();
555
            // This will sometimes be an underestimate, but it's no big deal; we just sleep some more.
556
            sched.fire_in(delay);
557
        }
558
    }
559
}
560

            
561
#[cfg(feature = "relay")]
562
#[async_trait]
563
impl<R: Runtime> ChannelProvider for ChanMgr<R> {
564
    type BuildSpec = OwnedChanTarget;
565

            
566
    fn get_or_launch(
567
        self: Arc<Self>,
568
        reactor_id: tor_proto::circuit::UniqId,
569
        target: Self::BuildSpec,
570
        tx: tor_proto::relay::channel_provider::OutboundChanSender,
571
    ) -> tor_proto::Result<()> {
572
        use tor_error::into_internal;
573

            
574
        debug!("Get or launch channel to {target} for circuit reactor {reactor_id}");
575

            
576
        let chanmgr = self.clone();
577
        self.runtime
578
            .spawn(async move {
579
                let r = chanmgr
580
                    .mgr
581
                    .get_or_launch(target, ChannelUsage::UserTraffic)
582
                    .await
583
                    .map_err(|e| tor_proto::Error::ChanProto(e.to_string())); // Is it a ChanProto?
584
                // Send back the channel.
585
                tx.send(r.map(|(chan, _)| chan));
586
            })
587
            .map_err(into_internal!("Failed to launch channel provider task"))?;
588

            
589
        Ok(())
590
    }
591
}