1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
53
#![warn(unnameable_types)]
54

            
55
use std::sync::{Arc, Mutex};
56

            
57
use arti_client::{IntoTorAddr, TorClient};
58
use ureq::{
59
    http::{Uri, uri::Scheme},
60
    tls::TlsProvider as UreqTlsProvider,
61
    unversioned::{
62
        resolver::{ArrayVec, ResolvedSocketAddrs, Resolver as UreqResolver},
63
        transport::{Buffers, Connector as UreqConnector, LazyBuffers, NextTimeout, Transport},
64
    },
65
};
66

            
67
use educe::Educe;
68
use thiserror::Error;
69
use tor_proto::client::stream::{DataReader, DataWriter};
70
use tor_rtcompat::{Runtime, ToplevelBlockOn};
71

            
72
#[cfg(feature = "rustls")]
73
use ureq::unversioned::transport::RustlsConnector;
74

            
75
#[cfg(feature = "native-tls")]
76
use ureq::unversioned::transport::NativeTlsConnector;
77

            
78
use futures::io::{AsyncReadExt, AsyncWriteExt};
79

            
80
/// High-level functionality for accessing the Tor network as a client.
81
pub use arti_client;
82

            
83
/// Compatibility between different async runtimes for Arti.
84
pub use tor_rtcompat;
85

            
86
/// Underlying HTTP/S client library.
87
pub use ureq;
88

            
89
/// **Default usage**: Returns an instance of [`ureq::Agent`] using the default [`Connector`].
90
///
91
/// Equivalent to `Connector::new()?.agent()`.
92
///
93
/// # Example
94
///
95
/// ```rust,no_run
96
/// arti_ureq::default_agent()
97
///     .expect("Failed to create default agent.")
98
///     .get("http://check.torproject.org/api/ip")
99
///     .call()
100
///     .expect("Failed to make request.");
101
/// ```
102
///
103
/// Warning: This method creates a default [`arti_client::TorClient`]. Using multiple concurrent
104
/// instances of `TorClient` is not recommended. Most programs should create a single `TorClient` centrally.
105
pub fn default_agent() -> Result<ureq::Agent, Error> {
106
    Ok(Connector::new()?.agent())
107
}
108

            
109
/// **Main entrypoint**: Object for making HTTP/S requests through Tor.
110
///
111
/// This type embodies an [`arti_client::TorClient`] and implements [`ureq::unversioned::transport::Connector`],
112
/// allowing HTTP/HTTPS requests to be made with `ureq` over Tor.
113
///
114
/// Also bridges between async I/O (in Arti and Tokio) and sync I/O (in `ureq`).
115
///
116
/// ## A `Connector` object can be constructed in different ways.
117
///
118
/// ### 1. Use [`Connector::new`] to create a `Connector` with a default `TorClient`.
119
/// ```rust,no_run
120
/// let connector = arti_ureq::Connector::new().expect("Failed to create Connector.");
121
/// ```
122
///
123
/// ### 2. Use [`Connector::with_tor_client`] to create a `Connector` with a specific `TorClient`.
124
/// ```rust,no_run
125
/// let tor_client = arti_client::TorClient::with_runtime(
126
///     tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime.")
127
/// )
128
/// .create_unbootstrapped()
129
/// .expect("Error creating Tor Client.");
130
///
131
/// let connector = arti_ureq::Connector::with_tor_client(tor_client);
132
/// ```
133
///
134
/// ### 3. Use [`Connector::builder`] to create a `ConnectorBuilder` and configure a `Connector` with it.
135
/// ```rust,no_run
136
/// let connector = arti_ureq::Connector::<tor_rtcompat::PreferredRuntime>::builder()
137
///    .expect("Failed to create ConnectorBuilder.")
138
///    .build()
139
///    .expect("Failed to create Connector.");
140
/// ```
141
///
142
///
143
/// ## Usage of `Connector`.
144
///
145
/// A `Connector` can be used to retrieve an [`ureq::Agent`] with [`Connector::agent`] or pass the `Connector`
146
/// to [`ureq::Agent::with_parts`] along with a custom [`ureq::config::Config`] and a resolver
147
/// obtained from [`Connector::resolver`] to retrieve a more configurable [`ureq::Agent`].
148
///
149
/// ### Retrieve an `ureq::Agent`.
150
/// ```rust,no_run
151
/// let connector = arti_ureq::Connector::new().expect("Failed to create Connector.");
152
/// let ureq_agent = connector.agent();
153
/// ```
154
///
155
/// ### Pass as argument to `ureq::Agent::with_parts`.
156
///
157
/// We highly advice only using `Resolver` instead of e.g `ureq`'s [`ureq::unversioned::resolver::DefaultResolver`] to avoid DNS leaks.
158
///
159
/// ```rust,no_run
160
/// let connector = arti_ureq::Connector::new().expect("Failed to create Connector.");
161
/// let resolver = connector.resolver();
162
///
163
/// let ureq_agent = ureq::Agent::with_parts(
164
///    ureq::config::Config::default(),
165
///    connector,
166
///    resolver,
167
/// );
168
/// ```
169
#[derive(Educe)]
170
#[educe(Debug(bound(false)))]
171
pub struct Connector<R: Runtime> {
172
    /// [`arti_client::TorClient`] used to make requests.
173
    #[educe(Debug(ignore))]
174
    client: Arc<TorClient<R>>,
175

            
176
    /// Selected [`ureq::tls::TlsProvider`]. Possible options are `Rustls` or `NativeTls`. The default is `Rustls`.
177
    tls_provider: UreqTlsProvider,
178
}
179

            
180
/// Object for constructing a [`Connector`].
181
///
182
/// Returned by [`Connector::builder`].
183
///
184
/// # Example
185
///
186
/// ```rust,no_run
187
/// // `Connector` using `NativeTls` as Tls provider.
188
/// let arti_connector = arti_ureq::Connector::<tor_rtcompat::PreferredRuntime>::builder()
189
///    .expect("Failed to create ConnectorBuilder.")
190
///     .tls_provider(ureq::tls::TlsProvider::NativeTls)
191
///     .build()
192
///     .expect("Failed to create Connector.");
193
///
194
/// // Retrieve `ureq::Agent` from the `Connector`.
195
/// let ureq_agent = arti_connector.agent();
196
/// ```
197
pub struct ConnectorBuilder<R: Runtime> {
198
    /// Configured [`arti_client::TorClient`] to be used with [`Connector`].
199
    client: Option<Arc<TorClient<R>>>,
200

            
201
    /// Runtime
202
    ///
203
    /// If `client` is `None`, is used to create one.
204
    /// If `client` is `Some`. we discard this in `.build()` in favour of `.client.runtime()`.
205
    //
206
    // (We could replace `client` and `runtime` with `Either<TorClient<R>, R>` or some such,
207
    // but that would probably be more confusing.)
208
    runtime: R,
209

            
210
    /// Custom selected TlsProvider. Default is `Rustls`. Possible options are `Rustls` or `NativeTls`.
211
    tls_provider: Option<UreqTlsProvider>,
212
}
213

            
214
/// Custom [`ureq::unversioned::transport::Transport`] enabling `ureq` to use
215
/// [`arti_client::TorClient`] for making requests over Tor.
216
#[derive(Educe)]
217
#[educe(Debug)]
218
struct HttpTransport<R: Runtime> {
219
    /// Reader handle to Arti's read stream.
220
    // TODO #1859
221
    r: Arc<Mutex<DataReader>>,
222

            
223
    /// Writer handle to Arti's write stream.
224
    w: Arc<Mutex<DataWriter>>, // TODO #1859
225

            
226
    /// Buffer to store data.
227
    #[educe(Debug(ignore))]
228
    buffer: LazyBuffers,
229

            
230
    /// Runtime used to bridge between sync (`ureq`) and async I/O (`arti`).
231
    rt: R,
232
}
233

            
234
/// Resolver implementing trait [`ureq::unversioned::resolver::Resolver`].
235
///
236
/// Resolves the host to an IP address using [`arti_client::TorClient::resolve`] avoiding DNS leaks.
237
///
238
/// An instance of [`Resolver`] can easily be retrieved using [`Connector::resolver()`].
239
///
240
/// This is needed when using `ureq::Agent::with_parts`,
241
/// to avoid leaking DNS queries to the public local network.
242
/// Usually, use [`Connector::agent`] instead,
243
/// in which case you don't need to deal explicitly with a `Resolver`.
244
///
245
/// # Example
246
///
247
/// ```rust,no_run
248
/// // Retrieve the resolver directly from your `Connector`.
249
/// let arti_connector = arti_ureq::Connector::new().expect("Failed to create Connector.");
250
/// let arti_resolver = arti_connector.resolver();
251
/// let ureq_agent = ureq::Agent::with_parts(
252
///     ureq::config::Config::default(),
253
///     arti_connector,
254
///     arti_resolver,
255
/// );
256
/// ```
257
#[derive(Educe)]
258
#[educe(Debug)]
259
pub struct Resolver<R: Runtime> {
260
    /// [`arti_client::TorClient`] which contains the method [`arti_client::TorClient::resolve`].
261
    ///
262
    /// Use [`Connector::resolver`] or pass the client from your `Connector` to create an instance of `Resolver`.
263
    #[educe(Debug(ignore))]
264
    client: Arc<TorClient<R>>,
265
}
266

            
267
/// Error making or using http connection.
268
#[derive(Error, Debug)]
269
#[non_exhaustive]
270
pub enum Error {
271
    /// Unsupported URI scheme.
272
    #[error("unsupported URI scheme in {uri:?}")]
273
    UnsupportedUriScheme {
274
        /// URI.
275
        uri: Uri,
276
    },
277

            
278
    /// Missing hostname.
279
    #[error("Missing hostname in {uri:?}")]
280
    MissingHostname {
281
        /// URI.
282
        uri: Uri,
283
    },
284

            
285
    /// Tor connection failed.
286
    #[error("Tor connection failed")]
287
    Arti(#[from] arti_client::Error),
288

            
289
    /// General I/O error.
290
    #[error("General I/O error")]
291
    Io(#[from] std::io::Error),
292

            
293
    /// TLS configuration mismatch.
294
    #[error("TLS provider in config does not match the one in Connector.")]
295
    TlsConfigMismatch,
296
}
297

            
298
// Map our own error kinds to Arti's error classification.
299
impl tor_error::HasKind for Error {
300
    #[rustfmt::skip]
301
    fn kind(&self) -> tor_error::ErrorKind {
302
        use tor_error::ErrorKind as EK;
303
        match self {
304
            Error::UnsupportedUriScheme{..} => EK::NotImplemented,
305
            Error::MissingHostname{..}      => EK::BadApiUsage,
306
            Error::Arti(e)                  => e.kind(),
307
            Error::Io(..)                   => EK::Other,
308
            Error::TlsConfigMismatch        => EK::BadApiUsage,
309
        }
310
    }
311
}
312

            
313
// Convert our own error type to ureq's error type.
314
impl std::convert::From<Error> for ureq::Error {
315
    fn from(err: Error) -> Self {
316
        match err {
317
            Error::MissingHostname { uri } => {
318
                ureq::Error::BadUri(format!("Missing hostname in {uri:?}"))
319
            }
320
            Error::UnsupportedUriScheme { uri } => {
321
                ureq::Error::BadUri(format!("Unsupported URI scheme in {uri:?}"))
322
            }
323
            Error::Arti(e) => ureq::Error::Io(std::io::Error::other(e)), // TODO #1858
324
            Error::Io(e) => ureq::Error::Io(e),
325
            Error::TlsConfigMismatch => {
326
                ureq::Error::Tls("TLS provider in config does not match the one in Connector.")
327
            }
328
        }
329
    }
330
}
331

            
332
// Implementation of trait [`ureq::unversioned::transport::Transport`] for [`HttpTransport`].
333
//
334
// Due to this implementation [`Connector`] can have a valid transport to be used with `ureq`.
335
//
336
// In this implementation we map the `ureq` buffer to the `arti` stream. And map the
337
// methods to receive and transmit data between `ureq` and `arti`.
338
//
339
// Here we also bridge between the sync context `ureq` is usually called from and Arti's async I/O
340
// by blocking the provided runtime. Preferably a runtime only used for `arti` should be provided.
341
impl<R: Runtime + ToplevelBlockOn> Transport for HttpTransport<R> {
342
    // Obtain buffers used by ureq.
343
    fn buffers(&mut self) -> &mut dyn Buffers {
344
        &mut self.buffer
345
    }
346

            
347
    // Write received data from ureq request to arti stream.
348
    fn transmit_output(&mut self, amount: usize, _timeout: NextTimeout) -> Result<(), ureq::Error> {
349
        let mut writer = self.w.lock().expect("lock poisoned");
350

            
351
        let buffer = self.buffer.output();
352
        let data_to_write = &buffer[..amount];
353

            
354
        self.rt.block_on(async {
355
            writer.write_all(data_to_write).await?;
356
            writer.flush().await?;
357
            Ok(())
358
        })
359
    }
360

            
361
    // Read data from arti stream to ureq buffer.
362
    fn await_input(&mut self, _timeout: NextTimeout) -> Result<bool, ureq::Error> {
363
        let mut reader = self.r.lock().expect("lock poisoned");
364

            
365
        let buffers = self.buffer.input_append_buf();
366
        let size = self.rt.block_on(reader.read(buffers))?;
367
        self.buffer.input_appended(size);
368

            
369
        Ok(size > 0)
370
    }
371

            
372
    // Check if the connection is open.
373
    fn is_open(&mut self) -> bool {
374
        // We use `TorClient::connect` without `StreamPrefs::optimistic`,
375
        // so `.is_connected()` tells us whether the stream has *ceased to be* open;
376
        // i.e., we don't risk returning `false` because the stream isn't open *yet*.
377
        self.r.lock().is_ok_and(|guard| {
378
            guard
379
                .client_stream_ctrl()
380
                .is_some_and(|ctrl| ctrl.is_connected())
381
        })
382
    }
383
}
384

            
385
impl ConnectorBuilder<tor_rtcompat::PreferredRuntime> {
386
    /// Returns instance of [`ConnectorBuilder`] with default values.
387
    pub fn new() -> Result<Self, Error> {
388
        Ok(ConnectorBuilder {
389
            client: None,
390
            runtime: tor_rtcompat::PreferredRuntime::create()?,
391
            tls_provider: None,
392
        })
393
    }
394
}
395

            
396
impl<R: Runtime> ConnectorBuilder<R> {
397
    /// Creates instance of [`Connector`] from the builder.
398
1
    pub fn build(self) -> Result<Connector<R>, Error> {
399
1
        let client = match self.client {
400
1
            Some(client) => client,
401
            None => TorClient::with_runtime(self.runtime).create_unbootstrapped()?,
402
        };
403

            
404
1
        let tls_provider = self.tls_provider.unwrap_or_else(get_default_tls_provider);
405

            
406
1
        Ok(Connector {
407
1
            client,
408
1
            tls_provider,
409
1
        })
410
1
    }
411

            
412
    /// Creates new [`Connector`] with an explicitly specified [`tor_rtcompat::Runtime`].
413
    ///
414
    /// The value `runtime` is only used if no [`arti_client::TorClient`] is configured using [`ConnectorBuilder::tor_client`].
415
1
    pub fn with_runtime(runtime: R) -> Result<ConnectorBuilder<R>, Error> {
416
1
        Ok(ConnectorBuilder {
417
1
            client: None,
418
1
            runtime,
419
1
            tls_provider: None,
420
1
        })
421
1
    }
422

            
423
    /// Configure a custom Tor client to be used with [`Connector`].
424
    ///
425
    /// Will also cause `client`'s `Runtime` to be used (obtained via [`TorClient::runtime()`]).
426
    ///
427
    /// If the client isn't `TorClient<PreferredRuntime>`, use [`ConnectorBuilder::with_runtime()`]
428
    /// to create a suitable `ConnectorBuilder`.
429
1
    pub fn tor_client(mut self, client: Arc<TorClient<R>>) -> ConnectorBuilder<R> {
430
1
        self.runtime = client.runtime().clone();
431
1
        self.client = Some(client);
432
1
        self
433
1
    }
434

            
435
    /// Configure the TLS provider to be used with [`Connector`].
436
    pub fn tls_provider(mut self, tls_provider: UreqTlsProvider) -> Self {
437
        self.tls_provider = Some(tls_provider);
438
        self
439
    }
440
}
441

            
442
// Implementation of trait [`ureq::unversioned::resolver::Resolver`] for [`Resolver`].
443
//
444
// `Resolver` can be used in [`ureq::Agent::with_parts`] to resolve the host to an IP address.
445
//
446
// Uses [`arti_client::TorClient::resolve`].
447
//
448
// We highly advice only using `Resolver` instead of e.g `ureq`'s [`ureq::unversioned::resolver::DefaultResolver`] to avoid DNS leaks.
449
impl<R: Runtime + ToplevelBlockOn> UreqResolver for Resolver<R> {
450
    /// Method to resolve the host to an IP address using `arti_client::TorClient::resolve`.
451
    fn resolve(
452
        &self,
453
        uri: &Uri,
454
        _config: &ureq::config::Config,
455
        _timeout: NextTimeout,
456
    ) -> Result<ResolvedSocketAddrs, ureq::Error> {
457
        // We just retrieve the IP addresses using `arti_client::TorClient::resolve` and output
458
        // it in a format that ureq can use.
459
        let (host, port) = uri_to_host_port(uri)?;
460
        let ips = self
461
            .client
462
            .runtime()
463
            .block_on(async { self.client.resolve(&host).await })
464
            .map_err(Error::from)?;
465

            
466
        let mut array_vec: ResolvedSocketAddrs = ArrayVec::from_fn(|_| {
467
            core::net::SocketAddr::new(core::net::IpAddr::V4(core::net::Ipv4Addr::UNSPECIFIED), 0)
468
        });
469

            
470
        for ip in ips.into_iter() {
471
            let socket_addr = core::net::SocketAddr::new(ip, port);
472

            
473
            // If the ResolvedSocketAddrs is full, we stop pushing
474
            // and discard the remaining addresses.
475
            //
476
            // Eventually, we may want to do something more clever here,
477
            // like shuffling the addresses, or making sure we always return
478
            // a good mix of address families, etc., but this seems good enough
479
            // for now.
480
            if array_vec.try_push(socket_addr).is_err() {
481
                break;
482
            }
483
        }
484

            
485
        Ok(array_vec)
486
    }
487
}
488

            
489
impl<R: Runtime + ToplevelBlockOn> Connector<R> {
490
    /// Creates new instance with the provided [`arti_client::TorClient`].
491
    pub fn with_tor_client(client: Arc<TorClient<R>>) -> Connector<R> {
492
        Connector {
493
            client,
494
            tls_provider: get_default_tls_provider(),
495
        }
496
    }
497
}
498

            
499
impl<R: Runtime + ToplevelBlockOn> UreqConnector<()> for Connector<R> {
500
    type Out = Box<dyn Transport>;
501

            
502
    /// Makes a connection using the Tor client.
503
    ///
504
    /// Returns a `HttpTransport` which implements trait [`ureq::unversioned::transport::Transport`].
505
    fn connect(
506
        &self,
507
        details: &ureq::unversioned::transport::ConnectionDetails,
508
        _chained: Option<()>,
509
    ) -> Result<Option<Self::Out>, ureq::Error> {
510
        // Retrieve host and port from the ConnectionDetails.
511
        let (host, port) = uri_to_host_port(details.uri)?;
512

            
513
        // Convert to an address we can use to connect over the Tor network.
514
        let addr = (host.as_str(), port)
515
            .into_tor_addr()
516
            .map_err(|e| Error::Arti(e.into()))?;
517

            
518
        // Retrieve stream from Tor connection.
519
        let stream = self
520
            .client
521
            .runtime()
522
            .block_on(async { self.client.connect(addr).await })
523
            .map_err(Error::from)?;
524

            
525
        // Return a HttpTransport with a reader and writer to the stream.
526
        let (r, w) = stream.split();
527
        Ok(Some(Box::new(HttpTransport {
528
            r: Arc::new(Mutex::new(r)),
529
            w: Arc::new(Mutex::new(w)),
530
            buffer: LazyBuffers::new(2048, 2048),
531
            rt: self.client.runtime().clone(),
532
        })))
533
    }
534
}
535

            
536
impl Connector<tor_rtcompat::PreferredRuntime> {
537
    /// Returns new `Connector` with default values.
538
    ///
539
    /// To configure a non-default `Connector`,
540
    /// use [`ConnectorBuilder`].
541
    ///
542
    /// Warning: This method creates a default [`arti_client::TorClient`]. Using multiple concurrent
543
    /// instances of `TorClient` is not recommended. Most programs should create a single `TorClient` centrally.
544
    pub fn new() -> Result<Self, Error> {
545
        Self::builder()?.build()
546
    }
547
}
548

            
549
impl<R: Runtime + ToplevelBlockOn> Connector<R> {
550
    /// Returns instance of [`Resolver`] implementing trait [`ureq::unversioned::resolver::Resolver`].
551
    pub fn resolver(&self) -> Resolver<R> {
552
        Resolver {
553
            client: self.client.clone(),
554
        }
555
    }
556

            
557
    /// Returns instance of [`ureq::Agent`].
558
    ///
559
    /// Equivalent to using [`ureq::Agent::with_parts`] with the default [`ureq::config::Config`]
560
    /// and this `Connector` and the resolver obtained from [`Connector::resolver()`].
561
    ///
562
    /// # Example
563
    ///
564
    /// ```rust,no_run
565
    /// let ureq_agent = arti_ureq::Connector::new()
566
    ///     .expect("Failed to create Connector")
567
    ///     .agent();
568
    ///
569
    /// // Use the agent to make a request.
570
    /// ureq_agent
571
    ///     .get("https://check.torproject.org/api/ip")
572
    ///     .call()
573
    ///     .expect("Failed to make request.");
574
    /// ```
575
    pub fn agent(self) -> ureq::Agent {
576
        let resolver = self.resolver();
577

            
578
        let ureq_config = ureq::config::Config::builder()
579
            .tls_config(
580
                ureq::tls::TlsConfig::builder()
581
                    .provider(self.tls_provider)
582
                    .build(),
583
            )
584
            .build();
585

            
586
        ureq::Agent::with_parts(ureq_config, self.connector_chain(), resolver)
587
    }
588

            
589
    /// Returns instance of [`ureq::Agent`] using the provided [`ureq::config::Config`].
590
    ///
591
    /// Equivalent to [`Connector::agent`] but allows the user to provide a custom [`ureq::config::Config`].
592
    pub fn agent_with_ureq_config(
593
        self,
594
        config: ureq::config::Config,
595
    ) -> Result<ureq::Agent, Error> {
596
        let resolver = self.resolver();
597

            
598
        if self.tls_provider != config.tls_config().provider() {
599
            return Err(Error::TlsConfigMismatch);
600
        }
601

            
602
        Ok(ureq::Agent::with_parts(
603
            config,
604
            self.connector_chain(),
605
            resolver,
606
        ))
607
    }
608

            
609
    /// Returns connector chain depending on features flag.
610
    fn connector_chain(self) -> impl UreqConnector {
611
        let chain = self;
612

            
613
        #[cfg(feature = "rustls")]
614
        let chain = chain.chain(RustlsConnector::default());
615

            
616
        #[cfg(feature = "native-tls")]
617
        let chain = chain.chain(NativeTlsConnector::default());
618

            
619
        chain
620
    }
621
}
622

            
623
/// Returns the default [`ureq::tls::TlsProvider`] based on the features flag.
624
2
pub fn get_default_tls_provider() -> UreqTlsProvider {
625
2
    if cfg!(feature = "native-tls") {
626
2
        UreqTlsProvider::NativeTls
627
    } else {
628
        UreqTlsProvider::Rustls
629
    }
630
2
}
631

            
632
/// Implementation to make [`ConnectorBuilder`] accessible from [`Connector`].
633
///
634
/// # Example
635
///
636
/// ```rust,no_run
637
/// let rt = tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime.");
638
/// let tls_provider = arti_ureq::get_default_tls_provider();
639
///
640
/// let client = arti_client::TorClient::with_runtime(rt.clone())
641
///     .create_unbootstrapped()
642
///     .expect("Error creating Tor Client.");
643
///
644
/// let builder = arti_ureq::ConnectorBuilder::<tor_rtcompat::PreferredRuntime>::new()
645
///     .expect("Failed to create ConnectorBuilder.")
646
///     .tor_client(client)
647
///     .tls_provider(tls_provider);
648
///
649
/// let arti_connector = builder.build();
650
/// ```
651
impl Connector<tor_rtcompat::PreferredRuntime> {
652
    /// Returns new [`ConnectorBuilder`] with default values.
653
    pub fn builder() -> Result<ConnectorBuilder<tor_rtcompat::PreferredRuntime>, Error> {
654
        ConnectorBuilder::new()
655
    }
656
}
657

            
658
/// Parse the URI.
659
///
660
/// Obtain the host and port.
661
3
fn uri_to_host_port(uri: &Uri) -> Result<(String, u16), Error> {
662
3
    let host = uri
663
3
        .host()
664
        .ok_or_else(|| Error::MissingHostname { uri: uri.clone() })?;
665

            
666
3
    let port = match uri.scheme() {
667
3
        Some(scheme) if scheme == &Scheme::HTTPS => Ok(443),
668
1
        Some(scheme) if scheme == &Scheme::HTTP => Ok(80),
669
        Some(_) => Err(Error::UnsupportedUriScheme { uri: uri.clone() }),
670
        None => Err(Error::UnsupportedUriScheme { uri: uri.clone() }),
671
    }?;
672

            
673
3
    Ok((host.to_owned(), port))
674
3
}
675

            
676
#[cfg(test)]
677
mod arti_ureq_test {
678
    // @@ begin test lint list maintained by maint/add_warning @@
679
    #![allow(clippy::bool_assert_comparison)]
680
    #![allow(clippy::clone_on_copy)]
681
    #![allow(clippy::dbg_macro)]
682
    #![allow(clippy::mixed_attributes_style)]
683
    #![allow(clippy::print_stderr)]
684
    #![allow(clippy::print_stdout)]
685
    #![allow(clippy::single_char_pattern)]
686
    #![allow(clippy::unwrap_used)]
687
    #![allow(clippy::unchecked_time_subtraction)]
688
    #![allow(clippy::useless_vec)]
689
    #![allow(clippy::needless_pass_by_value)]
690
    #![allow(clippy::string_slice)] // See arti#2571
691
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
692

            
693
    use super::*;
694
    use arti_client::config::TorClientConfigBuilder;
695
    use std::str::FromStr;
696
    use test_temp_dir::test_temp_dir;
697

            
698
    const ARTI_TEST_LIVE_NETWORK: &str = "ARTI_TEST_LIVE_NETWORK";
699
    const ARTI_TESTING_ON_LOCAL: &str = "ARTI_TESTING_ON_LOCAL";
700

            
701
    // Helper function to check if two types are equal. The types in this library are to
702
    // complex to use the `==` operator or (Partial)Eq. So we compare the types of the individual properties instead.
703
4
    fn assert_equal_types<T>(_: &T, _: &T) {}
704

            
705
    // Helper function to check if the environment variable ARTI_TEST_LIVE_NETWORK is set to 1.
706
    // We only want to run tests using the live network when the user explicitly wants to.
707
2
    fn test_live_network() -> bool {
708
2
        let run_test = std::env::var(ARTI_TEST_LIVE_NETWORK).is_ok_and(|v| v == "1");
709
2
        if !run_test {
710
2
            println!("Skipping test, set {}=1 to run.", ARTI_TEST_LIVE_NETWORK);
711
        }
712

            
713
2
        run_test
714
2
    }
715

            
716
    // Helper function to check if the environment variable ARTI_TESTING_ON_LOCAL is set to 1.
717
    // Some tests, especially those that create default `Connector` instances, or test the `ConnectorBuilder`,
718
    // are not reliable when run on CI.  We don't know why that is.  It's probably a bug.  TODO fix the tests!
719
3
    fn testing_on_local() -> bool {
720
3
        let run_test = std::env::var(ARTI_TESTING_ON_LOCAL).is_ok_and(|v| v == "1");
721
3
        if !run_test {
722
3
            println!("Skipping test, set {}=1 to run.", ARTI_TESTING_ON_LOCAL);
723
        }
724

            
725
3
        run_test
726
3
    }
727

            
728
    // Helper method to allow tests to be ran in a closure.
729
1
    fn test_with_tor_client<R: Runtime>(rt: R, f: impl FnOnce(Arc<TorClient<R>>)) {
730
1
        let temp_dir = test_temp_dir!();
731
1
        temp_dir.used_by(move |temp_dir| {
732
1
            let arti_config = TorClientConfigBuilder::from_directories(
733
1
                temp_dir.join("state"),
734
1
                temp_dir.join("cache"),
735
1
            )
736
1
            .build()
737
1
            .expect("Failed to build TorClientConfig");
738

            
739
1
            let tor_client = arti_client::TorClient::with_runtime(rt)
740
1
                .config(arti_config)
741
1
                .create_unbootstrapped()
742
1
                .expect("Error creating Tor Client.");
743

            
744
1
            f(tor_client);
745
1
        });
746
1
    }
747

            
748
    // Helper function to make a request to check.torproject.org/api/ip and check if
749
    // it was done over Tor.
750
    fn request_is_tor(agent: ureq::Agent, https: bool) -> bool {
751
        let mut request = agent
752
            .get(format!(
753
                "http{}://check.torproject.org/api/ip",
754
                if https { "s" } else { "" }
755
            ))
756
            .call()
757
            .expect("Failed to make request.");
758
        let response = request
759
            .body_mut()
760
            .read_to_string()
761
            .expect("Failed to read body.");
762
        let json_response: serde_json::Value =
763
            serde_json::from_str(&response).expect("Failed to parse JSON.");
764
        json_response
765
            .get("IsTor")
766
            .expect("Failed to retrieve IsTor property from response")
767
            .as_bool()
768
            .expect("Failed to convert IsTor to bool")
769
    }
770

            
771
    // Quick internal test to check if our helper function `equal_types` works as expected.
772
    // Otherwise our other tests might not be reliable.
773
    #[test]
774
1
    fn test_equal_types() {
775
1
        assert_equal_types(&1, &i32::MIN);
776
1
        assert_equal_types(&1, &i64::MIN);
777
1
        assert_equal_types(&String::from("foo"), &String::with_capacity(1));
778
1
    }
779

            
780
    // `Connector::new` should return the default `Connector`.
781
    // This test is only ran when ARTI_TESTING_ON_LOCAL is set to 1.
782
    #[test]
783
    #[cfg(all(feature = "rustls", not(feature = "native-tls")))]
784
    fn articonnector_new_returns_default() {
785
        if !testing_on_local() {
786
            return;
787
        }
788

            
789
        let actual_connector = Connector::new().expect("Failed to create Connector.");
790
        let expected_connector = Connector {
791
            client: TorClient::with_runtime(
792
                tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime."),
793
            )
794
            .create_unbootstrapped()
795
            .expect("Error creating Tor Client."),
796
            tls_provider: UreqTlsProvider::Rustls,
797
        };
798

            
799
        assert_equal_types(&expected_connector, &actual_connector);
800
        assert_equal_types(
801
            &actual_connector.client.runtime().clone(),
802
            &tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime."),
803
        );
804
        assert_eq!(
805
            &actual_connector.tls_provider,
806
            &ureq::tls::TlsProvider::Rustls,
807
        );
808
    }
809

            
810
    // `Connector::with_tor_client` should return a `Connector` with specified Tor client set.
811
    // This test is only ran when ARTI_TESTING_ON_LOCAL is set to 1.
812
    #[test]
813
    #[cfg(all(feature = "rustls", not(feature = "native-tls")))]
814
    fn articonnector_with_tor_client() {
815
        if !testing_on_local() {
816
            return;
817
        }
818

            
819
        let tor_client = TorClient::with_runtime(
820
            tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime."),
821
        )
822
        .create_unbootstrapped()
823
        .expect("Error creating Tor Client.");
824

            
825
        let actual_connector = Connector::with_tor_client(tor_client);
826
        let expected_connector = Connector {
827
            client: TorClient::with_runtime(
828
                tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime."),
829
            )
830
            .create_unbootstrapped()
831
            .expect("Error creating Tor Client."),
832
            tls_provider: UreqTlsProvider::Rustls,
833
        };
834

            
835
        assert_equal_types(&expected_connector, &actual_connector);
836
        assert_equal_types(
837
            &actual_connector.client.runtime().clone(),
838
            &tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime."),
839
        );
840
        assert_eq!(
841
            &actual_connector.tls_provider,
842
            &ureq::tls::TlsProvider::Rustls,
843
        );
844
    }
845

            
846
    // The default instance returned by `Connector::builder` should equal to the default `Connector`.
847
    // This test is only ran when ARTI_TESTING_ON_LOCAL is set to 1.
848
    #[test]
849
1
    fn articonnectorbuilder_new_returns_default() {
850
1
        if !testing_on_local() {
851
1
            return;
852
        }
853

            
854
        let expected = Connector::new().expect("Failed to create Connector.");
855
        let actual = Connector::<tor_rtcompat::PreferredRuntime>::builder()
856
            .expect("Failed to create ConnectorBuilder.")
857
            .build()
858
            .expect("Failed to create Connector.");
859

            
860
        assert_equal_types(&expected, &actual);
861
        assert_equal_types(&expected.client.runtime(), &actual.client.runtime());
862
        assert_eq!(&expected.tls_provider, &actual.tls_provider);
863
1
    }
864

            
865
    // `ConnectorBuilder::with_runtime` should return a `ConnectorBuilder` with the specified runtime set.
866
    // This test is only ran when ARTI_TESTING_ON_LOCAL is set to 1.
867
    #[cfg(all(feature = "tokio", feature = "rustls"))]
868
    #[test]
869
1
    fn articonnectorbuilder_with_runtime() {
870
1
        if !testing_on_local() {
871
1
            return;
872
        }
873

            
874
        let arti_connector = ConnectorBuilder::with_runtime(
875
            tor_rtcompat::tokio::TokioRustlsRuntime::create().expect("Failed to create runtime."),
876
        )
877
        .expect("Failed to create ConnectorBuilder.")
878
        .build()
879
        .expect("Failed to create Connector.");
880

            
881
        assert_equal_types(
882
            &arti_connector.client.runtime().clone(),
883
            &tor_rtcompat::tokio::TokioRustlsRuntime::create().expect("Failed to create runtime."),
884
        );
885

            
886
        let arti_connector = ConnectorBuilder::with_runtime(
887
            tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime."),
888
        )
889
        .expect("Failed to create ConnectorBuilder.")
890
        .build()
891
        .expect("Failed to create Connector.");
892

            
893
        assert_equal_types(
894
            &arti_connector.client.runtime().clone(),
895
            &tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime."),
896
        );
897
1
    }
898

            
899
    // `ConnectorBuilder::tor_client` should return a `Connector` with the specified `TorClient` set.
900
    #[cfg(all(feature = "tokio", feature = "rustls"))]
901
    #[test]
902
1
    fn articonnectorbuilder_set_tor_client() {
903
        let rt =
904
1
            tor_rtcompat::tokio::TokioRustlsRuntime::create().expect("Failed to create runtime.");
905

            
906
1
        test_with_tor_client(rt.clone(), move |tor_client| {
907
1
            let arti_connector = ConnectorBuilder::with_runtime(rt)
908
1
                .expect("Failed to create ConnectorBuilder.")
909
1
                .tor_client(tor_client.clone().isolated_client())
910
1
                .build()
911
1
                .expect("Failed to create Connector.");
912

            
913
1
            assert_equal_types(
914
1
                &arti_connector.client.runtime().clone(),
915
1
                &tor_rtcompat::tokio::TokioRustlsRuntime::create()
916
1
                    .expect("Failed to create runtime."),
917
1
            );
918
1
        });
919
1
    }
920

            
921
    // Test if the method `uri_to_host_port` returns the correct parameters.
922
    #[test]
923
1
    fn test_uri_to_host_port() {
924
1
        let uri = Uri::from_str("http://torproject.org").expect("Error parsing uri.");
925
1
        let (host, port) = uri_to_host_port(&uri).expect("Error parsing uri.");
926

            
927
1
        assert_eq!(host, "torproject.org");
928
1
        assert_eq!(port, 80);
929

            
930
1
        let uri = Uri::from_str("https://torproject.org").expect("Error parsing uri.");
931
1
        let (host, port) = uri_to_host_port(&uri).expect("Error parsing uri.");
932

            
933
1
        assert_eq!(host, "torproject.org");
934
1
        assert_eq!(port, 443);
935

            
936
1
        let uri = Uri::from_str("https://www.torproject.org/test").expect("Error parsing uri.");
937
1
        let (host, port) = uri_to_host_port(&uri).expect("Error parsing uri.");
938

            
939
1
        assert_eq!(host, "www.torproject.org");
940
1
        assert_eq!(port, 443);
941
1
    }
942

            
943
    // Test if `arti-ureq` default agent uses Tor to make the request.
944
    // This test is only ran when ARTI_TEST_LIVE_NETWORK is set to 1.
945
    #[test]
946
1
    fn request_goes_over_tor() {
947
1
        if !test_live_network() {
948
1
            return;
949
        }
950

            
951
        let is_tor = request_is_tor(
952
            default_agent().expect("Failed to retrieve default agent."),
953
            true,
954
        );
955

            
956
        assert_eq!(is_tor, true);
957
1
    }
958

            
959
    // Test if `arti-ureq` default agent uses Tor to make the request.
960
    // This test also checks if the Tor API returns false when the request is made with an
961
    // `ureq` agent that is not configured to use Tor to ensure the test is reliable.
962
    // This test is only ran when ARTI_TEST_LIVE_NETWORK is set to 1.
963
    #[test]
964
    #[cfg(all(feature = "rustls", not(feature = "native-tls")))]
965
    fn request_goes_over_tor_with_unsafe_check() {
966
        if !test_live_network() {
967
            return;
968
        }
969

            
970
        let is_tor = request_is_tor(ureq::Agent::new_with_defaults(), true);
971
        assert_eq!(is_tor, false);
972

            
973
        let is_tor = request_is_tor(
974
            default_agent().expect("Failed to retrieve default agent."),
975
            true,
976
        );
977
        assert_eq!(is_tor, true);
978
    }
979

            
980
    // Test if the `ureq` client configured with `Connector` uses Tor tor make the request using bare HTTP.
981
    // This test is only ran when ARTI_TEST_LIVE_NETWORK is set to 1.
982
    #[test]
983
1
    fn request_with_bare_http() {
984
1
        if !test_live_network() {
985
1
            return;
986
        }
987

            
988
        let rt = tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime.");
989

            
990
        test_with_tor_client(rt, |tor_client| {
991
            let arti_connector = Connector::with_tor_client(tor_client);
992
            let is_tor = request_is_tor(arti_connector.agent(), false);
993

            
994
            assert_eq!(is_tor, true);
995
        });
996
1
    }
997

            
998
    // Test if `get_default_tls_provider` correctly derives the TLS provider from the feature flags.
999
    #[test]
1
    fn test_get_default_tls_provider() {
        #[cfg(feature = "native-tls")]
1
        assert_eq!(get_default_tls_provider(), UreqTlsProvider::NativeTls);
        #[cfg(not(feature = "native-tls"))]
        assert_eq!(get_default_tls_provider(), UreqTlsProvider::Rustls);
1
    }
    // Test if configuring the `Connector` using `get_default_tls_provider` correctly sets the TLS provider
    // based on the feature flags.
    // This test is only ran when ARTI_TESTING_ON_LOCAL is set to 1.
    #[test]
1
    fn test_tor_client_with_get_default_tls_provider() {
1
        if !testing_on_local() {
1
            return;
        }
        let tor_client = TorClient::with_runtime(
            tor_rtcompat::PreferredRuntime::create().expect("Failed to create runtime."),
        )
        .create_unbootstrapped()
        .expect("Error creating Tor Client.");
        let arti_connector = Connector::<tor_rtcompat::PreferredRuntime>::builder()
            .expect("Failed to create ConnectorBuilder.")
            .tor_client(tor_client.clone().isolated_client())
            .tls_provider(get_default_tls_provider())
            .build()
            .expect("Failed to create Connector.");
        #[cfg(feature = "native-tls")]
        assert_eq!(
            &arti_connector.tls_provider,
            &ureq::tls::TlsProvider::NativeTls,
        );
        #[cfg(not(feature = "native-tls"))]
        assert_eq!(
            &arti_connector.tls_provider,
            &ureq::tls::TlsProvider::Rustls,
        );
1
    }
}