1#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![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#![warn(clippy::cognitive_complexity)]
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_duration_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)] #![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] pub mod config;
48pub mod err;
49
50#[cfg(feature = "managed-pts")]
51pub mod ipc;
52
53#[cfg(feature = "managed-pts")]
54mod managed;
55
56use crate::config::{TransportConfig, TransportOptions};
57use crate::err::PtError;
58use oneshot_fused_workaround as oneshot;
59use std::collections::HashMap;
60use std::net::SocketAddr;
61use std::path::PathBuf;
62use std::sync::{Arc, RwLock};
63use tor_config_path::CfgPathResolver;
64use tor_linkspec::PtTransportName;
65use tor_rtcompat::Runtime;
66use tor_socksproto::SocksVersion;
67#[cfg(any(feature = "tor-channel-factory", feature = "managed-pts"))]
68use tracing::info;
69use tracing::warn;
70#[cfg(feature = "managed-pts")]
71use {
72 crate::managed::{PtReactor, PtReactorMessage},
73 futures::channel::mpsc::{self, UnboundedSender},
74 futures::task::SpawnExt,
75 tor_error::error_report,
76};
77#[cfg(feature = "tor-channel-factory")]
78use {
79 async_trait::async_trait,
80 tor_chanmgr::{
81 builder::ChanBuilder,
82 factory::{AbstractPtError, ChannelFactory},
83 transport::ExternalProxyPlugin,
84 },
85 tracing::trace,
86};
87
88#[derive(Default, Debug)]
90struct PtSharedState {
91 #[allow(dead_code)]
95 managed_cmethods: HashMap<PtTransportName, PtClientMethod>,
96 configured: HashMap<PtTransportName, TransportOptions>,
98}
99
100pub struct PtMgr<R> {
103 #[allow(dead_code)]
105 runtime: R,
106 state: Arc<RwLock<PtSharedState>>,
108 #[cfg(feature = "managed-pts")]
110 tx: UnboundedSender<PtReactorMessage>,
111}
112
113impl<R: Runtime> PtMgr<R> {
114 fn transform_config(
116 binaries: Vec<TransportConfig>,
117 ) -> Result<HashMap<PtTransportName, TransportOptions>, tor_error::Bug> {
118 let mut ret = HashMap::new();
119 for thing in binaries {
124 for tn in thing.protocols.iter() {
125 ret.insert(tn.clone(), thing.clone().try_into()?);
126 }
127 }
128 for opt in ret.values() {
129 if let TransportOptions::Unmanaged(u) = opt {
130 if !u.is_localhost() {
131 warn!("Configured to connect to a PT on a non-local addresses. This is usually insecure! We recommend running PTs on localhost only.");
132 }
133 }
134 }
135 Ok(ret)
136 }
137
138 pub fn new(
141 transports: Vec<TransportConfig>,
142 #[allow(unused)] state_dir: PathBuf,
143 path_resolver: Arc<CfgPathResolver>,
144 rt: R,
145 ) -> Result<Self, PtError> {
146 let state = PtSharedState {
147 managed_cmethods: Default::default(),
148 configured: Self::transform_config(transports)?,
149 };
150 let state = Arc::new(RwLock::new(state));
151
152 #[cfg(feature = "managed-pts")]
154 let tx = {
155 let (tx, rx) = mpsc::unbounded();
156
157 let mut reactor =
158 PtReactor::new(rt.clone(), state.clone(), rx, state_dir, path_resolver);
159 rt.spawn(async move {
160 loop {
161 match reactor.run_one_step().await {
162 Ok(true) => return,
163 Ok(false) => {}
164 Err(e) => {
165 error_report!(e, "PtReactor failed");
166 return;
167 }
168 }
169 }
170 })
171 .map_err(|e| PtError::Spawn { cause: Arc::new(e) })?;
172
173 tx
174 };
175
176 Ok(Self {
177 runtime: rt,
178 state,
179 #[cfg(feature = "managed-pts")]
180 tx,
181 })
182 }
183
184 pub fn reconfigure(
186 &self,
187 how: tor_config::Reconfigure,
188 transports: Vec<TransportConfig>,
189 ) -> Result<(), tor_config::ReconfigureError> {
190 let configured = Self::transform_config(transports)?;
191 if how == tor_config::Reconfigure::CheckAllOrNothing {
192 return Ok(());
193 }
194 {
195 let mut inner = self.state.write().expect("ptmgr poisoned");
196 inner.configured = configured;
197 }
198 #[cfg(feature = "managed-pts")]
201 let _ = self.tx.unbounded_send(PtReactorMessage::Reconfigured);
202 Ok(())
203 }
204
205 #[cfg(feature = "tor-channel-factory")]
211 async fn get_cmethod_for_transport(
212 &self,
213 transport: &PtTransportName,
214 ) -> Result<Option<PtClientMethod>, PtError> {
215 #[allow(unused)]
216 let (cfg, managed_cmethod) = {
217 let inner = self.state.read().expect("ptmgr poisoned");
221 let cfg = inner.configured.get(transport);
222 let managed_cmethod = inner.managed_cmethods.get(transport);
223 (cfg.cloned(), managed_cmethod.cloned())
224 };
225
226 match cfg {
227 Some(TransportOptions::Unmanaged(cfg)) => {
228 let cmethod = cfg.cmethod();
229 trace!(
230 "Found configured unmanaged transport {transport} accessible via {cmethod:?}"
231 );
232 Ok(Some(cmethod))
233 }
234 #[cfg(feature = "managed-pts")]
235 Some(TransportOptions::Managed(_cfg)) => {
236 match managed_cmethod {
237 Some(cmethod) => {
239 trace!("Found configured managed transport {transport} accessible via {cmethod:?}");
240 Ok(Some(cmethod))
241 }
242 None => {
244 Ok(Some(self.spawn_transport(transport).await?))
266 }
267 }
268 }
269 None => {
271 trace!("Got a request for transport {transport}, which is not configured.");
272 Ok(None)
273 }
274 }
275 }
276
277 #[cfg(all(feature = "tor-channel-factory", feature = "managed-pts"))]
279 async fn spawn_transport(
280 &self,
281 transport: &PtTransportName,
282 ) -> Result<PtClientMethod, PtError> {
283 info!("Got a request for transport {transport}, which is not currently running. Launching it.");
286
287 let (tx, rx) = oneshot::channel();
288 self.tx
289 .unbounded_send(PtReactorMessage::Spawn {
290 pt: transport.clone(),
291 result: tx,
292 })
293 .map_err(|_| {
294 PtError::Internal(tor_error::internal!("PT reactor closed unexpectedly"))
295 })?;
296
297 let method = match rx.await {
298 Err(_) => {
299 return Err(PtError::Internal(tor_error::internal!(
300 "PT reactor closed unexpectedly"
301 )));
302 }
303 Ok(Err(e)) => {
304 warn!("PT for {transport} failed to launch: {e}");
305 return Err(e);
306 }
307 Ok(Ok(method)) => method,
308 };
309
310 info!("Successfully launched PT for {transport} at {method:?}.");
311 Ok(method)
312 }
313}
314
315#[derive(Debug, Clone, PartialEq, Eq)]
317pub struct PtClientMethod {
318 pub(crate) kind: SocksVersion,
320 pub(crate) endpoint: SocketAddr,
322}
323
324impl PtClientMethod {
325 pub fn kind(&self) -> SocksVersion {
327 self.kind
328 }
329
330 pub fn endpoint(&self) -> SocketAddr {
332 self.endpoint
333 }
334}
335
336#[cfg(feature = "tor-channel-factory")]
337#[async_trait]
338impl<R: Runtime> tor_chanmgr::factory::AbstractPtMgr for PtMgr<R> {
339 async fn factory_for_transport(
340 &self,
341 transport: &PtTransportName,
342 ) -> Result<Option<Arc<dyn ChannelFactory + Send + Sync>>, Arc<dyn AbstractPtError>> {
343 let cmethod = match self.get_cmethod_for_transport(transport).await {
344 Err(e) => return Err(Arc::new(e)),
345 Ok(None) => return Ok(None),
346 Ok(Some(m)) => m,
347 };
348
349 let proxy = ExternalProxyPlugin::new(self.runtime.clone(), cmethod.endpoint, cmethod.kind);
350 let factory = ChanBuilder::new(self.runtime.clone(), proxy);
351 Ok(Some(Arc::new(factory)))
354 }
355}