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
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
#![allow(clippy::redundant_field_names)] // TODO beta clippy bug, rust-clippy/issues/17525
53

            
54
mod caps;
55
mod connect;
56
mod err;
57
mod isol_map;
58
mod keys;
59
mod pow;
60
mod proto_oneshot;
61
mod relay_info;
62
mod state;
63

            
64
use std::future::Future;
65
use std::sync::{Arc, Mutex, MutexGuard};
66

            
67
use futures::StreamExt as _;
68
use futures::stream::BoxStream;
69
use tor_rtcompat::SpawnExt as _;
70

            
71
use educe::Educe;
72
use tracing::{debug, instrument};
73

            
74
use tor_circmgr::ClientOnionServiceDataTunnel;
75
use tor_circmgr::hspool::HsCircPool;
76
use tor_circmgr::isolation::StreamIsolation;
77
use tor_error::{Bug, internal};
78
use tor_hscrypto::pk::HsId;
79
use tor_netdir::NetDir;
80
use tor_rtcompat::Runtime;
81

            
82
pub use err::FailedAttemptError;
83
pub use err::{ConnError, DescriptorError, DescriptorErrorDetail, StartupError};
84
pub use keys::{HsClientDescEncKeypairSpecifier, HsClientSecretKeys, HsClientSecretKeysBuilder};
85
pub use relay_info::InvalidTarget;
86
pub use state::HsClientConnectorConfig;
87

            
88
use err::{IntroPtIndex, rend_pt_identity_for_error};
89
use state::{Config, MockableConnectorData, Services};
90

            
91
/// An object that negotiates connections with onion services
92
///
93
/// This can be used by multiple requests on behalf of different clients,
94
/// with potentially different HS service discovery keys (`KS_hsc_*`)
95
/// and potentially different circuit isolation.
96
///
97
/// The principal entrypoint is
98
/// [`get_or_launch_tunnel()`](HsClientConnector::get_or_launch_tunnel).
99
///
100
/// This object is handle-like: it is fairly cheap to clone,
101
///  and contains `Arc`s internally.
102
#[derive(Educe)]
103
#[educe(Clone)]
104
pub struct HsClientConnector<R: Runtime, D: state::MockableConnectorData = connect::Data> {
105
    /// The runtime
106
    runtime: R,
107
    /// A [`HsCircPool`] that we use to build circuits to HsDirs, introduction
108
    /// points, and rendezvous points.
109
    circpool: Arc<HsCircPool<R>>,
110
    /// Information we are remembering about different onion services.
111
    services: Arc<Mutex<state::Services<D>>>,
112
    /// For mocking in tests of `state.rs`
113
    mock_for_state: D::MockGlobalState,
114
}
115

            
116
impl<R: Runtime> HsClientConnector<R, connect::Data> {
117
    /// Create a new `HsClientConnector`
118
    ///
119
    /// `housekeeping_prompt` should yield "occasionally",
120
    /// perhaps every few hours or maybe daily.
121
    ///
122
    /// In Arti we arrange for this to happen when we have a new consensus.
123
    ///
124
    /// Housekeeping events shouldn't arrive while we're dormant,
125
    /// since the housekeeping might involve processing that ought to be deferred.
126
    // This ^ is why we don't have a separate "launch background tasks" method.
127
    // It is fine for this background task to be launched pre-bootstrap, since it willp
128
    // do nothing until it gets events.
129
    pub fn new(
130
        runtime: R,
131
        circpool: Arc<HsCircPool<R>>,
132
        config: &impl HsClientConnectorConfig,
133
        housekeeping_prompt: BoxStream<'static, ()>,
134
    ) -> Result<Self, StartupError> {
135
        let config = Config {
136
            retry: config.as_ref().clone(),
137
        };
138
        let connector = HsClientConnector {
139
            runtime,
140
            circpool,
141
            services: Arc::new(Mutex::new(Services::new(config))),
142
            mock_for_state: (),
143
        };
144
        connector.spawn_housekeeping_task(housekeeping_prompt)?;
145
        Ok(connector)
146
    }
147

            
148
    /// Connect to a hidden service
149
    ///
150
    /// On success, this function will return an open
151
    /// rendezvous circuit with an authenticated connection to the onion service
152
    /// whose identity is `hs_id`.  If such a circuit already exists, and its isolation
153
    /// is compatible with `isolation`, that circuit may be returned; otherwise,
154
    /// a new circuit will be created.
155
    ///
156
    /// Once a circuit is returned, the caller can use it to open new streams to the
157
    /// onion service. To do so, call [`ClientOnionServiceDataTunnel::begin_stream`] on it.
158
    ///
159
    /// Each HS connection request must provide the appropriate
160
    /// service discovery keys to use -
161
    /// or [`default`](HsClientSecretKeys::default)
162
    /// if the hidden service is not running in restricted discovery mode.
163
    //
164
    // This returns an explicit `impl Future` so that we can write the `Send` bound.
165
    // Without this, it is possible for `Services::get_or_launch_connection`
166
    // to not return a `Send` future.
167
    // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/1034#note_2881718
168
    #[instrument(skip_all, level = "trace")]
169
    pub fn get_or_launch_tunnel<'r>(
170
        &'r self,
171
        netdir: &'r Arc<NetDir>,
172
        hs_id: HsId,
173
        secret_keys: HsClientSecretKeys,
174
        isolation: StreamIsolation,
175
    ) -> impl Future<Output = Result<Arc<ClientOnionServiceDataTunnel>, ConnError>> + Send + Sync + 'r
