Skip to main content

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