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