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