Skip to main content

trillium_server_common/client/
destination.rs

1use crate::Url;
2use smallvec::SmallVec;
3use std::{borrow::Cow, io, net::SocketAddr};
4
5/// Everything a [`Connector`](crate::Connector) needs to open one connection: where to dial,
6/// whether to wrap it in TLS, and any per-connection ALPN.
7///
8/// Construct with [`new_with_host`](Destination::new_with_host) — resolve a domain, or dial
9/// pre-resolved addresses while validating against the domain — or
10/// [`new_with_socket_addrs`](Destination::new_with_socket_addrs) — dial pre-resolved addresses as a
11/// bare IP, with no SNI. There is deliberately no `Default`: a destination with neither a host nor
12/// any address is unconnectable, so each constructor fills at least one dial source.
13#[derive(Debug, Clone)]
14pub struct Destination {
15    secure: bool,
16    host: Option<String>,
17    port: u16,
18    addrs: SmallVec<[SocketAddr; 4]>,
19    /// `None` leaves the connector's configured default ALPN in place; `Some` overrides it for
20    /// this connection — including `Some([])`, which advertises no ALPN at all.
21    alpn: Option<SmallVec<[Cow<'static, [u8]>; 4]>>,
22}
23
24impl Destination {
25    /// A destination identified by host name and port.
26    ///
27    /// With no [`addrs`](Destination::with_addrs) added, the connector resolves `host` itself.
28    /// Adding pre-resolved addresses dials those instead while still validating the certificate
29    /// against `host`.
30    pub fn new_with_host(secure: bool, host: impl Into<String>, port: u16) -> Self {
31        Self {
32            secure,
33            host: Some(host.into()),
34            port,
35            addrs: SmallVec::new(),
36            alpn: None,
37        }
38    }
39
40    /// A destination identified only by pre-resolved socket addresses: a bare-IP connection with no
41    /// SNI. [`Connector::connect_to`](crate::Connector::connect_to) validates TLS against the
42    /// address actually dialed; [`Connector::connect_over`](crate::Connector::connect_over), which
43    /// does not dial, validates against the first address. The port is taken from the first
44    /// address.
45    pub fn new_with_socket_addrs(
46        secure: bool,
47        addrs: impl IntoIterator<Item = SocketAddr>,
48    ) -> Self {
49        let addrs = addrs.into_iter().collect::<SmallVec<[SocketAddr; 4]>>();
50        let port = addrs.first().map_or(0, SocketAddr::port);
51        Self {
52            secure,
53            host: None,
54            port,
55            addrs,
56            alpn: None,
57        }
58    }
59
60    /// Build a destination from a URL: maps `http`/`https` to plaintext/TLS and extracts the host
61    /// and port. An IP-literal host becomes a
62    /// [`new_with_socket_addrs`](Destination::new_with_socket_addrs) destination, so it is never
63    /// sent to a resolver; a domain becomes a [`new_with_host`](Destination::new_with_host)
64    /// destination.
65    ///
66    /// # Errors
67    ///
68    /// Returns an error if the scheme is neither `http` nor `https`, or the URL has no host or
69    /// port.
70    pub fn from_url(url: &Url) -> io::Result<Self> {
71        let secure = match url.scheme() {
72            "http" => false,
73            "https" => true,
74            other => {
75                return Err(io::Error::new(
76                    io::ErrorKind::InvalidInput,
77                    format!("unknown scheme {other}"),
78                ));
79            }
80        };
81        let port = url.port_or_known_default().ok_or_else(|| {
82            io::Error::new(io::ErrorKind::InvalidInput, format!("{url} missing port"))
83        })?;
84        match url.host() {
85            Some(url::Host::Domain(domain)) => Ok(Self::new_with_host(secure, domain, port)),
86            Some(url::Host::Ipv4(ip)) => Ok(Self::new_with_socket_addrs(
87                secure,
88                [SocketAddr::from((ip, port))],
89            )),
90            Some(url::Host::Ipv6(ip)) => Ok(Self::new_with_socket_addrs(
91                secure,
92                [SocketAddr::from((ip, port))],
93            )),
94            None => Err(io::Error::new(
95                io::ErrorKind::InvalidInput,
96                format!("{url} missing host"),
97            )),
98        }
99    }
100
101    /// Reconstruct a URL for this destination, used by the default
102    /// [`connect_to`](crate::Connector::connect_to) implementation to fall back to
103    /// [`connect`](crate::Connector::connect). Pre-resolved addresses and ALPN are not represented.
104    ///
105    /// # Errors
106    ///
107    /// Returns an error if the destination has neither a host nor any address, or the result does
108    /// not parse as a URL.
109    pub fn to_url(&self) -> io::Result<Url> {
110        let scheme = if self.secure { "https" } else { "http" };
111        let authority = match &self.host {
112            Some(host) => format!("{host}:{}", self.port),
113            None => self
114                .addrs
115                .first()
116                .ok_or_else(|| {
117                    io::Error::new(
118                        io::ErrorKind::InvalidInput,
119                        "destination has neither host nor addresses",
120                    )
121                })?
122                .to_string(),
123        };
124        Url::parse(&format!("{scheme}://{authority}"))
125            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))
126    }
127
128    /// Whether this destination should be reached over TLS.
129    #[must_use]
130    pub fn secure(&self) -> bool {
131        self.secure
132    }
133
134    /// The host name used for resolution and certificate validation, or `None` for a bare-IP
135    /// destination.
136    #[must_use]
137    pub fn host(&self) -> Option<&str> {
138        self.host.as_deref()
139    }
140
141    /// The origin port. Pre-resolved [`addrs`](Destination::addrs) carry their own ports; this is
142    /// the port used when resolving the host.
143    #[must_use]
144    pub fn port(&self) -> u16 {
145        self.port
146    }
147
148    /// The pre-resolved addresses to dial, or an empty slice to resolve the host.
149    #[must_use]
150    pub fn addrs(&self) -> &[SocketAddr] {
151        &self.addrs
152    }
153
154    /// The per-connection ALPN override: `Some` advertises exactly these protocols for this
155    /// connection (`Some([])` advertises none), `None` leaves the connector's configured default in
156    /// place.
157    #[must_use]
158    pub fn alpn(&self) -> Option<&[Cow<'static, [u8]>]> {
159        self.alpn.as_deref()
160    }
161
162    /// Set the pre-resolved addresses to dial, replacing any already present.
163    #[must_use]
164    pub fn with_addrs(mut self, addrs: impl IntoIterator<Item = SocketAddr>) -> Self {
165        self.set_addrs(addrs);
166        self
167    }
168
169    /// Set the pre-resolved addresses to dial, replacing any already present.
170    pub fn set_addrs(&mut self, addrs: impl IntoIterator<Item = SocketAddr>) -> &mut Self {
171        self.addrs = addrs.into_iter().collect();
172        self
173    }
174
175    /// Override the ALPN protocols to advertise for this connection, replacing any already present.
176    /// An empty iterator advertises no ALPN at all; to instead defer to the connector's configured
177    /// default, use [`without_alpn`](Destination::without_alpn).
178    #[must_use]
179    pub fn with_alpn(mut self, alpn: impl IntoIterator<Item = Cow<'static, [u8]>>) -> Self {
180        self.set_alpn(alpn);
181        self
182    }
183
184    /// Override the ALPN protocols to advertise for this connection, replacing any already present.
185    /// An empty iterator advertises no ALPN at all; to instead defer to the connector's configured
186    /// default, use [`clear_alpn`](Destination::clear_alpn).
187    pub fn set_alpn(&mut self, alpn: impl IntoIterator<Item = Cow<'static, [u8]>>) -> &mut Self {
188        self.alpn = Some(alpn.into_iter().collect());
189        self
190    }
191
192    /// Clear any per-connection ALPN override so this connection uses the connector's configured
193    /// default.
194    #[must_use]
195    pub fn without_alpn(mut self) -> Self {
196        self.clear_alpn();
197        self
198    }
199
200    /// Clear any per-connection ALPN override so this connection uses the connector's configured
201    /// default.
202    pub fn clear_alpn(&mut self) -> &mut Self {
203        self.alpn = None;
204        self
205    }
206
207    /// Return a copy of this destination with the `secure` flag overridden.
208    #[must_use]
209    pub fn with_secure(mut self, secure: bool) -> Self {
210        self.secure = secure;
211        self
212    }
213}