176
    {
177
        // As in tor-circmgr,  we take `StreamIsolation`, to ensure that callers in
178
        // arti-client pass us the final overall isolation,
179
        // including the per-TorClient isolation.
180
        // But internally we need a Box<dyn Isolation> since we need .join().
181
        let isolation = Box::new(isolation);
182
        Services::get_or_launch_connection(self, netdir, hs_id, isolation, secret_keys)
183
    }
184
}
185

            
186
impl<R: Runtime, D: MockableConnectorData> HsClientConnector<R, D> {
187
    /// Lock the `Services` table and return the guard
188
    ///
189
    /// Convenience method
190
65
    fn services(&self) -> Result<MutexGuard<Services<D>>, Bug> {
191
65
        self.services
192
65
            .lock()
193
65
            .map_err(|_| internal!("HS connector poisoned"))
194
65
    }
195

            
196
    /// Spawn a task which watches `prompt` and calls [`Services::run_housekeeping`]
197
    fn spawn_housekeeping_task(
198
        &self,
199
        mut prompt: BoxStream<'static, ()>,
200
    ) -> Result<(), StartupError> {
201
        self.runtime
202
            .spawn({
203
                let connector = self.clone();
204
                let runtime = self.runtime.clone();
205
                async move {
206
                    while let Some(()) = prompt.next().await {
207
                        let Ok(mut services) = connector.services() else {
208
                            break;
209
                        };
210

            
211
                        // (Currently) this is "expire old data".
212
                        services.run_housekeeping(runtime.now());
213
                    }
214
                    debug!("HS connector housekeeping task exiting (EOF on prompt stream)");
215
                }
216
            })
217
            .map_err(|cause| StartupError::Spawn {
218
                spawning: "housekeeping task",
219
                cause: cause.into(),
220
            })
221
    }
222
}
223

            
224
/// Return a list of the protocols [supported](tor_protover::doc_supported) by this crate,
225
/// running as a hidden service client.
226
35
pub fn supported_hsclient_protocols() -> tor_protover::Protocols {
227
    use tor_protover::named::*;
228
    // WARNING: REMOVING ELEMENTS FROM THIS LIST CAN BE DANGEROUS!
229
    // SEE [`tor_protover::doc_changing`]
230
35
    [
231
35
        HSINTRO_V3,
232
35
        // Technically, there is nothing for a client to do to support HSINTRO_RATELIM.
233
35
        // See torspec#319
234
35
        HSINTRO_RATELIM,
235
35
        HSREND_V3,
236
35
        HSDIR_V3,
237
35
    ]
238
35
    .into_iter()
239
35
    .collect()
240
35
}
241

            
242
#[cfg(test)]
243
mod test {
244
    // @@ begin test lint list maintained by maint/add_warning @@
245
    #![allow(clippy::bool_assert_comparison)]
246
    #![allow(clippy::clone_on_copy)]
247
    #![allow(clippy::dbg_macro)]
248
    #![allow(clippy::mixed_attributes_style)]
249
    #![allow(clippy::print_stderr)]
250
    #![allow(clippy::print_stdout)]
251
    #![allow(clippy::single_char_pattern)]
252
    #![allow(clippy::unwrap_used)]
253
    #![allow(clippy::unchecked_time_subtraction)]
254
    #![allow(clippy::useless_vec)]
255
    #![allow(clippy::needless_pass_by_value)]
256
    #![allow(clippy::string_slice)] // See arti#2571
257
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
258

            
259
    use super::*;
260

            
261
    #[test]
262
    fn protocols() {
263
        let pr = supported_hsclient_protocols();
264
        let expected = "HSIntro=4-5 HSRend=2 HSDir=2".parse().unwrap();
265
        assert_eq!(pr, expected);
266
    }
267
}