1
//! A general interface for Tor client usage.
2
//!
3
//! To construct a client, run the [`TorClient::create_bootstrapped`] method.
4
//! Once the client is bootstrapped, you can make anonymous
5
//! connections ("streams") over the Tor network using
6
//! [`TorClient::connect`].
7

            
8
#[cfg(feature = "rpc")]
9
use {derive_deftly::Deftly, tor_rpcbase::templates::*};
10

            
11
use crate::address::{IntoTorAddr, ResolveInstructions, StreamInstructions};
12

            
13
use crate::config::{
14
    ClientAddrConfig, SoftwareStatusOverrideConfig, StreamTimeoutConfig, TorClientConfig,
15
};
16
use safelog::{Sensitive, sensitive};
17
use tor_async_utils::{DropNotifyWatchSender, PostageWatchSenderExt};
18
use tor_chanmgr::ChanMgrConfig;
19
use tor_circmgr::ClientDataTunnel;
20
use tor_circmgr::isolation::{Isolation, StreamIsolation};
21
use tor_circmgr::{IsolationToken, TargetPort, isolation::StreamIsolationBuilder};
22
use tor_config::MutCfg;
23
#[cfg(feature = "bridge-client")]
24
use tor_dirmgr::bridgedesc::BridgeDescMgr;
25
use tor_dirmgr::{DirMgrStore, Timeliness};
26
use tor_error::{Bug, error_report, internal};
27
use tor_guardmgr::{GuardMgr, RetireCircuits};
28
use tor_keymgr::Keystore;
29
use tor_memquota::MemoryQuotaTracker;
30
use tor_netdir::{NetDirProvider, params::NetParameters};
31
use tor_persist::StateMgr;
32
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
33
use tor_persist::TestingStateMgr;
34
#[cfg(feature = "onion-service-service")]
35
use tor_persist::state_dir::StateDirectory;
36
use tor_proto::client::stream::{DataStream, IpVersionPreference, StreamParameters};
37
#[cfg(all(
38
    any(feature = "native-tls", feature = "rustls"),
39
    any(feature = "async-std", feature = "tokio"),
40
))]
41
use tor_rtcompat::PreferredRuntime;
42
use tor_rtcompat::{Runtime, SleepProviderExt};
43
#[cfg(feature = "onion-service-client")]
44
use {
45
    tor_config::BoolOrAuto,
46
    tor_hsclient::{HsClientConnector, HsClientDescEncKeypairSpecifier, HsClientSecretKeysBuilder},
47
    tor_hscrypto::pk::{HsClientDescEncKey, HsClientDescEncKeypair, HsClientDescEncSecretKey},
48
    tor_netdir::DirEvent,
49
};
50

            
51
#[cfg(all(feature = "onion-service-service", feature = "experimental-api"))]
52
use tor_hsservice::HsIdKeypairSpecifier;
53
#[cfg(all(feature = "onion-service-client", feature = "experimental-api"))]
54
use {tor_hscrypto::pk::HsId, tor_hscrypto::pk::HsIdKeypair, tor_keymgr::KeystoreSelector};
55

            
56
use tor_keymgr::{ArtiNativeKeystore, KeyMgr, KeyMgrBuilder, config::ArtiKeystoreKind};
57

            
58
#[cfg(feature = "ephemeral-keystore")]
59
use tor_keymgr::ArtiEphemeralKeystore;
60

            
61
#[cfg(feature = "ctor-keystore")]
62
use tor_keymgr::{CTorClientKeystore, CTorServiceKeystore};
63

            
64
use futures::StreamExt as _;
65
use futures::lock::Mutex as AsyncMutex;
66
use std::net::IpAddr;
67
use std::result::Result as StdResult;
68
use std::sync::{Arc, Mutex};
69
use tor_rtcompat::SpawnExt;
70

            
71
use crate::err::ErrorDetail;
72
use crate::{TorClientBuilder, status, util};
73
#[cfg(feature = "geoip")]
74
use tor_geoip::CountryCode;
75
use tor_rtcompat::scheduler::TaskHandle;
76
use tracing::{debug, info, instrument};
77

            
78
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
79
use tor_persist::FsStateMgr as UsingStateMgr;
80

            
81
// TODO wasm: This is not the right choice, but at least it compiles.
82
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
83
use tor_persist::TestingStateMgr as UsingStateMgr;
84

            
85
/// An active client session on the Tor network.
86
///
87
/// While it's running, it will fetch directory information, build
88
/// circuits, and make connections for you.
89
///
90
/// Cloning this object makes a new reference to the same underlying
91
/// handles: it's usually better to clone the `TorClient` than it is to
92
/// create a new one.
93
///
94
/// # In the Arti RPC System
95
///
96
/// An open client on the Tor network.
97
///
98
/// A `TorClient` can be used to open anonymous connections,
99
/// and (eventually) perform other activities.
100
///
101
/// You can use an `RpcSession` as a `TorClient`, or use the `isolated_client` method
102
/// to create a new `TorClient` whose stream will not share circuits with any other Tor client.
103
///
104
/// This ObjectID for this object can be used as the target of a SOCKS stream.
105
// TODO(nickm): This type now has 5 Arcs inside it, and 2 types that have
106
// implicit Arcs inside them! maybe it's time to replace much of the insides of
107
// this with an Arc<TorClientInner>?
108
#[derive(Clone)]
109
#[cfg_attr(
110
    feature = "rpc",
111
    derive(Deftly),
112
    derive_deftly(Object),
113
    deftly(rpc(expose_outside_of_session))
114
)]
115
pub struct TorClient<R: Runtime> {
116
    /// Asynchronous runtime object.
117
    runtime: R,
118
    /// Default isolation token for streams through this client.
119
    ///
120
    /// This is eventually used for `owner_token` in `tor-circmgr/src/usage.rs`, and is orthogonal
121
    /// to the `stream_isolation` which comes from `connect_prefs` (or a passed-in `StreamPrefs`).
122
    /// (ie, both must be the same to share a circuit).
123
    client_isolation: IsolationToken,
124
    /// Connection preferences.  Starts out as `Default`,  Inherited by our clones.
125
    connect_prefs: StreamPrefs,
126
    /// Memory quota tracker
127
    memquota: Arc<MemoryQuotaTracker>,
128
    /// Channel manager, used by circuits etc.,
129
    ///
130
    /// Used directly by client only for reconfiguration.
131
    chanmgr: Arc<tor_chanmgr::ChanMgr<R>>,
132
    /// Circuit manager for keeping our circuits up to date and building
133
    /// them on-demand.
134
    circmgr: Arc<tor_circmgr::CircMgr<R>>,
135
    /// Directory manager persistent storage.
136
    #[cfg_attr(not(feature = "bridge-client"), allow(dead_code))]
137
    dirmgr_store: DirMgrStore<R>,
138
    /// Directory manager for keeping our directory material up to date.
139
    dirmgr: Arc<dyn tor_dirmgr::DirProvider>,
140
    /// Bridge descriptor manager
141
    ///
142
    /// None until we have bootstrapped.
143
    ///
144
    /// Lock hierarchy: don't acquire this before dormant
145
    //
146
    // TODO: after or as part of https://gitlab.torproject.org/tpo/core/arti/-/issues/634
147
    // this can be   bridge_desc_mgr: BridgeDescMgr<R>>
148
    // since BridgeDescMgr is Clone and all its methods take `&self` (it has a lock inside)
149
    // Or maybe BridgeDescMgr should not be Clone, since we want to make Weaks of it,
150
    // which we can't do when the Arc is inside.
151
    #[cfg(feature = "bridge-client")]
152
    bridge_desc_mgr: Arc<Mutex<Option<Arc<BridgeDescMgr<R>>>>>,
153
    /// Pluggable transport manager.
154
    #[cfg(feature = "pt-client")]
155
    pt_mgr: Arc<tor_ptmgr::PtMgr<R>>,
156
    /// HS client connector
157
    #[cfg(feature = "onion-service-client")]
158
    hsclient: HsClientConnector<R>,
159
    /// Circuit pool for providing onion services with circuits.
160
    #[cfg(any(feature = "onion-service-client", feature = "onion-service-service"))]
161
    hs_circ_pool: Arc<tor_circmgr::hspool::HsCircPool<R>>,
162
    /// A handle to this client's [`InertTorClient`].
163
    ///
164
    /// Used for accessing the key manager and other persistent state.
165
    inert_client: InertTorClient,
166
    /// Guard manager
167
    #[cfg_attr(not(feature = "bridge-client"), allow(dead_code))]
168
    guardmgr: GuardMgr<R>,
169
    /// Location on disk where we store persistent data containing both location and Mistrust information.
170
    ///
171
    ///
172
    /// This path is configured via `[storage]` in the config but is not used directly as a
173
    /// StateDirectory in most places. Instead, its path and Mistrust information are copied
174
    /// to subsystems like `dirmgr`, `keymgr`, and `statemgr` during `TorClient` creation.
175
    #[cfg(feature = "onion-service-service")]
176
    state_directory: StateDirectory,
177
    /// Location on disk where we store persistent data (cooked state manager).
178
    statemgr: UsingStateMgr,
179
    /// Client address configuration
180
    addrcfg: Arc<MutCfg<ClientAddrConfig>>,
181
    /// Client DNS configuration
182
    timeoutcfg: Arc<MutCfg<StreamTimeoutConfig>>,
183
    /// Software status configuration.
184
    software_status_cfg: Arc<MutCfg<SoftwareStatusOverrideConfig>>,
185
    /// Mutex used to serialize concurrent attempts to reconfigure a TorClient.
186
    ///
187
    /// See [`TorClient::reconfigure`] for more information on its use.
188
    reconfigure_lock: Arc<Mutex<()>>,
189

            
190
    /// A stream of bootstrap messages that we can clone when a client asks for
191
    /// it.
192
    ///
193
    /// (We don't need to observe this stream ourselves, since it drops each
194
    /// unobserved status change when the next status change occurs.)
195
    status_receiver: status::BootstrapEvents,
196

            
197
    /// mutex used to prevent two tasks from trying to bootstrap at once.
198
    bootstrap_in_progress: Arc<AsyncMutex<()>>,
199

            
200
    /// Whether or not we should call `bootstrap` before doing things that require
201
    /// bootstrapping. If this is `false`, we will just call `wait_for_bootstrap`
202
    /// instead.
203
    should_bootstrap: BootstrapBehavior,
204

            
205
    /// Shared boolean for whether we're currently in "dormant mode" or not.
206
    //
207
    // The sent value is `Option`, so that `None` is sent when the sender, here,
208
    // is dropped,.  That shuts down the monitoring task.
209
    dormant: Arc<Mutex<DropNotifyWatchSender<Option<DormantMode>>>>,
210

            
211
    /// The path resolver given to us by a [`TorClientConfig`].
212
    ///
213
    /// We must not add our own variables to it since `TorClientConfig` uses it to perform its own
214
    /// path expansions. If we added our own variables, it would introduce an inconsistency where
215
    /// paths expanded by the `TorClientConfig` would expand differently than when expanded by us.
216
    // This is an Arc so that we can make cheap clones of it.
217
    path_resolver: Arc<tor_config_path::CfgPathResolver>,
218
}
219

            
220
/// A Tor client that is not runnable.
221
///
222
/// Can be used to access the state that would be used by a running [`TorClient`].
223
///
224
/// An `InertTorClient` never connects to the network.
225
#[derive(Clone)]
226
pub struct InertTorClient {
227
    /// The key manager.
228
    ///
229
    /// This is used for retrieving private keys, certificates, and other sensitive data (for
230
    /// example, for retrieving the keys necessary for connecting to hidden services that are
231
    /// running in restricted discovery mode).
232
    ///
233
    /// If this crate is compiled _with_ the `keymgr` feature, [`TorClient`] will use a functional
234
    /// key manager implementation.
235
    ///
236
    /// If this crate is compiled _without_ the `keymgr` feature, then [`TorClient`] will use a
237
    /// no-op key manager implementation instead.
238
    ///
239
    /// See the [`KeyMgr`] documentation for more details.
240
    keymgr: Option<Arc<KeyMgr>>,
241
}
242

            
243
impl InertTorClient {
244
    /// Create an `InertTorClient` from a `TorClientConfig`.
245
1746
    pub(crate) fn new(config: &TorClientConfig) -> StdResult<Self, ErrorDetail> {
246
1746
        let keymgr = Self::create_keymgr(config)?;
247

            
248
1746
        Ok(Self { keymgr })
249
1746
    }
250

            
251
    /// Create a [`KeyMgr`] using the specified configuration.
252
    ///
253
    /// Returns `Ok(None)` if keystore use is disabled.
254
1746
    fn create_keymgr(config: &TorClientConfig) -> StdResult<Option<Arc<KeyMgr>>, ErrorDetail> {
255
1746
        let keystore = config.storage.keystore();
256
1746
        let permissions = config.storage.permissions();
257
1746
        let primary_store: Box<dyn Keystore> = match keystore.primary_kind() {
258
            Some(ArtiKeystoreKind::Native) => {
259
1746
                let (state_dir, _mistrust) = config.state_dir()?;
260
1746
                let key_store_dir = state_dir.join("keystore");
261

            
262
1746
                let native_store =
263
1746
                    ArtiNativeKeystore::from_path_and_mistrust(&key_store_dir, permissions)?;
264
                // Should only log fs paths at debug level or lower,
265
                // unless they're part of a diagnostic message.
266
1746
                debug!("Using keystore from {key_store_dir:?}");
267

            
268
1746
                Box::new(native_store)
269
            }
270
            #[cfg(feature = "ephemeral-keystore")]
271
            Some(ArtiKeystoreKind::Ephemeral) => {
272
                // TODO: make the keystore ID somehow configurable
273
                let ephemeral_store: ArtiEphemeralKeystore =
274
                    ArtiEphemeralKeystore::new("ephemeral".to_string());
275
                Box::new(ephemeral_store)
276
            }
277
            None => {
278
                info!("Running without a keystore");
279
                return Ok(None);
280
            }
281
            ty => return Err(internal!("unrecognized keystore type {ty:?}").into()),
282
        };
283

            
284
1746
        let mut builder = KeyMgrBuilder::default().primary_store(primary_store);
285

            
286
        #[cfg(feature = "ctor-keystore")]
287
1746
        for config in config.storage.keystore().ctor_svc_stores() {
288
476
            let store: Box<dyn Keystore> = Box::new(CTorServiceKeystore::from_path_and_mistrust(
289
476
                config.path(),
290
476
                permissions,
291
476
                config.id().clone(),
292
                // TODO: these nicknames should be cross-checked with configured
293
                // svc nicknames as part of config validation!!!
294
476
                config.nickname().clone(),
295
            )?);
296

            
297
476
            builder.secondary_stores().push(store);
298
        }
299

            
300
        #[cfg(feature = "ctor-keystore")]
301
1746
        for config in config.storage.keystore().ctor_client_stores() {
302
204
            let store: Box<dyn Keystore> = Box::new(CTorClientKeystore::from_path_and_mistrust(
303
204
                config.path(),
304
204
                permissions,
305
204
                config.id().clone(),
306
            )?);
307

            
308
204
            builder.secondary_stores().push(store);
309
        }
310

            
311
1746
        let keymgr = builder
312
1746
            .build()
313
1746
            .map_err(|_| internal!("failed to build keymgr"))?;
314
1746
        Ok(Some(Arc::new(keymgr)))
315
1746
    }
316

            
317
    /// Generate a service discovery keypair for connecting to a hidden service running in
318
    /// "restricted discovery" mode.
319
    ///
320
    /// See [`TorClient::generate_service_discovery_key`].
321
    //
322
    // TODO: decide whether this should use get_or_generate before making it
323
    // non-experimental
324
    #[cfg(all(
325
        feature = "onion-service-client",
326
        feature = "experimental-api",
327
        feature = "keymgr"
328
    ))]
