tlspuffin/tls/rustls/client/
client_conn.rs

1use std::error::Error as StdError;
2use std::fmt;
3
4use crate::tls::rustls::verify;
5
6/// Encodes ways a client can know the expected name of the server.
7///
8/// This currently covers knowing the DNS name of the server, but
9/// will be extended in the future to knowing the IP address of the
10/// server, as well as supporting privacy-preserving names for the
11/// server ("ECH").  For this reason this enum is `non_exhaustive`.
12///
13/// # Making one
14///
15/// If you have a DNS name as a `&str`, this type implements `TryFrom<&str>`,
16/// so you can do:
17///
18/// ```
19/// # use tlspuffin::tls::rustls::client::client_conn::ServerName;
20/// ServerName::try_from("example.com").expect("invalid DNS name");
21///
22/// // or, alternatively...
23///
24/// let x = "example.com".try_into().expect("invalid DNS name");
25/// # let _: ServerName = x;
26/// ```
27#[non_exhaustive]
28#[derive(Debug, PartialEq, Clone)]
29pub enum ServerName {
30    /// The server is identified by a DNS name.  The name
31    /// is sent in the TLS Server Name Indication (SNI)
32    /// extension.
33    DnsName(verify::DnsName),
34}
35
36impl ServerName {
37    /// Return the name that should go in the SNI extension.
38    /// If [`None`] is returned, the SNI extension is not included
39    /// in the handshake.
40    pub fn for_sni(&self) -> Option<webpki::DnsNameRef<'_>> {
41        match self {
42            Self::DnsName(dns_name) => Some(dns_name.0.as_ref()),
43        }
44    }
45
46    /// Return a prefix-free, unique encoding for the name.
47    pub fn encode(&self) -> Vec<u8> {
48        enum UniqueTypeCode {
49            DnsName = 0x01,
50        }
51
52        let Self::DnsName(dns_name) = self;
53        let bytes = dns_name.0.as_ref();
54
55        let mut r = Vec::with_capacity(2 + bytes.as_ref().len());
56        r.push(UniqueTypeCode::DnsName as u8);
57        r.push(bytes.as_ref().len() as u8);
58        r.extend_from_slice(bytes.as_ref());
59
60        r
61    }
62}
63
64/// Attempt to make a ServerName from a string by parsing
65/// it as a DNS name.
66impl TryFrom<&str> for ServerName {
67    type Error = InvalidDnsNameError;
68
69    fn try_from(s: &str) -> Result<Self, Self::Error> {
70        match webpki::DnsNameRef::try_from_ascii_str(s) {
71            Ok(dns) => Ok(Self::DnsName(verify::DnsName(dns.into()))),
72            Err(webpki::InvalidDnsNameError) => Err(InvalidDnsNameError),
73        }
74    }
75}
76
77/// The provided input could not be parsed because
78/// it is not a syntactically-valid DNS Name.
79#[derive(Debug)]
80pub struct InvalidDnsNameError;
81
82impl fmt::Display for InvalidDnsNameError {
83    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84        f.write_str("invalid dns name")
85    }
86}
87
88impl StdError for InvalidDnsNameError {}