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