tuwunel_service/resolver/
fed.rs1use std::{
2 fmt,
3 net::{IpAddr, SocketAddr},
4};
5
6use serde::{Deserialize, Serialize};
7use tuwunel_core::{arrayvec::ArrayString, smallstr::SmallString, utils::math::Expected};
8
9use super::DestString;
10
11#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
12pub enum FedDest {
13 Literal(SocketAddr),
14 Named(HostString, PortString),
15}
16
17pub(super) type HostString = SmallString<[u8; 32]>;
19
20pub(super) type PortString = ArrayString<16>;
22
23const DEFAULT_PORT: &str = ":8448";
24
25pub(crate) fn get_ip_with_port(dest_str: &str) -> Option<FedDest> {
26 dest_str
27 .parse()
28 .map(FedDest::Literal)
29 .or_else(|_| {
30 unbracket(dest_str)
31 .parse()
32 .map(|ip_addr: IpAddr| FedDest::Literal(SocketAddr::new(ip_addr, 8448)))
33 })
34 .ok()
35}
36
37#[inline]
38pub(super) fn unbracket(host: &str) -> &str {
39 host.strip_prefix('[')
40 .and_then(|host| host.strip_suffix(']'))
41 .unwrap_or(host)
42}
43
44pub(crate) fn add_port_to_hostname(dest: &str) -> FedDest {
45 let (host, port) = match dest.find(':') {
46 | None => (dest, DEFAULT_PORT),
47 | Some(pos) => dest.split_at(pos),
48 };
49
50 FedDest::Named(
51 host.into(),
52 PortString::from(port).unwrap_or_else(|_| FedDest::default_port()),
53 )
54}
55
56impl FedDest {
57 pub(crate) fn https_string(&self) -> DestString {
58 match self {
59 | Self::Literal(addr) => format!("https://{addr}").into(),
60 | Self::Named(host, port) => format!("https://{host}{port}").into(),
61 }
62 }
63
64 pub(crate) fn uri_string(&self) -> DestString {
65 match self {
66 | Self::Literal(addr) => addr.to_string().into(),
67 | Self::Named(host, port) => [host.as_str(), port.as_str()].concat().into(),
68 }
69 }
70
71 #[inline]
72 pub(crate) fn hostname(&self) -> HostString {
73 match &self {
74 | Self::Literal(addr) => addr.ip().to_string().into(),
75 | Self::Named(host, _) => host.clone(),
76 }
77 }
78
79 #[inline]
80 #[expect(clippy::string_slice)]
81 pub(crate) fn port(&self) -> Option<u16> {
82 match &self {
83 | Self::Literal(addr) => Some(addr.port()),
84 | Self::Named(_, port) => port[1..].parse().ok(),
85 }
86 }
87
88 #[inline]
89 #[must_use]
90 pub fn default_port() -> PortString {
91 PortString::from(DEFAULT_PORT).expect("default port string")
92 }
93
94 #[inline]
95 #[must_use]
96 pub fn size(&self) -> usize {
97 match self {
98 | Self::Literal(saddr) => size_of_val(saddr),
99 | Self::Named(host, port) => host.len().expected_add(port.capacity()),
100 }
101 }
102}
103
104impl fmt::Display for FedDest {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 f.write_str(self.uri_string().as_str())
107 }
108}