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