1
//! Traits and code to define different mechanisms for building Channels to
2
//! different kinds of targets.
3

            
4
use std::sync::{Arc, Mutex};
5

            
6
use crate::event::ChanMgrEventSender;
7
use async_trait::async_trait;
8
use tor_error::{HasKind, HasRetryTime, internal};
9
use tor_linkspec::{HasChanMethod, HasRelayIds, OwnedChanTarget, PtTransportName};
10
use tor_proto::channel::Channel;
11
use tor_proto::memquota::ChannelAccount;
12
use tracing::{debug, instrument};
13

            
14
#[cfg(feature = "relay")]
15
use safelog::Sensitive;
16

            
17
/// An opaque type that lets a `ChannelFactory` update the `ChanMgr` about bootstrap progress.
18
///
19
/// A future release of this crate might make this type less opaque.
20
// FIXME(eta): Do that.
21
#[derive(Clone)]
22
pub struct BootstrapReporter(pub(crate) Arc<Mutex<ChanMgrEventSender>>);
23

            
24
impl BootstrapReporter {
25
    #[cfg(test)]
26
    /// Create a useless version of this type to satisfy some test.
27
32
    pub(crate) fn fake() -> Self {
28
32
        let (snd, _rcv) = crate::event::channel();
29
32
        Self(Arc::new(Mutex::new(snd)))
30
32
    }
31
}
32

            
33
/// An object that knows how to build `Channels` to `ChanTarget`s.
34
///
35
/// This trait must be object-safe.
36
///
37
/// Every [`ChanMgr`](crate::ChanMgr) has a `ChannelFactory` that it uses to
38
/// construct all of its channels.
39
///
40
/// A `ChannelFactory` can be implemented in terms of a
41
/// [`TransportImplHelper`](crate::transport::TransportImplHelper), by wrapping it in a
42
/// `ChanBuilder`.
43
///
44
// FIXME(eta): Rectify the below situation.
45
/// (In fact, as of the time of writing, this is the *only* way to implement this trait
46
/// outside of this crate while keeping bootstrap status reporting, since `BootstrapReporter`
47
/// is an opaque type.)
48
#[async_trait]
49
pub trait ChannelFactory: Send + Sync {
50
    /// Open an authenticated channel to `target`.
51
    ///
52
    /// This method does does not necessarily handle retries or timeouts,
53
    /// although some of its implementations may.
54
    ///
55
    /// This method does not necessarily handle every kind of transport. If the
56
    /// caller provides a target with an unsupported
57
    /// [`TransportId`](tor_linkspec::TransportId), this method should return
58
    /// [`Error::NoSuchTransport`](crate::Error::NoSuchTransport).
59
    async fn connect_via_transport(
60
        &self,
61
        target: &OwnedChanTarget,
62
        reporter: BootstrapReporter,
63
        memquota: ChannelAccount,
64
    ) -> crate::Result<Arc<Channel>>;
65
}
66

            
67
/// Similar to [`ChannelFactory`], but for building channels from incoming streams.
68
// This is a separate trait since for some `ChannelFactory`s like the one returned from
69
// `tor_ptmgr::PtMgr::factory_for_transport`, it doesn't make sense to deal with incoming streams
70
// (all PT connections are outgoing).
71
#[async_trait]
72
pub trait IncomingChannelFactory: Send + Sync {
73
    /// The type of byte stream that's required to build channels for incoming connections.
74
    type Stream: Send + Sync + 'static;
75

            
76
    /// Open a channel from `peer` with the given `stream`. The channel may or may not be
77
    /// authenticated.
78
    #[cfg(feature = "relay")]
79
    async fn accept_from_transport(
80
        &self,
81
        peer: Sensitive<std::net::SocketAddr>,
82
        stream: Self::Stream,
83
        memquota: ChannelAccount,
84
    ) -> crate::Result<Arc<Channel>>;
85
}
86

            
87
#[async_trait]
88
impl<CF> crate::mgr::AbstractChannelFactory for CF
89
where
90
    CF: ChannelFactory + IncomingChannelFactory + Sync,
91
{
92
    type Channel = tor_proto::channel::Channel;
93
    type BuildSpec = OwnedChanTarget;
94
    type Stream = CF::Stream;
95

            
96
    #[instrument(skip_all, level = "trace")]
97
    async fn build_channel(
98
        &self,
99
        target: &Self::BuildSpec,
100
        reporter: BootstrapReporter,
101
        memquota: ChannelAccount,
102
    ) -> crate::Result<Arc<Self::Channel>> {
103
        debug!("Attempting to open a new channel to {target}");
104
        self.connect_via_transport(target, reporter, memquota).await
105
    }
106

            
107
    #[cfg(feature = "relay")]
108
    #[instrument(skip_all, level = "trace")]
109
    async fn build_channel_using_incoming(
110
        &self,
111
        peer: Sensitive<std::net::SocketAddr>,
112
        stream: Self::Stream,
113
        memquota: ChannelAccount,
114
    ) -> crate::Result<Arc<tor_proto::channel::Channel>> {
115
        debug!("Attempting to open a new channel from {peer}");
116
        let chan = self.accept_from_transport(peer, stream, memquota).await?;
117
        debug!(
118
            channel_id = %chan.unique_id(),
119
            authenticated = HasRelayIds::has_any_identity(chan.as_ref()),
120
            "Opened a new channel from {peer}"
121
        );
122
        Ok(chan)
123
    }
124
}
125

            
126
/// The error type returned by a pluggable transport manager.
127
pub trait AbstractPtError:
128
    std::error::Error + HasKind + HasRetryTime + Send + Sync + std::fmt::Debug
