tor_hsclient/
lib.rs

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