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(bound(false)))]
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
    #[allow(unused)]
114
    mock_for_state: D::MockGlobalState,
115
}
116

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

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

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

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

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

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

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

            
260
    use super::*;
261

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