Skip to main content

tor_chanmgr/
lib.rs

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#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40#![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44#![allow(clippy::needless_lifetimes)] // See arti#1765
45#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46#![allow(clippy::collapsible_if)] // See arti#2342
47#![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] // See arti#2571
49#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51
52pub mod builder;
53mod config;
54mod err;
55mod event;
56pub mod factory;
57mod mgr;
58#[cfg(test)]
59mod testing;
60pub mod transport;
61
62use futures::StreamExt;
63use futures::select_biased;
64use std::result::Result as StdResult;
65use std::sync::{Arc, Weak};
66use std::time::Duration;
67use tor_config::ReconfigureError;
68use tor_error::error_report;
69use tor_linkspec::{ChanTarget, OwnedChanTarget};
70use tor_netdir::{NetDirProvider, params::NetParameters};
71use tor_proto::channel::Channel;
72#[cfg(feature = "experimental-api")]
73use tor_proto::memquota::ChannelAccount;
74use tor_proto::memquota::ToplevelAccount;
75use tor_rtcompat::SpawnExt;
76use tracing::debug;
77use tracing::instrument;
78use void::{ResultVoidErrExt, Void};
79
80#[cfg(feature = "relay")]
81use {
82    async_trait::async_trait, safelog::Sensitive, tor_proto::relay::CreateRequestHandler,
83    tor_proto::relay::channel_provider::ChannelProvider,
84};
85
86pub use err::Error;
87
88pub use config::{ChannelConfig, ChannelConfigBuilder, ProxyProtocol};
89pub use mgr::ChanMgrConfig;
90
91use tor_rtcompat::Runtime;
92
93/// A Result as returned by this crate.
94pub type Result<T> = std::result::Result<T, Error>;
95
96use crate::factory::BootstrapReporter;
97pub use event::{ConnBlockage, ConnStatus, ConnStatusEvents};
98use tor_rtcompat::scheduler::{TaskHandle, TaskSchedule};
99
100/// An object that remembers a set of live channels, and launches new ones on
101/// request.
102///
103/// Use the [`ChanMgr::get_or_launch`] function to create a new [`Channel`], or
104/// get one if it exists.  (For a slightly lower-level API that does no caching,
105/// see [`ChannelFactory`](factory::ChannelFactory) and its implementors.
106///
107/// Each channel is kept open as long as there is a reference to it, or
108/// something else (such as the relay or a network error) kills the channel.
109///
110/// After a `ChanMgr` launches a channel, it keeps a reference to it until that
111/// channel has been unused (that is, had no circuits attached to it) for a
112/// certain amount of time. (Currently this interval is chosen randomly from
113/// between 180-270 seconds, but this is an implementation detail that may change
114/// in the future.)
115pub struct ChanMgr<R: Runtime> {
116    /// Internal channel manager object that does the actual work.
117    ///
118    /// ## How this is built
119    ///
120    /// This internal manager is parameterized over an
121    /// [`mgr::AbstractChannelFactory`], which here is instantiated with a [`factory::CompoundFactory`].
122    /// The `CompoundFactory` itself holds:
123    ///   * A `dyn` [`factory::AbstractPtMgr`] that can provide a `dyn`
124    ///     [`factory::ChannelFactory`] for each supported pluggable transport.
125    ///     This starts out as `None`, but can be replaced with [`ChanMgr::set_pt_mgr`].
126    ///     The `TorClient` code currently sets this using `tor_ptmgr::PtMgr`.
127    ///     `PtMgr` currently returns `ChannelFactory` implementations that are
128    ///     built using [`transport::proxied::ExternalProxyPlugin`], which implements
129    ///     [`transport::TransportImplHelper`], which in turn is wrapped into a
130    ///     `ChanBuilder` to implement `ChannelFactory`.
131    ///   * A generic [`factory::ChannelFactory`] that it uses for everything else
132    ///     We instantiate this with a
133    ///     [`builder::ChanBuilder`] using a [`transport::default::DefaultTransport`].
134    // This type is a bit long, but I think it's better to just state it here explicitly rather than
135    // hiding parts of it behind a type alias to make it look nicer.
136    mgr: mgr::AbstractChanMgr<
137        factory::CompoundFactory<builder::ChanBuilder<R, transport::DefaultTransport<R>>>,
138    >,
139
140    /// Stream of [`ConnStatus`] events.
141    bootstrap_status: event::ConnStatusEvents,
142
143    /// The runtime. Needed to possibly spawn tasks.
144    #[allow(unused)] // Relay use this, not client yet. Keep it here instead of gating.
145    runtime: R,
146}
147
148/// Description of how we got a channel.
149#[non_exhaustive]
150#[derive(Debug, Copy, Clone, Eq, PartialEq)]
151pub enum ChanProvenance {
152    /// This channel was newly launched, or was in progress and finished while
153    /// we were waiting.
154    NewlyCreated,
155    /// This channel already existed when we asked for it.
156    Preexisting,
157}
158
159/// Dormancy state, as far as the channel manager is concerned
160///
161/// This is usually derived in higher layers from `arti_client::DormantMode`.
162#[non_exhaustive]
163#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
164pub enum Dormancy {
165    /// Not dormant
166    ///
167    /// Channels will operate normally.
168    #[default]
169    Active,
170    /// Totally dormant
171    ///
172    /// Channels will not perform any spontaneous activity (eg, netflow padding)
173    Dormant,
174}
175
176/// The usage that we have in mind when requesting a channel.
177///
178/// A channel may be used in multiple ways.  Each time a channel is requested
179/// from `ChanMgr` a separate `ChannelUsage` is passed in to tell the `ChanMgr`
180/// how the channel will be used this time.
181///
182/// To be clear, the `ChannelUsage` is aspect of a _request_ for a channel, and
183/// is not an immutable property of the channel itself.
184///
185/// This type is obtained from a `tor_circmgr::usage::SupportedCircUsage` in
186/// `tor_circmgr::usage`, and it has roughly the same set of variants.
187#[derive(Clone, Debug, Copy, Eq, PartialEq)]
188#[non_exhaustive]
189pub enum ChannelUsage {
190    /// Requesting a channel to use for BEGINDIR-based non-anonymous directory
191    /// connections.
192    Dir,
193
194    /// Requesting a channel to transmit user traffic (including exit traffic)
195    /// over the network.
196    ///
197    /// This includes the case where we are constructing a circuit preemptively,
198    /// and _planning_ to use it for user traffic later on.
199    UserTraffic,
200
201    /// Requesting a channel that the caller does not plan to used at all, or
202    /// which it plans to use only for testing circuits.
203    UselessCircuit,
204}
205
206impl<R: Runtime> ChanMgr<R> {
207    /// Construct a new channel manager.
208    ///
209    /// A new `ChannelAccount` will be made from `memquota`, for each Channel.
210    ///
211    /// The `ChannelAccount` is used for data associated with this channel.
212    ///
213    /// This does *not* (currently) include downstream outbound data
214    /// (ie, data processed by the channel implementation here,
215    /// awaiting TLS processing and actual transmission).
216    /// In any case we try to keep those buffers small.
217    ///
218    /// The ChannelAccount *does* track upstream outbound data
219    /// (ie, data processed by a circuit, but not yet by the channel),
220    /// even though that data relates to a specific circuit.
221    /// TODO #1652 use `CircuitAccount` for circuit->channel queue.
222    ///
223    /// # Usage note
224    ///
225    /// For the manager to work properly, you will need to call `ChanMgr::launch_background_tasks`.
226    ///
227    /// The `keymgr` is only needed for a relay which is used for authenticating its channel to
228    /// other relays. Pass `None` for a client.
229    pub fn new(
230        runtime: R,
231        config: ChanMgrConfig,
232        dormancy: Dormancy,
233        netparams: &NetParameters,
234        memquota: ToplevelAccount,
235    ) -> Result<Self>
236    where
237        R: 'static,
238    {
239        let (sender, receiver) = event::channel();
240        let sender = Arc::new(std::sync::Mutex::new(sender));
241        let reporter = BootstrapReporter(sender);
242        let transport =
243            transport::DefaultTransport::new(runtime.clone(), config.cfg.outbound_proxy.clone());
244        cfg_if::cfg_if! {
245            if #[cfg(feature = "relay")] {
246                let builder = if let Some(auth_material) = &config.auth_material {
247                    builder::ChanBuilder::new_relay(runtime.clone(), transport, auth_material.clone(), config.my_addrs, None)?
248                        .with_bandwidth_pools(config.bw_pools)
249                        .allow_any_addrs(config.allow_any_addrs)
250                } else {
251                    // Yes, clients can have the "relay" feature enabled (unit tests).
252                    builder::ChanBuilder::new_client(runtime.clone(), transport)
253                };
254            } else {
255                let builder =  builder::ChanBuilder::new_client(runtime.clone(), transport);
256            }
257        };
258
259        let factory = factory::CompoundFactory::new(
260            Arc::new(builder),
261            #[cfg(feature = "pt-client")]
262            None,
263        );
264
265        // Warn if outbound_proxy is configured to a non-loopback address
266        if let Some(ref proxy) = config.cfg.outbound_proxy {
267            if !proxy.is_loopback() {
268                tracing::warn!(
269                    proxy_addr = %proxy,
270                    "outbound_proxy is configured to a non-loopback address; \
271                     this may expose Tor traffic to an untrusted intermediate"
272                );
273            }
274        }
275
276        let mgr =
277            mgr::AbstractChanMgr::new(factory, config.cfg, dormancy, netparams, reporter, memquota);
278
279        Ok(ChanMgr {
280            mgr,
281            bootstrap_status: receiver,
282            runtime,
283        })
284    }
285
286    /// Launch the periodic daemon tasks required by the manager to function properly.
287    ///
288    /// Returns a [`TaskHandle`] that can be used to manage
289    /// those daemon tasks that poll periodically.
290    #[instrument(level = "trace", skip_all)]
291    pub fn launch_background_tasks(
292        self: &Arc<Self>,
293        runtime: &R,
294        netdir: Arc<dyn NetDirProvider>,
295    ) -> Result<Vec<TaskHandle>> {
296        runtime
297            .spawn(Self::continually_update_channels_config(
298                Arc::downgrade(self),
299                netdir,
300            ))
301            .map_err(|e| Error::from_spawn("channels config task", e))?;
302
303        let (sched, handle) = TaskSchedule::new(runtime.clone());
304        runtime
305            .spawn(Self::continually_expire_channels(
306                sched,
307                Arc::downgrade(self),
308            ))
309            .map_err(|e| Error::from_spawn("channel expiration task", e))?;
310        Ok(vec![handle])
311    }
312
313    /// Build a channel for an incoming stream.
314    ///
315    /// The `my_addrs` are the IP address(es) that are advertised by the relay in the consensus. We
316    /// need to pass them so they can be sent in the NETINFO cell.
317    ///
318    /// The channel may or may not be authenticated. This method will wait until the channel is
319    /// usable, and may return an error if we already have an existing channel to this peer.
320    #[cfg(feature = "relay")]
321    pub async fn handle_incoming(
322        &self,
323        src: Sensitive<std::net::SocketAddr>,
324        stream: <R as tor_rtcompat::NetStreamProvider>::Stream,
325    ) -> Result<Arc<Channel>> {
326        let result = self.mgr.handle_incoming(src, stream).await;
327
328        #[cfg(feature = "metrics")]
329        self.mgr.metrics.increment_inbound_channels_built(&result);
330
331        result
332    }
333
334    /// Try to get a suitable channel to the provided `target`,
335    /// launching one if one does not exist.
336    ///
337    /// This function does not guarantee that the returned channel
338    /// satisfies all of the properties of `target`. For example if an
339    /// existing channel is returned, it might not be connected to any
340    /// of the addresses specified in `target`.
341    // ^ see https://gitlab.torproject.org/tpo/core/arti/-/issues/2344
342    ///
343    /// If there is already a channel launch attempt in progress, this
344    /// function will wait until that launch is complete, and succeed
345    /// or fail depending on its outcome.
346    #[instrument(level = "trace", skip_all)]
347    pub async fn get_or_launch<T: ChanTarget + ?Sized>(
348        &self,
349        target: &T,
350        usage: ChannelUsage,
351    ) -> Result<(Arc<Channel>, ChanProvenance)> {
352        let targetinfo = OwnedChanTarget::from_chan_target(target);
353
354        let (chan, provenance) = self.mgr.get_or_launch(targetinfo, usage).await?;
355        // Double-check the match to make sure that the RSA identity is
356        // what we wanted too.
357        chan.check_match(target)
358            .map_err(|e| Error::from_proto_no_skew(e, target))?;
359        Ok((chan, provenance))
360    }
361
362    /// Return a stream of [`ConnStatus`] events to tell us about changes
363    /// in our ability to connect to the internet.
364    ///
365    /// Note that this stream can be lossy: the caller will not necessarily
366    /// observe every event on the stream
367    pub fn bootstrap_events(&self) -> ConnStatusEvents {
368        self.bootstrap_status.clone()
369    }
370
371    /// Expire all channels that have been unused for too long.
372    ///
373    /// Return the duration from now until next channel expires.
374    pub fn expire_channels(&self) -> Duration {
375        self.mgr.expire_channels()
376    }
377
378    /// Notifies the chanmgr to be dormant like dormancy
379    pub fn set_dormancy(
380        &self,
381        dormancy: Dormancy,
382        netparams: Arc<dyn AsRef<NetParameters>>,
383    ) -> StdResult<(), tor_error::Bug> {
384        self.mgr.set_dormancy(dormancy, netparams)
385    }
386
387    /// Reconfigure all channels
388    pub fn reconfigure(
389        &self,
390        config: &ChannelConfig,
391        how: tor_config::Reconfigure,
392        netparams: Arc<dyn AsRef<NetParameters>>,
393    ) -> StdResult<(), ReconfigureError> {
394        if how == tor_config::Reconfigure::CheckAllOrNothing {
395            // Since `self.mgr.reconfigure` returns an error type of `Bug` and not
396            // `ReconfigureError` (see check below), the reconfigure should only fail due to bugs.
397            // This means we can return `Ok` here since there should never be an error with the
398            // provided `config` values.
399            return Ok(());
400        }
401
402        let r = self.mgr.reconfigure(config, netparams);
403
404        // Check that `self.mgr.reconfigure` returns an error type of `Bug` (see comment above).
405        let _: Option<&tor_error::Bug> = r.as_ref().err();
406
407        Ok(r?)
408    }
409
410    /// Replace the transport registry with one that may know about
411    /// more transports.
412    ///
413    /// Note that the [`ChannelFactory`](factory::ChannelFactory) instances returned by `ptmgr` are
414    /// required to time-out channels that take too long to build.  You'll get
415    /// this behavior by default if the factories implement [`ChannelFactory`](factory::ChannelFactory) using
416    /// [`transport::proxied::ExternalProxyPlugin`], which `tor-ptmgr` does.
417    #[cfg(feature = "pt-client")]
418    pub fn set_pt_mgr(&self, ptmgr: Arc<dyn factory::AbstractPtMgr + 'static>) {
419        self.mgr.with_mut_builder(|f| f.replace_ptmgr(ptmgr));
420    }
421
422    /// Replace the relay auth material used for building new channels.
423    ///
424    /// This rebuilds the internal channel builder with the provided `auth_material`, which includes a
425    /// new TLS cert and key. Existing channels are not affected, only newly created channels will
426    /// use the new keys.
427    #[cfg(feature = "relay")]
428    pub fn set_relay_auth_material(
429        &self,
430        auth_material: Arc<tor_proto::RelayChannelAuthMaterial>,
431    ) -> Result<()> {
432        let mut result = Ok(());
433        self.mgr.with_mut_builder(|f| {
434            match f
435                .default_factory()
436                .rebuild_with_auth_material(auth_material)
437            {
438                Ok(b) => f.replace_default_factory(Arc::new(b)),
439                Err(e) => result = Err(e),
440            }
441        });
442        result
443    }
444
445    /// This will be used to handle CREATE* requests on channels.
446    ///
447    /// This handler will only be used for new channels, not existing channels.
448    ///
449    /// This will *not* be updated in any way by the channel manager,
450    /// for example by a netdir update or when any keys change.
451    /// The caller must handle this.
452    /// The idea is that the channel manager shouldn't need to deal with circuit-specific stuff.
453    ///
454    /// It's expected to only ever call this once.
455    /// Ideally it would be an `Option` in the constructor,
456    /// but we don't want conditionally-compiled constructor arguments,
457    /// and the [`CreateRequestHandler`] requires a [`dyn ChannelProvider`]
458    /// which is typically this [`ChanMgr`] itself.
459    #[cfg(feature = "relay")]
460    pub fn set_create_request_handler(&self, handler: Arc<CreateRequestHandler>) -> Result<()> {
461        let mut result = Ok(());
462        self.mgr.with_mut_builder(|f| {
463            match f
464                .default_factory()
465                .rebuild_with_create_request_handler(handler)
466            {
467                Ok(b) => f.replace_default_factory(Arc::new(b)),
468                Err(e) => result = Err(e),
469            }
470        });
471        result
472    }
473
474    /// Try to create a new, unmanaged channel to `target`.
475    ///
476    /// Unlike [`get_or_launch`](ChanMgr::get_or_launch), this function always
477    /// creates a new channel, never retries transient failure, and does not
478    /// register this channel with the `ChanMgr`.
479    ///
480    /// Generally you should not use this function; `get_or_launch` is usually a
481    /// better choice.  This function is the right choice if, for whatever
482    /// reason, you need to manage the lifetime of the channel you create, and
483    /// make sure that no other code with access to this `ChanMgr` will be able
484    /// to use the channel.
485    #[cfg(feature = "experimental-api")]
486    #[instrument(level = "trace", skip_all)]
487    pub async fn build_unmanaged_channel(
488        &self,
489        target: impl tor_linkspec::IntoOwnedChanTarget,
490        memquota: ChannelAccount,
491    ) -> Result<Arc<Channel>> {
492        use factory::ChannelFactory as _;
493        let target = target.to_owned();
494
495        self.mgr
496            .channels
497            .builder()
498            .connect_via_transport(&target, self.mgr.reporter.clone(), memquota)
499            .await
500    }
501
502    /// Watch for things that ought to change the configuration of all channels in the client
503    ///
504    /// Currently this handles enabling and disabling channel padding.
505    ///
506    /// This is a daemon task that runs indefinitely in the background,
507    /// and exits when we find that `chanmgr` is dropped.
508    #[instrument(level = "trace", skip_all)]
509    async fn continually_update_channels_config(
510        self_: Weak<Self>,
511        netdir: Arc<dyn NetDirProvider>,
512    ) {
513        use tor_netdir::DirEvent as DE;
514        let mut netdir_stream = netdir.events().fuse();
515        let netdir = {
516            let weak = Arc::downgrade(&netdir);
517            drop(netdir);
518            weak
519        };
520        let termination_reason: std::result::Result<Void, &str> = async move {
521            loop {
522                select_biased! {
523                    direvent = netdir_stream.next() => {
524                        let direvent = direvent.ok_or("EOF on netdir provider event stream")?;
525                        if ! matches!(direvent, DE::NewConsensus) { continue };
526                        let self_ = self_.upgrade().ok_or("channel manager gone away")?;
527                        let netdir = netdir.upgrade().ok_or("netdir gone away")?;
528                        let netparams = netdir.params();
529                        self_.mgr.update_netparams(netparams).map_err(|e| {
530                            error_report!(e, "continually_update_channels_config: failed to process!");
531                            "error processing netdir"
532                        })?;
533                    }
534                }
535            }
536        }
537        .await;
538        debug!(
539            "continually_update_channels_config: shutting down: {}",
540            termination_reason.void_unwrap_err()
541        );
542    }
543
544    /// Periodically expire any channels that have been unused beyond
545    /// the maximum duration allowed.
546    ///
547    /// Exist when we find that `chanmgr` is dropped
548    ///
549    /// This is a daemon task that runs indefinitely in the background
550    #[instrument(level = "trace", skip_all)]
551    async fn continually_expire_channels(mut sched: TaskSchedule<R>, chanmgr: Weak<Self>) {
552        while sched.next().await.is_some() {
553            let Some(cm) = Weak::upgrade(&chanmgr) else {
554                // channel manager is closed.
555                return;
556            };
557            let delay = cm.expire_channels();
558            // This will sometimes be an underestimate, but it's no big deal; we just sleep some more.
559            sched.fire_in(delay);
560        }
561    }
562}
563
564#[cfg(feature = "relay")]
565#[async_trait]
566impl<R: Runtime> ChannelProvider for ChanMgr<R> {
567    type BuildSpec = OwnedChanTarget;
568
569    fn get_or_launch(
570        self: Arc<Self>,
571        reactor_id: tor_proto::circuit::UniqId,
572        target: Self::BuildSpec,
573        tx: tor_proto::relay::channel_provider::OutboundChanSender,
574    ) -> tor_proto::Result<()> {
575        use tor_error::into_internal;
576
577        debug!("Get or launch channel to {target} for circuit reactor {reactor_id}");
578
579        let chanmgr = self.clone();
580        self.runtime
581            .spawn(async move {
582                let r = chanmgr
583                    .mgr
584                    .get_or_launch(target, ChannelUsage::UserTraffic)
585                    .await
586                    .map_err(|e| tor_proto::Error::ChanProto(e.to_string())); // Is it a ChanProto?
587                // Send back the channel.
588                tx.send(r.map(|(chan, _)| chan));
589            })
590            .map_err(into_internal!("Failed to launch channel provider task"))?;
591
592        Ok(())
593    }
594}