329
    #[cfg_attr(
330
        docsrs,
331
        doc(cfg(all(
332
            feature = "onion-service-client",
333
            feature = "experimental-api",
334
            feature = "keymgr"
335
        )))
336
    )]
337
102
    pub fn generate_service_discovery_key(
338
102
        &self,
339
102
        selector: KeystoreSelector,
340
102
        hsid: HsId,
341
102
    ) -> crate::Result<HsClientDescEncKey> {
342
102
        let mut rng = tor_llcrypto::rng::CautiousRng;
343
102
        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
344
102
        let key = self
345
102
            .keymgr
346
102
            .as_ref()
347
102
            .ok_or(ErrorDetail::KeystoreRequired {
348
102
                action: "generate client service discovery key",
349
102
            })?
350
102
            .generate::<HsClientDescEncKeypair>(
351
102
                &spec, selector, &mut rng, false, /* overwrite */
352
            )?;
353

            
354
102
        Ok(key.public().clone())
355
102
    }
356

            
357
    /// Rotate the service discovery keypair for connecting to a hidden service running in
358
    /// "restricted discovery" mode.
359
    ///
360
    /// See [`TorClient::rotate_service_discovery_key`].
361
    #[cfg(all(
362
        feature = "onion-service-client",
363
        feature = "experimental-api",
364
        feature = "keymgr"
365
    ))]
366
34
    pub fn rotate_service_discovery_key(
367
34
        &self,
368
34
        selector: KeystoreSelector,
369
34
        hsid: HsId,
370
34
    ) -> crate::Result<HsClientDescEncKey> {
371
34
        let mut rng = tor_llcrypto::rng::CautiousRng;
372
34
        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
373
34
        let key = self
374
34
            .keymgr
375
34
            .as_ref()
376
34
            .ok_or(ErrorDetail::KeystoreRequired {
377
34
                action: "rotate client service discovery key",
378
34
            })?
379
34
            .generate::<HsClientDescEncKeypair>(
380
34
                &spec, selector, &mut rng, true, /* overwrite */
381
            )?;
382

            
383
34
        Ok(key.public().clone())
384
34
    }
385

            
386
    /// Insert a service discovery secret key for connecting to a hidden service running in
387
    /// "restricted discovery" mode
388
    ///
389
    /// See [`TorClient::insert_service_discovery_key`].
390
    #[cfg(all(
391
        feature = "onion-service-client",
392
        feature = "experimental-api",
393
        feature = "keymgr"
394
    ))]
395
    #[cfg_attr(
396
        docsrs,
397
        doc(cfg(all(
398
            feature = "onion-service-client",
399
            feature = "experimental-api",
400
            feature = "keymgr"
401
        )))
402
    )]
403
    pub fn insert_service_discovery_key(
404
        &self,
405
        selector: KeystoreSelector,
406
        hsid: HsId,
407
        hs_client_desc_enc_secret_key: HsClientDescEncSecretKey,
408
    ) -> crate::Result<HsClientDescEncKey> {
409
        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
410
        let client_desc_enc_key = HsClientDescEncKey::from(&hs_client_desc_enc_secret_key);
411
        let client_desc_enc_keypair =
412
            HsClientDescEncKeypair::new(client_desc_enc_key.clone(), hs_client_desc_enc_secret_key);
413
        let _key = self
414
            .keymgr
415
            .as_ref()
416
            .ok_or(ErrorDetail::KeystoreRequired {
417
                action: "insert client service discovery key",
418
            })?
419
            .insert::<HsClientDescEncKeypair>(client_desc_enc_keypair, &spec, selector, false)?;
420
        Ok(client_desc_enc_key)
421
    }
422

            
423
    /// Return the service discovery public key for the service with the specified `hsid`.
424
    ///
425
    /// See [`TorClient::get_service_discovery_key`].
426
    #[cfg(all(feature = "onion-service-client", feature = "experimental-api"))]
427
    #[cfg_attr(
428
        docsrs,
429
        doc(cfg(all(feature = "onion-service-client", feature = "experimental-api")))
430
    )]
431
476
    pub fn get_service_discovery_key(
432
476
        &self,
433
476
        hsid: HsId,
434
476
    ) -> crate::Result<Option<HsClientDescEncKey>> {
435
476
        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
436
476
        let key = self
437
476
            .keymgr
438
476
            .as_ref()
439
476
            .ok_or(ErrorDetail::KeystoreRequired {
440
476
                action: "get client service discovery key",
441
476
            })?
442
476
            .get::<HsClientDescEncKeypair>(&spec)?
443
483
            .map(|key| key.public().clone());
444

            
445
476
        Ok(key)
446
476
    }
447

            
448
    /// Removes the service discovery keypair for the service with the specified `hsid`.
449
    ///
450
    /// See [`TorClient::remove_service_discovery_key`].
451
    #[cfg(all(
452
        feature = "onion-service-client",
453
        feature = "experimental-api",
454
        feature = "keymgr"
455
    ))]
456
    #[cfg_attr(
457
        docsrs,
458
        doc(cfg(all(
459
            feature = "onion-service-client",
460
            feature = "experimental-api",
461
            feature = "keymgr"
462
        )))
463
    )]
464
34
    pub fn remove_service_discovery_key(
465
34
        &self,
466
34
        selector: KeystoreSelector,
467
34
        hsid: HsId,
468
34
    ) -> crate::Result<Option<()>> {
469
34
        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
470
34
        let result = self
471
34
            .keymgr
472
34
            .as_ref()
473
34
            .ok_or(ErrorDetail::KeystoreRequired {
474
34
                action: "remove client service discovery key",
475
34
            })?
476
34
            .remove::<HsClientDescEncKeypair>(&spec, selector)?;
477
34
        match result {
478
34
            Some(_) => Ok(Some(())),
479
            None => Ok(None),
480
        }
481
34
    }
482

            
483
    /// Getter for keymgr.
484
    #[cfg(feature = "onion-service-cli-extra")]
485
748
    pub fn keymgr(&self) -> crate::Result<&KeyMgr> {
486
748
        Ok(self.keymgr.as_ref().ok_or(ErrorDetail::KeystoreRequired {
487
748
            action: "get key manager handle",
488
748
        })?)
489
748
    }
490

            
491
    /// Create (but do not launch) a new
492
    /// [`OnionService`](tor_hsservice::OnionService)
493
    /// using the given configuration.
494
    ///
495
    /// See [`TorClient::create_onion_service`].
496
    #[cfg(feature = "onion-service-service")]
497
    #[instrument(skip_all, level = "trace")]
498
272
    pub fn create_onion_service(
499
272
        &self,
500
272
        config: &TorClientConfig,
501
272
        svc_config: tor_hsservice::OnionServiceConfig,
502
272
    ) -> crate::Result<tor_hsservice::OnionService> {
503
272
        let keymgr = self.keymgr.as_ref().ok_or(ErrorDetail::KeystoreRequired {
504
272
            action: "create onion service",
505
272
        })?;
506

            
507
272
        let (state_dir, mistrust) = config.state_dir()?;
508
272
        let state_dir =
509
272
            self::StateDirectory::new(state_dir, mistrust).map_err(ErrorDetail::StateAccess)?;
510

            
511
272
        Ok(tor_hsservice::OnionService::builder()
512
272
            .config(svc_config)
513
272
            .keymgr(keymgr.clone())
514
272
            .state_dir(state_dir)
515
272
            .build()
516
272
            .map_err(ErrorDetail::OnionServiceSetup)?)
517
272
    }
