Skip to main content

tor_rtcompat/
lib.rs

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 #1645 (either remove this, or decide to have it everywhere)
53#![cfg_attr(not(all(feature = "full")), allow(unused))]
54
55#[cfg(all(
56    any(feature = "native-tls", feature = "rustls"),
57    any(feature = "async-std", feature = "tokio", feature = "smol")
58))]
59pub(crate) mod impls;
60pub mod task;
61
62mod coarse_time;
63mod compound;
64mod dyn_time;
65pub mod general;
66pub mod join_set;
67mod network;
68mod opaque;
69pub mod scheduler;
70mod timer;
71mod traits;
72pub mod unimpl;
73pub mod unix;
74
75#[cfg(any(feature = "async-std", feature = "tokio", feature = "smol"))]
76use std::io;
77pub use traits::{
78    Blocking, CertifiedConn, CoarseTimeProvider, JoinSet, JoinSetProvider, NetStreamListener,
79    NetStreamProvider, NoOpStreamOpsHandle, Runtime, SleepProvider, SpawnExt, StreamOps,
80    TlsProvider, ToplevelBlockOn, ToplevelRuntime, UdpProvider, UdpSocket, UnsupportedStreamOp,
81};
82
83pub use coarse_time::{CoarseDuration, CoarseInstant, RealCoarseTimeProvider};
84pub use dyn_time::DynTimeProvider;
85pub use network::{
86    CommonConnectOptions, CommonListenOptions, TcpConnectOptions, TcpListenOptions,
87    UnixConnectOptions, UnixListenOptions,
88};
89pub use timer::{SleepProviderExt, Timeout, TimeoutError};
90
91/// Traits used to describe TLS connections and objects that can
92/// create them.
93pub mod tls {
94    #[cfg(all(
95        any(feature = "native-tls", feature = "rustls"),
96        any(feature = "async-std", feature = "tokio", feature = "smol")
97    ))]
98    pub use crate::impls::unimpl_tls::UnimplementedTls;
99    pub use crate::traits::{
100        CertifiedConn, TlsAcceptorSettings, TlsConnector, TlsServerUnsupported,
101    };
102
103    #[cfg(all(
104        feature = "native-tls",
105        any(feature = "tokio", feature = "async-std", feature = "smol")
106    ))]
107    pub use crate::impls::native_tls::NativeTlsProvider;
108    #[cfg(all(
109        feature = "rustls",
110        any(feature = "tokio", feature = "async-std", feature = "smol")
111    ))]
112    pub use crate::impls::rustls::RustlsProvider;
113    #[cfg(all(
114        feature = "rustls",
115        feature = "tls-server",
116        any(feature = "tokio", feature = "async-std", feature = "smol")
117    ))]
118    pub use crate::impls::rustls::rustls_server::{RustlsAcceptor, RustlsServerStream};
119}
120
121#[cfg(all(any(feature = "native-tls", feature = "rustls"), feature = "tokio"))]
122pub mod tokio;
123
124#[cfg(all(any(feature = "native-tls", feature = "rustls"), feature = "async-std"))]
125pub mod async_std;
126
127#[cfg(all(any(feature = "native-tls", feature = "rustls"), feature = "smol"))]
128pub mod smol;
129
130pub use compound::{CompoundRuntime, RuntimeSubstExt};
131
132#[cfg(all(
133    any(feature = "native-tls", feature = "rustls"),
134    feature = "async-std",
135    not(feature = "tokio")
136))]
137use async_std as preferred_backend_mod;
138#[cfg(all(any(feature = "native-tls", feature = "rustls"), feature = "tokio"))]
139use tokio as preferred_backend_mod;
140
141/// The runtime that we prefer to use, out of all the runtimes compiled into the
142/// tor-rtcompat crate.
143///
144/// If `tokio` and `async-std` are both available, we prefer `tokio` for its
145/// performance.
146/// If `native_tls` and `rustls` are both available, we prefer `native_tls` since
147/// it has been used in Arti for longer.
148///
149/// The process [**may not fork**](crate#do-not-fork)
150/// (except, very carefully, before exec)
151/// after creating this or any other `Runtime`.
152#[cfg(all(
153    any(feature = "native-tls", feature = "rustls"),
154    any(feature = "async-std", feature = "tokio")
155))]
156#[derive(Clone)]
157pub struct PreferredRuntime {
158    /// The underlying runtime object.
159    inner: preferred_backend_mod::PreferredRuntime,
160}
161
162#[cfg(all(
163    any(feature = "native-tls", feature = "rustls"),
164    any(feature = "async-std", feature = "tokio")
165))]
166crate::opaque::implement_opaque_runtime! {
167    PreferredRuntime { inner : preferred_backend_mod::PreferredRuntime }
168}
169
170#[cfg(all(
171    any(feature = "native-tls", feature = "rustls"),
172    any(feature = "async-std", feature = "tokio")
173))]
174impl PreferredRuntime {
175    /// Obtain a [`PreferredRuntime`] from the currently running asynchronous runtime.
176    /// Generally, this is what you want.
177    ///
178    /// This tries to get a handle to a currently running asynchronous runtime, and
179    /// wraps it; the returned [`PreferredRuntime`] isn't the same thing as the
180    /// asynchronous runtime object itself (e.g. `tokio::runtime::Runtime`).
181    ///
182    /// # Panics
183    ///
184    /// When `tor-rtcompat` is compiled with the `tokio` feature enabled
185    /// (regardless of whether the `async-std` feature is also enabled),
186    /// panics if called outside of Tokio runtime context.
187    /// See `tokio::runtime::Handle::current`.
188    ///
189    /// # Usage notes
190    ///
191    /// Once you have a runtime returned by this function, you should
192    /// just create more handles to it via [`Clone`].
193    ///
194    /// # Limitations
195    ///
196    /// If the `tor-rtcompat` crate was compiled with `tokio` support,
197    /// this function will never return a runtime based on `async_std`.
198    ///
199    /// The process [**may not fork**](crate#do-not-fork)
200    /// (except, very carefully, before exec)
201    /// after creating this or any other `Runtime`.
202    //
203    // ## Note to Arti developers
204    //
205    // We should never call this from inside other Arti crates, or from
206    // library crates that want to support multiple runtimes!  This
207    // function is for Arti _users_ who want to wrap some existing Tokio
208    // or Async_std runtime as a [`Runtime`].  It is not for library
209    // crates that want to work with multiple runtimes.
210    pub fn current() -> io::Result<Self> {
211        let rt = preferred_backend_mod::PreferredRuntime::current()?;
212
213        Ok(Self { inner: rt })
214    }
215
216    /// Create and return a new instance of the default [`Runtime`].
217    ///
218    /// Generally you should call this function at most once, and then use
219    /// [`Clone::clone()`] to create additional references to that runtime.
220    ///
221    /// Tokio users may want to avoid this function and instead obtain a runtime using
222    /// [`PreferredRuntime::current`]: this function always _builds_ a runtime,
223    /// and if you already have a runtime, that isn't what you want with Tokio.
224    ///
225    /// If you need more fine-grained control over a runtime, you can create it
226    /// using an appropriate builder type or function.
227    ///
228    /// The process [**may not fork**](crate#do-not-fork)
229    /// (except, very carefully, before exec)
230    /// after creating this or any other `Runtime`.
231    //
232    // ## Note to Arti developers
233    //
234    // We should never call this from inside other Arti crates, or from
235    // library crates that want to support multiple runtimes!  This
236    // function is for Arti _users_ who want to wrap some existing Tokio
237    // or Async_std runtime as a [`Runtime`].  It is not for library
238    // crates that want to work with multiple runtimes.
239    pub fn create() -> io::Result<Self> {
240        let rt = preferred_backend_mod::PreferredRuntime::create()?;
241
242        Ok(Self { inner: rt })
243    }
244
245    /// Helper to run a single test function in a freshly created runtime.
246    ///
247    /// # Panics
248    ///
249    /// Panics if we can't create this runtime.
250    ///
251    /// # Warning
252    ///
253    /// This API is **NOT** for consumption outside Arti. Semver guarantees are not provided.
254    #[doc(hidden)]
255    pub fn run_test<P, F, O>(func: P) -> O
256    where
257        P: FnOnce(Self) -> F,
258        F: futures::Future<Output = O>,
259    {
260        let runtime = Self::create().expect("Failed to create runtime");
261        runtime.clone().block_on(func(runtime))
262    }
263}
264
265/// Helpers for test_with_all_runtimes
266///
267/// # Warning
268///
269/// This API is **NOT** for consumption outside Arti. Semver guarantees are not provided.
270#[doc(hidden)]
271pub mod testing__ {
272    /// A trait for an object that might represent a test failure, or which
273    /// might just be `()`.
274    pub trait TestOutcome {
275        /// Abort if the test has failed.
276        fn check_ok(&self);
277    }
278    impl TestOutcome for () {
279        fn check_ok(&self) {}
280    }
281    impl<E: std::fmt::Debug> TestOutcome for Result<(), E> {
282        fn check_ok(&self) {
283            self.as_ref().expect("Test failure");
284        }
285    }
286}
287
288/// Helper: define a macro that expands a token tree iff a pair of features are
289/// both present.
290macro_rules! declare_conditional_macro {
291    ( $(#[$meta:meta])* macro $name:ident = ($f1:expr, $f2:expr) ) => {
292        $( #[$meta] )*
293        #[cfg(all(feature=$f1, feature=$f2))]
294        #[macro_export]
295        macro_rules! $name {
296            ($tt:tt) => {
297                $tt
298            };
299        }
300
301        $( #[$meta] )*
302        #[cfg(not(all(feature=$f1, feature=$f2)))]
303        #[macro_export]
304        macro_rules! $name {
305            ($tt:tt) => {};
306        }
307
308        // Needed so that we can access this macro at this path, both within the
309        // crate and without.
310        pub use $name;
311    };
312}
313
314/// Defines macros that will expand when certain runtimes are available.
315#[doc(hidden)]
316pub mod cond {
317    declare_conditional_macro! {
318        /// Expand a token tree if the TokioNativeTlsRuntime is available.
319        #[doc(hidden)]
320        macro if_tokio_native_tls_present = ("tokio", "native-tls")
321    }
322    declare_conditional_macro! {
323        /// Expand a token tree if the TokioRustlsRuntime is available.
324        #[doc(hidden)]
325        macro if_tokio_rustls_present = ("tokio", "rustls")
326    }
327    declare_conditional_macro! {
328        /// Expand a token tree if the TokioNativeTlsRuntime is available.
329        #[doc(hidden)]
330        macro if_async_std_native_tls_present = ("async-std", "native-tls")
331    }
332    declare_conditional_macro! {
333        /// Expand a token tree if the TokioNativeTlsRuntime is available.
334        #[doc(hidden)]
335        macro if_async_std_rustls_present = ("async-std", "rustls")
336    }
337    declare_conditional_macro! {
338        /// Expand a token tree if the SmolNativeTlsRuntime is available.
339        #[doc(hidden)]
340        macro if_smol_native_tls_present = ("smol", "native-tls")
341    }
342    declare_conditional_macro! {
343        /// Expand a token tree if the SmolRustlsRuntime is available.
344        #[doc(hidden)]
345        macro if_smol_rustls_present = ("smol", "rustls")
346    }
347}
348
349/// Run a test closure, passing as argument every supported runtime.
350///
351/// Usually, prefer `tor_rtmock::MockRuntime::test_with_various` to this.
352/// Use this macro only when you need to interact with things
353/// that `MockRuntime` can't handle,
354///
355/// If everything in your test case is supported by `MockRuntime`,
356/// you should use that instead:
357/// that will give superior test coverage *and* a (more) deterministic test.
358///
359/// (This is a macro so that it can repeat the closure as multiple separate
360/// expressions, so it can take on two different types, if needed.)
361//
362// NOTE(eta): changing this #[cfg] can affect tests inside this crate that use
363//            this macro, like in scheduler.rs
364#[macro_export]
365#[cfg(all(
366    any(feature = "native-tls", feature = "rustls"),
367    any(feature = "tokio", feature = "async-std", feature = "smol"),
368))]
369macro_rules! test_with_all_runtimes {
370    ( $fn:expr ) => {{
371        use $crate::cond::*;
372        use $crate::testing__::TestOutcome;
373        // We have to do this outcome-checking business rather than just using
374        // the ? operator or calling expect() because some of the closures that
375        // we use this macro with return (), and some return Result.
376
377        if_tokio_native_tls_present! {{
378           $crate::tokio::TokioNativeTlsRuntime::run_test($fn).check_ok();
379        }}
380        if_tokio_rustls_present! {{
381            $crate::tokio::TokioRustlsRuntime::run_test($fn).check_ok();
382        }}
383        if_async_std_native_tls_present! {{
384            $crate::async_std::AsyncStdNativeTlsRuntime::run_test($fn).check_ok();
385        }}
386        if_async_std_rustls_present! {{
387            $crate::async_std::AsyncStdRustlsRuntime::run_test($fn).check_ok();
388        }}
389        if_smol_native_tls_present! {{
390            $crate::smol::SmolNativeTlsRuntime::run_test($fn).check_ok();
391        }}
392        if_smol_rustls_present! {{
393            $crate::smol::SmolRustlsRuntime::run_test($fn).check_ok();
394        }}
395    }};
396}
397
398/// Run a test closure, passing as argument one supported runtime.
399///
400/// Usually, prefer `tor_rtmock::MockRuntime::test_with_various` to this.
401/// Use this macro only when you need to interact with things
402/// that `MockRuntime` can't handle.
403///
404/// If everything in your test case is supported by `MockRuntime`,
405/// you should use that instead:
406/// that will give superior test coverage *and* a (more) deterministic test.
407///
408/// (Always prefers tokio if present.)
409#[macro_export]
410#[cfg(all(
411    any(feature = "native-tls", feature = "rustls"),
412    any(feature = "tokio", feature = "async-std"),
413))]
414macro_rules! test_with_one_runtime {
415    ( $fn:expr ) => {{ $crate::PreferredRuntime::run_test($fn) }};
416}
417
418#[cfg(all(
419    test,
420    any(feature = "native-tls", feature = "rustls"),
421    any(feature = "async-std", feature = "tokio", feature = "smol"),
422    not(miri), // Many of these tests use real sockets or SystemTime.
423))]
424mod test {
425    // @@ begin test lint list maintained by maint/add_warning @@
426    #![allow(clippy::bool_assert_comparison)]
427    #![allow(clippy::clone_on_copy)]
428    #![allow(clippy::dbg_macro)]
429    #![allow(clippy::mixed_attributes_style)]
430    #![allow(clippy::print_stderr)]
431    #![allow(clippy::print_stdout)]
432    #![allow(clippy::single_char_pattern)]
433    #![allow(clippy::unwrap_used)]
434    #![allow(clippy::unchecked_time_subtraction)]
435    #![allow(clippy::useless_vec)]
436    #![allow(clippy::needless_pass_by_value)]
437    #![allow(clippy::string_slice)] // See arti#2571
438    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
439    #![allow(clippy::unnecessary_wraps)]
440    use crate::SleepProviderExt;
441    use crate::ToplevelRuntime;
442
443    use crate::traits::*;
444
445    use futures::io::{AsyncReadExt, AsyncWriteExt};
446    use futures::stream::StreamExt;
447    use native_tls_crate as native_tls;
448    use std::io::Result as IoResult;
449    use std::net::SocketAddr;
450    use std::net::{Ipv4Addr, SocketAddrV4};
451    use web_time_compat::{Duration, Instant, InstantExt, SystemTimeExt};
452
453    // Test "sleep" with a tiny delay, and make sure that at least that
454    // much delay happens.
455    fn small_delay<R: ToplevelRuntime>(runtime: &R) -> IoResult<()> {
456        let rt = runtime.clone();
457        runtime.block_on(async {
458            let i1 = Instant::get();
459            let one_msec = Duration::from_millis(1);
460            rt.sleep(one_msec).await;
461            let i2 = Instant::get();
462            assert!(i2 >= i1 + one_msec);
463        });
464        Ok(())
465    }
466
467    // Try a timeout operation that will succeed.
468    fn small_timeout_ok<R: ToplevelRuntime>(runtime: &R) -> IoResult<()> {
469        let rt = runtime.clone();
470        runtime.block_on(async {
471            let one_day = Duration::from_secs(86400);
472            let outcome = rt.timeout(one_day, async { 413_u32 }).await;
473            assert_eq!(outcome, Ok(413));
474        });
475        Ok(())
476    }
477
478    // Try a timeout operation that will time out.
479    fn small_timeout_expire<R: ToplevelRuntime>(runtime: &R) -> IoResult<()> {
480        use futures::future::pending;
481
482        let rt = runtime.clone();
483        runtime.block_on(async {
484            let one_micros = Duration::from_micros(1);
485            let outcome = rt.timeout(one_micros, pending::<()>()).await;
486            assert_eq!(outcome, Err(crate::TimeoutError));
487            assert_eq!(
488                outcome.err().unwrap().to_string(),
489                "Timeout expired".to_string()
490            );
491        });
492        Ok(())
493    }
494    // Try a little wallclock delay.
495    //
496    // NOTE: This test will fail if the clock jumps a lot while it's
497    // running.  We should use simulated time instead.
498    fn tiny_wallclock<R: ToplevelRuntime>(runtime: &R) -> IoResult<()> {
499        let rt = runtime.clone();
500        runtime.block_on(async {
501            let i1 = Instant::get();
502            let now = runtime.wallclock();
503            let one_millis = Duration::from_millis(1);
504            let one_millis_later = now + one_millis;
505
506            rt.sleep_until_wallclock(one_millis_later).await;
507
508            let i2 = Instant::get();
509            let newtime = runtime.wallclock();
510            assert!(newtime >= one_millis_later);
511            assert!(i2 - i1 >= one_millis);
512        });
513        Ok(())
514    }
515
516    // Try connecting to ourself and sending a little data.
517    //
518    // NOTE: requires Ipv4 localhost.
519    fn self_connect_tcp<R: ToplevelRuntime>(runtime: &R) -> IoResult<()> {
520        let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0);
521        let rt1 = runtime.clone();
522
523        let listen_options = Default::default();
524        let listener =
525            runtime.block_on(rt1.listen(&(SocketAddr::from(localhost)), &listen_options))?;
526        let addr = listener.local_addr()?;
527
528        runtime.block_on(async {
529            let task1 = async {
530                let mut buf = vec![0_u8; 11];
531                let (mut con, _addr) = listener.incoming().next().await.expect("closed?")?;
532                con.read_exact(&mut buf[..]).await?;
533                IoResult::Ok(buf)
534            };
535            let task2 = async {
536                let connect_options = Default::default();
537                let mut con = rt1.connect(&addr, &connect_options).await?;
538                con.write_all(b"Hello world").await?;
539                con.flush().await?;
540                IoResult::Ok(())
541            };
542
543            let (data, send_r) = futures::join!(task1, task2);
544            send_r?;
545
546            assert_eq!(&data?[..], b"Hello world");
547
548            Ok(())
549        })
550    }
551
552    // Try connecting to ourself and sending a little data.
553    //
554    // NOTE: requires Ipv4 localhost.
555    fn self_connect_udp<R: ToplevelRuntime>(runtime: &R) -> IoResult<()> {
556        let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0);
557        let rt1 = runtime.clone();
558
559        let socket1 = runtime.block_on(rt1.bind(&(localhost.into())))?;
560        let addr1 = socket1.local_addr()?;
561
562        let socket2 = runtime.block_on(rt1.bind(&(localhost.into())))?;
563        let addr2 = socket2.local_addr()?;
564
565        runtime.block_on(async {
566            let task1 = async {
567                let mut buf = [0_u8; 16];
568                let (len, addr) = socket1.recv(&mut buf[..]).await?;
569                IoResult::Ok((buf[..len].to_vec(), addr))
570            };
571            let task2 = async {
572                socket2.send(b"Hello world", &addr1).await?;
573                IoResult::Ok(())
574            };
575
576            let (recv_r, send_r) = futures::join!(task1, task2);
577            send_r?;
578            let (buff, addr) = recv_r?;
579            assert_eq!(addr2, addr);
580            assert_eq!(&buff, b"Hello world");
581
582            Ok(())
583        })
584    }
585
586    // Try out our incoming connection stream code.
587    //
588    // We launch a few connections and make sure that we can read data on
589    // them.
590    fn listener_stream<R: ToplevelRuntime>(runtime: &R) -> IoResult<()> {
591        let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0);
592        let rt1 = runtime.clone();
593
594        let listen_options = Default::default();
595        let listener = runtime
596            .block_on(rt1.listen(&SocketAddr::from(localhost), &listen_options))
597            .unwrap();
598        let addr = listener.local_addr().unwrap();
599        let mut stream = listener.incoming();
600
601        runtime.block_on(async {
602            let task1 = async {
603                let mut n = 0_u32;
604                loop {
605                    let (mut con, _addr) = stream.next().await.unwrap()?;
606                    let mut buf = [0_u8; 11];
607                    con.read_exact(&mut buf[..]).await?;
608                    n += 1;
609                    if &buf[..] == b"world done!" {
610                        break IoResult::Ok(n);
611                    }
612                }
613            };
614            let task2 = async {
615                let connect_options = Default::default();
616                for _ in 0_u8..5 {
617                    let mut con = rt1.connect(&addr, &connect_options).await?;
618                    con.write_all(b"Hello world").await?;
619                    con.flush().await?;
620                }
621                let mut con = rt1.connect(&addr, &connect_options).await?;
622                con.write_all(b"world done!").await?;
623                con.flush().await?;
624                con.close().await?;
625                IoResult::Ok(())
626            };
627
628            let (n, send_r) = futures::join!(task1, task2);
629            send_r?;
630
631            assert_eq!(n?, 6);
632
633            Ok(())
634        })
635    }
636
637    // Try listening on an address and connecting there, except using TLS.
638    //
639    // Note that since we didn't have TLS server support when this test was first written,
640    // we're going to use a thread.
641    fn simple_tls<R: ToplevelRuntime>(runtime: &R) -> IoResult<()> {
642        /*
643         A simple expired self-signed rsa-2048 certificate.
644
645         Generated by running the make-cert.c program in tor-rtcompat/test-data-helper,
646         and then making a PFX file using
647
648         openssl pkcs12 -export -certpbe PBE-SHA1-3DES -out test.pfx -inkey test.key -in test.crt
649
650         The password is "abc".
651        */
652        static PFX_ID: &[u8] = include_bytes!("test.pfx");
653        // Note that we need to set a password on the pkcs12 file, since apparently
654        // OSX doesn't support pkcs12 with empty passwords. (That was arti#111).
655        static PFX_PASSWORD: &str = "abc";
656
657        let localhost = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0);
658        let listener = std::net::TcpListener::bind(localhost)?;
659        let addr = listener.local_addr()?;
660
661        let identity = native_tls::Identity::from_pkcs12(PFX_ID, PFX_PASSWORD).unwrap();
662
663        // See note on function for why we're using a thread here.
664        let th = std::thread::spawn(move || {
665            // Accept a single TLS connection and run an echo server
666            use std::io::{Read, Write};
667            let acceptor = native_tls::TlsAcceptor::new(identity).unwrap();
668            let (con, _addr) = listener.accept()?;
669            let mut con = acceptor.accept(con).unwrap();
670            let mut buf = [0_u8; 16];
671            loop {
672                let n = con.read(&mut buf)?;
673                if n == 0 {
674                    break;
675                }
676                con.write_all(&buf[..n])?;
677            }
678            IoResult::Ok(())
679        });
680
681        let connector = runtime.tls_connector();
682
683        runtime.block_on(async {
684            let text = b"I Suddenly Dont Understand Anything";
685            let mut buf = vec![0_u8; text.len()];
686            let connect_options = Default::default();
687            let conn = runtime.connect(&addr, &connect_options).await?;
688            let mut conn = connector.negotiate_unvalidated(conn, "Kan.Aya").await?;
689            assert!(conn.peer_certificate()?.is_some());
690            conn.write_all(text).await?;
691            conn.flush().await?;
692            conn.read_exact(&mut buf[..]).await?;
693            assert_eq!(&buf[..], text);
694            conn.close().await?;
695            IoResult::Ok(())
696        })?;
697
698        th.join().unwrap()?;
699        IoResult::Ok(())
700    }
701
702    fn simple_tls_server<R: ToplevelRuntime>(runtime: &R) -> IoResult<()> {
703        let mut rng = tor_basic_utils::test_rng::testing_rng();
704        let tls_cert = tor_cert_x509::TlsKeyAndCert::create(
705            &mut rng,
706            std::time::SystemTime::get(),
707            "prospit.example.org",
708            "derse.example.org",
709        )
710        .unwrap();
711        let cert = tls_cert.certificates_der()[0].to_vec();
712        let settings = TlsAcceptorSettings::new(tls_cert).unwrap();
713
714        let Ok(tls_acceptor) = runtime.tls_acceptor(settings) else {
715            println!("Skipping tls-server test for runtime {:?}", runtime);
716            return IoResult::Ok(());
717        };
718        println!("Running tls-server test for runtime {:?}", runtime);
719
720        let tls_connector = runtime.tls_connector();
721
722        let localhost: SocketAddr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0).into();
723        let rt1 = runtime.clone();
724
725        let msg = b"Derse Reviles Him And Outlaws Frogs Wherever They Can";
726        runtime.block_on(async move {
727            let listen_options = Default::default();
728            let listener = runtime.listen(&localhost, &listen_options).await.unwrap();
729            let address = listener.local_addr().unwrap();
730
731            let h1 = runtime
732                .spawn_with_handle(async move {
733                    let conn = listener.incoming().next().await.unwrap().unwrap().0;
734                    let mut conn = tls_acceptor.negotiate_unvalidated(conn, "").await.unwrap();
735
736                    let mut buf = vec![];
737                    conn.read_to_end(&mut buf).await.unwrap();
738                    (buf, conn.own_certificate().unwrap().unwrap().into_owned())
739                })
740                .unwrap();
741
742            let h2 = runtime
743                .spawn_with_handle(async move {
744                    let connect_options = Default::default();
745                    let conn = rt1.connect(&address, &connect_options).await.unwrap();
746                    let mut conn = tls_connector
747                        .negotiate_unvalidated(conn, "prospit.example.org")
748                        .await
749                        .unwrap();
750                    conn.write_all(msg).await.unwrap();
751                    conn.close().await.unwrap();
752                    conn.peer_certificate().unwrap().unwrap().into_owned()
753                })
754                .unwrap();
755
756            let (received, server_own_cert) = h1.await;
757            let client_peer_cert = h2.await;
758            assert_eq!(received, msg);
759            assert_eq!(&server_own_cert, &cert);
760            assert_eq!(&client_peer_cert, &cert);
761        });
762        IoResult::Ok(())
763    }
764
765    macro_rules! tests_with_runtime {
766        { $runtime:expr  => $($id:ident),* $(,)? } => {
767            $(
768                #[test]
769                fn $id() -> std::io::Result<()> {
770                    super::$id($runtime)
771                }
772            )*
773        }
774    }
775
776    macro_rules! runtime_tests {
777        { $($id:ident),* $(,)? } =>
778        {
779           #[cfg(feature="tokio")]
780            mod tokio_runtime_tests {
781                tests_with_runtime! { &crate::tokio::PreferredRuntime::create()? => $($id),* }
782            }
783            #[cfg(feature="async-std")]
784            mod async_std_runtime_tests {
785                tests_with_runtime! { &crate::async_std::PreferredRuntime::create()? => $($id),* }
786            }
787            #[cfg(feature="smol")]
788            mod smol_runtime_tests {
789                tests_with_runtime! { &crate::smol::PreferredRuntime::create()? => $($id),* }
790            }
791            mod default_runtime_tests {
792                tests_with_runtime! { &crate::PreferredRuntime::create()? => $($id),* }
793            }
794        }
795    }
796
797    macro_rules! tls_runtime_tests {
798        { $($id:ident),* $(,)? } =>
799        {
800            #[cfg(all(feature="tokio", feature = "native-tls"))]
801            mod tokio_native_tls_tests {
802                tests_with_runtime! { &crate::tokio::TokioNativeTlsRuntime::create()? => $($id),* }
803            }
804            #[cfg(all(feature="async-std", feature = "native-tls"))]
805            mod async_std_native_tls_tests {
806                tests_with_runtime! { &crate::async_std::AsyncStdNativeTlsRuntime::create()? => $($id),* }
807            }
808            #[cfg(all(feature="smol", feature = "native-tls"))]
809            mod smol_native_tls_tests {
810                tests_with_runtime! { &crate::smol::SmolNativeTlsRuntime::create()? => $($id),* }
811            }
812            #[cfg(all(feature="tokio", feature="rustls"))]
813            mod tokio_rustls_tests {
814                tests_with_runtime! {  &crate::tokio::TokioRustlsRuntime::create()? => $($id),* }
815            }
816            #[cfg(all(feature="async-std", feature="rustls"))]
817            mod async_std_rustls_tests {
818                tests_with_runtime! {  &crate::async_std::AsyncStdRustlsRuntime::create()? => $($id),* }
819            }
820            #[cfg(all(feature="smol", feature="rustls"))]
821            mod smol_rustls_tests {
822                tests_with_runtime! {  &crate::smol::SmolRustlsRuntime::create()? => $($id),* }
823            }
824            mod default_runtime_tls_tests {
825                tests_with_runtime! { &crate::PreferredRuntime::create()? => $($id),* }
826            }
827        }
828    }
829
830    runtime_tests! {
831        small_delay,
832        small_timeout_ok,
833        small_timeout_expire,
834        tiny_wallclock,
835        self_connect_tcp,
836        self_connect_udp,
837        listener_stream,
838    }
839
840    tls_runtime_tests! {
841        simple_tls,
842        simple_tls_server,
843    }
844}