tor_rtcompat/traits.rs
1//! Declarations for traits that we need our runtimes to implement.
2use async_trait::async_trait;
3use asynchronous_codec::Framed;
4use futures::future::{FutureExt, RemoteHandle};
5use futures::stream;
6use futures::task::{Spawn, SpawnError};
7use futures::{AsyncRead, AsyncWrite, Future};
8use std::any::Any;
9use std::borrow::Cow;
10use std::fmt::Debug;
11use std::io::{self, Result as IoResult};
12use std::net;
13use tor_general_addr::unix;
14use web_time_compat::{Duration, Instant, InstantExt, SystemTime, SystemTimeExt};
15
16#[cfg(feature = "tls-server")]
17use tor_cert_x509::TlsKeyAndCert;
18
19use crate::network::{TcpListenOptions, UnixListenOptions};
20
21/// A runtime for use by Tor client library code.
22///
23/// This trait comprises several other traits that we require all of our
24/// runtimes to provide:
25///
26/// * [`futures::task::Spawn`] or [`SpawnExt`] to launch new background tasks.
27/// * [`SleepProvider`] to pause a task for a given amount of time.
28/// * [`CoarseTimeProvider`] for a cheaper but less accurate notion of time.
29/// * [`NetStreamProvider`] to launch and accept network connections.
30/// * [`TlsProvider`] to launch TLS connections.
31/// * [`Blocking`] to be able to run synchronous (cpubound or IO) code,
32/// and *re*-enter the async context from synchronous thread
33/// (This may become optional in the future, if/when we add WASM
34/// support).
35///
36/// A value which is only `Runtime` cannot be used as an *entry point* to the runtime.
37/// For that, it must also implement [`ToplevelBlockOn`],
38/// making it a [`ToplevelRuntime`].
39/// Since you can only [enter a runtime](ToplevelBlockOn::block_on) once,
40/// typically you use a `ToplevelRuntime` to enter the runtime,
41/// and use it as only a `Runtime` afterwards.
42/// This means that library code should typically
43/// deal with `Runtime` rather than `ToplevelRuntime`.
44///
45/// We require that every `Runtime` has an efficient [`Clone`] implementation
46/// that gives a new opaque reference to the same underlying runtime.
47///
48/// Additionally, every `Runtime` is [`Send`] and [`Sync`], though these
49/// requirements may be somewhat relaxed in the future.
50///
51/// At some future point,
52/// Arti may require that the runtime `impl<S> TlsProvider<S>` (for suitable`S`),
53/// rather than just for their own `TcpStream`s.
54/// I.e., Arti may start to require that the runtime's TLS provider can wrap any streams,
55/// not only the runtime's own TCP streams.
56/// This might be expressed as an additional supertrait bound on `Runtime`,
57/// eg when Rust supports GATs,
58/// or as an additional bound on the Arti APIs that currently use `Runtime`.
59/// For API future compatibility, if you `impl Runtime for MyRuntime`,
60/// you should also ensure that you
61/// ```ignore
62/// impl<S> TlsProvider<S> for MyRuntime
63/// where S: futures::AsyncRead + futures::AsyncWrite + Unpin + Send + 'static
64/// ```
65//
66/// Perhaps we will need this if we make our own TLS connections *through* Tor,
67/// rather than just channels to guards.
68pub trait Runtime:
69 Sync
70 + Send
71 + Spawn
72 + Blocking
73 + JoinSetProvider
74 + Clone
75 + SleepProvider
76 + CoarseTimeProvider
77 + NetStreamProvider<net::SocketAddr, ListenOptions = TcpListenOptions>
78 + NetStreamProvider<unix::SocketAddr, ListenOptions = UnixListenOptions>
79 + TlsProvider<<Self as NetStreamProvider<net::SocketAddr>>::Stream>
80 + UdpProvider
81 + Debug
82 + 'static
83{
84}
85
86impl<T> Runtime for T where
87 T: Sync
88 + Send
89 + Spawn
90 + Blocking
91 + JoinSetProvider
92 + Clone
93 + SleepProvider
94 + CoarseTimeProvider
95 + NetStreamProvider<net::SocketAddr, ListenOptions = TcpListenOptions>
96 + NetStreamProvider<unix::SocketAddr, ListenOptions = UnixListenOptions>
97 + TlsProvider<<Self as NetStreamProvider<net::SocketAddr>>::Stream>
98 + UdpProvider
99 + Debug
100 + 'static
101{
102}
103
104/// Trait representing a collection of tasks spawned on a [`Runtime`].
105///
106/// This is inspired by Tokio's [`JoinSet` API], which provides a convenient
107/// way to spawn tasks and receive their output asynchronously.
108///
109// Note: Our API is much smaller than Tokio's, because it only contains
110// the JoinSet functionality we actually need in Arti right now.
111// Parity with Tokio's API is a non-goal, but we can later extend
112// this API if it makes sense to do so. -gabi
113//
114/// [`JoinSet` API]: https://docs.rs/tokio/1.54.1/tokio/task/struct.JoinSet.html
115#[async_trait]
116pub trait JoinSet<T>: Send + Sync + 'static {
117 /// Spawn the provided `task` on the runtime.
118 ///
119 /// The provided `task` will start executing in the background immediately,
120 /// even if you don't call [`JoinSet::join_next`].
121 fn spawn<F>(&mut self, task: F) -> Result<(), SpawnError>
122 where
123 F: Future<Output = T> + Send + 'static;
124
125 /// Wait until one of the tasks completes, and return its output.
126 ///
127 /// Returns `None` if there are currently no tasks in this set.
128 ///
129 /// This function is cancel-safe, and therefore safe to use in a `select!` branch.
130 ///
131 /// # Limitations
132 ///
133 /// If a task panics, this function will yield a `Some(Err(..)` result.
134 /// However, this API doesn't provide a way of telling *which* task has panicked.
135 /// Callers wishing to keep track of panics can work around this limitation
136 /// by wrapping the task's code in [`catch_unwind`](std::panic::catch_unwind),
137 /// and arranging for the result returned from this function to contain
138 /// some additional information identifying the task it originated from
139 /// (either in a `Some(Ok(..))`, or in a `Some(Er(..))`,
140 /// although the latter would involve downcasting the `dyn Any`
141 /// to the concrete error type).
142 async fn join_next(&mut self) -> Option<Result<T, Box<dyn Any + Send>>>;
143}
144
145/// Trait for a runtime that can create [`JoinSet`]s.
146///
147// Note: Tokio's `JoinSet` panics if you try to use it from the
148// context of a non-tokio runtime, so we've had to invent our our own
149// runtime-agnostic `JoinSet` type for testing, and for use with `async-std` and `smol`.
150// The `JoinSetProvider` and `JoinSet` enable us to customize the `JoinSet` type
151// for each runtime.
152//
153// All of this `JoinSetProvider`/`JoinSet` indirection could have been
154// avoided by using the same (hand-rolled) `JoinSet` type for all our
155// runtimes. However, that would've meant doing away with Tokio's `JoinSet`
156// entirely, which in my opinion would be a bad idea,
157// because Tokio's implementation is more battle-tested, and has more eyes on it
158// (so one would hope this implies someone is also scrutinizing its performance!).
159//
160// I have also considered porting Tokio's `JoinSet` to `tor-tcompat,
161// but it's non-trivial enough that we wouldn't want to do that. -gabi
162pub trait JoinSetProvider: Clone + Send + Sync + 'static {
163 /// The [`JoinSet`] type of this runtime.
164 type JoinSet<T: Send + Sync + 'static>: JoinSet<T>;
165
166 /// Create a new [`JoinSet`] for use with this runtime.
167 ///
168 /// Important: the resulting `JoinSet` should only be used
169 /// from the context of the runtime it was created for.
170 /// Using the `JoinSet` with a different runtime can lead to panics,
171 /// or erroneous behavior.
172 fn new_join_set<T>(&self) -> Self::JoinSet<T>
173 where
174 T: Send + Sync + 'static;
175}
176
177/// A runtime that we can use to run Tor as a client.
178/// * [`ToplevelBlockOn`] to block on a top-level future and run it to completion
179/// (This may become optional in the future, if/when we add WASM
180/// support).
181///
182pub trait ToplevelRuntime: Runtime + ToplevelBlockOn {}
183impl<T: Runtime + ToplevelBlockOn> ToplevelRuntime for T {}
184
185/// Trait for a runtime that can wait until a timer has expired.
186///
187/// Every `SleepProvider` also implements
188/// [`SleepProviderExt`](crate::SleepProviderExt); see that trait
189/// for other useful functions.
190pub trait SleepProvider: Clone + Send + Sync + 'static {
191 /// A future returned by [`SleepProvider::sleep()`]
192 type SleepFuture: Future<Output = ()> + Send + 'static;
193 /// Return a future that will be ready after `duration` has
194 /// elapsed.
195 #[must_use = "sleep() returns a future, which does nothing unless used"]
196 fn sleep(&self, duration: Duration) -> Self::SleepFuture;
197
198 /// Return the SleepProvider's view of the current instant.
199 ///
200 /// (This is the same as `Instant::now`, if not running in test mode.)
201 fn now(&self) -> Instant {
202 Instant::get()
203 }
204
205 /// Return the SleepProvider's view of the current wall-clock time.
206 ///
207 /// (This is the same as `SystemTime::now`, if not running in test mode.)
208 fn wallclock(&self) -> SystemTime {
209 SystemTime::get()
210 }
211
212 /// Signify that a test running under mock time shouldn't advance time yet, with a given
213 /// unique reason string. This is useful for making sure (mock) time doesn't advance while
214 /// things that might require some (real-world) time to complete do so, such as spawning a task
215 /// on another thread.
216 ///
217 /// Call `release_advance` with the same reason string in order to unblock.
218 ///
219 /// This method is only for testing: it should never have any
220 /// effect when invoked on non-testing runtimes.
221 fn block_advance<T: Into<String>>(&self, _reason: T) {}
222
223 /// Signify that the reason to withhold time advancing provided in a call to `block_advance` no
224 /// longer exists, and it's fine to move time forward if nothing else is blocking advances.
225 ///
226 /// This method is only for testing: it should never have any
227 /// effect when invoked on non-testing runtimes.
228 fn release_advance<T: Into<String>>(&self, _reason: T) {}
229
230 /// Allow a test running under mock time to advance time by the provided duration, even if the
231 /// above `block_advance` API has been used.
232 ///
233 /// This method is only for testing: it should never have any
234 /// effect when invoked on non-testing runtimes.
235 fn allow_one_advance(&self, _dur: Duration) {}
236}
237
238/// A provider of reduced-precision timestamps
239///
240/// This doesn't provide any facility for sleeping.
241/// If you want to sleep based on reduced-precision timestamps,
242/// convert the desired sleep duration to `std::time::Duration`
243/// and use [`SleepProvider`].
244pub trait CoarseTimeProvider: Clone + Send + Sync + 'static {
245 /// Return the `CoarseTimeProvider`'s view of the current instant.
246 ///
247 /// This is supposed to be cheaper than `std::time::Instant::now`.
248 fn now_coarse(&self) -> crate::coarse_time::CoarseInstant;
249}
250
251/// Trait for a runtime that can be entered to block on a toplevel future.
252///
253/// This trait is *not* implied by `Runtime`, only by `ToplevelRuntime`.
254/// `ToplevelRuntime` is available at the toplevel of each program,
255/// typically, where a concrete async executor is selected.
256pub trait ToplevelBlockOn: Clone + Send + Sync + 'static {
257 /// Run `future` until it is ready, and return its output.
258 ///
259 /// # Not reentrant!
260 ///
261 /// There should be one call to `block_on` (for each fresh `Runtime`),
262 /// at the toplevel of the program (or test case).
263 /// (Sequential calls to `block_on` from the same thread are allowed.)
264 ///
265 /// `block_on` may not function correctly if is called
266 /// from multiple threads simultaneously,
267 /// or if calls involving different `Runtime`s are interleaved on the same thread.
268 /// (Specific runtimes may offer better guarantees.)
269 ///
270 /// (`tor_rtmock::MockExecutor`'s implementation will often detect violations.)
271 fn block_on<F: Future>(&self, future: F) -> F::Output;
272}
273
274/// Support for interacting with blocking (non-async) code
275///
276/// This supports two use cases: blocking IO and CPU-intensive activities.
277/// (In both of these cases, simply calling the functions within an `async` task
278/// is a bad idea, because that can block the whole async runtime.)
279///
280/// ### Blocking IO
281///
282/// `Blocking` can be used to interact with libraries or OS primitives
283/// that only offer a synchronous, blocking, interface.
284///
285/// Use [`spawn_blocking`](Blocking::spawn_blocking)
286/// when it is convenient to have a long-running thread,
287/// for these operations.
288///
289/// Use [`blocking_io`](Blocking::blocking_io)
290/// when the blocking code is usually expected to complete quickly,
291/// and/or you will be switching back and forth a lot
292/// between sync and async contexts.
293/// Note that you cannot call back to async code from within `blocking_io`.
294///
295/// ### CPU-intensive activities
296///
297/// Perform CPU-intensive work, that ought not to block the program's main loop,
298/// via [`Blocking::spawn_blocking`].
299///
300/// `spawn_blocking` does not apply any limiting or prioritisation;
301/// its threads simply compete for CPU with other threads in the program.
302/// That must be done by the caller; therefore:
303///
304/// **Limit the number of cpu threads** spawned
305/// in order to limit the total amount of CPU time consumed by any part of the program.
306/// For example, consider using one CPU thread per Tor Hidden Service.
307///
308/// It is most performant to spawn a long-running thread,
309/// rather than to repeatedly spawn short-lived threads for individual work items.
310/// This also makes it easier to limit the number of concurrente cpu threads.
311/// For the same reason, [`Blocking::blocking_io`] should be avoided
312/// for the CPU-intensive use case.
313///
314/// ### Mapping to concrete functions from underlying libraries
315///
316/// The semantics of `Blocking` are heavily influenced by Tokio
317/// and by the desire to be able to use tor-rtmock's `MockExecutor` to test Arti code.
318///
319/// | `tor-rtcompat` | Tokio | `MockExecutor` |
320/// |------------------------------|-----------------------|--------------------------------|
321/// | `ToplevelBlockOn::block_on` | `Runtime::block_on` | `ToplevelBlockOn::block_on` |
322/// | `Blocking::spawn_blocking` | `task::spawn_blocking` | `subthread_spawn` |
323/// | `Blocking::reenter_block_on` | `Handle::block_on` | `subthread_block_on_future` |
324/// | `Blocking::blocking_io` | `block_in_place` | `subthread_spawn` |
325/// | (not available) | (not implemented) | `progress_until_stalled` etc. |
326///
327/// Re `block_on`, see also the docs for the underlying implementations in
328/// [tokio][tokio-threadpool] and
329/// [async-std][async-std-threadpool].
330///
331/// [tokio-threadpool]: https://docs.rs/tokio/latest/tokio/task/fn.spawn_blocking.html
332/// [async-std-threadpool]: https://docs.rs/async-std/latest/async_std/task/fn.spawn_blocking.html
333pub trait Blocking: Clone + Send + Sync + 'static {
334 /// Spawn a thread for blocking IO or CPU-bound work.
335 ///
336 /// This is used in two situations:
337 ///
338 /// * To perform blocking IO
339 /// * For cpu-intensive work
340 ///
341 /// See [`Blocking`]'s trait level docs for advice on choosing
342 /// between `spawn_blocking` and [`Blocking::blocking_io`].
343 ///
344 /// `Blocking::spawn_blocking` is similar to `std::thread::spawn`
345 /// but also makes any necessary arrangements so that `reenter_block_on`,
346 /// can be called on the spawned thread.
347 ///
348 /// However, `Blocking::spawn_blocking` *does not guarantee*
349 /// to use a completely fresh thread.
350 /// The implementation may have a thread pool, allowing it reuse an existing thread.
351 /// Correspondingly, if a very large number of `Blocking::spawn_blocking` calls,
352 /// are in progress at once, some of them may block.
353 /// (For example, the implementation for Tokio uses `tokio::task::spawn_blocking`,
354 /// which has both of these properties.)
355 ///
356 /// ### Typical use of `spawn_blocking`
357 ///
358 /// * Spawn the thread with `SpawnThread::spawn_blocking`.
359 /// * On that thread, receive work items from from the async environment
360 /// using async inter-task facilities (eg `futures::channel::mpsc::channel`),
361 /// called via [`reenter_block_on`](Blocking::reenter_block_on).
362 /// * Return answers with async inter-task facilities, calling either
363 /// a non-blocking immediate send (eg `[try_send`])
364 /// or an async send call via `reneter_block_on`.
365 ///
366 /// ### CPU-intensive work
367 ///
368 /// Limit the number of CPU-intensive concurrent threads spawned with `spawn_blocking`.
369 /// See the [trait-level docs](Blocking) for more details.
370 ///
371 /// ### Panics
372 ///
373 /// `Blocking::spawn_blocking` may only be called from within either:
374 ///
375 /// * A task or future being polled by this `Runtime`; or
376 /// * A thread itself spawned with `Blocking::spawn_blocking` on the this runtime.
377 ///
378 /// Otherwise it may malfunction or panic.
379 /// (`tor_rtmock::MockExecutor`'s implementation will usually detect violations.)
380 ///
381 /// If `f` panics, `ThreadHandle` will also panic when polled
382 /// (perhaps using `resume_unwind`).
383 fn spawn_blocking<F, T>(&self, f: F) -> Self::ThreadHandle<T>
384 where
385 F: FnOnce() -> T + Send + 'static,
386 T: Send + 'static;
387
388 /// Future from [`spawn_blocking`](Self::spawn_blocking)
389 ///
390 /// The function callback (`f: F` in [`spawn_blocking`](Self::spawn_blocking)
391 /// will start to run regardless of whether this future is awaited.
392 ///
393 /// Dropping this future doesn't stop the callback; it detaches it:
394 /// the function will continue to run, but its output can no longer be collected.
395 type ThreadHandle<T: Send + 'static>: Future<Output = T>;
396
397 /// Block on a future, from within `Blocking::spawn_blocking`
398 ///
399 /// Reenters the executor, blocking this thread until `future` is `Ready`.
400 ///
401 /// See [`spawn_blocking`](Blocking::spawn_blocking) and
402 /// [`Blocking`]'s trait-level docs for more details.
403 ///
404 /// It is not guaranteed what thread the future will be polled on.
405 /// In production `Runtime`s, it will usually be the thread calling `reenter_block_on`.
406 // All existing runtimes other than MockExecutor accept a non-Send future, but
407 // MockExecutor::subthread_block_on_future does not.
408 // If this restriction turns out to be awkward, MockExecutor could be changed, with some work.
409 ///
410 /// ### Panics
411 ///
412 /// Must only be called on a thread made with `Blocking::spawn_blocking`.
413 /// **Not** allowed within [`blocking_io`](Blocking::blocking_io).
414 ///
415 /// Otherwise it may malfunction or panic.
416 /// (`tor_rtmock::MockExecutor`'s implementation will usually detect violations.)
417 fn reenter_block_on<F>(&self, future: F) -> F::Output
418 where
419 F: Future,
420 F::Output: Send + 'static;
421
422 /// Perform some blocking IO from an async future
423 ///
424 /// Call the blocking function `f`, informing the async executor
425 /// that we are going to perform blocking IO.
426 ///
427 /// This is a usually-faster, but simpler, alternative to [`Blocking::spawn_blocking`].
428 ///
429 /// Its API can be more convenient than `spawn_blocking`.
430 /// `blocking_io` is intended to be more performant than `spawn_blocking`
431 /// when called repeatedly (ie, when switching quickly between sync and async).
432 ///
433 /// See [`Blocking`]'s trait-level docs for more information about
434 /// the performance properties, and on choosing between `blocking_io`
435 /// and `spawn_blocking`.
436 /// (Avoid using `blocking_io` for CPU-intensive work.)
437 ///
438 /// ### Limitations
439 ///
440 /// * `f` may **not** call [`Blocking::reenter_block_on`], so:
441 /// * `f` cannot execute any futures.
442 /// If this is needed, break up `f` into smaller pieces so that the
443 /// futures can be awaited outside the call to `blocking_io`,
444 /// or use `spawn_blocking` for the whole activity.
445 /// * `f` *may* be called on the calling thread when `blocking_io` is called,
446 /// on an executor thread when the returned future is polled,
447 /// or a different thread.
448 /// * Not suitable for CPU-intensive work
449 /// (mostly because there is no practical way to ration or limit
450 /// the amount of cpu time used).
451 /// Use `spawn_blocking` for that.
452 /// * Performance better than using `spawn_blocking` each time is not guaranteed.
453 ///
454 /// Otherwise the semantics are the same as
455 /// [`spawn_blocking`](Self::spawn_blocking).
456 ///
457 /// ### Panics
458 ///
459 /// `Blocking::block_in_place` may only be called from within
460 /// a task or future being polled by this `Runtime`.
461 ///
462 /// Otherwise it may malfunction or panic.
463 /// (`tor_rtmock::MockExecutor`'s implementation will usually detect violations.)
464 ///
465 /// ### Fallback (provided) implementation
466 ///
467 /// The fallback implementation is currently used with `async_std`.
468 /// It spawns a thread with `spawn_blocking`, once for each `blocking_io` call.
469 fn blocking_io<F, T>(&self, f: F) -> impl Future<Output = T>
470 where
471 F: FnOnce() -> T + Send + 'static,
472 T: Send + 'static,
473 {
474 self.spawn_blocking(f)
475 }
476}
477
478/// Extension trait for [`Spawn`].
479///
480/// This is very similar to, and preferred over, [`futures::task::SpawnExt`].
481/// Unlike `futures::task::SpawnExt`, it is compatible with tokio-console,
482/// and preserves span information for `tracing`.
483// If https://github.com/rust-lang/futures-rs/issues/2977 is ever addressed,
484// we can consider transitioning back to `futures::task::SpawnExt`.
485pub trait SpawnExt: Spawn {
486 /// Spawns a task that polls the given future with output `()` to completion.
487 ///
488 /// See [`futures::task::SpawnExt::spawn`].
489 #[track_caller]
490 fn spawn<Fut>(&self, future: Fut) -> Result<(), SpawnError>
491 where
492 Fut: Future<Output = ()> + Send + 'static,
493 {
494 use tracing::Instrument as _;
495 self.spawn_obj(Box::new(future.in_current_span()).into())
496 }
497
498 /// Spawns a task that polls the given future to completion and returns a future that resolves
499 /// to the spawned future’s output.
500 ///
501 /// See [`futures::task::SpawnExt::spawn_with_handle`].
502 #[track_caller]
503 fn spawn_with_handle<Fut>(
504 &self,
505 future: Fut,
506 ) -> Result<RemoteHandle<<Fut as Future>::Output>, SpawnError>
507 where
508 Fut: Future + Send + 'static,
509 <Fut as Future>::Output: Send,
510 {
511 let (future, handle) = future.remote_handle();
512 self.spawn(future)?;
513 Ok(handle)
514 }
515}
516
517impl<T: Spawn> SpawnExt for T {}
518
519/// Additional operations that can be performed on connected stream sockets.
520///
521/// Some operations provided by this trait set socket options (`setsockopt()`).
522/// Some socket options cannot be set after a stream socket is connected,
523/// so these options are not provided by this trait.
524/// Instead, they should be set through options given to
525/// [`NetStreamProvider::connect()`] or [`NetStreamProvider::listen()`].
526/// For example, see the options provided by [`TcpListenOptions`].
527pub trait StreamOps {
528 /// Set the [`TCP_NOTSENT_LOWAT`] socket option, if this `Stream` is a TCP stream.
529 ///
530 /// Implementations should return an [`UnsupportedStreamOp`] IO error
531 /// if the stream is not a TCP stream,
532 /// and on platforms where the operation is not supported.
533 ///
534 /// [`TCP_NOTSENT_LOWAT`]: https://lwn.net/Articles/560082/
535 fn set_tcp_notsent_lowat(&self, _notsent_lowat: u32) -> IoResult<()> {
536 Err(UnsupportedStreamOp {
537 op: "set_tcp_notsent_lowat",
538 reason: "unsupported object type",
539 }
540 .into())
541 }
542
543 /// Return a new handle that implements [`StreamOps`],
544 /// and that can be used independently of `self`.
545 fn new_handle(&self) -> Box<dyn StreamOps + Send + Unpin> {
546 Box::new(NoOpStreamOpsHandle)
547 }
548}
549
550/// A [`StreamOps`] handle that always returns an error.
551///
552/// Returned from [`StreamOps::new_handle`] for types and platforms
553/// that do not support `StreamOps`.
554#[derive(Copy, Clone, Debug, Default)]
555#[non_exhaustive]
556pub struct NoOpStreamOpsHandle;
557
558impl StreamOps for NoOpStreamOpsHandle {
559 fn new_handle(&self) -> Box<dyn StreamOps + Send + Unpin> {
560 Box::new(*self)
561 }
562}
563
564impl<T: StreamOps, C> StreamOps for Framed<T, C> {
565 fn set_tcp_notsent_lowat(&self, notsent_lowat: u32) -> IoResult<()> {
566 let inner: &T = self;
567 inner.set_tcp_notsent_lowat(notsent_lowat)
568 }
569
570 fn new_handle(&self) -> Box<dyn StreamOps + Send + Unpin> {
571 let inner: &T = self;
572 inner.new_handle()
573 }
574}
575
576/// Error: Tried to perform a [`StreamOps`] operation on an unsupported stream type
577/// or on an unsupported platform.
578///
579/// (For example, you can't call [`StreamOps::set_tcp_notsent_lowat`] on Windows
580/// or on a stream type that is not backed by a TCP socket.)
581#[derive(Clone, Debug, thiserror::Error)]
582#[error("Operation {op} not supported: {reason}")]
583pub struct UnsupportedStreamOp {
584 /// The unsupported operation.
585 op: &'static str,
586 /// The reason the operation is unsupported.
587 reason: &'static str,
588}
589
590impl UnsupportedStreamOp {
591 /// Construct a new `UnsupportedStreamOp` error with the provided operation and reason.
592 pub fn new(op: &'static str, reason: &'static str) -> Self {
593 Self { op, reason }
594 }
595}
596
597impl From<UnsupportedStreamOp> for io::Error {
598 fn from(value: UnsupportedStreamOp) -> Self {
599 io::Error::new(io::ErrorKind::Unsupported, value)
600 }
601}
602
603/// Trait for a runtime that can create and accept connections
604/// over network sockets.
605///
606/// (In Arti we use the [`AsyncRead`] and [`AsyncWrite`] traits from
607/// [`futures::io`] as more standard, even though the ones from Tokio
608/// can be a bit more efficient. Let's hope that they converge in the
609/// future.)
610// TODO: Use of async_trait is not ideal, since we have to box with every
611// call. Still, async_io basically makes that necessary :/
612#[async_trait]
613pub trait NetStreamProvider<ADDR = net::SocketAddr>: Clone + Send + Sync + 'static {
614 /// The type for the connections returned by [`Self::connect()`].
615 type Stream: AsyncRead + AsyncWrite + StreamOps + Send + Sync + Unpin + 'static;
616 /// The type for the listeners returned by [`Self::listen()`].
617 type Listener: NetStreamListener<ADDR, Stream = Self::Stream> + Send + Sync + Unpin + 'static;
618 /// The options that can be passed to [`Self::connect()`].
619 ///
620 /// It can include options set with `setsockopt`,
621 /// as well as options that influence higher layers (eg, the runtime).
622 ///
623 /// For connected streams,
624 /// you can use [`StreamOps`] to perform additional operations
625 /// or to configure additional options.
626 type ConnectOptions: Clone + Default + Send + Sync + Unpin + 'static;
627 /// The options that can be passed to [`Self::listen()`].
628 ///
629 /// This includes both options that affect the listening,
630 /// and options that will apply to any individual accepted connection streams.
631 ///
632 /// It can include options set with `setsockopt`,
633 /// as well as options that influence higher layers (eg, the runtime).
634 ///
635 /// For established streams that are accepted from a listener,
636 /// you can use [`StreamOps`] to perform additional operations
637 /// or to configure additional options.
638 type ListenOptions: Clone + Default + Send + Sync + Unpin + 'static;
639
640 /// Launch a connection connection to a given socket address.
641 ///
642 /// Note that unlike `std::net:TcpStream::connect`, we do not accept
643 /// any types other than a single `ADDR`. We do this because
644 /// we must be absolutely sure not to perform
645 /// unnecessary DNS lookups.
646 async fn connect(&self, addr: &ADDR, options: &Self::ConnectOptions) -> IoResult<Self::Stream>;
647
648 /// Open a listener on a given socket address.
649 async fn listen(&self, addr: &ADDR, options: &Self::ListenOptions) -> IoResult<Self::Listener>;
650}
651
652/// Trait for a local socket that accepts incoming streams.
653///
654/// These objects are returned by instances of [`NetStreamProvider`]. To use
655/// one,
656/// use `incoming` to convert this object into a [`stream::Stream`].
657pub trait NetStreamListener<ADDR = net::SocketAddr> {
658 /// The type of connections returned by [`Self::incoming()`].
659 type Stream: AsyncRead + AsyncWrite + StreamOps + Send + Sync + Unpin + 'static;
660
661 /// The type of [`stream::Stream`] returned by [`Self::incoming()`].
662 type Incoming: stream::Stream<Item = IoResult<(Self::Stream, ADDR)>>
663 + Send
664 + Sync
665 + Unpin
666 + 'static;
667
668 /// Wrap this listener into a new [`stream::Stream`] that yields
669 /// streams and addresses.
670 fn incoming(self) -> Self::Incoming;
671
672 /// Return the local address that this listener is bound to.
673 fn local_addr(&self) -> IoResult<ADDR>;
674}
675
676/// Trait for a runtime that can send and receive UDP datagrams.
677#[async_trait]
678pub trait UdpProvider: Clone + Send + Sync + 'static {
679 /// The type of Udp Socket returned by [`Self::bind()`]
680 type UdpSocket: UdpSocket + Send + Sync + Unpin + 'static;
681
682 /// Bind a local port to send and receive packets from
683 async fn bind(&self, addr: &net::SocketAddr) -> IoResult<Self::UdpSocket>;
684}
685
686/// Trait for a locally bound Udp socket that can send and receive datagrams.
687///
688/// These objects are returned by instances of [`UdpProvider`].
689//
690// NOTE that UdpSocket objects are _necessarily_ un-connected. If you need to
691// implement a connected Udp socket in the future, please make a new trait (and
692// a new type.)
693#[async_trait]
694pub trait UdpSocket {
695 /// Wait for an incoming datagram; return it along its address.
696 async fn recv(&self, buf: &mut [u8]) -> IoResult<(usize, net::SocketAddr)>;
697 /// Send a datagram to the provided address.
698 async fn send(&self, buf: &[u8], target: &net::SocketAddr) -> IoResult<usize>;
699 /// Return the local address that this socket is bound to.
700 fn local_addr(&self) -> IoResult<net::SocketAddr>;
701}
702
703/// An object with a peer certificate: typically a TLS connection.
704pub trait CertifiedConn {
705 /// Return the keying material (RFC 5705) given a label and an optional context.
706 fn export_keying_material(
707 &self,
708 len: usize,
709 label: &[u8],
710 context: Option<&[u8]>,
711 ) -> IoResult<Vec<u8>>;
712 /// Try to return the (DER-encoded) peer certificate for this
713 /// connection, if any.
714 fn peer_certificate(&self) -> IoResult<Option<Cow<'_, [u8]>>>;
715
716 /// Try to return the (DER-encoded) link certificate (if any) containing
717 /// the key we used to authenticate this connection.
718 ///
719 /// Ordinarily, this will return a certificate for server connections,
720 /// and None for client connections.
721 //
722 // NOTE: (The correct return value in the _absence_ of a certificate is None.
723 // Later, if we support optional certificates for clients,
724 // the place to return an Unsupported error would be
725 // from whatever function tries to set such a certificate.)
726 fn own_certificate(&self) -> IoResult<Option<Cow<'_, [u8]>>>;
727}
728
729/// An object that knows how to wrap a TCP connection (where the type of said TCP
730/// connection is `S`) with TLS.
731///
732/// # Usage notes
733///
734/// Note that because of Tor's peculiarities, this is not a
735/// general-purpose TLS type. Unlike typical users, Tor does not want
736/// its TLS library to check whether the certificates used in TLS are signed
737/// within the web PKI hierarchy, or what their hostnames are, or even whether
738/// they are valid. It *does*, however, check that the subject public key in the
739/// certificate is indeed correctly used to authenticate the TLS handshake.
740///
741/// If you are implementing something other than Tor, this is **not** the
742/// functionality you want.
743///
744/// How can this behavior be remotely safe, even in Tor? It only works for Tor
745/// because the certificate that a Tor relay uses in TLS is not actually being
746/// used to certify that relay's public key. Instead, the certificate only used
747/// as a container for the relay's public key. The real certification happens
748/// later, inside the TLS session, when the relay presents a CERTS cell.
749///
750/// Such sneakiness was especially necessary before TLS 1.3, which encrypts more
751/// of the handshake, and before pluggable transports, which make
752/// "innocuous-looking TLS handshakes" less important than they once were. Once
753/// TLS 1.3 is completely ubiquitous, we might be able to specify a simpler link
754/// handshake than Tor uses now.
755#[async_trait]
756pub trait TlsConnector<S> {
757 /// The type of connection returned by this connector
758 type Conn: AsyncRead + AsyncWrite + CertifiedConn + Unpin + Send + 'static;
759
760 /// Start a TLS session over the provided TCP stream `stream`.
761 ///
762 /// For a client connection,
763 /// declare `sni_hostname` as the desired hostname, but don't actually check
764 /// whether the hostname in the certificate matches it. The connector may
765 /// send `sni_hostname` as part of its handshake, if it supports
766 /// [SNI](https://en.wikipedia.org/wiki/Server_Name_Indication) or one of
767 /// the TLS 1.3 equivalents.
768 ///
769 /// (For a server connection, `sni_hostname` is ignored.)
770 async fn negotiate_unvalidated(&self, stream: S, sni_hostname: &str) -> IoResult<Self::Conn>;
771}
772
773/// Trait for a runtime that knows how to create TLS connections over
774/// TCP streams of type `S`.
775///
776/// This is separate from [`TlsConnector`] because eventually we may
777/// eventually want to support multiple `TlsConnector` implementations
778/// that use a single [`Runtime`].
779///
780/// See the [`TlsConnector`] documentation for a discussion of the Tor-specific
781/// limitations of this trait: If you are implementing something other than Tor,
782/// this is **not** the functionality you want.
783pub trait TlsProvider<S: StreamOps>: Clone + Send + Sync + 'static {
784 /// The Connector object that this provider can return.
785 type Connector: TlsConnector<S, Conn = Self::TlsStream> + Send + Sync + Unpin;
786
787 /// The type of the stream returned by that connector.
788 type TlsStream: AsyncRead + AsyncWrite + StreamOps + CertifiedConn + Unpin + Send + 'static;
789
790 /// The Acceptor object that this provider can return, for handling incoming connections.
791 type Acceptor: TlsConnector<S, Conn = Self::TlsServerStream> + Send + Sync + Unpin;
792
793 /// The type of stream returned by that Acceptor.
794 type TlsServerStream: AsyncRead
795 + AsyncWrite
796 + StreamOps
797 + CertifiedConn
798 + Unpin
799 + Send
800 + 'static;
801
802 /// Return a TLS connector for use with this runtime.
803 fn tls_connector(&self) -> Self::Connector;
804
805 /// Return a TLS acceptor for use with this runtime.
806 ///
807 /// Not every [`TlsProvider`] supports this method.
808 /// For those that do, this method is only supported
809 /// when `tor-rtcompat` is built with the `tls-server` feature.
810 /// When this method is unsupported, it returns an error.
811 fn tls_acceptor(&self, settings: TlsAcceptorSettings) -> IoResult<Self::Acceptor>;
812
813 /// Return true iff the keying material exporters (RFC 5705) is supported.
814 fn supports_keying_material_export(&self) -> bool;
815}
816
817/// Settings used for constructing a TlsAcceptor.
818#[derive(Debug, Clone)]
819#[non_exhaustive]
820pub struct TlsAcceptorSettings {
821 /// The certificates and keys for this acceptor.
822 #[cfg(feature = "tls-server")]
823 pub(crate) identity: TlsKeyAndCert,
824
825 /// Indicates that this type can not be constructed.
826 #[cfg(not(feature = "tls-server"))]
827 unconstructable: void::Void,
828 //
829 // TODO: Add support for additional certificates in a chain.
830 // TODO: Possibly, add support for PEM.
831}
832
833impl TlsAcceptorSettings {
834 /// Create a new TlsAcceptorSettings from a certificate and its associated private key,
835 /// both in DER format.
836 ///
837 /// Does not perform full (or even, necessarily, any) validation.
838 //
839 // TODO: It would be great to take a tor_cert::x509::TlsKeyAndCert instead,
840 // but that would (apparently) introduce a dependency cycle. It would be cool to figure out how
841 // to invert that.
842 #[allow(clippy::unnecessary_wraps)]
843 #[cfg(feature = "tls-server")]
844 pub fn new(identity: TlsKeyAndCert) -> std::io::Result<Self> {
845 Ok(Self { identity })
846 }
847
848 /// Return the primary certificate for this [`TlsAcceptorSettings`], in DER format.
849 pub fn cert_der(&self) -> &[u8] {
850 #[cfg(not(feature = "tls-server"))]
851 {
852 void::unreachable(self.unconstructable);
853 }
854 #[cfg(feature = "tls-server")]
855 self.identity.certificates_der()[0]
856 }
857}
858
859/// An error returned by TlsProvider::tls_acceptor when the TlsProvider does not have TLS server support.
860#[derive(Clone, Debug, thiserror::Error)]
861#[non_exhaustive]
862#[error("This TlsProvider does not support running as a server")]
863pub struct TlsServerUnsupported {}
864
865impl From<TlsServerUnsupported> for io::Error {
866 fn from(value: TlsServerUnsupported) -> Self {
867 io::Error::new(io::ErrorKind::Unsupported, value)
868 }
869}