518
}
519

            
520
/// Preferences for whether a [`TorClient`] should bootstrap on its own or not.
521
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
522
#[non_exhaustive]
523
pub enum BootstrapBehavior {
524
    /// Bootstrap the client automatically when requests are made that require the client to be
525
    /// bootstrapped.
526
    #[default]
527
    OnDemand,
528
    /// Make no attempts to automatically bootstrap. [`TorClient::bootstrap`] must be manually
529
    /// invoked in order for the [`TorClient`] to become useful.
530
    ///
531
    /// Attempts to use the client (e.g. by creating connections or resolving hosts over the Tor
532
    /// network) before calling [`bootstrap`](TorClient::bootstrap) will fail, and
533
    /// return an error that has kind [`ErrorKind::BootstrapRequired`](crate::ErrorKind::BootstrapRequired).
534
    Manual,
535
}
536

            
537
/// What level of sleep to put a Tor client into.
538
#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
539
#[non_exhaustive]
540
pub enum DormantMode {
541
    /// The client functions as normal, and background tasks run periodically.
542
    #[default]
543
    Normal,
544
    /// Background tasks are suspended, conserving CPU usage. Attempts to use the client will
545
    /// wake it back up again.
546
    Soft,
547
}
548

            
549
/// Preferences for how to route a stream over the Tor network.
550
#[derive(Debug, Default, Clone)]
551
pub struct StreamPrefs {
552
    /// What kind of IPv6/IPv4 we'd prefer, and how strongly.
553
    ip_ver_pref: IpVersionPreference,
554
    /// How should we isolate connection(s)?
555
    isolation: StreamIsolationPreference,
556
    /// Whether to return the stream optimistically.
557
    optimistic_stream: bool,
558
    // TODO GEOIP Ideally this would be unconditional, with CountryCode maybe being Void
559
    // This probably applies in many other places, so probably:   git grep 'cfg.*geoip'
560
    // and consider each one with a view to making it unconditional.  Background:
561
    //   https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/1537#note_2935256
562
    //   https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/1537#note_2942214
563
    #[cfg(feature = "geoip")]
564
    /// A country to restrict the exit relay's location to.
565
    country_code: Option<CountryCode>,
566
    /// Whether to try to make connections to onion services.
567
    ///
568
    /// `Auto` means to use the client configuration.
569
    #[cfg(feature = "onion-service-client")]
570
    pub(crate) connect_to_onion_services: BoolOrAuto,
571
}
572

            
573
/// Record of how we are isolating connections
574
#[derive(Debug, Default, Clone)]
575
enum StreamIsolationPreference {
576
    /// No additional isolation
577
    #[default]
578
    None,
579
    /// Isolation parameter to use for connections
580
    Explicit(Box<dyn Isolation>),
581
    /// Isolate every connection!
582
    EveryStream,
583
}
584

            
585
impl From<DormantMode> for tor_chanmgr::Dormancy {
586
296
    fn from(dormant: DormantMode) -> tor_chanmgr::Dormancy {
587
296
        match dormant {
588
296
            DormantMode::Normal => tor_chanmgr::Dormancy::Active,
589
            DormantMode::Soft => tor_chanmgr::Dormancy::Dormant,
590
        }
591
296
    }
592
}
593
#[cfg(feature = "bridge-client")]
594
impl From<DormantMode> for tor_dirmgr::bridgedesc::Dormancy {
595
    fn from(dormant: DormantMode) -> tor_dirmgr::bridgedesc::Dormancy {
596
        match dormant {
597
            DormantMode::Normal => tor_dirmgr::bridgedesc::Dormancy::Active,
598
            DormantMode::Soft => tor_dirmgr::bridgedesc::Dormancy::Dormant,
599
        }
600
    }
601
}
602

            
603
impl StreamPrefs {
604
    /// Construct a new StreamPrefs.
605
18
    pub fn new() -> Self {
606
18
        Self::default()
607
18
    }
608

            
609
    /// Indicate that a stream may be made over IPv4 or IPv6, but that
610
    /// we'd prefer IPv6.
611
2
    pub fn ipv6_preferred(&mut self) -> &mut Self {
612
2
        self.ip_ver_pref = IpVersionPreference::Ipv6Preferred;
613
2
        self
614
2
    }
615

            
616
    /// Indicate that a stream may only be made over IPv6.
617
    ///
618
    /// When this option is set, we will only pick exit relays that
619
    /// support IPv6, and we will tell them to only give us IPv6
620
    /// connections.
621
2
    pub fn ipv6_only(&mut self) -> &mut Self {
622
2
        self.ip_ver_pref = IpVersionPreference::Ipv6Only;
623
2
        self
624
2
    }
625

            
626
    /// Indicate that a stream may be made over IPv4 or IPv6, but that
627
    /// we'd prefer IPv4.
628
    ///
629
    /// This is the default.
630
2
    pub fn ipv4_preferred(&mut self) -> &mut Self {
631
2
        self.ip_ver_pref = IpVersionPreference::Ipv4Preferred;
632
2
        self
633
2
    }
634

            
635
    /// Indicate that a stream may only be made over IPv4.
636
    ///
637
    /// When this option is set, we will only pick exit relays that
638
    /// support IPv4, and we will tell them to only give us IPv4
639
    /// connections.
640
2
    pub fn ipv4_only(&mut self) -> &mut Self {
641
2
        self.ip_ver_pref = IpVersionPreference::Ipv4Only;
642
2
        self
643
2
    }
644

            
645
    /// Indicate that a stream should appear to come from the given country.
646
    ///
647
    /// When this option is set, we will only pick exit relays that
648
    /// have an IP address that matches the country in our GeoIP database.
649
    #[cfg(feature = "geoip")]
650
    pub fn exit_country(&mut self, country_code: CountryCode) -> &mut Self {
651
        self.country_code = Some(country_code);
652
        self
653
    }
654

            
655
    /// Indicate that we don't care which country a stream appears to come from.
656
    ///
657
    /// This is available even in the case where GeoIP support is compiled out,
658
    /// to make things easier.
659
    pub fn any_exit_country(&mut self) -> &mut Self {
660
        #[cfg(feature = "geoip")]
661
        {
662
            self.country_code = None;
663
        }
664
        self
665
    }
666

            
667
    /// Indicate that the stream should be opened "optimistically".
668
    ///
669
    /// By default, streams are not "optimistic". When you call
670
    /// [`TorClient::connect()`], it won't give you a stream until the
671
    /// exit node has confirmed that it has successfully opened a
672
    /// connection to your target address.  It's safer to wait in this
673
    /// way, but it is slower: it takes an entire round trip to get
674
    /// your confirmation.
675
    ///
676
    /// If a stream _is_ configured to be "optimistic", on the other
677
    /// hand, then `TorClient::connect()` will return the stream
678
    /// immediately, without waiting for an answer from the exit.  You
679
    /// can start sending data on the stream right away, though of
680
    /// course this data will be lost if the connection is not
681
    /// actually successful.
682
2
    pub fn optimistic(&mut self) -> &mut Self {
683
2
        self.optimistic_stream = true;
684
2
        self
685
2
    }
686

            
687
    /// Return true if this stream has been configured as "optimistic".
688
    ///
689
    /// See [`StreamPrefs::optimistic`] for more info.
690
    pub fn is_optimistic(&self) -> bool {
691
        self.optimistic_stream
692
    }
693

            
694
    /// Indicate whether connection to a hidden service (`.onion` service) should be allowed
695
    ///
696
    /// If `Explicit(false)`, attempts to connect to Onion Services will be forced to fail with
697
    /// an error of kind [`InvalidStreamTarget`](crate::ErrorKind::InvalidStreamTarget).
698
    ///
699
    /// If `Explicit(true)`, Onion Service connections are enabled.
700
    ///
701
    /// If `Auto`, the behaviour depends on the `address_filter.allow_onion_addrs`
702
    /// configuration option, which is in turn enabled by default.
703
    #[cfg(feature = "onion-service-client")]
704
42
    pub fn connect_to_onion_services(
705
42
        &mut self,
706
42
        connect_to_onion_services: BoolOrAuto,
707
42
    ) -> &mut Self {
708
42
        self.connect_to_onion_services = connect_to_onion_services;
709
42
        self
710
42
    }
711
    /// Return a TargetPort to describe what kind of exit policy our
712
    /// target circuit needs to support.
713
4
    fn wrap_target_port(&self, port: u16) -> TargetPort {
714
4
        match self.ip_ver_pref {
715
            IpVersionPreference::Ipv6Only => TargetPort::ipv6(port),
716
4
            _ => TargetPort::ipv4(port),
717
        }
718
4
    }
719

            
720
    /// Return a new StreamParameters based on this configuration.
721
4
    fn stream_parameters(&self) -> StreamParameters {
722
4
        let mut params = StreamParameters::default();
723
4
        params
724
4
            .ip_version(self.ip_ver_pref)
725
4
            .optimistic(self.optimistic_stream);
726
4
        params
727
4
    }
728

            
729
    /// Indicate that connections with these preferences should have their own isolation group
730
    ///
731
    /// This is a convenience method which creates a fresh [`IsolationToken`]
732
    /// and sets it for these preferences.
733
    ///
734
    /// This connection preference is orthogonal to isolation established by
735
    /// [`TorClient::isolated_client`].  Connections made with an `isolated_client` (and its
736
    /// clones) will not share circuits with the original client, even if the same
737
    /// `isolation` is specified via the `ConnectionPrefs` in force.
738
2
    pub fn new_isolation_group(&mut self) -> &mut Self {
739
2
        self.isolation = StreamIsolationPreference::Explicit(Box::new(IsolationToken::new()));
740
2
        self
741
2
    }
742

            
743
    /// Indicate which other connections might use the same circuit
744
    /// as this one.
745
    ///
746
    /// By default all connections made on all clones of a `TorClient` may share connections.
747
    /// Connections made with a particular `isolation` may share circuits with each other.
748
    ///
749
    /// This connection preference is orthogonal to isolation established by
750
    /// [`TorClient::isolated_client`].  Connections made with an `isolated_client` (and its
751
    /// clones) will not share circuits with the original client, even if the same
752
    /// `isolation` is specified via the `ConnectionPrefs` in force.
753
2
    pub fn set_isolation<T>(&mut self, isolation: T) -> &mut Self
754
2
    where
755
2
        T: Into<Box<dyn Isolation>>,
756
    {
757
2
        self.isolation = StreamIsolationPreference::Explicit(isolation.into());
758
2
        self
759
2
    }
760

            
761
    /// Indicate that no connection should share a circuit with any other.
762
    ///
763
    /// **Use with care:** This is likely to have poor performance, and imposes a much greater load
764
    /// on the Tor network.  Use this option only to make small numbers of connections each of
765
    /// which needs to be isolated from all other connections.
766
    ///
767
    /// (Don't just use this as a "get more privacy!!" method: the circuits
768
    /// that it put connections on will have no more privacy than any other
769
    /// circuits.  The only benefit is that these circuits will not be shared
770
    /// by multiple streams.)
771
    ///
772
    /// This can be undone by calling `set_isolation` or `new_isolation_group` on these
773
    /// preferences.
774
2
    pub fn isolate_every_stream(&mut self) -> &mut Self {
775
2
        self.isolation = StreamIsolationPreference::EveryStream;
776
2
        self
777
2
    }
778

            
779
    /// Return an [`Isolation`] which separates according to these `StreamPrefs` (only)
780
    ///
781
    /// This describes which connections or operations might use
782
    /// the same circuit(s) as this one.
783
    ///
784
    /// Since this doesn't have access to the `TorClient`,
785
    /// it doesn't separate streams which ought to be separated because of
786
    /// the way their `TorClient`s are isolated.
787
    /// For that, use [`TorClient::isolation`].
788
    fn prefs_isolation(&self) -> Option<Box<dyn Isolation>> {
789
        use StreamIsolationPreference as SIP;
790
        match self.isolation {
791
            SIP::None => None,
792
            SIP::Explicit(ref ig) => Some(ig.clone()),
793
            SIP::EveryStream => Some(Box::new(IsolationToken::new())),
794
        }
795
    }
796

            
797
    // TODO: Add some way to be IPFlexible, and require exit to support both.
798
}
799

            
800
#[cfg(all(
801
    any(feature = "native-tls", feature = "rustls"),
802
    any(feature = "async-std", feature = "tokio")
