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 config;
52
pub mod err;
53

            
54
#[cfg(feature = "managed-pts")]
55
pub mod ipc;
56

            
57
#[cfg(feature = "managed-pts")]
58
mod managed;
59

            
60
use crate::config::{TransportConfig, TransportOptions};
61
use crate::err::PtError;
62
use std::collections::HashMap;
63
use std::net::SocketAddr;
64
use std::path::PathBuf;
65
use std::sync::{Arc, RwLock};
66
use tor_chanmgr::ProxyProtocol;
67
use tor_config_path::CfgPathResolver;
68
use tor_linkspec::PtTransportName;
69
use tor_rtcompat::Runtime;
70
use tor_socksproto::SocksVersion;
71
use tracing::warn;
72
#[cfg(feature = "managed-pts")]
73
use {
74
    crate::managed::{PtReactor, PtReactorMessage},
75
    futures::channel::mpsc::{self, UnboundedSender},
76
    tor_error::error_report,
77
    tor_rtcompat::SpawnExt,
78
};
79
#[cfg(feature = "tor-channel-factory")]
80
use {
81
    async_trait::async_trait,
82
    tor_chanmgr::{
83
        builder::ChanBuilder,
84
        factory::{AbstractPtError, ChannelFactory},
85
        transport::ExternalProxyPlugin,
86
    },
87
    tracing::trace,
88
};
89
#[cfg(all(feature = "managed-pts", feature = "tor-channel-factory"))]
90
use {oneshot_fused_workaround as oneshot, tracing::info};
91

            
92
/// Shared mutable state between the `PtReactor` and `PtMgr`.
93
#[derive(Default, Debug)]
94
struct PtSharedState {
95
    /// Connection information for pluggable transports from currently running binaries.
96
    ///
97
    /// Unmanaged pluggable transports are not included in this map.
98
    #[cfg(feature = "managed-pts")]
99
    managed_cmethods: HashMap<PtTransportName, PtClientMethod>,
100
    /// Current configured set of pluggable transports.
101
    configured: HashMap<PtTransportName, TransportOptions>,
102
    /// The global Tor outbound proxy, if any.
103
    outbound_proxy: Option<ProxyProtocol>,
104
}
105

            
106
/// A pluggable transport manager knows how to make different
107
/// kinds of connections to the Tor network, for censorship avoidance.
108
pub struct PtMgr<R> {
109
    /// An underlying `Runtime`, used to spawn background tasks.
110
    #[allow(dead_code)]
111
    runtime: R,
112
    /// State for this `PtMgr` that's shared with the `PtReactor`.
113
    state: Arc<RwLock<PtSharedState>>,
114
    /// PtReactor channel when the `managed-pts` feature is enabled.
115
    #[cfg(feature = "managed-pts")]
116
    tx: UnboundedSender<PtReactorMessage>,
117
}
118

            
119
impl<R: Runtime> PtMgr<R> {
120
    /// Transform the config into a more useful representation indexed by transport name.
121
    fn transform_config(
122
        binaries: Vec<TransportConfig>,
123
    ) -> Result<HashMap<PtTransportName, TransportOptions>, tor_error::Bug> {
124
        let mut ret = HashMap::new();
125
        // FIXME(eta): You can currently specify overlapping protocols, and it'll
126
        //             just use the last transport specified.
127
        //             I attempted to fix this, but decided I didn't want to stare into the list
128
        //             builder macro void after trying it for 15 minutes.
129
        for thing in binaries {
130
            for tn in thing.protocols.iter() {
131
                ret.insert(tn.clone(), thing.clone().try_into()?);
132
            }
133
        }
134
        for opt in ret.values() {
135
            match opt {
136
                TransportOptions::Unmanaged(u) => {
137
                    if !u.is_localhost() {
138
                        warn!(
139
                            "Configured to connect to a PT on a non-local addresses. This is usually insecure! We recommend running PTs on localhost only."
140
                        );
141
                    }
142
                }
143
                #[cfg(feature = "managed-pts")]
144
                TransportOptions::Managed(_) => {
145
                    // Nothing to check here,
146
                    // since we should spawn the managed PT and
147
                    // we shouldn't know what address it will listen on yet.
148
                }
149
            }
150
        }
151
        Ok(ret)
152
    }
153

            
154
    /// Create a new PtMgr.
155
    // TODO: maybe don't have the Vec directly exposed?
156
    pub fn new(
157
        transports: Vec<TransportConfig>,
158
        #[allow(unused)] state_dir: PathBuf,
159
        #[allow(unused)] path_resolver: Arc<CfgPathResolver>,
160
        outbound_proxy: Option<ProxyProtocol>,
161
        rt: R,
162
    ) -> Result<Self, PtError> {
163
        let state = PtSharedState {
164
            #[cfg(feature = "managed-pts")]
165
            managed_cmethods: Default::default(),
166
            configured: Self::transform_config(transports)?,
167
            outbound_proxy,
168
        };
169
        let state = Arc::new(RwLock::new(state));
170

            
171
        // reactor is only needed if we support managed pts
172
        #[cfg(feature = "managed-pts")]
173
        let tx = {
174
            let (tx, rx) = mpsc::unbounded();
175

            
176
            let mut reactor =
177
                PtReactor::new(rt.clone(), state.clone(), rx, state_dir, path_resolver);
178
            rt.spawn(async move {
179
                loop {
180
                    match reactor.run_one_step().await {
181
                        Ok(true) => return,
182
                        Ok(false) => {}
183
                        Err(e) => {
184
                            error_report!(e, "PtReactor failed");
185
                            return;
186
                        }
187
                    }
188
                }
189
            })
190
            .map_err(|e| PtError::Spawn { cause: Arc::new(e) })?;
191

            
192
            tx
193
        };
194

            
195
        Ok(Self {
196
            runtime: rt,
197
            state,
198
            #[cfg(feature = "managed-pts")]
199
            tx,
200
        })
201
    }
202

            
203
    /// Reload the configuration
204
    pub fn reconfigure(
205
        &self,
206
        how: tor_config::Reconfigure,
207
        transports: Vec<TransportConfig>,
208
        outbound_proxy: Option<ProxyProtocol>,
209
    ) -> Result<(), tor_config::ReconfigureError> {
210
        let configured = Self::transform_config(transports)?;
211
        if how == tor_config::Reconfigure::CheckAllOrNothing {
212
            return Ok(());
213
        }
214
        {
215
            let mut inner = self.state.write().expect("ptmgr poisoned");
216
            inner.configured = configured;
217
            inner.outbound_proxy = outbound_proxy;
218
        }
219
        // We don't have any way of propagating this sanely; the caller will find out the reactor
220
        // has died later on anyway.
221
        // TODO(#2634):
222
        // PT reactor doesn't appear to update its running list when Reconfigured.
223
        // Change logic in PtReactor::run_one_step(...)
224
        // to update the running list upon receiving a reconfigured message.
225
        #[cfg(feature = "managed-pts")]
226
        let _ = self.tx.unbounded_send(PtReactorMessage::Reconfigured);
227
        Ok(())
228
    }
229

            
230
    /// Given a transport name, return a method that we can use to contact that transport.
231
    ///
232
    /// May have to launch a managed transport as needed.
233
    ///
234
    /// Returns Ok(None) if no such transport exists.
235
    #[cfg(feature = "tor-channel-factory")]
236
    async fn get_cmethod_for_transport(
237
        &self,
238
        transport: &PtTransportName,
239
    ) -> Result<Option<PtClientMethod>, PtError> {
240
        let (cfg, managed_cmethod) = {
241
            // NOTE(eta): This is using a RwLock inside async code (but not across an await point).
242
            //            Arguably this is fine since it's just a small read, and nothing should ever
243
            //            hold this lock for very long.
244
            let inner = self.state.read().expect("ptmgr poisoned");
245
            let cfg = inner.configured.get(transport);
246
            let managed_cmethod = inner.managed_cmethods.get(transport);
247
            (cfg.cloned(), managed_cmethod.cloned())
248
        };
249

            
250
        #[cfg(not(feature = "managed-pts"))]
251
        let _ = managed_cmethod; // avoid unused variable warning
252

            
253
        match cfg {
254
            Some(TransportOptions::Unmanaged(cfg)) => {
255
                let cmethod = cfg.cmethod();
256
                trace!(
257
                    "Found configured unmanaged transport {transport} accessible via {cmethod:?}"
258
                );
259
                Ok(Some(cmethod))
260
            }
261
            #[cfg(feature = "managed-pts")]
262
            Some(TransportOptions::Managed(_cfg)) => {
263
                match managed_cmethod {
264
                    // A configured-and-running cmethod.
265
                    Some(cmethod) => {
266
                        trace!(
267
                            "Found configured managed transport {transport} accessible via {cmethod:?}"
268
                        );
269
                        Ok(Some(cmethod))
270
                    }
271
                    // A configured-but-not-running cmethod.
272
                    None => {
273
                        // There is going to be a lot happening "under the hood" here.
274
                        //
275
                        // When we are asked to get a ChannelFactory for a given
276
                        // connection, we will need to:
277
                        //    - launch the binary for that transport if it is not already running*.
278
                        //    - If we launched the binary, talk to it and see which ports it
279
                        //      is listening on.
280
                        //    - Return a ChannelFactory that connects via one of those ports,
281
                        //      using the appropriate version of SOCKS, passing K=V parameters
282
                        //      encoded properly.
283
                        //
284
                        // * As in other managers, we'll need to avoid trying to launch the same
285
                        //   transport twice if we get two concurrent requests.
286
                        //
287
                        // Later if the binary crashes, we should detect that.  We should relaunch
288
                        // it on demand.
289
                        //
290
                        // On reconfigure, we should shut down any no-longer-used transports.
291
                        //
292
                        // Maybe, we should shut down transports that haven't been used
293
                        // for a long time.
294
                        Ok(Some(self.spawn_transport(transport).await?))
295
                    }
296
                }
297
            }
298
            // No configuration for this transport.
299
            None => {
300
                trace!("Got a request for transport {transport}, which is not configured.");
301
                Ok(None)
302
            }
303
        }
304
    }
305

            
306
    /// Communicate with the PT reactor to launch a managed transport.
307
    #[cfg(all(feature = "tor-channel-factory", feature = "managed-pts"))]
308
    async fn spawn_transport(
309
        &self,
310
        transport: &PtTransportName,
311
    ) -> Result<PtClientMethod, PtError> {
312
        // Tell the reactor to spawn the PT, and wait for it.
313
        // (The reactor will handle coalescing multiple requests.)
314
        info!(
315
            "Got a request for transport {transport}, which is not currently running. Launching it."
316
        );
317

            
318
        let (tx, rx) = oneshot::channel();
319
        self.tx
320
            .unbounded_send(PtReactorMessage::Spawn {
321
                pt: transport.clone(),
322
                result: tx,
323
            })
324
            .map_err(|_| {
325
                PtError::Internal(tor_error::internal!("PT reactor closed unexpectedly"))
326
            })?;
327

            
328
        let method = match rx.await {
329
            Err(_) => {
330
                return Err(PtError::Internal(tor_error::internal!(
331
                    "PT reactor closed unexpectedly"
332
                )));
333
            }
334
            Ok(Err(e)) => {
335
                warn!("PT for {transport} failed to launch: {e}");
336
                return Err(e);
337
            }
338
            Ok(Ok(method)) => method,
339
        };
340

            
341
        info!("Successfully launched PT for {transport} at {method:?}.");
342
        Ok(method)
343
    }
344
}
345

            
346
/// A SOCKS endpoint to connect through a pluggable transport.
347
#[derive(Debug, Clone, PartialEq, Eq)]
348
pub struct PtClientMethod {
349
    /// The SOCKS protocol version to use.
350
    pub(crate) kind: SocksVersion,
351
    /// The socket address to connect to.
352
    pub(crate) endpoint: SocketAddr,
353
}
354

            
355
impl PtClientMethod {
356
    /// Get the SOCKS protocol version to use.
357
    pub fn kind(&self) -> SocksVersion {
358
        self.kind
359
    }
360

            
361
    /// Get the socket address to connect to.
362
    pub fn endpoint(&self) -> SocketAddr {
363
        self.endpoint
364
    }
365
}
366

            
367
#[cfg(feature = "tor-channel-factory")]
368
#[async_trait]
369
impl<R: Runtime> tor_chanmgr::factory::AbstractPtMgr for PtMgr<R> {
370
    async fn factory_for_transport(
371
        &self,
372
        transport: &PtTransportName,
373
    ) -> Result<Option<Arc<dyn ChannelFactory + Send + Sync>>, Arc<dyn AbstractPtError>> {
374
        let cmethod = match self.get_cmethod_for_transport(transport).await {
375
            Err(e) => return Err(Arc::new(e)),
376
            Ok(None) => return Ok(None),
377
            Ok(Some(m)) => m,
378
        };
379

            
380
        let proxy = ExternalProxyPlugin::new(self.runtime.clone(), cmethod.endpoint, cmethod.kind);
381
        let factory = ChanBuilder::new_client(self.runtime.clone(), proxy);
382
        // FIXME(eta): Should we cache constructed factories? If no: should this still be an Arc?
383
        // FIXME(eta): Should we track what transports are live somehow, so we can shut them down?
384
        Ok(Some(Arc::new(factory)))
385
    }
386
}