Skip to main content

fetchlet_net/socket/
transport.rs

1use std::sync::Arc;
2
3use tokio_rustls::rustls::ClientConfig;
4
5use fetchlet::{ChannelFuture, SecureTransport, SocketRequest, SocketTransport};
6
7use super::relay::{StartTls, relay, relay_secure};
8use crate::network::{Connector, runtime, server_name};
9
10/// A [`SocketTransport`] that opens TCP connections, with TLS from the
11/// start for `secureTransport: "on"` and after `startTls()` for
12/// `"starttls"`.
13///
14/// Pair it with a `SocketPolicy` in a `SocketService`: the policy
15/// authorizes the names JavaScript connects to, and this transport resolves
16/// them and refuses any resolved address that is not public, such as
17/// loopback, private and link-local networks, unless
18/// [`allow_private_addresses`](Self::allow_private_addresses). A name that
19/// resolves to no allowed address fails with `PermissionDenied`.
20///
21/// Connecting and relaying run on the Tokio runtime that polls the host
22/// pump; an App without one fails each connect with `Configuration`. TLS
23/// verifies the server against the Mozilla roots in `webpki-roots`, or the
24/// configuration from [`with_tls_config`](Self::with_tls_config).
25#[derive(Clone)]
26pub struct TcpTransport {
27    connector: Connector,
28}
29
30impl TcpTransport {
31    /// Connect to public addresses, verifying TLS servers against the
32    /// `webpki-roots` certificates.
33    pub fn new() -> Self {
34        Self {
35            connector: Connector::new(),
36        }
37    }
38
39    /// Connect to public addresses, using `config` for TLS, such as one
40    /// that trusts a private certificate authority.
41    pub fn with_tls_config(config: Arc<ClientConfig>) -> Self {
42        Self {
43            connector: Connector::with_tls_config(config),
44        }
45    }
46
47    /// Also connect to loopback, private and other non-public addresses,
48    /// for a host whose services run beside it, such as a database on the
49    /// same network.
50    pub fn allow_private_addresses(mut self) -> Self {
51        self.connector.allow_private_addresses();
52        self
53    }
54}
55
56impl Default for TcpTransport {
57    fn default() -> Self {
58        Self::new()
59    }
60}
61
62impl std::fmt::Debug for TcpTransport {
63    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        formatter
65            .debug_struct("TcpTransport")
66            .field(
67                "allow_private_addresses",
68                &self.connector.allows_private_addresses(),
69            )
70            .finish_non_exhaustive()
71    }
72}
73
74impl SocketTransport for TcpTransport {
75    fn connect(&self, request: SocketRequest) -> ChannelFuture {
76        let connector = self.connector.clone();
77        Box::pin(async move {
78            let runtime = runtime("TcpTransport")?;
79            let SocketRequest {
80                address,
81                secure_transport,
82                end,
83                ..
84            } = request;
85            let host = address.host();
86            let stream = connector.connect(host, address.port()).await?;
87            match secure_transport {
88                SecureTransport::Off => {
89                    runtime.spawn(relay(stream, end, None));
90                }
91                SecureTransport::On => {
92                    let stream = connector.secure(stream, host).await?;
93                    runtime.spawn(relay_secure(stream, end));
94                }
95                SecureTransport::StartTls => {
96                    let upgrade = StartTls {
97                        connector: connector.tls_connector(),
98                        name: server_name(host)?,
99                    };
100                    runtime.spawn(relay(stream, end, Some(upgrade)));
101                }
102            }
103            Ok(())
104        })
105    }
106}