803
))]
804
impl TorClient<PreferredRuntime> {
805
    /// Bootstrap a connection to the Tor network, using the provided `config`.
806
    ///
807
    /// Returns a client once there is enough directory material to
808
    /// connect safely over the Tor network.
809
    ///
810
    /// Consider using [`TorClient::builder`] for more fine-grained control.
811
    ///
812
    /// # Panics
813
    ///
814
    /// If Tokio is being used (the default), panics if created outside the context of a currently
815
    /// running Tokio runtime. See the documentation for [`PreferredRuntime::current`] for
816
    /// more information.
817
    ///
818
    /// If using `async-std`, either take care to ensure Arti is not compiled with Tokio support,
819
    /// or manually create an `async-std` runtime using [`tor_rtcompat`] and use it with
820
    /// [`TorClient::with_runtime`].
821
    ///
822
    /// # Do not fork
823
    ///
824
    /// The process [**may not fork**](tor_rtcompat#do-not-fork)
825
    /// (except, very carefully, before exec)
826
    /// after calling this function, because it creates a [`PreferredRuntime`].
827
    pub async fn create_bootstrapped(config: TorClientConfig) -> crate::Result<Self> {
828
        let runtime = PreferredRuntime::current()
829
            .expect("TorClient could not get an asynchronous runtime; are you running in the right context?");
830

            
831
        Self::with_runtime(runtime)
832
            .config(config)
833
            .create_bootstrapped()
834
            .await
835
    }
836

            
837
    /// Return a new builder for creating TorClient objects.
838
    ///
839
    /// If you want to make a [`TorClient`] synchronously, this is what you want; call
840
    /// `TorClientBuilder::create_unbootstrapped` on the returned builder.
841
    ///
842
    /// # Panics
843
    ///
844
    /// If Tokio is being used (the default), panics if created outside the context of a currently
845
    /// running Tokio runtime. See the documentation for `tokio::runtime::Handle::current` for
846
    /// more information.
847
    ///
848
    /// If using `async-std`, either take care to ensure Arti is not compiled with Tokio support,
849
    /// or manually create an `async-std` runtime using [`tor_rtcompat`] and use it with
850
    /// [`TorClient::with_runtime`].
851
    ///
852
    /// # Do not fork
853
    ///
854
    /// The process [**may not fork**](tor_rtcompat#do-not-fork)
855
    /// (except, very carefully, before exec)
856
    /// after calling this function, because it creates a [`PreferredRuntime`].
857
    pub fn builder() -> TorClientBuilder<PreferredRuntime> {
858
        let runtime = PreferredRuntime::current()
859
            .expect("TorClient could not get an asynchronous runtime; are you running in the right context?");
860

            
861
        TorClientBuilder::new(runtime)
862
    }
863
}
864

            
865
impl<R: Runtime> TorClient<R> {
866
    /// Return a new builder for creating TorClient objects, with a custom provided [`Runtime`].
867
    ///
868
    /// See the [`tor_rtcompat`] crate for more information on custom runtimes.
869
250
    pub fn with_runtime(runtime: R) -> TorClientBuilder<R> {
870
250
        TorClientBuilder::new(runtime)
871
250
    }
872

            
873
    /// Implementation of `create_unbootstrapped`, split out in order to avoid manually specifying
874
    /// double error conversions.
875
    #[instrument(skip_all, level = "trace")]
876
22
    pub(crate) fn create_inner(
877
22
        runtime: R,
878
22
        config: &TorClientConfig,
879
22
        autobootstrap: BootstrapBehavior,
880
22
        dirmgr_builder: &dyn crate::builder::DirProviderBuilder<R>,
881
22
        dirmgr_extensions: tor_dirmgr::config::DirMgrExtensions,
882
22
    ) -> StdResult<Self, ErrorDetail> {
883
22
        if crate::util::running_as_setuid() {
884
            return Err(tor_error::bad_api_usage!(
885
                "Arti does not support running in a setuid or setgid context."
886
            )
887
            .into());
888
22
        }
889

            
890
22
        let memquota = MemoryQuotaTracker::new(&runtime, config.system.memory.clone())?;
891

            
892
22
        let path_resolver = Arc::new(config.path_resolver.clone());
893

            
894
22
        let (state_dir, mistrust) = config.state_dir()?;
895
        #[cfg(feature = "onion-service-service")]
896
22
        let state_directory =
897
22
            StateDirectory::new(&state_dir, mistrust).map_err(ErrorDetail::StateAccess)?;
898

            
899
22
        let dormant = DormantMode::Normal;
900
22
        let dir_cfg = {
901
22
            let mut c: tor_dirmgr::DirMgrConfig = config.dir_mgr_config()?;
902
22
            c.extensions = dirmgr_extensions;
903
22
            c
904
        };
905

            
906
22
        let statemgr = Self::statemgr_from_config(config)?;
907

            
908
        // Try to take state ownership early, so we'll know if we have it.
909
        // Note that this `try_lock()` may return `Ok` even if we can't acquire the lock.
910
        // (At this point we don't yet care if we have it.)
911
22
        let _ignore_status = statemgr.try_lock().map_err(ErrorDetail::StateMgrSetup)?;
912

            
913
22
        let addr_cfg = config.address_filter.clone();
914

            
915
22
        let (status_sender, status_receiver) = postage::watch::channel();
916
22
        let status_receiver = status::BootstrapEvents {
917
22
            inner: status_receiver,
918
22
        };
919
22
        let chanmgr = Arc::new(
920
22
            tor_chanmgr::ChanMgr::new(
921
22
                runtime.clone(),
922
22
                ChanMgrConfig::new(config.channel.clone()),
923
22
                dormant.into(),
924
22
                &NetParameters::from_map(&config.override_net_params),
925
22
                memquota.clone(),
926
            )
927
22
            .map_err(ErrorDetail::ChanMgrSetup)?,
928
        );
929
22
        let guardmgr = tor_guardmgr::GuardMgr::new(runtime.clone(), statemgr.clone(), config)
930
22
            .map_err(ErrorDetail::GuardMgrSetup)?;
931

            
932
        #[cfg(feature = "pt-client")]
933
22
        let pt_mgr = {
934
22
            let pt_state_dir = state_dir.as_path().join("pt_state");
935
22
            config.storage.permissions().make_directory(&pt_state_dir)?;
936

            
937
22
            let mgr = Arc::new(tor_ptmgr::PtMgr::new(
938
22
                config.bridges.transports.clone(),
939
22
                pt_state_dir,
940
22
                Arc::clone(&path_resolver),
941
22
                runtime.clone(),
942
            )?);
943

            
944
22
            chanmgr.set_pt_mgr(mgr.clone());
945

            
946
22
            mgr
947
        };
948

            
949
22
        let circmgr = Arc::new(
950
22
            tor_circmgr::CircMgr::new(
951
22
                config,
952
22
                statemgr.clone(),
953
22
                &runtime,
954
22
                Arc::clone(&chanmgr),
955
22
                &guardmgr,
956
            )
957
22
            .map_err(ErrorDetail::CircMgrSetup)?,
958
        );
959

            
960
22
        let timeout_cfg = config.stream_timeouts.clone();
961

            
962
22
        let dirmgr_store =
963
22
            DirMgrStore::new(&dir_cfg, runtime.clone(), false).map_err(ErrorDetail::DirMgrSetup)?;
964
22
        let dirmgr = dirmgr_builder
965
22
            .build(
966
22
                runtime.clone(),
967
22
                dirmgr_store.clone(),
968
22
                Arc::clone(&circmgr),
969
22
                dir_cfg,
970
            )
971
22
            .map_err(crate::Error::into_detail)?;
972

            
973
22
        let software_status_cfg = Arc::new(MutCfg::new(config.use_obsolete_software.clone()));
974
22
        let rtclone = runtime.clone();
975
        #[allow(clippy::print_stderr)]
976
22
        crate::protostatus::enforce_protocol_recommendations(
977
22
            &runtime,
978
22
            Arc::clone(&dirmgr),
979
22
            crate::software_release_date(),
980
22
            crate::supported_protocols(),
981
22
            Arc::clone(&software_status_cfg),
982
            // TODO #1932: It would be nice to have a cleaner shutdown mechanism here,
983
            // but that will take some work.
984
            |fatal| async move {
985
                use tor_error::ErrorReport as _;
986
                // We already logged this error, but let's tell stderr too.
987
                eprintln!(
988
                    "Shutting down because of unsupported software version.\nError was:\n{}",
989
                    fatal.report(),
990
                );
991
                if let Some(hint) = crate::err::Error::from(fatal).hint() {
992
                    eprintln!("{}", hint);
993
                }
994
                // Give the tracing module a while to flush everything, since it has no built-in
995
                // flush function.
996
                rtclone.sleep(std::time::Duration::new(5, 0)).await;
997
                std::process::exit(1);
998
            },
999
        )?;
22
        let mut periodic_task_handles = circmgr
22
            .launch_background_tasks(&runtime, &dirmgr, statemgr.clone())
22
            .map_err(ErrorDetail::CircMgrSetup)?;
22
        periodic_task_handles.extend(dirmgr.download_task_handle());
22
        periodic_task_handles.extend(
22
            chanmgr
22
                .launch_background_tasks(&runtime, dirmgr.clone().upcast_arc())
22
                .map_err(ErrorDetail::ChanMgrSetup)?,
        );
22
        let (dormant_send, dormant_recv) = postage::watch::channel_with(Some(dormant));
22
        let dormant_send = DropNotifyWatchSender::new(dormant_send);
        #[cfg(feature = "bridge-client")]
22
        let bridge_desc_mgr = Arc::new(Mutex::new(None));
        #[cfg(any(feature = "onion-service-client", feature = "onion-service-service"))]
22
        let hs_circ_pool = {
22
            let circpool = Arc::new(tor_circmgr::hspool::HsCircPool::new(&circmgr));
22
            circpool
22
                .launch_background_tasks(&runtime, &dirmgr.clone().upcast_arc())
22
                .map_err(ErrorDetail::CircMgrSetup)?;
22
            circpool
        };
        #[cfg(feature = "onion-service-client")]
22
        let hsclient = {
            // Prompt the hs connector to do its data housekeeping when we get a new consensus.
            // That's a time we're doing a bunch of thinking anyway, and it's not very frequent.
22
            let housekeeping = dirmgr.events().filter_map(|event| async move {
                match event {
                    DirEvent::NewConsensus => Some(()),
                    _ => None,
                }
            });
22
            let housekeeping = Box::pin(housekeeping);
22
            HsClientConnector::new(runtime.clone(), hs_circ_pool.clone(), config, housekeeping)?
        };
22
        runtime
22
            .spawn(tasks_monitor_dormant(
22
                dormant_recv,
22
                dirmgr.clone().upcast_arc(),
22
                chanmgr.clone(),
                #[cfg(feature = "bridge-client")]
22
                bridge_desc_mgr.clone(),
22
                periodic_task_handles,
            ))
22
            .map_err(|e| ErrorDetail::from_spawn("periodic task dormant monitor", e))?;
22
        let conn_status = chanmgr.bootstrap_events();
22
        let dir_status = dirmgr.bootstrap_events();
22
        let skew_status = circmgr.skew_events();
22
        runtime
22
            .spawn(status::report_status(
22
                status_sender,
22
                conn_status,
22
                dir_status,
22
                skew_status,
            ))
22
            .map_err(|e| ErrorDetail::from_spawn("top-level status reporter", e))?;
22
        let client_isolation = IsolationToken::new();
22
        let inert_client = InertTorClient::new(config)?;
22
        Ok(TorClient {
22
            runtime,
22
            client_isolation,
22
            connect_prefs: Default::default(),
22
            memquota,
22
            chanmgr,
22
            circmgr,
22
            dirmgr_store,
22
            dirmgr,
22
            #[cfg(feature = "bridge-client")]
22
            bridge_desc_mgr,
22
            #[cfg(feature = "pt-client")]
22
            pt_mgr,
22
            #[cfg(feature = "onion-service-client")]
22
            hsclient,
22
            #[cfg(any(feature = "onion-service-client", feature = "onion-service-service"))]
22
            hs_circ_pool,
22
            inert_client,
22
            guardmgr,
22
            statemgr,
22
            addrcfg: Arc::new(addr_cfg.into()),
22
            timeoutcfg: Arc::new(timeout_cfg.into()),
22
            reconfigure_lock: Arc::new(Mutex::new(())),
22
            status_receiver,
22
            bootstrap_in_progress: Arc::new(AsyncMutex::new(())),
22
            should_bootstrap: autobootstrap,
22
            dormant: Arc::new(Mutex::new(dormant_send)),
22
            #[cfg(feature = "onion-service-service")]
22
            state_directory,
22
            path_resolver,
22
            software_status_cfg,
22
        })
22
    }
    /// Construct a state manager from the client configuration.
22
    fn statemgr_from_config(config: &TorClientConfig) -> Result<UsingStateMgr, ErrorDetail> {
        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
        {
            use tor_persist::FsStateMgr;
22
            let (state_dir, mistrust) = config.state_dir()?;
22
            FsStateMgr::from_path_and_mistrust(state_dir, mistrust)
22
                .map_err(ErrorDetail::StateMgrSetup)
        }
        #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
        {
            unimplemented!()
        }
22
    }
    /// Bootstrap a connection to the Tor network, with a client created by `create_unbootstrapped`.
    ///
    /// Since cloned copies of a `TorClient` share internal state, you can bootstrap a client by
    /// cloning it and running this function in a background task (or similar). This function
    /// only needs to be called on one client in order to bootstrap all of its clones.
    ///
    /// Returns once there is enough directory material to connect safely over the Tor network.
    /// If the client or one of its clones has already been bootstrapped, returns immediately with
    /// success. If a bootstrap is in progress, waits for it to finish, then retries it if it
    /// failed (returning success if it succeeded).
    ///
    /// Bootstrap progress can be tracked by listening to the event receiver returned by
    /// [`bootstrap_events`](TorClient::bootstrap_events).
    ///
    /// # Failures
    ///
    /// If the bootstrapping process fails, returns an error. This function can safely be called
    /// again later to attempt to bootstrap another time.
    #[instrument(skip_all, level = "trace")]
    pub async fn bootstrap(&self) -> crate::Result<()> {
        self.bootstrap_inner().await.map_err(ErrorDetail::into)
    }
    /// Implementation of `bootstrap`, split out in order to avoid manually specifying
    /// double error conversions.
    async fn bootstrap_inner(&self) -> StdResult<(), ErrorDetail> {
        // Make sure we have a bridge descriptor manager, which is active iff required
        #[cfg(feature = "bridge-client")]
        {
            let mut dormant = self.dormant.lock().expect("dormant lock poisoned");
            let dormant = dormant.borrow();
            let dormant = dormant.ok_or_else(|| internal!("dormant dropped"))?.into();
            let mut bdm = self.bridge_desc_mgr.lock().expect("bdm lock poisoned");
            if bdm.is_none() {
                let new_bdm = Arc::new(BridgeDescMgr::new(
                    &Default::default(),
                    self.runtime.clone(),
                    self.dirmgr_store.clone(),
                    self.circmgr.clone(),
                    dormant,
                )?);
                self.guardmgr
                    .install_bridge_desc_provider(&(new_bdm.clone() as _))
                    .map_err(ErrorDetail::GuardMgrSetup)?;
                // If ^ that fails, we drop the BridgeDescMgr again.  It may do some
                // work but will hopefully eventually quit.
                *bdm = Some(new_bdm);
            }
        }
        // Wait for an existing bootstrap attempt to finish first.
        //
        // This is a futures::lock::Mutex, so it's okay to await while we hold it.
        let _bootstrap_lock = self.bootstrap_in_progress.lock().await;
        if self
            .statemgr
            .try_lock()
            .map_err(ErrorDetail::StateAccess)?
            .held()
        {
            debug!("It appears we have the lock on our state files.");
        } else {
            info!(
                "Another process has the lock on our state files. We'll proceed in read-only mode."
            );
        }
        // If we fail to bootstrap (i.e. we return before the disarm() point below), attempt to
        // unlock the state files.
        let unlock_guard = util::StateMgrUnlockGuard::new(&self.statemgr);
        self.dirmgr
            .bootstrap()
            .await
            .map_err(ErrorDetail::DirMgrBootstrap)?;
        // Since we succeeded, disarm the unlock guard.
        unlock_guard.disarm();
        Ok(())
    }
    /// ## For `BootstrapBehavior::OnDemand` clients
    ///
    /// Initiate a bootstrap by calling `bootstrap` (which is idempotent, so attempts to
    /// bootstrap twice will just do nothing).
    ///
    /// ## For `BootstrapBehavior::Manual` clients
    ///
    /// Check whether a bootstrap is in progress; if one is, wait until it finishes
    /// and then return. (Otherwise, return immediately.)
    #[instrument(skip_all, level = "trace")]
4
    async fn wait_for_bootstrap(&self) -> StdResult<(), ErrorDetail> {
4
        match self.should_bootstrap {
            BootstrapBehavior::OnDemand => {
                self.bootstrap_inner().await?;
            }
            BootstrapBehavior::Manual => {
                // Grab the lock, and immediately release it.  That will ensure that nobody else is trying to bootstrap.
                self.bootstrap_in_progress.lock().await;
            }
        }
        self.dormant
            .lock()
            .map_err(|_| internal!("dormant poisoned"))?
4
            .try_maybe_send(|dormant| {
                Ok::<_, Bug>(Some({
4
                    match dormant.ok_or_else(|| internal!("dormant dropped"))? {
                        DormantMode::Soft => DormantMode::Normal,
4
                        other @ DormantMode::Normal => other,
                    }
                }))
4
            })?;
        Ok(())
4
    }
    /// Change the configuration of this TorClient to `new_config`.
    ///
    /// The `how` describes whether to perform an all-or-nothing
    /// reconfiguration: either all of the configuration changes will be
    /// applied, or none will. If you have disabled all-or-nothing changes, then
    /// only fatal errors will be reported in this function's return value.
    ///
    /// This function applies its changes to **all** TorClient instances derived
    /// from the same call to `TorClient::create_*`: even ones whose circuits
    /// are isolated from this handle.
    ///
    /// # Limitations
    ///
    /// Although most options are reconfigurable, there are some whose values
    /// can't be changed on an a running TorClient.  Those options (or their
    /// sections) are explicitly documented not to be changeable.
    /// NOTE: Currently, not all of these non-reconfigurable options are
    /// documented. See [arti#1721][arti-1721].
    ///
    /// [arti-1721]: https://gitlab.torproject.org/tpo/core/arti/-/issues/1721
    ///
    /// Changing some options do not take effect immediately on all open streams
    /// and circuits, but rather affect only future streams and circuits.  Those
    /// are also explicitly documented.
    #[instrument(skip_all, level = "trace")]
4
    pub fn reconfigure(
4
        &self,
4
        new_config: &TorClientConfig,
4
        how: tor_config::Reconfigure,
4
    ) -> crate::Result<()> {
        // We need to hold this lock while we're reconfiguring the client: even
        // though the individual fields have their own synchronization, we can't
        // safely let two threads change them at once.  If we did, then we'd
        // introduce time-of-check/time-of-use bugs in checking our configuration,
        // deciding how to change it, then applying the changes.
4
        let guard = self.reconfigure_lock.lock().expect("Poisoned lock");
4
        match how {
            tor_config::Reconfigure::AllOrNothing => {
                // We have to check before we make any changes.
4
                self.reconfigure_inner(
4
                    new_config,
4
                    tor_config::Reconfigure::CheckAllOrNothing,
4
                    &guard,
                )?;
            }
            tor_config::Reconfigure::CheckAllOrNothing => {}
            tor_config::Reconfigure::WarnOnFailures => {}
            _ => {}
        }
        // Actually reconfigure
4
        self.reconfigure_inner(new_config, how, &guard)?;
4
        Ok(())
4
    }
    /// This is split out from `reconfigure` so we can do the all-or-nothing
    /// check without recursion. the caller to this method must hold the
    /// `reconfigure_lock`.
    #[instrument(level = "trace", skip_all)]
8
    fn reconfigure_inner(
8
        &self,
8
        new_config: &TorClientConfig,
8
        how: tor_config::Reconfigure,
8
        _reconfigure_lock_guard: &std::sync::MutexGuard<'_, ()>,
8
    ) -> crate::Result<()> {
        // We ignore 'new_config.path_resolver' here since CfgPathResolver does not impl PartialEq
        // and we have no way to compare them, but this field is explicitly documented as being
        // non-reconfigurable anyways.
8
        let dir_cfg = new_config.dir_mgr_config().map_err(wrap_err)?;
8
        let state_cfg = new_config
8
            .storage
8
            .expand_state_dir(&self.path_resolver)
8
            .map_err(wrap_err)?;
8
        let addr_cfg = &new_config.address_filter;
8
        let timeout_cfg = &new_config.stream_timeouts;
        // TODO wasm: This ins't really how things should be long term,
        // but once we have a more generic notion of configuring storage
        // we can change this to comply with it.
        #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
8
        if state_cfg != self.statemgr.path() {
            how.cannot_change("storage.state_dir").map_err(wrap_err)?;
8
        }
8
        self.memquota
8
            .reconfigure(new_config.system.memory.clone(), how)
8
            .map_err(wrap_err)?;
8
        let retire_circuits = self
8
            .circmgr
8
            .reconfigure(new_config, how)
8
            .map_err(wrap_err)?;
        #[cfg(any(feature = "onion-service-client", feature = "onion-service-service"))]
8
        if retire_circuits != RetireCircuits::None {
            self.hs_circ_pool.retire_all_circuits().map_err(wrap_err)?;
8
        }
8
        self.dirmgr.reconfigure(&dir_cfg, how).map_err(wrap_err)?;
8
        let netparams = self.dirmgr.params();
8
        self.chanmgr
8
            .reconfigure(&new_config.channel, how, netparams)
8
            .map_err(wrap_err)?;
        #[cfg(feature = "pt-client")]
8
        self.pt_mgr
8
            .reconfigure(how, new_config.bridges.transports.clone())
8
            .map_err(wrap_err)?;
8
        if how == tor_config::Reconfigure::CheckAllOrNothing {
4
            return Ok(());
4
        }
4
        self.addrcfg.replace(addr_cfg.clone());
4
        self.timeoutcfg.replace(timeout_cfg.clone());
4
        self.software_status_cfg
4
            .replace(new_config.use_obsolete_software.clone());
4
        Ok(())
8
    }
    /// Return a new isolated `TorClient` handle.
    ///
    /// The two `TorClient`s will share internal state and configuration, but
    /// their streams will never share circuits with one another.
    ///
    /// Use this function when you want separate parts of your program to
    /// each have a TorClient handle, but where you don't want their
    /// activities to be linkable to one another over the Tor network.
    ///
    /// Calling this function is usually preferable to creating a
    /// completely separate TorClient instance, since it can share its
    /// internals with the existing `TorClient`.
    ///
    /// (Connections made with clones of the returned `TorClient` may
    /// share circuits with each other.)
    #[must_use]
2
    pub fn isolated_client(&self) -> TorClient<R> {
2
        let mut result = self.clone();
2
        result.client_isolation = IsolationToken::new();
2
        result
2
    }
    /// Launch an anonymized connection to the provided address and port over
    /// the Tor network.
    ///
    /// Note that because Tor prefers to do DNS resolution on the remote side of
    /// the network, this function takes its address as a string:
    ///
    /// ```no_run
    /// # use arti_client::*;use tor_rtcompat::Runtime;
    /// # async fn ex<R:Runtime>(tor_client: TorClient<R>) -> Result<()> {
    /// // The most usual way to connect is via an address-port tuple.
    /// let socket = tor_client.connect(("www.example.com", 443)).await?;
    ///
    /// // You can also specify an address and port as a colon-separated string.
    /// let socket = tor_client.connect("www.example.com:443").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Hostnames are _strongly_ preferred here: if this function allowed the
    /// caller here to provide an IPAddr or [`IpAddr`] or
    /// [`SocketAddr`](std::net::SocketAddr) address, then
    ///
    /// ```no_run
    /// # use arti_client::*; use tor_rtcompat::Runtime;
    /// # async fn ex<R:Runtime>(tor_client: TorClient<R>) -> Result<()> {
    /// # use std::net::ToSocketAddrs;
    /// // BAD: We're about to leak our target address to the local resolver!
    /// let address = "www.example.com:443".to_socket_addrs().unwrap().next().unwrap();
    /// // 🤯 Oh no! Now any eavesdropper can tell where we're about to connect! 🤯
    ///
    /// // Fortunately, this won't compile, since SocketAddr doesn't implement IntoTorAddr.
    /// // let socket = tor_client.connect(address).await?;
    /// //                                 ^^^^^^^ the trait `IntoTorAddr` is not implemented for `std::net::SocketAddr`
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// If you really do need to connect to an IP address rather than a
    /// hostname, and if you're **sure** that the IP address came from a safe
    /// location, there are a few ways to do so.
    ///
    /// ```no_run
    /// # use arti_client::{TorClient,Result};use tor_rtcompat::Runtime;
    /// # use std::net::{SocketAddr,IpAddr};
    /// # async fn ex<R:Runtime>(tor_client: TorClient<R>) -> Result<()> {
    /// # use std::net::ToSocketAddrs;
    /// // ⚠️This is risky code!⚠️
    /// // (Make sure your addresses came from somewhere safe...)
    ///
    /// // If we have a fixed address, we can just provide it as a string.
    /// let socket = tor_client.connect("192.0.2.22:443").await?;
    /// let socket = tor_client.connect(("192.0.2.22", 443)).await?;
    ///
    /// // If we have a SocketAddr or an IpAddr, we can use the
    /// // DangerouslyIntoTorAddr trait.
    /// use arti_client::DangerouslyIntoTorAddr;
    /// let sockaddr = SocketAddr::from(([192, 0, 2, 22], 443));
    /// let ipaddr = IpAddr::from([192, 0, 2, 22]);
    /// let socket = tor_client.connect(sockaddr.into_tor_addr_dangerously().unwrap()).await?;
    /// let socket = tor_client.connect((ipaddr, 443).into_tor_addr_dangerously().unwrap()).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[instrument(skip_all, level = "trace")]
4
    pub async fn connect<A: IntoTorAddr>(&self, target: A) -> crate::Result<DataStream> {
        self.connect_with_prefs(target, &self.connect_prefs).await
4
    }
    /// Launch an anonymized connection to the provided address and
    /// port over the Tor network, with explicit connection preferences.
    ///
    /// Note that because Tor prefers to do DNS resolution on the remote
    /// side of the network, this function takes its address as a string.
    /// (See [`TorClient::connect()`] for more information.)
    #[instrument(skip_all, level = "trace")]
4
    pub async fn connect_with_prefs<A: IntoTorAddr>(
4
        &self,
4
        target: A,
4
        prefs: &StreamPrefs,
4
    ) -> crate::Result<DataStream> {
        let addr = target.into_tor_addr().map_err(wrap_err)?;
        let mut stream_parameters = prefs.stream_parameters();
        // This macro helps prevent code duplication in the match below.
        //
        // Ideally, the match should resolve to a tuple consisting of the
        // tunnel, and the address, port and stream params,
        // but that's not currently possible because
        // the Exit and Hs branches use different tunnel types.
        //
        // TODO: replace with an async closure (when our MSRV allows it),
        // or with a more elegant approach.
        macro_rules! begin_stream {
            ($tunnel:expr, $addr:expr, $port:expr, $stream_params:expr) => {{
                let fut = $tunnel.begin_stream($addr, $port, $stream_params);
                self.runtime
                    .timeout(self.timeoutcfg.get().connect_timeout, fut)
                    .await
                    .map_err(|_| ErrorDetail::ExitTimeout)?
                    .map_err(|cause| ErrorDetail::StreamFailed {
                        cause,
                        kind: "data",
                    })
            }};
        }
        let stream = match addr.into_stream_instructions(&self.addrcfg.get(), prefs)? {
            StreamInstructions::Exit {
                hostname: addr,
                port,
            } => {
                let exit_ports = [prefs.wrap_target_port(port)];
                let tunnel = self
                    .get_or_launch_exit_tunnel(&exit_ports, prefs)
                    .await
                    .map_err(wrap_err)?;
                debug!("Got a circuit for {}:{}", sensitive(&addr), port);
                begin_stream!(tunnel, &addr, port, Some(stream_parameters))
            }
            #[cfg(not(feature = "onion-service-client"))]
            #[allow(unused_variables)] // for hostname and port
            StreamInstructions::Hs {
                hsid,
                hostname,
                port,
            } => void::unreachable(hsid.0),
            #[cfg(feature = "onion-service-client")]
            StreamInstructions::Hs {
                hsid,
                hostname,
                port,
            } => {
                use safelog::DisplayRedacted as _;
                self.wait_for_bootstrap().await?;
                let netdir = self.netdir(Timeliness::Timely, "connect to a hidden service")?;
                let mut hs_client_secret_keys_builder = HsClientSecretKeysBuilder::default();
                if let Some(keymgr) = &self.inert_client.keymgr {
                    let desc_enc_key_spec = HsClientDescEncKeypairSpecifier::new(hsid);
                    let ks_hsc_desc_enc =
                        keymgr.get::<HsClientDescEncKeypair>(&desc_enc_key_spec)?;
                    if let Some(ks_hsc_desc_enc) = ks_hsc_desc_enc {
                        debug!(
                            "Found descriptor decryption key for {}",
                            hsid.display_redacted()
                        );
                        hs_client_secret_keys_builder.ks_hsc_desc_enc(ks_hsc_desc_enc);
                    }
                };
                let hs_client_secret_keys = hs_client_secret_keys_builder
                    .build()
                    .map_err(ErrorDetail::Configuration)?;
                let tunnel = self
                    .hsclient
                    .get_or_launch_tunnel(
                        &netdir,
                        hsid,
                        hs_client_secret_keys,
                        self.isolation(prefs),
                    )
                    .await
                    .map_err(|cause| ErrorDetail::ObtainHsCircuit { cause, hsid })?;
                // On connections to onion services, we have to suppress
                // everything except the port from the BEGIN message.  We also
                // disable optimistic data.
                stream_parameters
                    .suppress_hostname()
                    .suppress_begin_flags()
                    .optimistic(false);
                begin_stream!(tunnel, &hostname, port, Some(stream_parameters))
            }
        };
        Ok(stream?)
4
    }
    /// Sets the default preferences for future connections made with this client.
    ///
    /// The preferences set with this function will be inherited by clones of this client, but
    /// updates to the preferences in those clones will not propagate back to the original.  I.e.,
    /// the preferences are copied by `clone`.
    ///
    /// Connection preferences always override configuration, even configuration set later
    /// (eg, by a config reload).
    pub fn set_stream_prefs(&mut self, connect_prefs: StreamPrefs) {
        self.connect_prefs = connect_prefs;
    }
    /// Provides a new handle on this client, but with adjusted default preferences.
    ///
    /// Connections made with e.g. [`connect`](TorClient::connect) on the returned handle will use
    /// `connect_prefs`.  This is a convenience wrapper for `clone` and `set_connect_prefs`.
    #[must_use]
    pub fn clone_with_prefs(&self, connect_prefs: StreamPrefs) -> Self {
        let mut result = self.clone();
        result.set_stream_prefs(connect_prefs);
        result
    }
    /// On success, return a list of IP addresses.
    #[instrument(skip_all, level = "trace")]
    pub async fn resolve(&self, hostname: &str) -> crate::Result<Vec<IpAddr>> {
        self.resolve_with_prefs(hostname, &self.connect_prefs).await
    }
    /// On success, return a list of IP addresses, but use prefs.
    #[instrument(skip_all, level = "trace")]
    pub async fn resolve_with_prefs(
        &self,
        hostname: &str,
        prefs: &StreamPrefs,
    ) -> crate::Result<Vec<IpAddr>> {
        // TODO This dummy port is only because `address::Host` is not pub(crate),
        // but I see no reason why it shouldn't be?  Then `into_resolve_instructions`
        // should be a method on `Host`, not `TorAddr`.  -Diziet.
        let addr = (hostname, 1).into_tor_addr().map_err(wrap_err)?;
        match addr.into_resolve_instructions(&self.addrcfg.get(), prefs)? {
            ResolveInstructions::Exit(hostname) => {
                let circ = self.get_or_launch_exit_tunnel(&[], prefs).await?;
                let resolve_future = circ.resolve(&hostname);
                let addrs = self
                    .runtime
                    .timeout(self.timeoutcfg.get().resolve_timeout, resolve_future)
                    .await
                    .map_err(|_| ErrorDetail::ExitTimeout)?
                    .map_err(|cause| ErrorDetail::StreamFailed {
                        cause,
                        kind: "DNS lookup",
                    })?;
                Ok(addrs)
            }
            ResolveInstructions::Return(addrs) => Ok(addrs),
        }
    }
    /// Perform a remote DNS reverse lookup with the provided IP address.
    ///
    /// On success, return a list of hostnames.
    #[instrument(skip_all, level = "trace")]
    pub async fn resolve_ptr(&self, addr: IpAddr) -> crate::Result<Vec<String>> {
        self.resolve_ptr_with_prefs(addr, &self.connect_prefs).await
    }
    /// Perform a remote DNS reverse lookup with the provided IP address.
    ///
    /// On success, return a list of hostnames.
    #[instrument(level = "trace", skip_all)]
    pub async fn resolve_ptr_with_prefs(
        &self,
        addr: IpAddr,
        prefs: &StreamPrefs,
    ) -> crate::Result<Vec<String>> {
        let circ = self.get_or_launch_exit_tunnel(&[], prefs).await?;
        let resolve_ptr_future = circ.resolve_ptr(addr);
        let hostnames = self
            .runtime
            .timeout(
                self.timeoutcfg.get().resolve_ptr_timeout,
                resolve_ptr_future,
            )
            .await
            .map_err(|_| ErrorDetail::ExitTimeout)?
            .map_err(|cause| ErrorDetail::StreamFailed {
                cause,
                kind: "reverse DNS lookup",
            })?;
        Ok(hostnames)
    }
    /// Return a reference to this client's directory manager.
    ///
    /// This function is unstable. It is only enabled if the crate was
    /// built with the `experimental-api` feature.
    #[cfg(feature = "experimental-api")]
    pub fn dirmgr(&self) -> &Arc<dyn tor_dirmgr::DirProvider> {
        &self.dirmgr
    }
    /// Return a reference to this client's circuit manager.
    ///
    /// This function is unstable. It is only enabled if the crate was
    /// built with the `experimental-api` feature.
    #[cfg(feature = "experimental-api")]
    pub fn circmgr(&self) -> &Arc<tor_circmgr::CircMgr<R>> {
        &self.circmgr
    }
    /// Return a reference to this client's channel manager.
    ///
    /// This function is unstable. It is only enabled if the crate was
    /// built with the `experimental-api` feature.
    #[cfg(feature = "experimental-api")]
    pub fn chanmgr(&self) -> &Arc<tor_chanmgr::ChanMgr<R>> {
        &self.chanmgr
    }
    /// Return a reference to this client's circuit pool.
    ///
    /// This function is unstable. It is only enabled if the crate was
    /// built with the `experimental-api` feature and any of `onion-service-client`
    /// or `onion-service-service` features. This method is required to invoke
    /// tor_hsservice::OnionService::launch()
    #[cfg(all(
        feature = "experimental-api",
        any(feature = "onion-service-client", feature = "onion-service-service")
    ))]
    pub fn hs_circ_pool(&self) -> &Arc<tor_circmgr::hspool::HsCircPool<R>> {
        &self.hs_circ_pool
    }
    /// Return a reference to the runtime being used by this client.
    //
    // This API is not a hostage to fortune since we already require that R: Clone,
    // and necessarily a TorClient must have a clone of it.
    //
    // We provide it simply to save callers who have a TorClient from
    // having to separately keep their own handle,
