1#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![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)] #![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] mod connect;
48mod err;
49mod isol_map;
50mod keys;
51mod pow;
52mod proto_oneshot;
53mod relay_info;
54mod state;
55
56use std::future::Future;
57use std::sync::{Arc, Mutex, MutexGuard};
58
59use futures::stream::BoxStream;
60use futures::task::SpawnExt as _;
61use futures::StreamExt as _;
62
63use educe::Educe;
64use tracing::debug;
65
66use tor_circmgr::hspool::HsCircPool;
67use tor_circmgr::isolation::StreamIsolation;
68use tor_error::{internal, Bug};
69use tor_hscrypto::pk::HsId;
70use tor_netdir::NetDir;
71use tor_proto::circuit::ClientCirc;
72use tor_rtcompat::Runtime;
73
74pub use err::FailedAttemptError;
75pub use err::{ConnError, DescriptorError, DescriptorErrorDetail, StartupError};
76pub use keys::{HsClientDescEncKeypairSpecifier, HsClientSecretKeys, HsClientSecretKeysBuilder};
77pub use relay_info::InvalidTarget;
78pub use state::HsClientConnectorConfig;
79
80use err::{rend_pt_identity_for_error, IntroPtIndex, RendPtIdentityForError};
81use state::{Config, MockableConnectorData, Services};
82
83#[derive(Educe)]
95#[educe(Clone)]
96pub struct HsClientConnector<R: Runtime, D: state::MockableConnectorData = connect::Data> {
97 runtime: R,
99 circpool: Arc<HsCircPool<R>>,
102 services: Arc<Mutex<state::Services<D>>>,
104 mock_for_state: D::MockGlobalState,
106}
107
108impl<R: Runtime> HsClientConnector<R, connect::Data> {
109 pub fn new(
122 runtime: R,
123 circpool: Arc<HsCircPool<R>>,
124 config: &impl HsClientConnectorConfig,
125 housekeeping_prompt: BoxStream<'static, ()>,
126 ) -> Result<Self, StartupError> {
127 let config = Config {
128 retry: config.as_ref().clone(),
129 };
130 let connector = HsClientConnector {
131 runtime,
132 circpool,
133 services: Arc::new(Mutex::new(Services::new(config))),
134 mock_for_state: (),
135 };
136 connector.spawn_housekeeping_task(housekeeping_prompt)?;
137 Ok(connector)
138 }
139
140 pub fn get_or_launch_circuit<'r>(
161 &'r self,
162 netdir: &'r Arc<NetDir>,
163 hs_id: HsId,
164 secret_keys: HsClientSecretKeys,
165 isolation: StreamIsolation,
166 ) -> impl Future<Output = Result<Arc<ClientCirc>, ConnError>> + Send + Sync + 'r {
167 let isolation = Box::new(isolation);
172 Services::get_or_launch_connection(self, netdir, hs_id, isolation, secret_keys)
173 }
174
175 #[deprecated(since = "0.5.1", note = "Use get_or_launch_circuit instead.")]
180 pub fn get_or_launch_connection<'r>(
181 &'r self,
182 netdir: &'r Arc<NetDir>,
183 hs_id: HsId,
184 secret_keys: HsClientSecretKeys,
185 isolation: StreamIsolation,
186 ) -> impl Future<Output = Result<Arc<ClientCirc>, ConnError>> + Send + Sync + 'r {
187 self.get_or_launch_circuit(netdir, hs_id, secret_keys, isolation)
188 }
189}
190
191impl<R: Runtime, D: MockableConnectorData> HsClientConnector<R, D> {
192 fn services(&self) -> Result<MutexGuard<Services<D>>, Bug> {
196 self.services
197 .lock()
198 .map_err(|_| internal!("HS connector poisoned"))
199 }
200
201 fn spawn_housekeeping_task(
203 &self,
204 mut prompt: BoxStream<'static, ()>,
205 ) -> Result<(), StartupError> {
206 self.runtime
207 .spawn({
208 let connector = self.clone();
209 let runtime = self.runtime.clone();
210 async move {
211 while let Some(()) = prompt.next().await {
212 let Ok(mut services) = connector.services() else {
213 break;
214 };
215
216 services.run_housekeeping(runtime.now());
218 }
219 debug!("HS connector housekeeping task exiting (EOF on prompt stream)");
220 }
221 })
222 .map_err(|cause| StartupError::Spawn {
223 spawning: "housekeeping task",
224 cause: cause.into(),
225 })
226 }
227}
228
229pub fn supported_hsclient_protocols() -> tor_protover::Protocols {
232 use tor_protover::named::*;
233 [
236 HSINTRO_V3,
237 HSINTRO_RATELIM,
240 HSREND_V3,
241 HSDIR_V3,
242 ]
243 .into_iter()
244 .collect()
245}
246
247#[cfg(test)]
248mod test {
249 #![allow(clippy::bool_assert_comparison)]
251 #![allow(clippy::clone_on_copy)]
252 #![allow(clippy::dbg_macro)]
253 #![allow(clippy::mixed_attributes_style)]
254 #![allow(clippy::print_stderr)]
255 #![allow(clippy::print_stdout)]
256 #![allow(clippy::single_char_pattern)]
257 #![allow(clippy::unwrap_used)]
258 #![allow(clippy::unchecked_duration_subtraction)]
259 #![allow(clippy::useless_vec)]
260 #![allow(clippy::needless_pass_by_value)]
261 use super::*;
264
265 #[test]
266 fn protocols() {
267 let pr = supported_hsclient_protocols();
268 let expected = "HSIntro=4-5 HSRend=2 HSDir=2".parse().unwrap();
269 assert_eq!(pr, expected);
270 }
271}