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
#![cfg_attr(not(ci_arti_stable), allow(renamed_and_removed_lints))]
5
#![cfg_attr(not(ci_arti_nightly), allow(unknown_lints))]
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::unnecessary_wraps)]
34
#![warn(clippy::unseparated_literal_suffix)]
35
#![deny(clippy::unwrap_used)]
36
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
37
#![allow(clippy::uninlined_format_args)]
38
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
39
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
40
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
41
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
42

            
43
mod connect;
44
mod err;
45
mod isol_map;
46
mod keys;
47
mod proto_oneshot;
48
mod relay_info;
49
mod state;
50

            
51
use std::future::Future;
52
use std::sync::{Arc, Mutex, MutexGuard};
53

            
54
use futures::stream::BoxStream;
55
use futures::task::SpawnExt as _;
56
use futures::StreamExt as _;
57

            
58
use educe::Educe;
59
use tracing::debug;
60

            
61
use tor_circmgr::hspool::HsCircPool;
62
use tor_circmgr::isolation::StreamIsolation;
63
use tor_error::{internal, Bug};
64
use tor_hscrypto::pk::HsId;
65
use tor_netdir::NetDir;
66
use tor_proto::circuit::ClientCirc;
67
use tor_rtcompat::Runtime;
68

            
69
pub use err::FailedAttemptError;
70
pub use err::{ConnError, DescriptorError, DescriptorErrorDetail, StartupError};
71
pub use keys::{HsClientDescEncKeypairSpecifier, HsClientSecretKeys, HsClientSecretKeysBuilder};
72
pub use relay_info::InvalidTarget;
73
pub use state::HsClientConnectorConfig;
74

            
75
use err::{rend_pt_identity_for_error, IntroPtIndex, RendPtIdentityForError};
76
use state::{Config, MockableConnectorData, Services};
77

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

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

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

            
169
    /// A deprecated alias for `get_or_launch_circuit`.
170
    ///
171
    /// We renamed it to be
172
    /// more clear about what exactly it is launching.
173
    #[deprecated(since = "0.5.1", note = "Use get_or_launch_circuit instead.")]
174
    pub fn get_or_launch_connection<'r>(
175
        &'r self,
176
        netdir: &'r Arc<NetDir>,
177
        hs_id: HsId,
178
        secret_keys: HsClientSecretKeys,
179
        isolation: StreamIsolation,
180
    ) -> impl Future<Output = Result<Arc<ClientCirc>, ConnError>> + Send + Sync + 'r {
181
        self.get_or_launch_circuit(netdir, hs_id, secret_keys, isolation)
182
    }
183
}
184

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

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

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