4
    pub fn runtime(&self) -> &R {
4
        &self.runtime
4
    }
    /// Return a netdir that is timely according to the rules of `timeliness`.
    ///
    /// The `action` string is a description of what we wanted to do with the
    /// directory, to be put into the error message if we couldn't find a directory.
4
    fn netdir(
4
        &self,
4
        timeliness: Timeliness,
4
        action: &'static str,
4
    ) -> StdResult<Arc<tor_netdir::NetDir>, ErrorDetail> {
        use tor_netdir::Error as E;
4
        match self.dirmgr.netdir(timeliness) {
            Ok(netdir) => Ok(netdir),
            Err(E::NoInfo) | Err(E::NotEnoughInfo) => {
4
                Err(ErrorDetail::BootstrapRequired { action })
            }
            Err(error) => Err(ErrorDetail::NoDir { error, action }),
        }
4
    }
    /// Get or launch an exit-suitable circuit with a given set of
    /// exit ports.
    #[instrument(skip_all, level = "trace")]
4
    async fn get_or_launch_exit_tunnel(
4
        &self,
4
        exit_ports: &[TargetPort],
4
        prefs: &StreamPrefs,
4
    ) -> StdResult<ClientDataTunnel, ErrorDetail> {
        // TODO HS probably this netdir ought to be made in connect_with_prefs
        // like for StreamInstructions::Hs.
        self.wait_for_bootstrap().await?;
        let dir = self.netdir(Timeliness::Timely, "build a circuit")?;
        let tunnel = self
            .circmgr
            .get_or_launch_exit(
                dir.as_ref().into(),
                exit_ports,
                self.isolation(prefs),
                #[cfg(feature = "geoip")]
                prefs.country_code,
            )
            .await
            .map_err(|cause| ErrorDetail::ObtainExitCircuit {
                cause,
                exit_ports: Sensitive::new(exit_ports.into()),
            })?;
        drop(dir); // This decreases the refcount on the netdir.
        Ok(tunnel)
4
    }
    /// Return an overall [`Isolation`] for this `TorClient` and a `StreamPrefs`.
    ///
    /// This describes which operations might use
    /// circuit(s) with this one.
    ///
    /// This combines isolation information from
    /// [`StreamPrefs::prefs_isolation`]
    /// and the `TorClient`'s isolation (eg from [`TorClient::isolated_client`]).
    fn isolation(&self, prefs: &StreamPrefs) -> StreamIsolation {
        let mut b = StreamIsolationBuilder::new();
        // Always consider our client_isolation.
        b.owner_token(self.client_isolation);
        // Consider stream isolation too, if it's set.
        if let Some(tok) = prefs.prefs_isolation() {
            b.stream_isolation(tok);
        }
        // Failure should be impossible with this builder.
        b.build().expect("Failed to construct StreamIsolation")
    }
    /// Try to launch an onion service with a given configuration.
    ///
    /// Returns `Ok(None)` if the service specified is disabled in the config.
    ///
    /// This onion service will not actually handle any requests on its own: you
    /// will need to
    /// pull [`RendRequest`](tor_hsservice::RendRequest) objects from the returned stream,
    /// [`accept`](tor_hsservice::RendRequest::accept) the ones that you want to
    /// answer, and then wait for them to give you [`StreamRequest`](tor_hsservice::StreamRequest)s.
    ///
    /// You may find the [`tor_hsservice::handle_rend_requests`] API helpful for
    /// translating `RendRequest`s into `StreamRequest`s.
    ///
    /// If you want to forward all the requests from an onion service to a set
    /// of local ports, you may want to use the `tor-hsrproxy` crate.
    #[cfg(feature = "onion-service-service")]
    #[instrument(skip_all, level = "trace")]
    pub fn launch_onion_service(
        &self,
        config: tor_hsservice::OnionServiceConfig,
    ) -> crate::Result<
        Option<(
            Arc<tor_hsservice::RunningOnionService>,
            impl futures::Stream<Item = tor_hsservice::RendRequest> + use<R>,
        )>,
    > {
        let nickname = config.nickname();
        if !config.enabled() {
            info!(
                nickname=%nickname,
                "Skipping onion service because it was disabled in the config"
            );
            return Ok(None);
        }
        let keymgr = self
            .inert_client
            .keymgr
            .as_ref()
            .ok_or(ErrorDetail::KeystoreRequired {
                action: "launch onion service",
            })?
            .clone();
        let state_dir = self.state_directory.clone();
        let service = tor_hsservice::OnionService::builder()
            .config(config) // TODO #1186: Allow override of KeyMgr for "ephemeral" operation?
            .keymgr(keymgr)
            // TODO #1186: Allow override of StateMgr for "ephemeral" operation?
            .state_dir(state_dir)
            .build()
            .map_err(ErrorDetail::LaunchOnionService)?;
        Ok(service
            .launch(
                self.runtime.clone(),
                self.dirmgr.clone().upcast_arc(),
                self.hs_circ_pool.clone(),
                Arc::clone(&self.path_resolver),
            )
            .map_err(ErrorDetail::LaunchOnionService)?)
    }
    /// Try to launch an onion service with a given configuration and provided
    /// [`HsIdKeypair`]. If an onion service with the given nickname already has an
    /// associated `HsIdKeypair`  in this `TorClient`'s `KeyMgr`, then this operation
    /// fails rather than overwriting the existing key.
    ///
    /// Returns `Ok(None)` if the service specified is disabled in the config.
    ///
    /// The specified `HsIdKeypair` will be inserted in the primary keystore.
    ///
    /// **Important**: depending on the configuration of your
    /// [primary keystore](tor_keymgr::config::PrimaryKeystoreConfig),
    /// the `HsIdKeypair` **may** get persisted to disk.
    /// By default, Arti's primary keystore is the [native](ArtiKeystoreKind::Native),
    /// disk-based keystore.
    ///
    /// This onion service will not actually handle any requests on its own: you
    /// will need to
    /// pull [`RendRequest`](tor_hsservice::RendRequest) objects from the returned stream,
    /// [`accept`](tor_hsservice::RendRequest::accept) the ones that you want to
    /// answer, and then wait for them to give you [`StreamRequest`](tor_hsservice::StreamRequest)s.
    ///
    /// You may find the [`tor_hsservice::handle_rend_requests`] API helpful for
    /// translating `RendRequest`s into `StreamRequest`s.
    ///
    /// If you want to forward all the requests from an onion service to a set
    /// of local ports, you may want to use the `tor-hsrproxy` crate.
    #[cfg(all(feature = "onion-service-service", feature = "experimental-api"))]
    #[instrument(skip_all, level = "trace")]
    pub fn launch_onion_service_with_hsid(
        &self,
        config: tor_hsservice::OnionServiceConfig,
        id_keypair: HsIdKeypair,
    ) -> crate::Result<
        Option<(
            Arc<tor_hsservice::RunningOnionService>,
            impl futures::Stream<Item = tor_hsservice::RendRequest> + use<R>,
        )>,
    > {
        let nickname = config.nickname();
        let hsid_spec = HsIdKeypairSpecifier::new(nickname.clone());
        let selector = KeystoreSelector::Primary;
        let _kp = self
            .inert_client
            .keymgr
            .as_ref()
            .ok_or(ErrorDetail::KeystoreRequired {
                action: "launch onion service ex",
            })?
            .insert::<HsIdKeypair>(id_keypair, &hsid_spec, selector, false)?;
        self.launch_onion_service(config)
    }
    /// Generate a service discovery keypair for connecting to a hidden service running in
    /// "restricted discovery" mode.
    ///
    /// The `selector` argument is used for choosing the keystore in which to generate the keypair.
    /// While most users will want to write to the [`Primary`](KeystoreSelector::Primary), if you
    /// have configured this `TorClient` with a non-default keystore and wish to generate the
    /// keypair in it, you can do so by calling this function with a [KeystoreSelector::Id]
    /// specifying the keystore ID of your keystore.
    ///
    // Note: the selector argument exists for future-proofing reasons. We don't currently support
    // configuring custom or non-default keystores (see #1106).
    ///
    /// Returns an error if the key already exists in the specified key store.
    ///
    /// Important: the public part of the generated keypair must be shared with the service, and
    /// the service needs to be configured to allow the owner of its private counterpart to
    /// discover its introduction points. The caller is responsible for sharing the public part of
    /// the key with the hidden service.
    ///
    /// This function does not require the `TorClient` to be running or bootstrapped.
    //
    // TODO: decide whether this should use get_or_generate before making it
    // non-experimental
    #[cfg(all(
        feature = "onion-service-client",
        feature = "experimental-api",
        feature = "keymgr"
    ))]
    pub fn generate_service_discovery_key(
        &self,
        selector: KeystoreSelector,
        hsid: HsId,
    ) -> crate::Result<HsClientDescEncKey> {
        self.inert_client
            .generate_service_discovery_key(selector, hsid)
    }
    /// Rotate the service discovery keypair for connecting to a hidden service running in
    /// "restricted discovery" mode.
    ///
    /// **If the specified keystore already contains a restricted discovery keypair
    /// for the service, it will be overwritten.** Otherwise, a new keypair is generated.
    ///
    /// The `selector` argument is used for choosing the keystore in which to generate the keypair.
    /// While most users will want to write to the [`Primary`](KeystoreSelector::Primary), if you
    /// have configured this `TorClient` with a non-default keystore and wish to generate the
    /// keypair in it, you can do so by calling this function with a [KeystoreSelector::Id]
    /// specifying the keystore ID of your keystore.
    ///
    // Note: the selector argument exists for future-proofing reasons. We don't currently support
    // configuring custom or non-default keystores (see #1106).
    ///
    /// Important: the public part of the generated keypair must be shared with the service, and
    /// the service needs to be configured to allow the owner of its private counterpart to
    /// discover its introduction points. The caller is responsible for sharing the public part of
    /// the key with the hidden service.
    ///
    /// This function does not require the `TorClient` to be running or bootstrapped.
    #[cfg(all(
        feature = "onion-service-client",
        feature = "experimental-api",
        feature = "keymgr"
    ))]
    #[cfg_attr(
        docsrs,
        doc(cfg(all(
            feature = "onion-service-client",
            feature = "experimental-api",
            feature = "keymgr"
        )))
    )]
    pub fn rotate_service_discovery_key(
        &self,
        selector: KeystoreSelector,
        hsid: HsId,
    ) -> crate::Result<HsClientDescEncKey> {
        self.inert_client
            .rotate_service_discovery_key(selector, hsid)
    }
    /// Insert a service discovery secret key for connecting to a hidden service running in
    /// "restricted discovery" mode
    ///
    /// The `selector` argument is used for choosing the keystore in which to generate the keypair.
    /// While most users will want to write to the [`Primary`](KeystoreSelector::Primary), if you
    /// have configured this `TorClient` with a non-default keystore and wish to insert the
    /// key in it, you can do so by calling this function with a [KeystoreSelector::Id]
    ///
    // Note: the selector argument exists for future-proofing reasons. We don't currently support
    // configuring custom or non-default keystores (see #1106).
    ///
    /// Returns an error if the key already exists in the specified key store.
    ///
    /// Important: the public part of the generated keypair must be shared with the service, and
    /// the service needs to be configured to allow the owner of its private counterpart to
    /// discover its introduction points. The caller is responsible for sharing the public part of
    /// the key with the hidden service.
    ///
    /// This function does not require the `TorClient` to be running or bootstrapped.
    #[cfg(all(
        feature = "onion-service-client",
        feature = "experimental-api",
        feature = "keymgr"
    ))]
    #[cfg_attr(
        docsrs,
        doc(cfg(all(
            feature = "onion-service-client",
            feature = "experimental-api",
            feature = "keymgr"
        )))
    )]
    pub fn insert_service_discovery_key(
        &self,
        selector: KeystoreSelector,
        hsid: HsId,
        hs_client_desc_enc_secret_key: HsClientDescEncSecretKey,
    ) -> crate::Result<HsClientDescEncKey> {
        self.inert_client.insert_service_discovery_key(
            selector,
            hsid,
            hs_client_desc_enc_secret_key,
        )
    }
    /// Return the service discovery public key for the service with the specified `hsid`.
    ///
    /// Returns `Ok(None)` if no such key exists.
    ///
    /// This function does not require the `TorClient` to be running or bootstrapped.
    #[cfg(all(feature = "onion-service-client", feature = "experimental-api"))]
    #[cfg_attr(
        docsrs,
        doc(cfg(all(feature = "onion-service-client", feature = "experimental-api")))
    )]
    pub fn get_service_discovery_key(
        &self,
        hsid: HsId,
    ) -> crate::Result<Option<HsClientDescEncKey>> {
        self.inert_client.get_service_discovery_key(hsid)
    }
    /// Removes the service discovery keypair for the service with the specified `hsid`.
    ///
    /// Returns an error if the selected keystore is not the default keystore or one of the
    /// configured secondary stores.
    ///
    /// Returns `Ok(None)` if no such keypair exists whereas `Ok(Some()) means the keypair was successfully removed.
    ///
    /// Returns `Err` if an error occurred while trying to remove the key.
    #[cfg(all(
        feature = "onion-service-client",
        feature = "experimental-api",
        feature = "keymgr"
    ))]
    #[cfg_attr(
        docsrs,
        doc(cfg(all(
            feature = "onion-service-client",
            feature = "experimental-api",
            feature = "keymgr"
        )))
    )]
    pub fn remove_service_discovery_key(
        &self,
        selector: KeystoreSelector,
        hsid: HsId,
    ) -> crate::Result<Option<()>> {
        self.inert_client
            .remove_service_discovery_key(selector, hsid)
    }
    /// Create (but do not launch) a new
    /// [`OnionService`](tor_hsservice::OnionService)
    /// using the given configuration.
    ///
    /// This is useful for managing an onion service without needing to start a `TorClient` or the
    /// onion service itself.
    /// If you only wish to run the onion service, see
    /// [`TorClient::launch_onion_service()`]
    /// which allows you to launch an onion service from a running `TorClient`.
    ///
    /// The returned `OnionService` can be launched using
    /// [`OnionService::launch()`](tor_hsservice::OnionService::launch).
    /// Note that `launch()` requires a [`NetDirProvider`],
    /// [`HsCircPool`](tor_circmgr::hspool::HsCircPool), etc,
    /// which you should obtain from a running `TorClient`.
    /// But these are only accessible from a `TorClient` if the "experimental-api" feature is
    /// enabled.
    /// The behaviour is not specified if you create the `OnionService` with
    /// `create_onion_service()` using one [`TorClientConfig`],
    /// but launch it using a `TorClient` generated from a different `TorClientConfig`.
    // TODO #2249: Look into this behaviour more, and possibly error if there is a different config.
    #[cfg(feature = "onion-service-service")]
    #[instrument(skip_all, level = "trace")]
