1
#![cfg_attr(docsrs, feature(doc_auto_cfg, 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_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)] // 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
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
46

            
47
mod connect;
48
mod err;
49
mod isol_map;
50
mod keys;
51
mod pow;
52
mod proto_oneshot;
53
mod relay_info;
54
mod state;
55

            
56
use std::future::Future;
57
use std::sync::{Arc, Mutex, MutexGuard};
58

            
59
use futures::StreamExt as _;
60
use futures::stream::BoxStream;
61
use futures::task::SpawnExt as _;
62

            
63
use educe::Educe;
64
use tracing::debug;
65

            
66
use tor_circmgr::ClientOnionServiceDataTunnel;
67
use tor_circmgr::hspool::HsCircPool;
68
use tor_circmgr::isolation::StreamIsolation;
69
use tor_error::{Bug, internal};
70
use tor_hscrypto::pk::HsId;
71
use tor_netdir::NetDir;
72
use tor_rtcompat::Runtime;
73

            
74
pub use err::FailedAttemptError;
75
pub use err::{ConnError, DescriptorError, DescriptorErrorDetail, StartupError};
76
pub use keys::{HsClientDescEncKeypairSpecifier, HsClientSecretKeys, HsClientSecretKeysBuilder};
77
pub use relay_info::InvalidTarget;
78
pub use state::HsClientConnectorConfig;
79

            
80
use err::{IntroPtIndex, RendPtIdentityForError, rend_pt_identity_for_error};
81
use state::{Config, MockableConnectorData, Services};
82

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

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

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

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

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

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

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

            
233
#[cfg(test)]
234
mod test {
235
    // @@ begin test lint list maintained by maint/add_warning @@
236
    #![allow(clippy::bool_assert_comparison)]
237
    #![allow(clippy::clone_on_copy)]
238
    #![allow(clippy::dbg_macro)]
239
    #![allow(clippy::mixed_attributes_style)]
240
    #![allow(clippy::print_stderr)]
241
    #![allow(clippy::print_stdout)]
242
    #![allow(clippy::single_char_pattern)]
243
    #![allow(clippy::unwrap_used)]
244
    #![allow(clippy::unchecked_duration_subtraction)]
245
    #![allow(clippy::useless_vec)]
246
    #![allow(clippy::needless_pass_by_value)]
247
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
248

            
249
    use super::*;
250

            
251
    #[test]
252
    fn protocols() {
253
        let pr = supported_hsclient_protocols();
254
        let expected = "HSIntro=4-5 HSRend=2 HSDir=2".parse().unwrap();
255
        assert_eq!(pr, expected);
256
    }
257
}