arti_client/
client.rs

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")]
9use {derive_deftly::Deftly, tor_rpcbase::templates::*};
10
11use crate::address::{IntoTorAddr, ResolveInstructions, StreamInstructions};
12
13use crate::config::{
14    ClientAddrConfig, SoftwareStatusOverrideConfig, StreamTimeoutConfig, TorClientConfig,
15};
16use safelog::{Sensitive, sensitive};
17use tor_async_utils::{DropNotifyWatchSender, PostageWatchSenderExt};
18use tor_circmgr::ClientDataTunnel;
19use tor_circmgr::isolation::{Isolation, StreamIsolation};
20use tor_circmgr::{IsolationToken, TargetPort, isolation::StreamIsolationBuilder};
21use tor_config::MutCfg;
22#[cfg(feature = "bridge-client")]
23use tor_dirmgr::bridgedesc::BridgeDescMgr;
24use tor_dirmgr::{DirMgrStore, Timeliness};
25use tor_error::{Bug, error_report, internal};
26use tor_guardmgr::{GuardMgr, RetireCircuits};
27use tor_keymgr::Keystore;
28use tor_memquota::MemoryQuotaTracker;
29use tor_netdir::{NetDirProvider, params::NetParameters};
30#[cfg(feature = "onion-service-service")]
31use tor_persist::state_dir::StateDirectory;
32use tor_persist::{FsStateMgr, StateMgr};
33use tor_proto::client::stream::{DataStream, IpVersionPreference, StreamParameters};
34#[cfg(all(
35    any(feature = "native-tls", feature = "rustls"),
36    any(feature = "async-std", feature = "tokio"),
37))]
38use tor_rtcompat::PreferredRuntime;
39use tor_rtcompat::{Runtime, SleepProviderExt};
40#[cfg(feature = "onion-service-client")]
41use {
42    tor_config::BoolOrAuto,
43    tor_hsclient::{HsClientConnector, HsClientDescEncKeypairSpecifier, HsClientSecretKeysBuilder},
44    tor_hscrypto::pk::{HsClientDescEncKey, HsClientDescEncKeypair, HsClientDescEncSecretKey},
45    tor_netdir::DirEvent,
46};
47
48#[cfg(all(feature = "onion-service-service", feature = "experimental-api"))]
49use tor_hsservice::HsIdKeypairSpecifier;
50#[cfg(all(feature = "onion-service-client", feature = "experimental-api"))]
51use {tor_hscrypto::pk::HsId, tor_hscrypto::pk::HsIdKeypair, tor_keymgr::KeystoreSelector};
52
53use tor_keymgr::{ArtiNativeKeystore, KeyMgr, KeyMgrBuilder, config::ArtiKeystoreKind};
54
55#[cfg(feature = "ephemeral-keystore")]
56use tor_keymgr::ArtiEphemeralKeystore;
57
58#[cfg(feature = "ctor-keystore")]
59use tor_keymgr::{CTorClientKeystore, CTorServiceKeystore};
60
61use futures::StreamExt as _;
62use futures::lock::Mutex as AsyncMutex;
63use futures::task::SpawnExt;
64use std::net::IpAddr;
65use std::result::Result as StdResult;
66use std::sync::{Arc, Mutex};
67
68use crate::err::ErrorDetail;
69use crate::{TorClientBuilder, status, util};
70#[cfg(feature = "geoip")]
71use tor_geoip::CountryCode;
72use tor_rtcompat::scheduler::TaskHandle;
73use tracing::{debug, info, instrument};
74
75/// An active client session on the Tor network.
76///
77/// While it's running, it will fetch directory information, build
78/// circuits, and make connections for you.
79///
80/// Cloning this object makes a new reference to the same underlying
81/// handles: it's usually better to clone the `TorClient` than it is to
82/// create a new one.
83///
84/// # In the Arti RPC System
85///
86/// An open client on the Tor network.
87///
88/// A `TorClient` can be used to open anonymous connections,
89/// and (eventually) perform other activities.
90///
91/// You can use an `RpcSession` as a `TorClient`, or use the `isolated_client` method
92/// to create a new `TorClient` whose stream will not share circuits with any other Tor client.
93///
94/// This ObjectID for this object can be used as the target of a SOCKS stream.
95// TODO(nickm): This type now has 5 Arcs inside it, and 2 types that have
96// implicit Arcs inside them! maybe it's time to replace much of the insides of
97// this with an Arc<TorClientInner>?
98#[derive(Clone)]
99#[cfg_attr(
100    feature = "rpc",
101    derive(Deftly),
102    derive_deftly(Object),
103    deftly(rpc(expose_outside_of_session))
104)]
105pub struct TorClient<R: Runtime> {
106    /// Asynchronous runtime object.
107    runtime: R,
108    /// Default isolation token for streams through this client.
109    ///
110    /// This is eventually used for `owner_token` in `tor-circmgr/src/usage.rs`, and is orthogonal
111    /// to the `stream_isolation` which comes from `connect_prefs` (or a passed-in `StreamPrefs`).
112    /// (ie, both must be the same to share a circuit).
113    client_isolation: IsolationToken,
114    /// Connection preferences.  Starts out as `Default`,  Inherited by our clones.
115    connect_prefs: StreamPrefs,
116    /// Memory quota tracker
117    memquota: Arc<MemoryQuotaTracker>,
118    /// Channel manager, used by circuits etc.,
119    ///
120    /// Used directly by client only for reconfiguration.
121    chanmgr: Arc<tor_chanmgr::ChanMgr<R>>,
122    /// Circuit manager for keeping our circuits up to date and building
123    /// them on-demand.
124    circmgr: Arc<tor_circmgr::CircMgr<R>>,
125    /// Directory manager persistent storage.
126    #[cfg_attr(not(feature = "bridge-client"), allow(dead_code))]
127    dirmgr_store: DirMgrStore<R>,
128    /// Directory manager for keeping our directory material up to date.
129    dirmgr: Arc<dyn tor_dirmgr::DirProvider>,
130    /// Bridge descriptor manager
131    ///
132    /// None until we have bootstrapped.
133    ///
134    /// Lock hierarchy: don't acquire this before dormant
135    //
136    // TODO: after or as part of https://gitlab.torproject.org/tpo/core/arti/-/issues/634
137    // this can be   bridge_desc_mgr: BridgeDescMgr<R>>
138    // since BridgeDescMgr is Clone and all its methods take `&self` (it has a lock inside)
139    // Or maybe BridgeDescMgr should not be Clone, since we want to make Weaks of it,
140    // which we can't do when the Arc is inside.
141    #[cfg(feature = "bridge-client")]
142    bridge_desc_mgr: Arc<Mutex<Option<Arc<BridgeDescMgr<R>>>>>,
143    /// Pluggable transport manager.
144    #[cfg(feature = "pt-client")]
145    pt_mgr: Arc<tor_ptmgr::PtMgr<R>>,
146    /// HS client connector
147    #[cfg(feature = "onion-service-client")]
148    hsclient: HsClientConnector<R>,
149    /// Circuit pool for providing onion services with circuits.
150    #[cfg(any(feature = "onion-service-client", feature = "onion-service-service"))]
151    hs_circ_pool: Arc<tor_circmgr::hspool::HsCircPool<R>>,
152    /// A handle to this client's [`InertTorClient`].
153    ///
154    /// Used for accessing the key manager and other persistent state.
155    inert_client: InertTorClient,
156    /// Guard manager
157    #[cfg_attr(not(feature = "bridge-client"), allow(dead_code))]
158    guardmgr: GuardMgr<R>,
159    /// Location on disk where we store persistent data containing both location and Mistrust information.
160    ///
161    ///
162    /// This path is configured via `[storage]` in the config but is not used directly as a
163    /// StateDirectory in most places. Instead, its path and Mistrust information are copied
164    /// to subsystems like `dirmgr`, `keymgr`, and `statemgr` during `TorClient` creation.
165    #[cfg(feature = "onion-service-service")]
166    state_directory: StateDirectory,
167    /// Location on disk where we store persistent data (cooked state manager).
168    statemgr: FsStateMgr,
169    /// Client address configuration
170    addrcfg: Arc<MutCfg<ClientAddrConfig>>,
171    /// Client DNS configuration
172    timeoutcfg: Arc<MutCfg<StreamTimeoutConfig>>,
173    /// Software status configuration.
174    software_status_cfg: Arc<MutCfg<SoftwareStatusOverrideConfig>>,
175    /// Mutex used to serialize concurrent attempts to reconfigure a TorClient.
176    ///
177    /// See [`TorClient::reconfigure`] for more information on its use.
178    reconfigure_lock: Arc<Mutex<()>>,
179
180    /// A stream of bootstrap messages that we can clone when a client asks for
181    /// it.
182    ///
183    /// (We don't need to observe this stream ourselves, since it drops each
184    /// unobserved status change when the next status change occurs.)
185    status_receiver: status::BootstrapEvents,
186
187    /// mutex used to prevent two tasks from trying to bootstrap at once.
188    bootstrap_in_progress: Arc<AsyncMutex<()>>,
189
190    /// Whether or not we should call `bootstrap` before doing things that require
191    /// bootstrapping. If this is `false`, we will just call `wait_for_bootstrap`
192    /// instead.
193    should_bootstrap: BootstrapBehavior,
194
195    /// Shared boolean for whether we're currently in "dormant mode" or not.
196    //
197    // The sent value is `Option`, so that `None` is sent when the sender, here,
198    // is dropped,.  That shuts down the monitoring task.
199    dormant: Arc<Mutex<DropNotifyWatchSender<Option<DormantMode>>>>,
200
201    /// The path resolver given to us by a [`TorClientConfig`].
202    ///
203    /// We must not add our own variables to it since `TorClientConfig` uses it to perform its own
204    /// path expansions. If we added our own variables, it would introduce an inconsistency where
205    /// paths expanded by the `TorClientConfig` would expand differently than when expanded by us.
206    // This is an Arc so that we can make cheap clones of it.
207    path_resolver: Arc<tor_config_path::CfgPathResolver>,
208}
209
210/// A Tor client that is not runnable.
211///
212/// Can be used to access the state that would be used by a running [`TorClient`].
213///
214/// An `InertTorClient` never connects to the network.
215#[derive(Clone)]
216pub struct InertTorClient {
217    /// The key manager.
218    ///
219    /// This is used for retrieving private keys, certificates, and other sensitive data (for
220    /// example, for retrieving the keys necessary for connecting to hidden services that are
221    /// running in restricted discovery mode).
222    ///
223    /// If this crate is compiled _with_ the `keymgr` feature, [`TorClient`] will use a functional
224    /// key manager implementation.
225    ///
226    /// If this crate is compiled _without_ the `keymgr` feature, then [`TorClient`] will use a
227    /// no-op key manager implementation instead.
228    ///
229    /// See the [`KeyMgr`] documentation for more details.
230    keymgr: Option<Arc<KeyMgr>>,
231}
232
233impl InertTorClient {
234    /// Create an `InertTorClient` from a `TorClientConfig`.
235    pub(crate) fn new(config: &TorClientConfig) -> StdResult<Self, ErrorDetail> {
236        let keymgr = Self::create_keymgr(config)?;
237
238        Ok(Self { keymgr })
239    }
240
241    /// Create a [`KeyMgr`] using the specified configuration.
242    ///
243    /// Returns `Ok(None)` if keystore use is disabled.
244    fn create_keymgr(config: &TorClientConfig) -> StdResult<Option<Arc<KeyMgr>>, ErrorDetail> {
245        let keystore = config.storage.keystore();
246        let permissions = config.storage.permissions();
247        let primary_store: Box<dyn Keystore> = match keystore.primary_kind() {
248            Some(ArtiKeystoreKind::Native) => {
249                let (state_dir, _mistrust) = config.state_dir()?;
250                let key_store_dir = state_dir.join("keystore");
251
252                let native_store =
253                    ArtiNativeKeystore::from_path_and_mistrust(&key_store_dir, permissions)?;
254                info!("Using keystore from {key_store_dir:?}");
255
256                Box::new(native_store)
257            }
258            #[cfg(feature = "ephemeral-keystore")]
259            Some(ArtiKeystoreKind::Ephemeral) => {
260                // TODO: make the keystore ID somehow configurable
261                let ephemeral_store: ArtiEphemeralKeystore =
262                    ArtiEphemeralKeystore::new("ephemeral".to_string());
263                Box::new(ephemeral_store)
264            }
265            None => {
266                info!("Running without a keystore");
267                return Ok(None);
268            }
269            ty => return Err(internal!("unrecognized keystore type {ty:?}").into()),
270        };
271
272        let mut builder = KeyMgrBuilder::default().primary_store(primary_store);
273
274        #[cfg(feature = "ctor-keystore")]
275        for config in config.storage.keystore().ctor_svc_stores() {
276            let store: Box<dyn Keystore> = Box::new(CTorServiceKeystore::from_path_and_mistrust(
277                config.path(),
278                permissions,
279                config.id().clone(),
280                // TODO: these nicknames should be cross-checked with configured
281                // svc nicknames as part of config validation!!!
282                config.nickname().clone(),
283            )?);
284
285            builder.secondary_stores().push(store);
286        }
287
288        #[cfg(feature = "ctor-keystore")]
289        for config in config.storage.keystore().ctor_client_stores() {
290            let store: Box<dyn Keystore> = Box::new(CTorClientKeystore::from_path_and_mistrust(
291                config.path(),
292                permissions,
293                config.id().clone(),
294            )?);
295
296            builder.secondary_stores().push(store);
297        }
298
299        let keymgr = builder
300            .build()
301            .map_err(|_| internal!("failed to build keymgr"))?;
302        Ok(Some(Arc::new(keymgr)))
303    }
304
305    /// Generate a service discovery keypair for connecting to a hidden service running in
306    /// "restricted discovery" mode.
307    ///
308    /// See [`TorClient::generate_service_discovery_key`].
309    //
310    // TODO: decide whether this should use get_or_generate before making it
311    // non-experimental
312    #[cfg(all(
313        feature = "onion-service-client",
314        feature = "experimental-api",
315        feature = "keymgr"
316    ))]
317    #[cfg_attr(
318        docsrs,
319        doc(cfg(all(
320            feature = "onion-service-client",
321            feature = "experimental-api",
322            feature = "keymgr"
323        )))
324    )]
325    pub fn generate_service_discovery_key(
326        &self,
327        selector: KeystoreSelector,
328        hsid: HsId,
329    ) -> crate::Result<HsClientDescEncKey> {
330        let mut rng = tor_llcrypto::rng::CautiousRng;
331        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
332        let key = self
333            .keymgr
334            .as_ref()
335            .ok_or(ErrorDetail::KeystoreRequired {
336                action: "generate client service discovery key",
337            })?
338            .generate::<HsClientDescEncKeypair>(
339                &spec, selector, &mut rng, false, /* overwrite */
340            )?;
341
342        Ok(key.public().clone())
343    }
344
345    /// Rotate the service discovery keypair for connecting to a hidden service running in
346    /// "restricted discovery" mode.
347    ///
348    /// See [`TorClient::rotate_service_discovery_key`].
349    #[cfg(all(
350        feature = "onion-service-client",
351        feature = "experimental-api",
352        feature = "keymgr"
353    ))]
354    #[cfg_attr(
355        docsrs,
356        doc(cfg(all(
357            feature = "onion-service-client",
358            feature = "experimental-api",
359            feature = "keymgr"
360        )))
361    )]
362    pub fn rotate_service_discovery_key(
363        &self,
364        selector: KeystoreSelector,
365        hsid: HsId,
366    ) -> crate::Result<HsClientDescEncKey> {
367        let mut rng = tor_llcrypto::rng::CautiousRng;
368        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
369        let key = self
370            .keymgr
371            .as_ref()
372            .ok_or(ErrorDetail::KeystoreRequired {
373                action: "rotate client service discovery key",
374            })?
375            .generate::<HsClientDescEncKeypair>(
376                &spec, selector, &mut rng, true, /* overwrite */
377            )?;
378
379        Ok(key.public().clone())
380    }
381
382    /// Insert a service discovery secret key for connecting to a hidden service running in
383    /// "restricted discovery" mode
384    ///
385    /// See [`TorClient::insert_service_discovery_key`].
386    #[cfg(all(
387        feature = "onion-service-client",
388        feature = "experimental-api",
389        feature = "keymgr"
390    ))]
391    #[cfg_attr(
392        docsrs,
393        doc(cfg(all(
394            feature = "onion-service-client",
395            feature = "experimental-api",
396            feature = "keymgr"
397        )))
398    )]
399    pub fn insert_service_discovery_key(
400        &self,
401        selector: KeystoreSelector,
402        hsid: HsId,
403        hs_client_desc_enc_secret_key: HsClientDescEncSecretKey,
404    ) -> crate::Result<HsClientDescEncKey> {
405        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
406        let client_desc_enc_key = HsClientDescEncKey::from(&hs_client_desc_enc_secret_key);
407        let client_desc_enc_keypair =
408            HsClientDescEncKeypair::new(client_desc_enc_key.clone(), hs_client_desc_enc_secret_key);
409        let _key = self
410            .keymgr
411            .as_ref()
412            .ok_or(ErrorDetail::KeystoreRequired {
413                action: "insert client service discovery key",
414            })?
415            .insert::<HsClientDescEncKeypair>(client_desc_enc_keypair, &spec, selector, false)?;
416        Ok(client_desc_enc_key)
417    }
418
419    /// Return the service discovery public key for the service with the specified `hsid`.
420    ///
421    /// See [`TorClient::get_service_discovery_key`].
422    #[cfg(all(feature = "onion-service-client", feature = "experimental-api"))]
423    #[cfg_attr(
424        docsrs,
425        doc(cfg(all(feature = "onion-service-client", feature = "experimental-api")))
426    )]
427    pub fn get_service_discovery_key(
428        &self,
429        hsid: HsId,
430    ) -> crate::Result<Option<HsClientDescEncKey>> {
431        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
432        let key = self
433            .keymgr
434            .as_ref()
435            .ok_or(ErrorDetail::KeystoreRequired {
436                action: "get client service discovery key",
437            })?
438            .get::<HsClientDescEncKeypair>(&spec)?
439            .map(|key| key.public().clone());
440
441        Ok(key)
442    }
443
444    /// Removes the service discovery keypair for the service with the specified `hsid`.
445    ///
446    /// See [`TorClient::remove_service_discovery_key`].
447    #[cfg(all(
448        feature = "onion-service-client",
449        feature = "experimental-api",
450        feature = "keymgr"
451    ))]
452    #[cfg_attr(
453        docsrs,
454        doc(cfg(all(
455            feature = "onion-service-client",
456            feature = "experimental-api",
457            feature = "keymgr"
458        )))
459    )]
460    pub fn remove_service_discovery_key(
461        &self,
462        selector: KeystoreSelector,
463        hsid: HsId,
464    ) -> crate::Result<Option<()>> {
465        let spec = HsClientDescEncKeypairSpecifier::new(hsid);
466        let result = self
467            .keymgr
468            .as_ref()
469            .ok_or(ErrorDetail::KeystoreRequired {
470                action: "remove client service discovery key",
471            })?
472            .remove::<HsClientDescEncKeypair>(&spec, selector)?;
473        match result {
474            Some(_) => Ok(Some(())),
475            None => Ok(None),
476        }
477    }
478
479    /// Getter for keymgr.
480    #[cfg(feature = "onion-service-cli-extra")]
481    pub fn keymgr(&self) -> crate::Result<&KeyMgr> {
482        Ok(self.keymgr.as_ref().ok_or(ErrorDetail::KeystoreRequired {
483            action: "get key manager handle",
484        })?)
485    }
486}
487
488/// Preferences for whether a [`TorClient`] should bootstrap on its own or not.
489#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
490#[non_exhaustive]
491pub enum BootstrapBehavior {
492    /// Bootstrap the client automatically when requests are made that require the client to be
493    /// bootstrapped.
494    #[default]
495    OnDemand,
496    /// Make no attempts to automatically bootstrap. [`TorClient::bootstrap`] must be manually
497    /// invoked in order for the [`TorClient`] to become useful.
498    ///
499    /// Attempts to use the client (e.g. by creating connections or resolving hosts over the Tor
500    /// network) before calling [`bootstrap`](TorClient::bootstrap) will fail, and
501    /// return an error that has kind [`ErrorKind::BootstrapRequired`](crate::ErrorKind::BootstrapRequired).
502    Manual,
503}
504
505/// What level of sleep to put a Tor client into.
506#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
507#[non_exhaustive]
508pub enum DormantMode {
509    /// The client functions as normal, and background tasks run periodically.
510    #[default]
511    Normal,
512    /// Background tasks are suspended, conserving CPU usage. Attempts to use the client will
513    /// wake it back up again.
514    Soft,
515}
516
517/// Preferences for how to route a stream over the Tor network.
518#[derive(Debug, Default, Clone)]
519pub struct StreamPrefs {
520    /// What kind of IPv6/IPv4 we'd prefer, and how strongly.
521    ip_ver_pref: IpVersionPreference,
522    /// How should we isolate connection(s)?
523    isolation: StreamIsolationPreference,
524    /// Whether to return the stream optimistically.
525    optimistic_stream: bool,
526    // TODO GEOIP Ideally this would be unconditional, with CountryCode maybe being Void
527    // This probably applies in many other places, so probably:   git grep 'cfg.*geoip'
528    // and consider each one with a view to making it unconditional.  Background:
529    //   https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/1537#note_2935256
530    //   https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/1537#note_2942214
531    #[cfg(feature = "geoip")]
532    /// A country to restrict the exit relay's location to.
533    country_code: Option<CountryCode>,
534    /// Whether to try to make connections to onion services.
535    ///
536    /// `Auto` means to use the client configuration.
537    #[cfg(feature = "onion-service-client")]
538    pub(crate) connect_to_onion_services: BoolOrAuto,
539}
540
541/// Record of how we are isolating connections
542#[derive(Debug, Default, Clone)]
543enum StreamIsolationPreference {
544    /// No additional isolation
545    #[default]
546    None,
547    /// Isolation parameter to use for connections
548    Explicit(Box<dyn Isolation>),
549    /// Isolate every connection!
550    EveryStream,
551}
552
553impl From<DormantMode> for tor_chanmgr::Dormancy {
554    fn from(dormant: DormantMode) -> tor_chanmgr::Dormancy {
555        match dormant {
556            DormantMode::Normal => tor_chanmgr::Dormancy::Active,
557            DormantMode::Soft => tor_chanmgr::Dormancy::Dormant,
558        }
559    }
560}
561#[cfg(feature = "bridge-client")]
562impl From<DormantMode> for tor_dirmgr::bridgedesc::Dormancy {
563    fn from(dormant: DormantMode) -> tor_dirmgr::bridgedesc::Dormancy {
564        match dormant {
565            DormantMode::Normal => tor_dirmgr::bridgedesc::Dormancy::Active,
566            DormantMode::Soft => tor_dirmgr::bridgedesc::Dormancy::Dormant,
567        }
568    }
569}
570
571impl StreamPrefs {
572    /// Construct a new StreamPrefs.
573    pub fn new() -> Self {
574        Self::default()
575    }
576
577    /// Indicate that a stream may be made over IPv4 or IPv6, but that
578    /// we'd prefer IPv6.
579    pub fn ipv6_preferred(&mut self) -> &mut Self {
580        self.ip_ver_pref = IpVersionPreference::Ipv6Preferred;
581        self
582    }
583
584    /// Indicate that a stream may only be made over IPv6.
585    ///
586    /// When this option is set, we will only pick exit relays that
587    /// support IPv6, and we will tell them to only give us IPv6
588    /// connections.
589    pub fn ipv6_only(&mut self) -> &mut Self {
590        self.ip_ver_pref = IpVersionPreference::Ipv6Only;
591        self
592    }
593
594    /// Indicate that a stream may be made over IPv4 or IPv6, but that
595    /// we'd prefer IPv4.
596    ///
597    /// This is the default.
598    pub fn ipv4_preferred(&mut self) -> &mut Self {
599        self.ip_ver_pref = IpVersionPreference::Ipv4Preferred;
600        self
601    }
602
603    /// Indicate that a stream may only be made over IPv4.
604    ///
605    /// When this option is set, we will only pick exit relays that
606    /// support IPv4, and we will tell them to only give us IPv4
607    /// connections.
608    pub fn ipv4_only(&mut self) -> &mut Self {
609        self.ip_ver_pref = IpVersionPreference::Ipv4Only;
610        self
611    }
612
613    /// Indicate that a stream should appear to come from the given country.
614    ///
615    /// When this option is set, we will only pick exit relays that
616    /// have an IP address that matches the country in our GeoIP database.
617    #[cfg(feature = "geoip")]
618    #[cfg_attr(docsrs, doc(cfg(feature = "geoip")))]
619    pub fn exit_country(&mut self, country_code: CountryCode) -> &mut Self {
620        self.country_code = Some(country_code);
621        self
622    }
623
624    /// Indicate that we don't care which country a stream appears to come from.
625    ///
626    /// This is available even in the case where GeoIP support is compiled out,
627    /// to make things easier.
628    pub fn any_exit_country(&mut self) -> &mut Self {
629        #[cfg(feature = "geoip")]
630        {
631            self.country_code = None;
632        }
633        self
634    }
635
636    /// Indicate that the stream should be opened "optimistically".
637    ///
638    /// By default, streams are not "optimistic". When you call
639    /// [`TorClient::connect()`], it won't give you a stream until the
640    /// exit node has confirmed that it has successfully opened a
641    /// connection to your target address.  It's safer to wait in this
642    /// way, but it is slower: it takes an entire round trip to get
643    /// your confirmation.
644    ///
645    /// If a stream _is_ configured to be "optimistic", on the other
646    /// hand, then `TorClient::connect()` will return the stream
647    /// immediately, without waiting for an answer from the exit.  You
648    /// can start sending data on the stream right away, though of
649    /// course this data will be lost if the connection is not
650    /// actually successful.
651    pub fn optimistic(&mut self) -> &mut Self {
652        self.optimistic_stream = true;
653        self
654    }
655
656    /// Return true if this stream has been configured as "optimistic".
657    ///
658    /// See [`StreamPrefs::optimistic`] for more info.
659    pub fn is_optimistic(&self) -> bool {
660        self.optimistic_stream
661    }
662
663    /// Indicate whether connection to a hidden service (`.onion` service) should be allowed
664    ///
665    /// If `Explicit(false)`, attempts to connect to Onion Services will be forced to fail with
666    /// an error of kind [`InvalidStreamTarget`](crate::ErrorKind::InvalidStreamTarget).
667    ///
668    /// If `Explicit(true)`, Onion Service connections are enabled.
669    ///
670    /// If `Auto`, the behaviour depends on the `address_filter.allow_onion_addrs`
671    /// configuration option, which is in turn enabled by default.
672    #[cfg(feature = "onion-service-client")]
673    pub fn connect_to_onion_services(
674        &mut self,
675        connect_to_onion_services: BoolOrAuto,
676    ) -> &mut Self {
677        self.connect_to_onion_services = connect_to_onion_services;
678        self
679    }
680    /// Return a TargetPort to describe what kind of exit policy our
681    /// target circuit needs to support.
682    fn wrap_target_port(&self, port: u16) -> TargetPort {
683        match self.ip_ver_pref {
684            IpVersionPreference::Ipv6Only => TargetPort::ipv6(port),
685            _ => TargetPort::ipv4(port),
686        }
687    }
688
689    /// Return a new StreamParameters based on this configuration.
690    fn stream_parameters(&self) -> StreamParameters {
691        let mut params = StreamParameters::default();
692        params
693            .ip_version(self.ip_ver_pref)
694            .optimistic(self.optimistic_stream);
695        params
696    }
697
698    /// Indicate that connections with these preferences should have their own isolation group
699    ///
700    /// This is a convenience method which creates a fresh [`IsolationToken`]
701    /// and sets it for these preferences.
702    ///
703    /// This connection preference is orthogonal to isolation established by
704    /// [`TorClient::isolated_client`].  Connections made with an `isolated_client` (and its
705    /// clones) will not share circuits with the original client, even if the same
706    /// `isolation` is specified via the `ConnectionPrefs` in force.
707    pub fn new_isolation_group(&mut self) -> &mut Self {
708        self.isolation = StreamIsolationPreference::Explicit(Box::new(IsolationToken::new()));
709        self
710    }
711
712    /// Indicate which other connections might use the same circuit
713    /// as this one.
714    ///
715    /// By default all connections made on all clones of a `TorClient` may share connections.
716    /// Connections made with a particular `isolation` may share circuits with each other.
717    ///
718    /// This connection preference is orthogonal to isolation established by
719    /// [`TorClient::isolated_client`].  Connections made with an `isolated_client` (and its
720    /// clones) will not share circuits with the original client, even if the same
721    /// `isolation` is specified via the `ConnectionPrefs` in force.
722    pub fn set_isolation<T>(&mut self, isolation: T) -> &mut Self
723    where
724        T: Into<Box<dyn Isolation>>,
725    {
726        self.isolation = StreamIsolationPreference::Explicit(isolation.into());
727        self
728    }
729
730    /// Indicate that no connection should share a circuit with any other.
731    ///
732    /// **Use with care:** This is likely to have poor performance, and imposes a much greater load
733    /// on the Tor network.  Use this option only to make small numbers of connections each of
734    /// which needs to be isolated from all other connections.
735    ///
736    /// (Don't just use this as a "get more privacy!!" method: the circuits
737    /// that it put connections on will have no more privacy than any other
738    /// circuits.  The only benefit is that these circuits will not be shared
739    /// by multiple streams.)
740    ///
741    /// This can be undone by calling `set_isolation` or `new_isolation_group` on these
742    /// preferences.
743    pub fn isolate_every_stream(&mut self) -> &mut Self {
744        self.isolation = StreamIsolationPreference::EveryStream;
745        self
746    }
747
748    /// Return an [`Isolation`] which separates according to these `StreamPrefs` (only)
749    ///
750    /// This describes which connections or operations might use
751    /// the same circuit(s) as this one.
752    ///
753    /// Since this doesn't have access to the `TorClient`,
754    /// it doesn't separate streams which ought to be separated because of
755    /// the way their `TorClient`s are isolated.
756    /// For that, use [`TorClient::isolation`].
757    fn prefs_isolation(&self) -> Option<Box<dyn Isolation>> {
758        use StreamIsolationPreference as SIP;
759        match self.isolation {
760            SIP::None => None,
761            SIP::Explicit(ref ig) => Some(ig.clone()),
762            SIP::EveryStream => Some(Box::new(IsolationToken::new())),
763        }
764    }
765
766    // TODO: Add some way to be IPFlexible, and require exit to support both.
767}
768
769#[cfg(all(
770    any(feature = "native-tls", feature = "rustls"),
771    any(feature = "async-std", feature = "tokio")
772))]
773impl TorClient<PreferredRuntime> {
774    /// Bootstrap a connection to the Tor network, using the provided `config`.
775    ///
776    /// Returns a client once there is enough directory material to
777    /// connect safely over the Tor network.
778    ///
779    /// Consider using [`TorClient::builder`] for more fine-grained control.
780    ///
781    /// # Panics
782    ///
783    /// If Tokio is being used (the default), panics if created outside the context of a currently
784    /// running Tokio runtime. See the documentation for [`PreferredRuntime::current`] for
785    /// more information.
786    ///
787    /// If using `async-std`, either take care to ensure Arti is not compiled with Tokio support,
788    /// or manually create an `async-std` runtime using [`tor_rtcompat`] and use it with
789    /// [`TorClient::with_runtime`].
790    ///
791    /// # Do not fork
792    ///
793    /// The process [**may not fork**](tor_rtcompat#do-not-fork)
794    /// (except, very carefully, before exec)
795    /// after calling this function, because it creates a [`PreferredRuntime`].
796    pub async fn create_bootstrapped(config: TorClientConfig) -> crate::Result<Self> {
797        let runtime = PreferredRuntime::current()
798            .expect("TorClient could not get an asynchronous runtime; are you running in the right context?");
799
800        Self::with_runtime(runtime)
801            .config(config)
802            .create_bootstrapped()
803            .await
804    }
805
806    /// Return a new builder for creating TorClient objects.
807    ///
808    /// If you want to make a [`TorClient`] synchronously, this is what you want; call
809    /// `TorClientBuilder::create_unbootstrapped` on the returned builder.
810    ///
811    /// # Panics
812    ///
813    /// If Tokio is being used (the default), panics if created outside the context of a currently
814    /// running Tokio runtime. See the documentation for `tokio::runtime::Handle::current` for
815    /// more information.
816    ///
817    /// If using `async-std`, either take care to ensure Arti is not compiled with Tokio support,
818    /// or manually create an `async-std` runtime using [`tor_rtcompat`] and use it with
819    /// [`TorClient::with_runtime`].
820    ///
821    /// # Do not fork
822    ///
823    /// The process [**may not fork**](tor_rtcompat#do-not-fork)
824    /// (except, very carefully, before exec)
825    /// after calling this function, because it creates a [`PreferredRuntime`].
826    pub fn builder() -> TorClientBuilder<PreferredRuntime> {
827        let runtime = PreferredRuntime::current()
828            .expect("TorClient could not get an asynchronous runtime; are you running in the right context?");
829
830        TorClientBuilder::new(runtime)
831    }
832}
833
834impl<R: Runtime> TorClient<R> {
835    /// Return a new builder for creating TorClient objects, with a custom provided [`Runtime`].
836    ///
837    /// See the [`tor_rtcompat`] crate for more information on custom runtimes.
838    pub fn with_runtime(runtime: R) -> TorClientBuilder<R> {
839        TorClientBuilder::new(runtime)
840    }
841
842    /// Implementation of `create_unbootstrapped`, split out in order to avoid manually specifying
843    /// double error conversions.
844    pub(crate) fn create_inner(
845        runtime: R,
846        config: &TorClientConfig,
847        autobootstrap: BootstrapBehavior,
848        dirmgr_builder: &dyn crate::builder::DirProviderBuilder<R>,
849        dirmgr_extensions: tor_dirmgr::config::DirMgrExtensions,
850    ) -> StdResult<Self, ErrorDetail> {
851        if crate::util::running_as_setuid() {
852            return Err(tor_error::bad_api_usage!(
853                "Arti does not support running in a setuid or setgid context."
854            )
855            .into());
856        }
857
858        let memquota = MemoryQuotaTracker::new(&runtime, config.system.memory.clone())?;
859
860        let path_resolver = Arc::new(config.path_resolver.clone());
861
862        let (state_dir, mistrust) = config.state_dir()?;
863        #[cfg(feature = "onion-service-service")]
864        let state_directory =
865            StateDirectory::new(&state_dir, mistrust).map_err(ErrorDetail::StateAccess)?;
866
867        let dormant = DormantMode::Normal;
868        let dir_cfg = {
869            let mut c: tor_dirmgr::DirMgrConfig = config.dir_mgr_config()?;
870            c.extensions = dirmgr_extensions;
871            c
872        };
873        let statemgr = FsStateMgr::from_path_and_mistrust(&state_dir, mistrust)
874            .map_err(ErrorDetail::StateMgrSetup)?;
875        // Try to take state ownership early, so we'll know if we have it.
876        // Note that this `try_lock()` may return `Ok` even if we can't acquire the lock.
877        // (At this point we don't yet care if we have it.)
878        let _ignore_status = statemgr.try_lock().map_err(ErrorDetail::StateMgrSetup)?;
879
880        let addr_cfg = config.address_filter.clone();
881
882        let (status_sender, status_receiver) = postage::watch::channel();
883        let status_receiver = status::BootstrapEvents {
884            inner: status_receiver,
885        };
886        let chanmgr = Arc::new(tor_chanmgr::ChanMgr::new(
887            runtime.clone(),
888            &config.channel,
889            dormant.into(),
890            &NetParameters::from_map(&config.override_net_params),
891            memquota.clone(),
892            None,
893        ));
894        let guardmgr = tor_guardmgr::GuardMgr::new(runtime.clone(), statemgr.clone(), config)
895            .map_err(ErrorDetail::GuardMgrSetup)?;
896
897        #[cfg(feature = "pt-client")]
898        let pt_mgr = {
899            let pt_state_dir = state_dir.as_path().join("pt_state");
900            config.storage.permissions().make_directory(&pt_state_dir)?;
901
902            let mgr = Arc::new(tor_ptmgr::PtMgr::new(
903                config.bridges.transports.clone(),
904                pt_state_dir,
905                Arc::clone(&path_resolver),
906                runtime.clone(),
907            )?);
908
909            chanmgr.set_pt_mgr(mgr.clone());
910
911            mgr
912        };
913
914        let circmgr = Arc::new(
915            tor_circmgr::CircMgr::new(
916                config,
917                statemgr.clone(),
918                &runtime,
919                Arc::clone(&chanmgr),
920                &guardmgr,
921            )
922            .map_err(ErrorDetail::CircMgrSetup)?,
923        );
924
925        let timeout_cfg = config.stream_timeouts.clone();
926
927        let dirmgr_store =
928            DirMgrStore::new(&dir_cfg, runtime.clone(), false).map_err(ErrorDetail::DirMgrSetup)?;
929        let dirmgr = dirmgr_builder
930            .build(
931                runtime.clone(),
932                dirmgr_store.clone(),
933                Arc::clone(&circmgr),
934                dir_cfg,
935            )
936            .map_err(crate::Error::into_detail)?;
937
938        let software_status_cfg = Arc::new(MutCfg::new(config.use_obsolete_software.clone()));
939        let rtclone = runtime.clone();
940        #[allow(clippy::print_stderr)]
941        crate::protostatus::enforce_protocol_recommendations(
942            &runtime,
943            Arc::clone(&dirmgr),
944            crate::software_release_date(),
945            crate::supported_protocols(),
946            Arc::clone(&software_status_cfg),
947            // TODO #1932: It would be nice to have a cleaner shutdown mechanism here,
948            // but that will take some work.
949            |fatal| async move {
950                use tor_error::ErrorReport as _;
951                // We already logged this error, but let's tell stderr too.
952                eprintln!(
953                    "Shutting down because of unsupported software version.\nError was:\n{}",
954                    fatal.report(),
955                );
956                if let Some(hint) = crate::err::Error::from(fatal).hint() {
957                    eprintln!("{}", hint);
958                }
959                // Give the tracing module a while to flush everything, since it has no built-in
960                // flush function.
961                rtclone.sleep(std::time::Duration::new(5, 0)).await;
962                std::process::exit(1);
963            },
964        )?;
965
966        let mut periodic_task_handles = circmgr
967            .launch_background_tasks(&runtime, &dirmgr, statemgr.clone())
968            .map_err(ErrorDetail::CircMgrSetup)?;
969        periodic_task_handles.extend(dirmgr.download_task_handle());
970
971        periodic_task_handles.extend(
972            chanmgr
973                .launch_background_tasks(&runtime, dirmgr.clone().upcast_arc())
974                .map_err(ErrorDetail::ChanMgrSetup)?,
975        );
976
977        let (dormant_send, dormant_recv) = postage::watch::channel_with(Some(dormant));
978        let dormant_send = DropNotifyWatchSender::new(dormant_send);
979        #[cfg(feature = "bridge-client")]
980        let bridge_desc_mgr = Arc::new(Mutex::new(None));
981
982        #[cfg(any(feature = "onion-service-client", feature = "onion-service-service"))]
983        let hs_circ_pool = {
984            let circpool = Arc::new(tor_circmgr::hspool::HsCircPool::new(&circmgr));
985            circpool
986                .launch_background_tasks(&runtime, &dirmgr.clone().upcast_arc())
987                .map_err(ErrorDetail::CircMgrSetup)?;
988            circpool
989        };
990
991        #[cfg(feature = "onion-service-client")]
992        let hsclient = {
993            // Prompt the hs connector to do its data housekeeping when we get a new consensus.
994            // That's a time we're doing a bunch of thinking anyway, and it's not very frequent.
995            let housekeeping = dirmgr.events().filter_map(|event| async move {
996                match event {
997                    DirEvent::NewConsensus => Some(()),
998                    _ => None,
999                }
1000            });
1001            let housekeeping = Box::pin(housekeeping);
1002
1003            HsClientConnector::new(runtime.clone(), hs_circ_pool.clone(), config, housekeeping)?
1004        };
1005
1006        runtime
1007            .spawn(tasks_monitor_dormant(
1008                dormant_recv,
1009                dirmgr.clone().upcast_arc(),
1010                chanmgr.clone(),
1011                #[cfg(feature = "bridge-client")]
1012                bridge_desc_mgr.clone(),
1013                periodic_task_handles,
1014            ))
1015            .map_err(|e| ErrorDetail::from_spawn("periodic task dormant monitor", e))?;
1016
1017        let conn_status = chanmgr.bootstrap_events();
1018        let dir_status = dirmgr.bootstrap_events();
1019        let skew_status = circmgr.skew_events();
1020        runtime
1021            .spawn(status::report_status(
1022                status_sender,
1023                conn_status,
1024                dir_status,
1025                skew_status,
1026            ))
1027            .map_err(|e| ErrorDetail::from_spawn("top-level status reporter", e))?;
1028
1029        let client_isolation = IsolationToken::new();
1030        let inert_client = InertTorClient::new(config)?;
1031
1032        Ok(TorClient {
1033            runtime,
1034            client_isolation,
1035            connect_prefs: Default::default(),
1036            memquota,
1037            chanmgr,
1038            circmgr,
1039            dirmgr_store,
1040            dirmgr,
1041            #[cfg(feature = "bridge-client")]
1042            bridge_desc_mgr,
1043            #[cfg(feature = "pt-client")]
1044            pt_mgr,
1045            #[cfg(feature = "onion-service-client")]
1046            hsclient,
1047            #[cfg(any(feature = "onion-service-client", feature = "onion-service-service"))]
1048            hs_circ_pool,
1049            inert_client,
1050            guardmgr,
1051            statemgr,
1052            addrcfg: Arc::new(addr_cfg.into()),
1053            timeoutcfg: Arc::new(timeout_cfg.into()),
1054            reconfigure_lock: Arc::new(Mutex::new(())),
1055            status_receiver,
1056            bootstrap_in_progress: Arc::new(AsyncMutex::new(())),
1057            should_bootstrap: autobootstrap,
1058            dormant: Arc::new(Mutex::new(dormant_send)),
1059            #[cfg(feature = "onion-service-service")]
1060            state_directory,
1061            path_resolver,
1062            software_status_cfg,
1063        })
1064    }
1065
1066    /// Bootstrap a connection to the Tor network, with a client created by `create_unbootstrapped`.
1067    ///
1068    /// Since cloned copies of a `TorClient` share internal state, you can bootstrap a client by
1069    /// cloning it and running this function in a background task (or similar). This function
1070    /// only needs to be called on one client in order to bootstrap all of its clones.
1071    ///
1072    /// Returns once there is enough directory material to connect safely over the Tor network.
1073    /// If the client or one of its clones has already been bootstrapped, returns immediately with
1074    /// success. If a bootstrap is in progress, waits for it to finish, then retries it if it
1075    /// failed (returning success if it succeeded).
1076    ///
1077    /// Bootstrap progress can be tracked by listening to the event receiver returned by
1078    /// [`bootstrap_events`](TorClient::bootstrap_events).
1079    ///
1080    /// # Failures
1081    ///
1082    /// If the bootstrapping process fails, returns an error. This function can safely be called
1083    /// again later to attempt to bootstrap another time.
1084    #[instrument(skip_all, level = "trace")]
1085    pub async fn bootstrap(&self) -> crate::Result<()> {
1086        self.bootstrap_inner().await.map_err(ErrorDetail::into)
1087    }
1088
1089    /// Implementation of `bootstrap`, split out in order to avoid manually specifying
1090    /// double error conversions.
1091    async fn bootstrap_inner(&self) -> StdResult<(), ErrorDetail> {
1092        // Make sure we have a bridge descriptor manager, which is active iff required
1093        #[cfg(feature = "bridge-client")]
1094        {
1095            let mut dormant = self.dormant.lock().expect("dormant lock poisoned");
1096            let dormant = dormant.borrow();
1097            let dormant = dormant.ok_or_else(|| internal!("dormant dropped"))?.into();
1098
1099            let mut bdm = self.bridge_desc_mgr.lock().expect("bdm lock poisoned");
1100            if bdm.is_none() {
1101                let new_bdm = Arc::new(BridgeDescMgr::new(
1102                    &Default::default(),
1103                    self.runtime.clone(),
1104                    self.dirmgr_store.clone(),
1105                    self.circmgr.clone(),
1106                    dormant,
1107                )?);
1108                self.guardmgr
1109                    .install_bridge_desc_provider(&(new_bdm.clone() as _))
1110                    .map_err(ErrorDetail::GuardMgrSetup)?;
1111                // If ^ that fails, we drop the BridgeDescMgr again.  It may do some
1112                // work but will hopefully eventually quit.
1113                *bdm = Some(new_bdm);
1114            }
1115        }
1116
1117        // Wait for an existing bootstrap attempt to finish first.
1118        //
1119        // This is a futures::lock::Mutex, so it's okay to await while we hold it.
1120        let _bootstrap_lock = self.bootstrap_in_progress.lock().await;
1121
1122        if self
1123            .statemgr
1124            .try_lock()
1125            .map_err(ErrorDetail::StateAccess)?
1126            .held()
1127        {
1128            debug!("It appears we have the lock on our state files.");
1129        } else {
1130            info!(
1131                "Another process has the lock on our state files. We'll proceed in read-only mode."
1132            );
1133        }
1134
1135        // If we fail to bootstrap (i.e. we return before the disarm() point below), attempt to
1136        // unlock the state files.
1137        let unlock_guard = util::StateMgrUnlockGuard::new(&self.statemgr);
1138
1139        self.dirmgr
1140            .bootstrap()
1141            .await
1142            .map_err(ErrorDetail::DirMgrBootstrap)?;
1143
1144        // Since we succeeded, disarm the unlock guard.
1145        unlock_guard.disarm();
1146
1147        Ok(())
1148    }
1149
1150    /// ## For `BootstrapBehavior::OnDemand` clients
1151    ///
1152    /// Initiate a bootstrap by calling `bootstrap` (which is idempotent, so attempts to
1153    /// bootstrap twice will just do nothing).
1154    ///
1155    /// ## For `BootstrapBehavior::Manual` clients
1156    ///
1157    /// Check whether a bootstrap is in progress; if one is, wait until it finishes
1158    /// and then return. (Otherwise, return immediately.)
1159    #[instrument(skip_all, level = "trace")]
1160    async fn wait_for_bootstrap(&self) -> StdResult<(), ErrorDetail> {
1161        match self.should_bootstrap {
1162            BootstrapBehavior::OnDemand => {
1163                self.bootstrap_inner().await?;
1164            }
1165            BootstrapBehavior::Manual => {
1166                // Grab the lock, and immediately release it.  That will ensure that nobody else is trying to bootstrap.
1167                self.bootstrap_in_progress.lock().await;
1168            }
1169        }
1170        self.dormant
1171            .lock()
1172            .map_err(|_| internal!("dormant poisoned"))?
1173            .try_maybe_send(|dormant| {
1174                Ok::<_, Bug>(Some({
1175                    match dormant.ok_or_else(|| internal!("dormant dropped"))? {
1176                        DormantMode::Soft => DormantMode::Normal,
1177                        other @ DormantMode::Normal => other,
1178                    }
1179                }))
1180            })?;
1181        Ok(())
1182    }
1183
1184    /// Change the configuration of this TorClient to `new_config`.
1185    ///
1186    /// The `how` describes whether to perform an all-or-nothing
1187    /// reconfiguration: either all of the configuration changes will be
1188    /// applied, or none will. If you have disabled all-or-nothing changes, then
1189    /// only fatal errors will be reported in this function's return value.
1190    ///
1191    /// This function applies its changes to **all** TorClient instances derived
1192    /// from the same call to `TorClient::create_*`: even ones whose circuits
1193    /// are isolated from this handle.
1194    ///
1195    /// # Limitations
1196    ///
1197    /// Although most options are reconfigurable, there are some whose values
1198    /// can't be changed on an a running TorClient.  Those options (or their
1199    /// sections) are explicitly documented not to be changeable.
1200    /// NOTE: Currently, not all of these non-reconfigurable options are
1201    /// documented. See [arti#1721][arti-1721].
1202    ///
1203    /// [arti-1721]: https://gitlab.torproject.org/tpo/core/arti/-/issues/1721
1204    ///
1205    /// Changing some options do not take effect immediately on all open streams
1206    /// and circuits, but rather affect only future streams and circuits.  Those
1207    /// are also explicitly documented.
1208    #[instrument(skip_all, level = "trace")]
1209    pub fn reconfigure(
1210        &self,
1211        new_config: &TorClientConfig,
1212        how: tor_config::Reconfigure,
1213    ) -> crate::Result<()> {
1214        // We need to hold this lock while we're reconfiguring the client: even
1215        // though the individual fields have their own synchronization, we can't
1216        // safely let two threads change them at once.  If we did, then we'd
1217        // introduce time-of-check/time-of-use bugs in checking our configuration,
1218        // deciding how to change it, then applying the changes.
1219        let guard = self.reconfigure_lock.lock().expect("Poisoned lock");
1220
1221        match how {
1222            tor_config::Reconfigure::AllOrNothing => {
1223                // We have to check before we make any changes.
1224                self.reconfigure_inner(
1225                    new_config,
1226                    tor_config::Reconfigure::CheckAllOrNothing,
1227                    &guard,
1228                )?;
1229            }
1230            tor_config::Reconfigure::CheckAllOrNothing => {}
1231            tor_config::Reconfigure::WarnOnFailures => {}
1232            _ => {}
1233        }
1234
1235        // Actually reconfigure
1236        self.reconfigure_inner(new_config, how, &guard)?;
1237
1238        Ok(())
1239    }
1240
1241    /// This is split out from `reconfigure` so we can do the all-or-nothing
1242    /// check without recursion. the caller to this method must hold the
1243    /// `reconfigure_lock`.
1244    fn reconfigure_inner(
1245        &self,
1246        new_config: &TorClientConfig,
1247        how: tor_config::Reconfigure,
1248        _reconfigure_lock_guard: &std::sync::MutexGuard<'_, ()>,
1249    ) -> crate::Result<()> {
1250        // We ignore 'new_config.path_resolver' here since CfgPathResolver does not impl PartialEq
1251        // and we have no way to compare them, but this field is explicitly documented as being
1252        // non-reconfigurable anyways.
1253
1254        let dir_cfg = new_config.dir_mgr_config().map_err(wrap_err)?;
1255        let state_cfg = new_config
1256            .storage
1257            .expand_state_dir(&self.path_resolver)
1258            .map_err(wrap_err)?;
1259        let addr_cfg = &new_config.address_filter;
1260        let timeout_cfg = &new_config.stream_timeouts;
1261
1262        if state_cfg != self.statemgr.path() {
1263            how.cannot_change("storage.state_dir").map_err(wrap_err)?;
1264        }
1265
1266        self.memquota
1267            .reconfigure(new_config.system.memory.clone(), how)
1268            .map_err(wrap_err)?;
1269
1270        let retire_circuits = self
1271            .circmgr
1272            .reconfigure(new_config, how)
1273            .map_err(wrap_err)?;
1274
1275        #[cfg(any(feature = "onion-service-client", feature = "onion-service-service"))]
1276        if retire_circuits != RetireCircuits::None {
1277            self.hs_circ_pool.retire_all_circuits().map_err(wrap_err)?;
1278        }
1279
1280        self.dirmgr.reconfigure(&dir_cfg, how).map_err(wrap_err)?;
1281
1282        let netparams = self.dirmgr.params();
1283
1284        self.chanmgr
1285            .reconfigure(&new_config.channel, how, netparams)
1286            .map_err(wrap_err)?;
1287
1288        #[cfg(feature = "pt-client")]
1289        self.pt_mgr
1290            .reconfigure(how, new_config.bridges.transports.clone())
1291            .map_err(wrap_err)?;
1292
1293        if how == tor_config::Reconfigure::CheckAllOrNothing {
1294            return Ok(());
1295        }
1296
1297        self.addrcfg.replace(addr_cfg.clone());
1298        self.timeoutcfg.replace(timeout_cfg.clone());
1299        self.software_status_cfg
1300            .replace(new_config.use_obsolete_software.clone());
1301
1302        Ok(())
1303    }
1304
1305    /// Return a new isolated `TorClient` handle.
1306    ///
1307    /// The two `TorClient`s will share internal state and configuration, but
1308    /// their streams will never share circuits with one another.
1309    ///
1310    /// Use this function when you want separate parts of your program to
1311    /// each have a TorClient handle, but where you don't want their
1312    /// activities to be linkable to one another over the Tor network.
1313    ///
1314    /// Calling this function is usually preferable to creating a
1315    /// completely separate TorClient instance, since it can share its
1316    /// internals with the existing `TorClient`.
1317    ///
1318    /// (Connections made with clones of the returned `TorClient` may
1319    /// share circuits with each other.)
1320    #[must_use]
1321    pub fn isolated_client(&self) -> TorClient<R> {
1322        let mut result = self.clone();
1323        result.client_isolation = IsolationToken::new();
1324        result
1325    }
1326
1327    /// Launch an anonymized connection to the provided address and port over
1328    /// the Tor network.
1329    ///
1330    /// Note that because Tor prefers to do DNS resolution on the remote side of
1331    /// the network, this function takes its address as a string:
1332    ///
1333    /// ```no_run
1334    /// # use arti_client::*;use tor_rtcompat::Runtime;
1335    /// # async fn ex<R:Runtime>(tor_client: TorClient<R>) -> Result<()> {
1336    /// // The most usual way to connect is via an address-port tuple.
1337    /// let socket = tor_client.connect(("www.example.com", 443)).await?;
1338    ///
1339    /// // You can also specify an address and port as a colon-separated string.
1340    /// let socket = tor_client.connect("www.example.com:443").await?;
1341    /// # Ok(())
1342    /// # }
1343    /// ```
1344    ///
1345    /// Hostnames are _strongly_ preferred here: if this function allowed the
1346    /// caller here to provide an IPAddr or [`IpAddr`] or
1347    /// [`SocketAddr`](std::net::SocketAddr) address, then
1348    ///
1349    /// ```no_run
1350    /// # use arti_client::*; use tor_rtcompat::Runtime;
1351    /// # async fn ex<R:Runtime>(tor_client: TorClient<R>) -> Result<()> {
1352    /// # use std::net::ToSocketAddrs;
1353    /// // BAD: We're about to leak our target address to the local resolver!
1354    /// let address = "www.example.com:443".to_socket_addrs().unwrap().next().unwrap();
1355    /// // 🤯 Oh no! Now any eavesdropper can tell where we're about to connect! 🤯
1356    ///
1357    /// // Fortunately, this won't compile, since SocketAddr doesn't implement IntoTorAddr.
1358    /// // let socket = tor_client.connect(address).await?;
1359    /// //                                 ^^^^^^^ the trait `IntoTorAddr` is not implemented for `std::net::SocketAddr`
1360    /// # Ok(())
1361    /// # }
1362    /// ```
1363    ///
1364    /// If you really do need to connect to an IP address rather than a
1365    /// hostname, and if you're **sure** that the IP address came from a safe
1366    /// location, there are a few ways to do so.
1367    ///
1368    /// ```no_run
1369    /// # use arti_client::{TorClient,Result};use tor_rtcompat::Runtime;
1370    /// # use std::net::{SocketAddr,IpAddr};
1371    /// # async fn ex<R:Runtime>(tor_client: TorClient<R>) -> Result<()> {
1372    /// # use std::net::ToSocketAddrs;
1373    /// // ⚠️This is risky code!⚠️
1374    /// // (Make sure your addresses came from somewhere safe...)
1375    ///
1376    /// // If we have a fixed address, we can just provide it as a string.
1377    /// let socket = tor_client.connect("192.0.2.22:443").await?;
1378    /// let socket = tor_client.connect(("192.0.2.22", 443)).await?;
1379    ///
1380    /// // If we have a SocketAddr or an IpAddr, we can use the
1381    /// // DangerouslyIntoTorAddr trait.
1382    /// use arti_client::DangerouslyIntoTorAddr;
1383    /// let sockaddr = SocketAddr::from(([192, 0, 2, 22], 443));
1384    /// let ipaddr = IpAddr::from([192, 0, 2, 22]);
1385    /// let socket = tor_client.connect(sockaddr.into_tor_addr_dangerously().unwrap()).await?;
1386    /// let socket = tor_client.connect((ipaddr, 443).into_tor_addr_dangerously().unwrap()).await?;
1387    /// # Ok(())
1388    /// # }
1389    /// ```
1390    #[instrument(skip_all, level = "trace")]
1391    pub async fn connect<A: IntoTorAddr>(&self, target: A) -> crate::Result<DataStream> {
1392        self.connect_with_prefs(target, &self.connect_prefs).await
1393    }
1394
1395    /// Launch an anonymized connection to the provided address and
1396    /// port over the Tor network, with explicit connection preferences.
1397    ///
1398    /// Note that because Tor prefers to do DNS resolution on the remote
1399    /// side of the network, this function takes its address as a string.
1400    /// (See [`TorClient::connect()`] for more information.)
1401    #[instrument(skip_all, level = "trace")]
1402    pub async fn connect_with_prefs<A: IntoTorAddr>(
1403        &self,
1404        target: A,
1405        prefs: &StreamPrefs,
1406    ) -> crate::Result<DataStream> {
1407        let addr = target.into_tor_addr().map_err(wrap_err)?;
1408        let mut stream_parameters = prefs.stream_parameters();
1409        // This macro helps prevent code duplication in the match below.
1410        //
1411        // Ideally, the match should resolve to a tuple consisting of the
1412        // tunnel, and the address, port and stream params,
1413        // but that's not currently possible because
1414        // the Exit and Hs branches use different tunnel types.
1415        //
1416        // TODO: replace with an async closure (when our MSRV allows it),
1417        // or with a more elegant approach.
1418        macro_rules! begin_stream {
1419            ($tunnel:expr, $addr:expr, $port:expr, $stream_params:expr) => {{
1420                let fut = $tunnel.begin_stream($addr, $port, $stream_params);
1421                self.runtime
1422                    .timeout(self.timeoutcfg.get().connect_timeout, fut)
1423                    .await
1424                    .map_err(|_| ErrorDetail::ExitTimeout)?
1425                    .map_err(|cause| ErrorDetail::StreamFailed {
1426                        cause,
1427                        kind: "data",
1428                    })
1429            }};
1430        }
1431
1432        let stream = match addr.into_stream_instructions(&self.addrcfg.get(), prefs)? {
1433            StreamInstructions::Exit {
1434                hostname: addr,
1435                port,
1436            } => {
1437                let exit_ports = [prefs.wrap_target_port(port)];
1438                let tunnel = self
1439                    .get_or_launch_exit_tunnel(&exit_ports, prefs)
1440                    .await
1441                    .map_err(wrap_err)?;
1442                debug!("Got a circuit for {}:{}", sensitive(&addr), port);
1443                begin_stream!(tunnel, &addr, port, Some(stream_parameters))
1444            }
1445
1446            #[cfg(not(feature = "onion-service-client"))]
1447            #[allow(unused_variables)] // for hostname and port
1448            StreamInstructions::Hs {
1449                hsid,
1450                hostname,
1451                port,
1452            } => void::unreachable(hsid.0),
1453
1454            #[cfg(feature = "onion-service-client")]
1455            StreamInstructions::Hs {
1456                hsid,
1457                hostname,
1458                port,
1459            } => {
1460                use safelog::DisplayRedacted as _;
1461
1462                self.wait_for_bootstrap().await?;
1463                let netdir = self.netdir(Timeliness::Timely, "connect to a hidden service")?;
1464
1465                let mut hs_client_secret_keys_builder = HsClientSecretKeysBuilder::default();
1466
1467                if let Some(keymgr) = &self.inert_client.keymgr {
1468                    let desc_enc_key_spec = HsClientDescEncKeypairSpecifier::new(hsid);
1469
1470                    let ks_hsc_desc_enc =
1471                        keymgr.get::<HsClientDescEncKeypair>(&desc_enc_key_spec)?;
1472
1473                    if let Some(ks_hsc_desc_enc) = ks_hsc_desc_enc {
1474                        debug!(
1475                            "Found descriptor decryption key for {}",
1476                            hsid.display_redacted()
1477                        );
1478                        hs_client_secret_keys_builder.ks_hsc_desc_enc(ks_hsc_desc_enc);
1479                    }
1480                };
1481
1482                let hs_client_secret_keys = hs_client_secret_keys_builder
1483                    .build()
1484                    .map_err(ErrorDetail::Configuration)?;
1485
1486                let tunnel = self
1487                    .hsclient
1488                    .get_or_launch_tunnel(
1489                        &netdir,
1490                        hsid,
1491                        hs_client_secret_keys,
1492                        self.isolation(prefs),
1493                    )
1494                    .await
1495                    .map_err(|cause| ErrorDetail::ObtainHsCircuit { cause, hsid })?;
1496                // On connections to onion services, we have to suppress
1497                // everything except the port from the BEGIN message.  We also
1498                // disable optimistic data.
1499                stream_parameters
1500                    .suppress_hostname()
1501                    .suppress_begin_flags()
1502                    .optimistic(false);
1503
1504                begin_stream!(tunnel, &hostname, port, Some(stream_parameters))
1505            }
1506        };
1507
1508        Ok(stream?)
1509    }
1510
1511    /// Sets the default preferences for future connections made with this client.
1512    ///
1513    /// The preferences set with this function will be inherited by clones of this client, but
1514    /// updates to the preferences in those clones will not propagate back to the original.  I.e.,
1515    /// the preferences are copied by `clone`.
1516    ///
1517    /// Connection preferences always override configuration, even configuration set later
1518    /// (eg, by a config reload).
1519    pub fn set_stream_prefs(&mut self, connect_prefs: StreamPrefs) {
1520        self.connect_prefs = connect_prefs;
1521    }
1522
1523    /// Provides a new handle on this client, but with adjusted default preferences.
1524    ///
1525    /// Connections made with e.g. [`connect`](TorClient::connect) on the returned handle will use
1526    /// `connect_prefs`.  This is a convenience wrapper for `clone` and `set_connect_prefs`.
1527    #[must_use]
1528    pub fn clone_with_prefs(&self, connect_prefs: StreamPrefs) -> Self {
1529        let mut result = self.clone();
1530        result.set_stream_prefs(connect_prefs);
1531        result
1532    }
1533
1534    /// On success, return a list of IP addresses.
1535    #[instrument(skip_all, level = "trace")]
1536    pub async fn resolve(&self, hostname: &str) -> crate::Result<Vec<IpAddr>> {
1537        self.resolve_with_prefs(hostname, &self.connect_prefs).await
1538    }
1539
1540    /// On success, return a list of IP addresses, but use prefs.
1541    #[instrument(skip_all, level = "trace")]
1542    pub async fn resolve_with_prefs(
1543        &self,
1544        hostname: &str,
1545        prefs: &StreamPrefs,
1546    ) -> crate::Result<Vec<IpAddr>> {
1547        // TODO This dummy port is only because `address::Host` is not pub(crate),
1548        // but I see no reason why it shouldn't be?  Then `into_resolve_instructions`
1549        // should be a method on `Host`, not `TorAddr`.  -Diziet.
1550        let addr = (hostname, 1).into_tor_addr().map_err(wrap_err)?;
1551
1552        match addr.into_resolve_instructions(&self.addrcfg.get(), prefs)? {
1553            ResolveInstructions::Exit(hostname) => {
1554                let circ = self.get_or_launch_exit_tunnel(&[], prefs).await?;
1555
1556                let resolve_future = circ.resolve(&hostname);
1557                let addrs = self
1558                    .runtime
1559                    .timeout(self.timeoutcfg.get().resolve_timeout, resolve_future)
1560                    .await
1561                    .map_err(|_| ErrorDetail::ExitTimeout)?
1562                    .map_err(|cause| ErrorDetail::StreamFailed {
1563                        cause,
1564                        kind: "DNS lookup",
1565                    })?;
1566
1567                Ok(addrs)
1568            }
1569            ResolveInstructions::Return(addrs) => Ok(addrs),
1570        }
1571    }
1572
1573    /// Perform a remote DNS reverse lookup with the provided IP address.
1574    ///
1575    /// On success, return a list of hostnames.
1576    #[instrument(skip_all, level = "trace")]
1577    pub async fn resolve_ptr(&self, addr: IpAddr) -> crate::Result<Vec<String>> {
1578        self.resolve_ptr_with_prefs(addr, &self.connect_prefs).await
1579    }
1580
1581    /// Perform a remote DNS reverse lookup with the provided IP address.
1582    ///
1583    /// On success, return a list of hostnames.
1584    pub async fn resolve_ptr_with_prefs(
1585        &self,
1586        addr: IpAddr,
1587        prefs: &StreamPrefs,
1588    ) -> crate::Result<Vec<String>> {
1589        let circ = self.get_or_launch_exit_tunnel(&[], prefs).await?;
1590
1591        let resolve_ptr_future = circ.resolve_ptr(addr);
1592        let hostnames = self
1593            .runtime
1594            .timeout(
1595                self.timeoutcfg.get().resolve_ptr_timeout,
1596                resolve_ptr_future,
1597            )
1598            .await
1599            .map_err(|_| ErrorDetail::ExitTimeout)?
1600            .map_err(|cause| ErrorDetail::StreamFailed {
1601                cause,
1602                kind: "reverse DNS lookup",
1603            })?;
1604
1605        Ok(hostnames)
1606    }
1607
1608    /// Return a reference to this client's directory manager.
1609    ///
1610    /// This function is unstable. It is only enabled if the crate was
1611    /// built with the `experimental-api` feature.
1612    #[cfg(feature = "experimental-api")]
1613    pub fn dirmgr(&self) -> &Arc<dyn tor_dirmgr::DirProvider> {
1614        &self.dirmgr
1615    }
1616
1617    /// Return a reference to this client's circuit manager.
1618    ///
1619    /// This function is unstable. It is only enabled if the crate was
1620    /// built with the `experimental-api` feature.
1621    #[cfg(feature = "experimental-api")]
1622    pub fn circmgr(&self) -> &Arc<tor_circmgr::CircMgr<R>> {
1623        &self.circmgr
1624    }
1625
1626    /// Return a reference to this client's channel manager.
1627    ///
1628    /// This function is unstable. It is only enabled if the crate was
1629    /// built with the `experimental-api` feature.
1630    #[cfg(feature = "experimental-api")]
1631    pub fn chanmgr(&self) -> &Arc<tor_chanmgr::ChanMgr<R>> {
1632        &self.chanmgr
1633    }
1634
1635    /// Return a reference to this client's circuit pool.
1636    ///
1637    /// This function is unstable. It is only enabled if the crate was
1638    /// built with the `experimental-api` feature and any of `onion-service-client`
1639    /// or `onion-service-service` features. This method is required to invoke
1640    /// tor_hsservice::OnionService::launch()
1641    #[cfg(all(
1642        feature = "experimental-api",
1643        any(feature = "onion-service-client", feature = "onion-service-service")
1644    ))]
1645    pub fn hs_circ_pool(&self) -> &Arc<tor_circmgr::hspool::HsCircPool<R>> {
1646        &self.hs_circ_pool
1647    }
1648
1649    /// Return a reference to the runtime being used by this client.
1650    //
1651    // This API is not a hostage to fortune since we already require that R: Clone,
1652    // and necessarily a TorClient must have a clone of it.
1653    //
1654    // We provide it simply to save callers who have a TorClient from
1655    // having to separately keep their own handle,
1656    pub fn runtime(&self) -> &R {
1657        &self.runtime
1658    }
1659
1660    /// Return a netdir that is timely according to the rules of `timeliness`.
1661    ///
1662    /// The `action` string is a description of what we wanted to do with the
1663    /// directory, to be put into the error message if we couldn't find a directory.
1664    fn netdir(
1665        &self,
1666        timeliness: Timeliness,
1667        action: &'static str,
1668    ) -> StdResult<Arc<tor_netdir::NetDir>, ErrorDetail> {
1669        use tor_netdir::Error as E;
1670        match self.dirmgr.netdir(timeliness) {
1671            Ok(netdir) => Ok(netdir),
1672            Err(E::NoInfo) | Err(E::NotEnoughInfo) => {
1673                Err(ErrorDetail::BootstrapRequired { action })
1674            }
1675            Err(error) => Err(ErrorDetail::NoDir { error, action }),
1676        }
1677    }
1678
1679    /// Get or launch an exit-suitable circuit with a given set of
1680    /// exit ports.
1681    #[instrument(skip_all, level = "trace")]
1682    async fn get_or_launch_exit_tunnel(
1683        &self,
1684        exit_ports: &[TargetPort],
1685        prefs: &StreamPrefs,
1686    ) -> StdResult<ClientDataTunnel, ErrorDetail> {
1687        // TODO HS probably this netdir ought to be made in connect_with_prefs
1688        // like for StreamInstructions::Hs.
1689        self.wait_for_bootstrap().await?;
1690        let dir = self.netdir(Timeliness::Timely, "build a circuit")?;
1691
1692        let tunnel = self
1693            .circmgr
1694            .get_or_launch_exit(
1695                dir.as_ref().into(),
1696                exit_ports,
1697                self.isolation(prefs),
1698                #[cfg(feature = "geoip")]
1699                prefs.country_code,
1700            )
1701            .await
1702            .map_err(|cause| ErrorDetail::ObtainExitCircuit {
1703                cause,
1704                exit_ports: Sensitive::new(exit_ports.into()),
1705            })?;
1706        drop(dir); // This decreases the refcount on the netdir.
1707
1708        Ok(tunnel)
1709    }
1710
1711    /// Return an overall [`Isolation`] for this `TorClient` and a `StreamPrefs`.
1712    ///
1713    /// This describes which operations might use
1714    /// circuit(s) with this one.
1715    ///
1716    /// This combines isolation information from
1717    /// [`StreamPrefs::prefs_isolation`]
1718    /// and the `TorClient`'s isolation (eg from [`TorClient::isolated_client`]).
1719    fn isolation(&self, prefs: &StreamPrefs) -> StreamIsolation {
1720        let mut b = StreamIsolationBuilder::new();
1721        // Always consider our client_isolation.
1722        b.owner_token(self.client_isolation);
1723        // Consider stream isolation too, if it's set.
1724        if let Some(tok) = prefs.prefs_isolation() {
1725            b.stream_isolation(tok);
1726        }
1727        // Failure should be impossible with this builder.
1728        b.build().expect("Failed to construct StreamIsolation")
1729    }
1730
1731    /// Try to launch an onion service with a given configuration.
1732    ///
1733    /// This onion service will not actually handle any requests on its own: you
1734    /// will need to
1735    /// pull [`RendRequest`](tor_hsservice::RendRequest) objects from the returned stream,
1736    /// [`accept`](tor_hsservice::RendRequest::accept) the ones that you want to
1737    /// answer, and then wait for them to give you [`StreamRequest`](tor_hsservice::StreamRequest)s.
1738    ///
1739    /// You may find the [`tor_hsservice::handle_rend_requests`] API helpful for
1740    /// translating `RendRequest`s into `StreamRequest`s.
1741    ///
1742    /// If you want to forward all the requests from an onion service to a set
1743    /// of local ports, you may want to use the `tor-hsrproxy` crate.
1744    #[cfg(feature = "onion-service-service")]
1745    #[instrument(skip_all, level = "trace")]
1746    pub fn launch_onion_service(
1747        &self,
1748        config: tor_hsservice::OnionServiceConfig,
1749    ) -> crate::Result<(
1750        Arc<tor_hsservice::RunningOnionService>,
1751        impl futures::Stream<Item = tor_hsservice::RendRequest> + use<R>,
1752    )> {
1753        let keymgr = self
1754            .inert_client
1755            .keymgr
1756            .as_ref()
1757            .ok_or(ErrorDetail::KeystoreRequired {
1758                action: "launch onion service",
1759            })?
1760            .clone();
1761        let state_dir = self.state_directory.clone();
1762
1763        let service = tor_hsservice::OnionService::builder()
1764            .config(config) // TODO #1186: Allow override of KeyMgr for "ephemeral" operation?
1765            .keymgr(keymgr)
1766            // TODO #1186: Allow override of StateMgr for "ephemeral" operation?
1767            .state_dir(state_dir)
1768            .build()
1769            .map_err(ErrorDetail::LaunchOnionService)?;
1770        let (service, stream) = service
1771            .launch(
1772                self.runtime.clone(),
1773                self.dirmgr.clone().upcast_arc(),
1774                self.hs_circ_pool.clone(),
1775                Arc::clone(&self.path_resolver),
1776            )
1777            .map_err(ErrorDetail::LaunchOnionService)?;
1778
1779        Ok((service, stream))
1780    }
1781
1782    /// Try to launch an onion service with a given configuration and provided
1783    /// [`HsIdKeypair`]. If an onion service with the given nickname already has an
1784    /// associated `HsIdKeypair`  in this `TorClient`'s `KeyMgr`, then this operation
1785    /// fails rather than overwriting the existing key.
1786    ///
1787    /// The specified `HsIdKeypair` will be inserted in the primary keystore.
1788    ///
1789    /// **Important**: depending on the configuration of your
1790    /// [primary keystore](tor_keymgr::config::PrimaryKeystoreConfig),
1791    /// the `HsIdKeypair` **may** get persisted to disk.
1792    /// By default, Arti's primary keystore is the [native](ArtiKeystoreKind::Native),
1793    /// disk-based keystore.
1794    ///
1795    /// This onion service will not actually handle any requests on its own: you
1796    /// will need to
1797    /// pull [`RendRequest`](tor_hsservice::RendRequest) objects from the returned stream,
1798    /// [`accept`](tor_hsservice::RendRequest::accept) the ones that you want to
1799    /// answer, and then wait for them to give you [`StreamRequest`](tor_hsservice::StreamRequest)s.
1800    ///
1801    /// You may find the [`tor_hsservice::handle_rend_requests`] API helpful for
1802    /// translating `RendRequest`s into `StreamRequest`s.
1803    ///
1804    /// If you want to forward all the requests from an onion service to a set
1805    /// of local ports, you may want to use the `tor-hsrproxy` crate.
1806    #[cfg(all(feature = "onion-service-service", feature = "experimental-api"))]
1807    #[instrument(skip_all, level = "trace")]
1808    pub fn launch_onion_service_with_hsid(
1809        &self,
1810        config: tor_hsservice::OnionServiceConfig,
1811        id_keypair: HsIdKeypair,
1812    ) -> crate::Result<(
1813        Arc<tor_hsservice::RunningOnionService>,
1814        impl futures::Stream<Item = tor_hsservice::RendRequest> + use<R>,
1815    )> {
1816        let nickname = config.nickname();
1817        let hsid_spec = HsIdKeypairSpecifier::new(nickname.clone());
1818        let selector = KeystoreSelector::Primary;
1819
1820        let _kp = self
1821            .inert_client
1822            .keymgr
1823            .as_ref()
1824            .ok_or(ErrorDetail::KeystoreRequired {
1825                action: "launch onion service ex",
1826            })?
1827            .insert::<HsIdKeypair>(id_keypair, &hsid_spec, selector, false)?;
1828
1829        self.launch_onion_service(config)
1830    }
1831
1832    /// Generate a service discovery keypair for connecting to a hidden service running in
1833    /// "restricted discovery" mode.
1834    ///
1835    /// The `selector` argument is used for choosing the keystore in which to generate the keypair.
1836    /// While most users will want to write to the [`Primary`](KeystoreSelector::Primary), if you
1837    /// have configured this `TorClient` with a non-default keystore and wish to generate the
1838    /// keypair in it, you can do so by calling this function with a [KeystoreSelector::Id]
1839    /// specifying the keystore ID of your keystore.
1840    ///
1841    // Note: the selector argument exists for future-proofing reasons. We don't currently support
1842    // configuring custom or non-default keystores (see #1106).
1843    ///
1844    /// Returns an error if the key already exists in the specified key store.
1845    ///
1846    /// Important: the public part of the generated keypair must be shared with the service, and
1847    /// the service needs to be configured to allow the owner of its private counterpart to
1848    /// discover its introduction points. The caller is responsible for sharing the public part of
1849    /// the key with the hidden service.
1850    ///
1851    /// This function does not require the `TorClient` to be running or bootstrapped.
1852    //
1853    // TODO: decide whether this should use get_or_generate before making it
1854    // non-experimental
1855    #[cfg(all(
1856        feature = "onion-service-client",
1857        feature = "experimental-api",
1858        feature = "keymgr"
1859    ))]
1860    #[cfg_attr(
1861        docsrs,
1862        doc(cfg(all(
1863            feature = "onion-service-client",
1864            feature = "experimental-api",
1865            feature = "keymgr"
1866        )))
1867    )]
1868    pub fn generate_service_discovery_key(
1869        &self,
1870        selector: KeystoreSelector,
1871        hsid: HsId,
1872    ) -> crate::Result<HsClientDescEncKey> {
1873        self.inert_client
1874            .generate_service_discovery_key(selector, hsid)
1875    }
1876
1877    /// Rotate the service discovery keypair for connecting to a hidden service running in
1878    /// "restricted discovery" mode.
1879    ///
1880    /// **If the specified keystore already contains a restricted discovery keypair
1881    /// for the service, it will be overwritten.** Otherwise, a new keypair is generated.
1882    ///
1883    /// The `selector` argument is used for choosing the keystore in which to generate the keypair.
1884    /// While most users will want to write to the [`Primary`](KeystoreSelector::Primary), if you
1885    /// have configured this `TorClient` with a non-default keystore and wish to generate the
1886    /// keypair in it, you can do so by calling this function with a [KeystoreSelector::Id]
1887    /// specifying the keystore ID of your keystore.
1888    ///
1889    // Note: the selector argument exists for future-proofing reasons. We don't currently support
1890    // configuring custom or non-default keystores (see #1106).
1891    ///
1892    /// Important: the public part of the generated keypair must be shared with the service, and
1893    /// the service needs to be configured to allow the owner of its private counterpart to
1894    /// discover its introduction points. The caller is responsible for sharing the public part of
1895    /// the key with the hidden service.
1896    ///
1897    /// This function does not require the `TorClient` to be running or bootstrapped.
1898    #[cfg(all(
1899        feature = "onion-service-client",
1900        feature = "experimental-api",
1901        feature = "keymgr"
1902    ))]
1903    #[cfg_attr(
1904        docsrs,
1905        doc(cfg(all(
1906            feature = "onion-service-client",
1907            feature = "experimental-api",
1908            feature = "keymgr"
1909        )))
1910    )]
1911    pub fn rotate_service_discovery_key(
1912        &self,
1913        selector: KeystoreSelector,
1914        hsid: HsId,
1915    ) -> crate::Result<HsClientDescEncKey> {
1916        self.inert_client
1917            .rotate_service_discovery_key(selector, hsid)
1918    }
1919
1920    /// Insert a service discovery secret key for connecting to a hidden service running in
1921    /// "restricted discovery" mode
1922    ///
1923    /// The `selector` argument is used for choosing the keystore in which to generate the keypair.
1924    /// While most users will want to write to the [`Primary`](KeystoreSelector::Primary), if you
1925    /// have configured this `TorClient` with a non-default keystore and wish to insert the
1926    /// key in it, you can do so by calling this function with a [KeystoreSelector::Id]
1927    ///
1928    // Note: the selector argument exists for future-proofing reasons. We don't currently support
1929    // configuring custom or non-default keystores (see #1106).
1930    ///
1931    /// Returns an error if the key already exists in the specified key store.
1932    ///
1933    /// Important: the public part of the generated keypair must be shared with the service, and
1934    /// the service needs to be configured to allow the owner of its private counterpart to
1935    /// discover its introduction points. The caller is responsible for sharing the public part of
1936    /// the key with the hidden service.
1937    ///
1938    /// This function does not require the `TorClient` to be running or bootstrapped.
1939    #[cfg(all(
1940        feature = "onion-service-client",
1941        feature = "experimental-api",
1942        feature = "keymgr"
1943    ))]
1944    #[cfg_attr(
1945        docsrs,
1946        doc(cfg(all(
1947            feature = "onion-service-client",
1948            feature = "experimental-api",
1949            feature = "keymgr"
1950        )))
1951    )]
1952    pub fn insert_service_discovery_key(
1953        &self,
1954        selector: KeystoreSelector,
1955        hsid: HsId,
1956        hs_client_desc_enc_secret_key: HsClientDescEncSecretKey,
1957    ) -> crate::Result<HsClientDescEncKey> {
1958        self.inert_client.insert_service_discovery_key(
1959            selector,
1960            hsid,
1961            hs_client_desc_enc_secret_key,
1962        )
1963    }
1964
1965    /// Return the service discovery public key for the service with the specified `hsid`.
1966    ///
1967    /// Returns `Ok(None)` if no such key exists.
1968    ///
1969    /// This function does not require the `TorClient` to be running or bootstrapped.
1970    #[cfg(all(feature = "onion-service-client", feature = "experimental-api"))]
1971    #[cfg_attr(
1972        docsrs,
1973        doc(cfg(all(feature = "onion-service-client", feature = "experimental-api")))
1974    )]
1975    pub fn get_service_discovery_key(
1976        &self,
1977        hsid: HsId,
1978    ) -> crate::Result<Option<HsClientDescEncKey>> {
1979        self.inert_client.get_service_discovery_key(hsid)
1980    }
1981
1982    /// Removes the service discovery keypair for the service with the specified `hsid`.
1983    ///
1984    /// Returns an error if the selected keystore is not the default keystore or one of the
1985    /// configured secondary stores.
1986    ///
1987    /// Returns `Ok(None)` if no such keypair exists whereas `Ok(Some()) means the keypair was successfully removed.
1988    ///
1989    /// Returns `Err` if an error occurred while trying to remove the key.
1990    #[cfg(all(
1991        feature = "onion-service-client",
1992        feature = "experimental-api",
1993        feature = "keymgr"
1994    ))]
1995    #[cfg_attr(
1996        docsrs,
1997        doc(cfg(all(
1998            feature = "onion-service-client",
1999            feature = "experimental-api",
2000            feature = "keymgr"
2001        )))
2002    )]
2003    pub fn remove_service_discovery_key(
2004        &self,
2005        selector: KeystoreSelector,
2006        hsid: HsId,
2007    ) -> crate::Result<Option<()>> {
2008        self.inert_client
2009            .remove_service_discovery_key(selector, hsid)
2010    }
2011
2012    /// Create (but do not launch) a new
2013    /// [`OnionService`](tor_hsservice::OnionService)
2014    /// using the given configuration.
2015    ///
2016    /// This is useful for managing an onion service without needing to start a `TorClient` or the
2017    /// onion service itself.
2018    /// If you only wish to run the onion service, see
2019    /// [`TorClient::launch_onion_service()`]
2020    /// which allows you to launch an onion service from a running `TorClient`.
2021    ///
2022    /// The returned `OnionService` can be launched using
2023    /// [`OnionService::launch()`](tor_hsservice::OnionService::launch).
2024    /// Note that `launch()` requires a [`NetDirProvider`],
2025    /// [`HsCircPool`](tor_circmgr::hspool::HsCircPool), etc,
2026    /// which you should obtain from a running `TorClient`.
2027    /// But these are only accessible from a `TorClient` if the "experimental-api" feature is
2028    /// enabled.
2029    /// The behaviour is not specified if you create the `OnionService` with
2030    /// `create_onion_service()` using one [`TorClientConfig`],
2031    /// but launch it using a `TorClient` generated from a different `TorClientConfig`.
2032    #[cfg(feature = "onion-service-service")]
2033    #[instrument(skip_all, level = "trace")]
2034    pub fn create_onion_service(
2035        config: &TorClientConfig,
2036        svc_config: tor_hsservice::OnionServiceConfig,
2037    ) -> crate::Result<tor_hsservice::OnionService> {
2038        let inert_client = InertTorClient::new(config)?;
2039        let keymgr = inert_client.keymgr.ok_or(ErrorDetail::KeystoreRequired {
2040            action: "create onion service",
2041        })?;
2042
2043        let (state_dir, mistrust) = config.state_dir()?;
2044        let state_dir =
2045            self::StateDirectory::new(state_dir, mistrust).map_err(ErrorDetail::StateAccess)?;
2046
2047        Ok(tor_hsservice::OnionService::builder()
2048            .config(svc_config)
2049            .keymgr(keymgr)
2050            .state_dir(state_dir)
2051            .build()
2052            .map_err(ErrorDetail::OnionServiceSetup)?)
2053    }
2054
2055    /// Return a current [`status::BootstrapStatus`] describing how close this client
2056    /// is to being ready for user traffic.
2057    pub fn bootstrap_status(&self) -> status::BootstrapStatus {
2058        self.status_receiver.inner.borrow().clone()
2059    }
2060
2061    /// Return a stream of [`status::BootstrapStatus`] events that will be updated
2062    /// whenever the client's status changes.
2063    ///
2064    /// The receiver might not receive every update sent to this stream, though
2065    /// when it does poll the stream it should get the most recent one.
2066    //
2067    // TODO(nickm): will this also need to implement Send and 'static?
2068    pub fn bootstrap_events(&self) -> status::BootstrapEvents {
2069        self.status_receiver.clone()
2070    }
2071
2072    /// Change the client's current dormant mode, putting background tasks to sleep
2073    /// or waking them up as appropriate.
2074    ///
2075    /// This can be used to conserve CPU usage if you aren't planning on using the
2076    /// client for a while, especially on mobile platforms.
2077    ///
2078    /// See the [`DormantMode`] documentation for more details.
2079    pub fn set_dormant(&self, mode: DormantMode) {
2080        *self
2081            .dormant
2082            .lock()
2083            .expect("dormant lock poisoned")
2084            .borrow_mut() = Some(mode);
2085    }
2086
2087    /// Return a [`Future`] which resolves
2088    /// once this TorClient has stopped.
2089    #[cfg(feature = "experimental-api")]
2090    #[instrument(skip_all, level = "trace")]
2091    pub fn wait_for_stop(
2092        &self,
2093    ) -> impl futures::Future<Output = ()> + Send + Sync + 'static + use<R> {
2094        // We defer to the "wait for unlock" handle on our statemgr.
2095        //
2096        // The statemgr won't actually be unlocked until it is finally
2097        // dropped, which will happen when this TorClient is
2098        // dropped—which is what we want.
2099        self.statemgr.wait_for_unlock()
2100    }
2101}
2102
2103/// Monitor `dormant_mode` and enable/disable periodic tasks as applicable
2104///
2105/// This function is spawned as a task during client construction.
2106// TODO should this perhaps be done by each TaskHandle?
2107async fn tasks_monitor_dormant<R: Runtime>(
2108    mut dormant_rx: postage::watch::Receiver<Option<DormantMode>>,
2109    netdir: Arc<dyn NetDirProvider>,
2110    chanmgr: Arc<tor_chanmgr::ChanMgr<R>>,
2111    #[cfg(feature = "bridge-client")] bridge_desc_mgr: Arc<Mutex<Option<Arc<BridgeDescMgr<R>>>>>,
2112    periodic_task_handles: Vec<TaskHandle>,
2113) {
2114    while let Some(Some(mode)) = dormant_rx.next().await {
2115        let netparams = netdir.params();
2116
2117        chanmgr
2118            .set_dormancy(mode.into(), netparams)
2119            .unwrap_or_else(|e| error_report!(e, "couldn't set dormancy"));
2120
2121        // IEFI simplifies handling of exceptional cases, as "never mind, then".
2122        #[cfg(feature = "bridge-client")]
2123        (|| {
2124            let mut bdm = bridge_desc_mgr.lock().ok()?;
2125            let bdm = bdm.as_mut()?;
2126            bdm.set_dormancy(mode.into());
2127            Some(())
2128        })();
2129
2130        let is_dormant = matches!(mode, DormantMode::Soft);
2131
2132        for task in periodic_task_handles.iter() {
2133            if is_dormant {
2134                task.cancel();
2135            } else {
2136                task.fire();
2137            }
2138        }
2139    }
2140}
2141
2142/// Alias for TorError::from(Error)
2143pub(crate) fn wrap_err<T>(err: T) -> crate::Error
2144where
2145    ErrorDetail: From<T>,
2146{
2147    ErrorDetail::from(err).into()
2148}
2149
2150#[cfg(test)]
2151mod test {
2152    // @@ begin test lint list maintained by maint/add_warning @@
2153    #![allow(clippy::bool_assert_comparison)]
2154    #![allow(clippy::clone_on_copy)]
2155    #![allow(clippy::dbg_macro)]
2156    #![allow(clippy::mixed_attributes_style)]
2157    #![allow(clippy::print_stderr)]
2158    #![allow(clippy::print_stdout)]
2159    #![allow(clippy::single_char_pattern)]
2160    #![allow(clippy::unwrap_used)]
2161    #![allow(clippy::unchecked_duration_subtraction)]
2162    #![allow(clippy::useless_vec)]
2163    #![allow(clippy::needless_pass_by_value)]
2164    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
2165
2166    use tor_config::Reconfigure;
2167
2168    use super::*;
2169    use crate::config::TorClientConfigBuilder;
2170    use crate::{ErrorKind, HasKind};
2171
2172    #[test]
2173    fn create_unbootstrapped() {
2174        tor_rtcompat::test_with_one_runtime!(|rt| async {
2175            let state_dir = tempfile::tempdir().unwrap();
2176            let cache_dir = tempfile::tempdir().unwrap();
2177            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
2178                .build()
2179                .unwrap();
2180            let _ = TorClient::with_runtime(rt)
2181                .config(cfg)
2182                .bootstrap_behavior(BootstrapBehavior::Manual)
2183                .create_unbootstrapped()
2184                .unwrap();
2185        });
2186        tor_rtcompat::test_with_one_runtime!(|rt| async {
2187            let state_dir = tempfile::tempdir().unwrap();
2188            let cache_dir = tempfile::tempdir().unwrap();
2189            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
2190                .build()
2191                .unwrap();
2192            let _ = TorClient::with_runtime(rt)
2193                .config(cfg)
2194                .bootstrap_behavior(BootstrapBehavior::Manual)
2195                .create_unbootstrapped_async()
2196                .await
2197                .unwrap();
2198        });
2199    }
2200
2201    #[test]
2202    fn unbootstrapped_client_unusable() {
2203        tor_rtcompat::test_with_one_runtime!(|rt| async {
2204            let state_dir = tempfile::tempdir().unwrap();
2205            let cache_dir = tempfile::tempdir().unwrap();
2206            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
2207                .build()
2208                .unwrap();
2209            // Test sync
2210            let client = TorClient::with_runtime(rt)
2211                .config(cfg)
2212                .bootstrap_behavior(BootstrapBehavior::Manual)
2213                .create_unbootstrapped()
2214                .unwrap();
2215            let result = client.connect("example.com:80").await;
2216            assert!(result.is_err());
2217            assert_eq!(result.err().unwrap().kind(), ErrorKind::BootstrapRequired);
2218        });
2219        // Need a separate test for async because Runtime and TorClientConfig are consumed by the
2220        // builder
2221        tor_rtcompat::test_with_one_runtime!(|rt| async {
2222            let state_dir = tempfile::tempdir().unwrap();
2223            let cache_dir = tempfile::tempdir().unwrap();
2224            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
2225                .build()
2226                .unwrap();
2227            // Test sync
2228            let client = TorClient::with_runtime(rt)
2229                .config(cfg)
2230                .bootstrap_behavior(BootstrapBehavior::Manual)
2231                .create_unbootstrapped_async()
2232                .await
2233                .unwrap();
2234            let result = client.connect("example.com:80").await;
2235            assert!(result.is_err());
2236            assert_eq!(result.err().unwrap().kind(), ErrorKind::BootstrapRequired);
2237        });
2238    }
2239
2240    #[test]
2241    fn streamprefs_isolate_every_stream() {
2242        let mut observed = StreamPrefs::new();
2243        observed.isolate_every_stream();
2244        match observed.isolation {
2245            StreamIsolationPreference::EveryStream => (),
2246            _ => panic!("unexpected isolation: {:?}", observed.isolation),
2247        };
2248    }
2249
2250    #[test]
2251    fn streamprefs_new_has_expected_defaults() {
2252        let observed = StreamPrefs::new();
2253        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv4Preferred);
2254        assert!(!observed.optimistic_stream);
2255        // StreamIsolationPreference does not implement Eq, check manually.
2256        match observed.isolation {
2257            StreamIsolationPreference::None => (),
2258            _ => panic!("unexpected isolation: {:?}", observed.isolation),
2259        };
2260    }
2261
2262    #[test]
2263    fn streamprefs_new_isolation_group() {
2264        let mut observed = StreamPrefs::new();
2265        observed.new_isolation_group();
2266        match observed.isolation {
2267            StreamIsolationPreference::Explicit(_) => (),
2268            _ => panic!("unexpected isolation: {:?}", observed.isolation),
2269        };
2270    }
2271
2272    #[test]
2273    fn streamprefs_ipv6_only() {
2274        let mut observed = StreamPrefs::new();
2275        observed.ipv6_only();
2276        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv6Only);
2277    }
2278
2279    #[test]
2280    fn streamprefs_ipv6_preferred() {
2281        let mut observed = StreamPrefs::new();
2282        observed.ipv6_preferred();
2283        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv6Preferred);
2284    }
2285
2286    #[test]
2287    fn streamprefs_ipv4_only() {
2288        let mut observed = StreamPrefs::new();
2289        observed.ipv4_only();
2290        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv4Only);
2291    }
2292
2293    #[test]
2294    fn streamprefs_ipv4_preferred() {
2295        let mut observed = StreamPrefs::new();
2296        observed.ipv4_preferred();
2297        assert_eq!(observed.ip_ver_pref, IpVersionPreference::Ipv4Preferred);
2298    }
2299
2300    #[test]
2301    fn streamprefs_optimistic() {
2302        let mut observed = StreamPrefs::new();
2303        observed.optimistic();
2304        assert!(observed.optimistic_stream);
2305    }
2306
2307    #[test]
2308    fn streamprefs_set_isolation() {
2309        let mut observed = StreamPrefs::new();
2310        observed.set_isolation(IsolationToken::new());
2311        match observed.isolation {
2312            StreamIsolationPreference::Explicit(_) => (),
2313            _ => panic!("unexpected isolation: {:?}", observed.isolation),
2314        };
2315    }
2316
2317    #[test]
2318    fn reconfigure_all_or_nothing() {
2319        tor_rtcompat::test_with_one_runtime!(|rt| async {
2320            let state_dir = tempfile::tempdir().unwrap();
2321            let cache_dir = tempfile::tempdir().unwrap();
2322            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
2323                .build()
2324                .unwrap();
2325            let tor_client = TorClient::with_runtime(rt)
2326                .config(cfg.clone())
2327                .bootstrap_behavior(BootstrapBehavior::Manual)
2328                .create_unbootstrapped()
2329                .unwrap();
2330            tor_client
2331                .reconfigure(&cfg, Reconfigure::AllOrNothing)
2332                .unwrap();
2333        });
2334        tor_rtcompat::test_with_one_runtime!(|rt| async {
2335            let state_dir = tempfile::tempdir().unwrap();
2336            let cache_dir = tempfile::tempdir().unwrap();
2337            let cfg = TorClientConfigBuilder::from_directories(state_dir, cache_dir)
2338                .build()
2339                .unwrap();
2340            let tor_client = TorClient::with_runtime(rt)
2341                .config(cfg.clone())
2342                .bootstrap_behavior(BootstrapBehavior::Manual)
2343                .create_unbootstrapped_async()
2344                .await
2345                .unwrap();
2346            tor_client
2347                .reconfigure(&cfg, Reconfigure::AllOrNothing)
2348                .unwrap();
2349        });
2350    }
2351}