1#![cfg_attr(docsrs, feature(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#![allow(clippy::cognitive_complexity)] #![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)] #![allow(clippy::uninlined_format_args)]
41#![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)] #![allow(clippy::collapsible_if)] #![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] #![allow(recursion_depth_exceeding_limit)] pub mod config;
53pub mod err;
54
55#[cfg(feature = "managed-pts")]
56pub mod ipc;
57
58#[cfg(feature = "managed-pts")]
59mod managed;
60
61use crate::config::{TransportConfig, TransportOptions};
62use crate::err::PtError;
63use std::collections::HashMap;
64use std::net::SocketAddr;
65use std::path::PathBuf;
66use std::sync::{Arc, RwLock};
67use tor_chanmgr::ProxyProtocol;
68use tor_config_path::CfgPathResolver;
69use tor_linkspec::PtTransportName;
70use tor_rtcompat::Runtime;
71use tor_socksproto::SocksVersion;
72use tracing::warn;
73#[cfg(feature = "managed-pts")]
74use {
75 crate::managed::{PtReactor, PtReactorMessage},
76 futures::channel::mpsc::{self, UnboundedSender},
77 tor_error::error_report,
78 tor_rtcompat::SpawnExt,
79};
80#[cfg(feature = "tor-channel-factory")]
81use {
82 async_trait::async_trait,
83 tor_chanmgr::{
84 builder::ChanBuilder,
85 factory::{AbstractPtError, ChannelFactory},
86 transport::ExternalProxyPlugin,
87 },
88 tracing::trace,
89};
90#[cfg(all(feature = "managed-pts", feature = "tor-channel-factory"))]
91use {oneshot_fused_workaround as oneshot, tracing::info};
92
93#[derive(Default, Debug)]
95struct PtSharedState {
96 #[cfg(feature = "managed-pts")]
100 managed_cmethods: HashMap<PtTransportName, PtClientMethod>,
101 configured: HashMap<PtTransportName, TransportOptions>,
103 outbound_proxy: Option<ProxyProtocol>,
105}
106
107pub struct PtMgr<R> {
110 #[allow(dead_code)]
112 runtime: R,
113 state: Arc<RwLock<PtSharedState>>,
115 #[cfg(feature = "managed-pts")]
117 tx: UnboundedSender<PtReactorMessage>,
118}
119
120impl<R: Runtime> PtMgr<R> {
121 fn transform_config(
123 binaries: Vec<TransportConfig>,
124 ) -> Result<HashMap<PtTransportName, TransportOptions>, tor_error::Bug> {
125 let mut ret = HashMap::new();
126 for thing in binaries {
131 for tn in thing.protocols.iter() {
132 ret.insert(tn.clone(), thing.clone().try_into()?);
133 }
134 }
135 for opt in ret.values() {
136 match opt {
137 TransportOptions::Unmanaged(u) => {
138 if !u.is_localhost() {
139 warn!(
140 "Configured to connect to a PT on a non-local addresses. This is usually insecure! We recommend running PTs on localhost only."
141 );
142 }
143 }
144 #[cfg(feature = "managed-pts")]
145 TransportOptions::Managed(_) => {
146 }
150 }
151 }
152 Ok(ret)
153 }
154
155 pub fn new(
158 transports: Vec<TransportConfig>,
159 #[allow(unused)] state_dir: PathBuf,
160 #[allow(unused)] path_resolver: Arc<CfgPathResolver>,
161 outbound_proxy: Option<ProxyProtocol>,
162 rt: R,
163 ) -> Result<Self, PtError> {
164 let state = PtSharedState {
165 #[cfg(feature = "managed-pts")]
166 managed_cmethods: Default::default(),
167 configured: Self::transform_config(transports)?,
168 outbound_proxy,
169 };
170 let state = Arc::new(RwLock::new(state));
171
172 #[cfg(feature = "managed-pts")]
174 let tx = {
175 let (tx, rx) = mpsc::unbounded();
176
177 let mut reactor =
178 PtReactor::new(rt.clone(), state.clone(), rx, state_dir, path_resolver);
179 rt.spawn(async move {
180 loop {
181 match reactor.run_one_step().await {
182 Ok(true) => return,
183 Ok(false) => {}
184 Err(e) => {
185 error_report!(e, "PtReactor failed");
186 return;
187 }
188 }
189 }
190 })
191 .map_err(|e| PtError::Spawn { cause: Arc::new(e) })?;
192
193 tx
194 };
195
196 Ok(Self {
197 runtime: rt,
198 state,
199 #[cfg(feature = "managed-pts")]
200 tx,
201 })
202 }
203
204 pub fn reconfigure(
206 &self,
207 how: tor_config::Reconfigure,
208 transports: Vec<TransportConfig>,
209 outbound_proxy: Option<ProxyProtocol>,
210 ) -> Result<(), tor_config::ReconfigureError> {
211 let configured = Self::transform_config(transports)?;
212 if how == tor_config::Reconfigure::CheckAllOrNothing {
213 return Ok(());
214 }
215 {
216 let mut inner = self.state.write().expect("ptmgr poisoned");
217 inner.configured = configured;
218 inner.outbound_proxy = outbound_proxy;
219 }
220 #[cfg(feature = "managed-pts")]
227 let _ = self.tx.unbounded_send(PtReactorMessage::Reconfigured);
228 Ok(())
229 }
230
231 #[cfg(feature = "tor-channel-factory")]
237 async fn get_cmethod_for_transport(
238 &self,
239 transport: &PtTransportName,
240 ) -> Result<Option<PtClientMethod>, PtError> {
241 let (cfg, managed_cmethod) = {
242 let inner = self.state.read().expect("ptmgr poisoned");
246 let cfg = inner.configured.get(transport);
247 let managed_cmethod = inner.managed_cmethods.get(transport);
248 (cfg.cloned(), managed_cmethod.cloned())
249 };
250
251 #[cfg(not(feature = "managed-pts"))]
252 let _ = managed_cmethod; match cfg {
255 Some(TransportOptions::Unmanaged(cfg)) => {
256 let cmethod = cfg.cmethod();
257 trace!(
258 "Found configured unmanaged transport {transport} accessible via {cmethod:?}"
259 );
260 Ok(Some(cmethod))
261 }
262 #[cfg(feature = "managed-pts")]
263 Some(TransportOptions::Managed(_cfg)) => {
264 match managed_cmethod {
265 Some(cmethod) => {
267 trace!(
268 "Found configured managed transport {transport} accessible via {cmethod:?}"
269 );
270 Ok(Some(cmethod))
271 }
272 None => {
274 Ok(Some(self.spawn_transport(transport).await?))
296 }
297 }
298 }
299 None => {
301 trace!("Got a request for transport {transport}, which is not configured.");
302 Ok(None)
303 }
304 }
305 }
306
307 #[cfg(all(feature = "tor-channel-factory", feature = "managed-pts"))]
309 async fn spawn_transport(
310 &self,
311 transport: &PtTransportName,
312 ) -> Result<PtClientMethod, PtError> {
313 info!(
316 "Got a request for transport {transport}, which is not currently running. Launching it."
317 );
318
319 let (tx, rx) = oneshot::channel();
320 self.tx
321 .unbounded_send(PtReactorMessage::Spawn {
322 pt: transport.clone(),
323 result: tx,
324 })
325 .map_err(|_| {
326 PtError::Internal(tor_error::internal!("PT reactor closed unexpectedly"))
327 })?;
328
329 let method = match rx.await {
330 Err(_) => {
331 return Err(PtError::Internal(tor_error::internal!(
332 "PT reactor closed unexpectedly"
333 )));
334 }
335 Ok(Err(e)) => {
336 warn!("PT for {transport} failed to launch: {e}");
337 return Err(e);
338 }
339 Ok(Ok(method)) => method,
340 };
341
342 info!("Successfully launched PT for {transport} at {method:?}.");
343 Ok(method)
344 }
345}
346
347#[derive(Debug, Clone, PartialEq, Eq)]
349pub struct PtClientMethod {
350 pub(crate) kind: SocksVersion,
352 pub(crate) endpoint: SocketAddr,
354}
355
356impl PtClientMethod {
357 pub fn kind(&self) -> SocksVersion {
359 self.kind
360 }
361
362 pub fn endpoint(&self) -> SocketAddr {
364 self.endpoint
365 }
366}
367
368#[cfg(feature = "tor-channel-factory")]
369#[async_trait]
370impl<R: Runtime> tor_chanmgr::factory::AbstractPtMgr for PtMgr<R> {
371 async fn factory_for_transport(
372 &self,
373 transport: &PtTransportName,
374 ) -> Result<Option<Arc<dyn ChannelFactory + Send + Sync>>, Arc<dyn AbstractPtError>> {
375 let cmethod = match self.get_cmethod_for_transport(transport).await {
376 Err(e) => return Err(Arc::new(e)),
377 Ok(None) => return Ok(None),
378 Ok(Some(m)) => m,
379 };
380
381 let proxy = ExternalProxyPlugin::new(self.runtime.clone(), cmethod.endpoint, cmethod.kind);
382 let factory = ChanBuilder::new_client(self.runtime.clone(), proxy);
383 Ok(Some(Arc::new(factory)))
386 }
387}