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

            
50
mod caps;
51
mod connect;
52
mod err;
53
mod isol_map;
54
mod keys;
55
mod pow;
56
mod proto_oneshot;
57
mod relay_info;
58
mod state;
59

            
60
use std::future::Future;
61
use std::sync::{Arc, Mutex, MutexGuard};
62

            
63
use futures::StreamExt as _;
64
use futures::stream::BoxStream;
65
use tor_rtcompat::SpawnExt as _;
66

            
67
use educe::Educe;
68
use tracing::{debug, instrument};
69

            
70
use tor_circmgr::ClientOnionServiceDataTunnel;
71
use tor_circmgr::hspool::HsCircPool;
72
use tor_circmgr::isolation::StreamIsolation;
73
use tor_error::{Bug, internal};
74
use tor_hscrypto::pk::HsId;
75
use tor_netdir::NetDir;
76
use tor_rtcompat::Runtime;
77

            
78
pub use err::FailedAttemptError;
79
pub use err::{ConnError, DescriptorError, DescriptorErrorDetail, StartupError};
80
pub use keys::{HsClientDescEncKeypairSpecifier, HsClientSecretKeys, HsClientSecretKeysBuilder};
81
pub use relay_info::InvalidTarget;
82
pub use state::HsClientConnectorConfig;
83

            
84
use err::{IntroPtIndex, rend_pt_identity_for_error};
85
use state::{Config, MockableConnectorData, Services};
86

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

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

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

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

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

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

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

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

            
255
    use super::*;
256

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