129
{
130
}
131

            
132
/// A pluggable transport manager.
133
///
134
/// We can't directly reference the `PtMgr` type from `tor-ptmgr`, because of dependency resolution
135
/// constraints, so this defines the interface for what one should look like.
136
#[async_trait]
137
pub trait AbstractPtMgr: Send + Sync {
138
    /// Get a `ChannelFactory` for the provided `PtTransportName`.
139
    async fn factory_for_transport(
140
        &self,
141
        transport: &PtTransportName,
142
    ) -> Result<Option<Arc<dyn ChannelFactory + Send + Sync>>, Arc<dyn AbstractPtError>>;
143
}
144

            
145
#[async_trait]
146
impl<P> AbstractPtMgr for Option<P>
147
where
148
    P: AbstractPtMgr,
149
{
150
    async fn factory_for_transport(
151
        &self,
152
        transport: &PtTransportName,
153
    ) -> Result<Option<Arc<dyn ChannelFactory + Send + Sync>>, Arc<dyn AbstractPtError>> {
154
        match self {
155
            Some(mgr) => mgr.factory_for_transport(transport).await,
156
            None => Ok(None),
157
        }
158
    }
159
}
160

            
161
/// A ChannelFactory built from an optional PtMgr to use for pluggable transports, and a
162
/// ChannelFactory to use for everything else.
163
pub(crate) struct CompoundFactory<CF> {
164
    #[cfg(feature = "pt-client")]
165
    /// The PtMgr to use for pluggable transports
166
    ptmgr: Option<Arc<dyn AbstractPtMgr + 'static>>,
167
    /// The factory to use for everything else
168
    default_factory: Arc<CF>,
169
}
170

            
171
impl<CF> Clone for CompoundFactory<CF> {
172
    fn clone(&self) -> Self {
173
        Self {
174
            #[cfg(feature = "pt-client")]
175
            ptmgr: self.ptmgr.as_ref().map(Arc::clone),
176
            default_factory: Arc::clone(&self.default_factory),
177
        }
178
    }
179
}
180

            
181
#[async_trait]
182
impl<CF: ChannelFactory> ChannelFactory for CompoundFactory<CF> {
183
    #[instrument(skip_all, level = "trace")]
184
    async fn connect_via_transport(
185
        &self,
186
        target: &OwnedChanTarget,
187
        reporter: BootstrapReporter,
188
        memquota: ChannelAccount,
189
    ) -> crate::Result<Arc<Channel>> {
190
        use tor_linkspec::ChannelMethod::*;
191
        let factory = match target.chan_method() {
192
            Direct(_) => self.default_factory.clone(),
193
            #[cfg(feature = "pt-client")]
194
            Pluggable(a) => match self.ptmgr.as_ref() {
195
                Some(mgr) => mgr
196
                    .factory_for_transport(a.transport())
197
                    .await
198
                    .map_err(crate::Error::Pt)?
199
                    .ok_or_else(|| crate::Error::NoSuchTransport(a.transport().clone().into()))?,
200
                None => return Err(crate::Error::NoSuchTransport(a.transport().clone().into())),
201
            },
202
            #[allow(unreachable_patterns)]
203
            _ => {
204
                return Err(crate::Error::Internal(internal!(
205
                    "No support for channel method"
206
                )));
207
            }
208
        };
209

            
210
        factory
211
            .connect_via_transport(target, reporter, memquota)
212
            .await
213
    }
214
}
215

            
216
#[async_trait]
217
impl<CF: IncomingChannelFactory> IncomingChannelFactory for CompoundFactory<CF> {
218
    type Stream = CF::Stream;
219

            
220
    #[cfg(feature = "relay")]
221
    async fn accept_from_transport(
222
        &self,
223
        peer: Sensitive<std::net::SocketAddr>,
224
        stream: Self::Stream,
225
        memquota: ChannelAccount,
226
    ) -> crate::Result<Arc<Channel>> {
227
        self.default_factory
228
            .accept_from_transport(peer, stream, memquota)
229
            .await
230
    }
231
}
232

            
233
impl<CF: ChannelFactory + 'static> CompoundFactory<CF> {
234
    /// Create a new `Factory` that will try to use `ptmgr` to handle pluggable
235
    /// transports requests, and `default_factory` to handle everything else.
236
18
    pub(crate) fn new(
237
18
        default_factory: Arc<CF>,
238
18
        #[cfg(feature = "pt-client")] ptmgr: Option<Arc<dyn AbstractPtMgr + 'static>>,
239
18
    ) -> Self {
240
18
        Self {
241
18
            default_factory,
242
18
            #[cfg(feature = "pt-client")]
243
18
            ptmgr,
244
18
        }
245
18
    }
246

            
247
    #[cfg(feature = "pt-client")]
248
    /// Replace the PtMgr in this object.
249
    pub(crate) fn replace_ptmgr(&mut self, ptmgr: Arc<dyn AbstractPtMgr + 'static>) {
250
        self.ptmgr = Some(ptmgr);
251
    }
252

            
253
    /// Return a reference to the default channel factory.
254
    #[cfg(feature = "relay")]
255
    pub(crate) fn default_factory(&self) -> &CF {
256
        &self.default_factory
257
    }
258

            
259
    /// Replace the default channel factory.
260
    #[cfg(feature = "relay")]
261
    pub(crate) fn replace_default_factory(&mut self, factory: Arc<CF>) {
262
        self.default_factory = factory;
263
    }
264
}