48
    pub fn create_onion_service(
48
        config: &TorClientConfig,
48
        svc_config: tor_hsservice::OnionServiceConfig,
48
    ) -> crate::Result<tor_hsservice::OnionService> {
48
        let inert_client = InertTorClient::new(config)?;
48
        inert_client.create_onion_service(config, svc_config)
48
    }
    /// Return a current [`status::BootstrapStatus`] describing how close this client
    /// is to being ready for user traffic.
    pub fn bootstrap_status(&self) -> status::BootstrapStatus {
        self.status_receiver.inner.borrow().clone()
    }
    /// Return a stream of [`status::BootstrapStatus`] events that will be updated
    /// whenever the client's status changes.
    ///
    /// The receiver might not receive every update sent to this stream, though
    /// when it does poll the stream it should get the most recent one.
    //
    // TODO(nickm): will this also need to implement Send and 'static?
    pub fn bootstrap_events(&self) -> status::BootstrapEvents {
        self.status_receiver.clone()
    }
    /// Change the client's current dormant mode, putting background tasks to sleep
    /// or waking them up as appropriate.
    ///
    /// This can be used to conserve CPU usage if you aren't planning on using the
    /// client for a while, especially on mobile platforms.
    ///
    /// See the [`DormantMode`] documentation for more details.
    pub fn set_dormant(&self, mode: DormantMode) {
        *self
            .dormant
            .lock()
            .expect("dormant lock poisoned")
            .borrow_mut() = Some(mode);
    }
    /// Return a [`Future`] which resolves
    /// once this TorClient has stopped.
    #[cfg(feature = "experimental-api")]
    #[instrument(skip_all, level = "trace")]
    pub fn wait_for_stop(
        &self,
    ) -> impl futures::Future<Output = ()> + Send + Sync + 'static + use<R> {
        // We defer to the "wait for unlock" handle on our statemgr.
        //
        // The statemgr won't actually be unlocked until it is finally
        // dropped, which will happen when this TorClient is
        // dropped—which is what we want.
        self.statemgr.wait_for_unlock()
    }
    /// Getter for keymgr.
    #[cfg(feature = "onion-service-cli-extra")]
    pub fn keymgr(&self) -> crate::Result<&KeyMgr> {
        self.inert_client.keymgr()
    }
}
/// Monitor `dormant_mode` and enable/disable periodic tasks as applicable
///
/// This function is spawned as a task during client construction.
// TODO should this perhaps be done by each TaskHandle?
22
async fn tasks_monitor_dormant<R: Runtime>(
22
    mut dormant_rx: postage::watch::Receiver<Option<DormantMode>>,
22
    netdir: Arc<dyn NetDirProvider>,
22
    chanmgr: Arc<tor_chanmgr::ChanMgr<R>>,
22
    #[cfg(feature = "bridge-client")] bridge_desc_mgr: Arc<Mutex<Option<Arc<BridgeDescMgr<R>>>>>,
22
    periodic_task_handles: Vec<TaskHandle>,
22
) {
40
    while let Some(Some(mode)) = dormant_rx.next().await {
18
        let netparams = netdir.params();
18
        chanmgr
18
            .set_dormancy(mode.into(), netparams)
18
            .unwrap_or_else(|e| error_report!(e, "couldn't set dormancy"));
        // IEFI simplifies handling of exceptional cases, as "never mind, then".
        #[cfg(feature = "bridge-client")]
18
        (|| {
18
            let mut bdm = bridge_desc_mgr.lock().ok()?;
18
            let bdm = bdm.as_mut()?;
            bdm.set_dormancy(mode.into());
            Some(())
        })();
18
        let is_dormant = matches!(mode, DormantMode::Soft);
90
        for task in periodic_task_handles.iter() {
90
            if is_dormant {
                task.cancel();
90
            } else {
90
                task.fire();
90
            }
        }
    }
22
}
/// Alias for TorError::from(Error)
4
pub(crate) fn wrap_err<T>(err: T) -> crate::Error
4
where
4
    ErrorDetail: From<T>,
{
4
    ErrorDetail::from(err).into()
4
}
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use tor_config::Reconfigure;
    use super::*;
    use crate::config::TorClientConfigBuilder;
    use crate::{ErrorKind, HasKind};
    #[test]
    fn create_unbootstrapped() {
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let state_dir = tempfile::tempdir().unwrap();
            let cache_dir = tempfile::tempdir().unwrap();
            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
                .build()
                .unwrap();
            let _ = TorClient::with_runtime(rt)
                .config(cfg)
                .bootstrap_behavior(BootstrapBehavior::Manual)
                .create_unbootstrapped()
                .unwrap();
        });
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let state_dir = tempfile::tempdir().unwrap();
            let cache_dir = tempfile::tempdir().unwrap();
            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
                .build()
                .unwrap();
            let _ = TorClient::with_runtime(rt)
                .config(cfg)
                .bootstrap_behavior(BootstrapBehavior::Manual)
                .create_unbootstrapped_async()
                .await
                .unwrap();
        });
    }
    #[test]
    fn unbootstrapped_client_unusable() {
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let state_dir = tempfile::tempdir().unwrap();
            let cache_dir = tempfile::tempdir().unwrap();
            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
                .build()
                .unwrap();
            // Test sync
            let client = TorClient::with_runtime(rt)
                .config(cfg)
                .bootstrap_behavior(BootstrapBehavior::Manual)
                .create_unbootstrapped()
                .unwrap();
            let result = client.connect("example.com:80").await;
            assert!(result.is_err());
            assert_eq!(result.err().unwrap().kind(), ErrorKind::BootstrapRequired);
        });
        // Need a separate test for async because Runtime and TorClientConfig are consumed by the
        // builder
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let state_dir = tempfile::tempdir().unwrap();
            let cache_dir = tempfile::tempdir().unwrap();
            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
                .build()
                .unwrap();
            // Test sync
            let client = TorClient::with_runtime(rt)
                .config(cfg)
                .bootstrap_behavior(BootstrapBehavior::Manual)
                .create_unbootstrapped_async()
                .await
                .unwrap();
            let result = client.connect("example.com:80").await;
            assert!(result.is_err());
            assert_eq!(result.err().unwrap().kind(), ErrorKind::BootstrapRequired);
        });
    }
    #[test]
    fn streamprefs_isolate_every_stream() {
        let mut observed = StreamPrefs::new();
        observed.isolate_every_stream();
        match observed.isolation {
            StreamIsolationPreference::EveryStream => (),
            _ => panic!("unexpected isolation: {:?}", observed.isolation),
        };
    }
    #[test]
    fn streamprefs_new_has_expected_defaults() {
        let observed = StreamPrefs::new();
        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv4Preferred);
        assert!(!observed.optimistic_stream);
        // StreamIsolationPreference does not implement Eq, check manually.
        match observed.isolation {
            StreamIsolationPreference::None => (),
            _ => panic!("unexpected isolation: {:?}", observed.isolation),
        };
    }
    #[test]
    fn streamprefs_new_isolation_group() {
        let mut observed = StreamPrefs::new();
        observed.new_isolation_group();
        match observed.isolation {
            StreamIsolationPreference::Explicit(_) => (),
            _ => panic!("unexpected isolation: {:?}", observed.isolation),
        };
    }
    #[test]
    fn streamprefs_ipv6_only() {
        let mut observed = StreamPrefs::new();
        observed.ipv6_only();
        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv6Only);
    }
    #[test]
    fn streamprefs_ipv6_preferred() {
        let mut observed = StreamPrefs::new();
        observed.ipv6_preferred();
        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv6Preferred);
    }
    #[test]
    fn streamprefs_ipv4_only() {
        let mut observed = StreamPrefs::new();
        observed.ipv4_only();
        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv4Only);
    }
    #[test]
    fn streamprefs_ipv4_preferred() {
        let mut observed = StreamPrefs::new();
        observed.ipv4_preferred();
        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv4Preferred);
    }
    #[test]
    fn streamprefs_optimistic() {
        let mut observed = StreamPrefs::new();
        observed.optimistic();
        assert!(observed.optimistic_stream);
    }
    #[test]
    fn streamprefs_set_isolation() {
        let mut observed = StreamPrefs::new();
        observed.set_isolation(IsolationToken::new());
        match observed.isolation {
            StreamIsolationPreference::Explicit(_) => (),
            _ => panic!("unexpected isolation: {:?}", observed.isolation),
        };
    }
    #[test]
    fn reconfigure_all_or_nothing() {
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let state_dir = tempfile::tempdir().unwrap();
            let cache_dir = tempfile::tempdir().unwrap();
            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
                .build()
                .unwrap();
            let tor_client = TorClient::with_runtime(rt)
                .config(cfg.clone())
                .bootstrap_behavior(BootstrapBehavior::Manual)
                .create_unbootstrapped()
                .unwrap();
            tor_client
                .reconfigure(&cfg, Reconfigure::AllOrNothing)
                .unwrap();
        });
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let state_dir = tempfile::tempdir().unwrap();
            let cache_dir = tempfile::tempdir().unwrap();
            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
                .build()
                .unwrap();
            let tor_client = TorClient::with_runtime(rt)
                .config(cfg.clone())
                .bootstrap_behavior(BootstrapBehavior::Manual)
                .create_unbootstrapped_async()
                .await
                .unwrap();
            tor_client
                .reconfigure(&cfg, Reconfigure::AllOrNothing)
                .unwrap();
        });
    }
}