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