Skip to main content

tor_hsclient/
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//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50
51#![allow(clippy::redundant_field_names)] // TODO beta clippy bug, rust-clippy/issues/17525
52
53mod caps;
54mod connect;
55mod err;
56mod isol_map;
57mod keys;
58mod pow;
59mod proto_oneshot;
60mod relay_info;
61mod state;
62
63use std::future::Future;
64use std::sync::{Arc, Mutex, MutexGuard};
65
66use futures::StreamExt as _;
67use futures::stream::BoxStream;
68use tor_rtcompat::SpawnExt as _;
69
70use educe::Educe;
71use tracing::{debug, instrument};
72
73use tor_circmgr::ClientOnionServiceDataTunnel;
74use tor_circmgr::hspool::HsCircPool;
75use tor_circmgr::isolation::StreamIsolation;
76use tor_error::{Bug, internal};
77use tor_hscrypto::pk::HsId;
78use tor_netdir::NetDir;
79use tor_rtcompat::Runtime;
80
81pub use err::FailedAttemptError;
82pub use err::{ConnError, DescriptorError, DescriptorErrorDetail, StartupError};
83pub use keys::{HsClientDescEncKeypairSpecifier, HsClientSecretKeys, HsClientSecretKeysBuilder};
84pub use relay_info::InvalidTarget;
85pub use state::HsClientConnectorConfig;
86
87use err::{IntroPtIndex, rend_pt_identity_for_error};
88use state::{Config, MockableConnectorData, Services};
89
90/// An object that negotiates connections with onion services
91///
92/// This can be used by multiple requests on behalf of different clients,
93/// with potentially different HS service discovery keys (`KS_hsc_*`)
94/// and potentially different circuit isolation.
95///
96/// The principal entrypoint is
97/// [`get_or_launch_tunnel()`](HsClientConnector::get_or_launch_tunnel).
98///
99/// This object is handle-like: it is fairly cheap to clone,
100///  and contains `Arc`s internally.
101#[derive(Educe)]
102#[educe(Clone)]
103pub struct HsClientConnector<R: Runtime, D: state::MockableConnectorData = connect::Data> {
104    /// The runtime
105    runtime: R,
106    /// A [`HsCircPool`] that we use to build circuits to HsDirs, introduction
107    /// points, and rendezvous points.
108    circpool: Arc<HsCircPool<R>>,
109    /// Information we are remembering about different onion services.
110    services: Arc<Mutex<state::Services<D>>>,
111    /// For mocking in tests of `state.rs`
112    mock_for_state: D::MockGlobalState,
113}
114
115impl<R: Runtime> HsClientConnector<R, connect::Data> {
116    /// Create a new `HsClientConnector`
117    ///
118    /// `housekeeping_prompt` should yield "occasionally",
119    /// perhaps every few hours or maybe daily.
120    ///
121    /// In Arti we arrange for this to happen when we have a new consensus.
122    ///
123    /// Housekeeping events shouldn't arrive while we're dormant,
124    /// since the housekeeping might involve processing that ought to be deferred.
125    // This ^ is why we don't have a separate "launch background tasks" method.
126    // It is fine for this background task to be launched pre-bootstrap, since it willp
127    // do nothing until it gets events.
128    pub fn new(
129        runtime: R,
130        circpool: Arc<HsCircPool<R>>,
131        config: &impl HsClientConnectorConfig,
132        housekeeping_prompt: BoxStream<'static, ()>,
133    ) -> Result<Self, StartupError> {
134        let config = Config {
135            retry: config.as_ref().clone(),
136        };
137        let connector = HsClientConnector {
138            runtime,
139            circpool,
140            services: Arc::new(Mutex::new(Services::new(config))),
141            mock_for_state: (),
142        };
143        connector.spawn_housekeeping_task(housekeeping_prompt)?;
144        Ok(connector)
145    }
146
147    /// Connect to a hidden service
148    ///
149    /// On success, this function will return an open
150    /// rendezvous circuit with an authenticated connection to the onion service
151    /// whose identity is `hs_id`.  If such a circuit already exists, and its isolation
152    /// is compatible with `isolation`, that circuit may be returned; otherwise,
153    /// a new circuit will be created.
154    ///
155    /// Once a circuit is returned, the caller can use it to open new streams to the
156    /// onion service. To do so, call [`ClientOnionServiceDataTunnel::begin_stream`] on it.
157    ///
158    /// Each HS connection request must provide the appropriate
159    /// service discovery keys to use -
160    /// or [`default`](HsClientSecretKeys::default)
161    /// if the hidden service is not running in restricted discovery mode.
162    //
163    // This returns an explicit `impl Future` so that we can write the `Send` bound.
164    // Without this, it is possible for `Services::get_or_launch_connection`
165    // to not return a `Send` future.
166    // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/1034#note_2881718
167    #[instrument(skip_all, level = "trace")]
168    pub fn get_or_launch_tunnel<'r>(
169        &'r self,
170        netdir: &'r Arc<NetDir>,
171        hs_id: HsId,
172        secret_keys: HsClientSecretKeys,
173        isolation: StreamIsolation,
174    ) -> impl Future<Output = Result<Arc<ClientOnionServiceDataTunnel>, ConnError>> + Send + Sync + 'r
175    {
176        // As in tor-circmgr,  we take `StreamIsolation`, to ensure that callers in
177        // arti-client pass us the final overall isolation,
178        // including the per-TorClient isolation.
179        // But internally we need a Box<dyn Isolation> since we need .join().
180        let isolation = Box::new(isolation);
181        Services::get_or_launch_connection(self, netdir, hs_id, isolation, secret_keys)
182    }
183}
184
185impl<R: Runtime, D: MockableConnectorData> HsClientConnector<R, D> {
186    /// Lock the `Services` table and return the guard
187    ///
188    /// Convenience method
189    fn services(&self) -> Result<MutexGuard<Services<D>>, Bug> {
190        self.services
191            .lock()
192            .map_err(|_| internal!("HS connector poisoned"))
193    }
194
195    /// Spawn a task which watches `prompt` and calls [`Services::run_housekeeping`]
196    fn spawn_housekeeping_task(
197        &self,
198        mut prompt: BoxStream<'static, ()>,
199    ) -> Result<(), StartupError> {
200        self.runtime
201            .spawn({
202                let connector = self.clone();
203                let runtime = self.runtime.clone();
204                async move {
205                    while let Some(()) = prompt.next().await {
206                        let Ok(mut services) = connector.services() else {
207                            break;
208                        };
209
210                        // (Currently) this is "expire old data".
211                        services.run_housekeeping(runtime.now());
212                    }
213                    debug!("HS connector housekeeping task exiting (EOF on prompt stream)");
214                }
215            })
216            .map_err(|cause| StartupError::Spawn {
217                spawning: "housekeeping task",
218                cause: cause.into(),
219            })
220    }
221}
222
223/// Return a list of the protocols [supported](tor_protover::doc_supported) by this crate,
224/// running as a hidden service client.
225pub fn supported_hsclient_protocols() -> tor_protover::Protocols {
226    use tor_protover::named::*;
227    // WARNING: REMOVING ELEMENTS FROM THIS LIST CAN BE DANGEROUS!
228    // SEE [`tor_protover::doc_changing`]
229    [
230        HSINTRO_V3,
231        // Technically, there is nothing for a client to do to support HSINTRO_RATELIM.
232        // See torspec#319
233        HSINTRO_RATELIM,
234        HSREND_V3,
235        HSDIR_V3,
236    ]
237    .into_iter()
238    .collect()
239}
240
241#[cfg(test)]
242mod test {
243    // @@ begin test lint list maintained by maint/add_warning @@
244    #![allow(clippy::bool_assert_comparison)]
245    #![allow(clippy::clone_on_copy)]
246    #![allow(clippy::dbg_macro)]
247    #![allow(clippy::mixed_attributes_style)]
248    #![allow(clippy::print_stderr)]
249    #![allow(clippy::print_stdout)]
250    #![allow(clippy::single_char_pattern)]
251    #![allow(clippy::unwrap_used)]
252    #![allow(clippy::unchecked_time_subtraction)]
253    #![allow(clippy::useless_vec)]
254    #![allow(clippy::needless_pass_by_value)]
255    #![allow(clippy::string_slice)] // See arti#2571
256    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
257
258    use super::*;
259
260    #[test]
261    fn protocols() {
262        let pr = supported_hsclient_protocols();
263        let expected = "HSIntro=4-5 HSRend=2 HSDir=2".parse().unwrap();
264        assert_eq!(pr, expected);
265    }
266}