]>
git.proxmox.com Git - pve-installer.git/blob - proxmox-installer-common/src/utils.rs
3 net
::{AddrParseError, IpAddr}
,
8 use serde
::Deserialize
;
10 /// Possible errors that might occur when parsing CIDR addresses.
12 pub enum CidrAddressParseError
{
13 /// No delimiter for separating address and mask was found.
15 /// The IP address part could not be parsed.
16 InvalidAddr(AddrParseError
),
17 /// The mask could not be parsed.
18 InvalidMask(Option
<ParseIntError
>),
21 /// An IP address (IPv4 or IPv6), including network mask.
23 /// See the [`IpAddr`] type for more information how IP addresses are handled.
24 /// The mask is appropriately enforced to be `0 <= mask <= 32` for IPv4 or
25 /// `0 <= mask <= 128` for IPv6 addresses.
29 /// use std::net::{Ipv4Addr, Ipv6Addr};
30 /// use proxmox_installer_common::utils::CidrAddress;
31 /// let ipv4 = CidrAddress::new(Ipv4Addr::new(192, 168, 0, 1), 24).unwrap();
32 /// let ipv6 = CidrAddress::new(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0xc0a8, 1), 32).unwrap();
34 /// assert_eq!(ipv4.to_string(), "192.168.0.1/24");
35 /// assert_eq!(ipv6.to_string(), "2001:db8::c0a8:1/32");
37 #[derive(Clone, Debug, PartialEq)]
38 pub struct CidrAddress
{
44 /// Constructs a new CIDR address.
46 /// It fails if the mask is invalid for the given IP address.
47 pub fn new
<T
: Into
<IpAddr
>>(addr
: T
, mask
: usize) -> Result
<Self, CidrAddressParseError
> {
48 let addr
= addr
.into();
50 if mask
> mask_limit(&addr
) {
51 Err(CidrAddressParseError
::InvalidMask(None
))
53 Ok(Self { addr, mask }
)
57 /// Returns only the IP address part of the address.
58 pub fn addr(&self) -> IpAddr
{
62 /// Returns `true` if this address is an IPv4 address, `false` otherwise.
63 pub fn is_ipv4(&self) -> bool
{
67 /// Returns `true` if this address is an IPv6 address, `false` otherwise.
68 pub fn is_ipv6(&self) -> bool
{
72 /// Returns only the mask part of the address.
73 pub fn mask(&self) -> usize {
78 impl FromStr
for CidrAddress
{
79 type Err
= CidrAddressParseError
;
81 fn from_str(s
: &str) -> Result
<Self, Self::Err
> {
84 .ok_or(CidrAddressParseError
::NoDelimiter
)?
;
86 let addr
= addr
.parse().map_err(CidrAddressParseError
::InvalidAddr
)?
;
90 .map_err(|err
| CidrAddressParseError
::InvalidMask(Some(err
)))?
;
92 if mask
> mask_limit(&addr
) {
93 Err(CidrAddressParseError
::InvalidMask(None
))
95 Ok(Self { addr, mask }
)
100 impl fmt
::Display
for CidrAddress
{
101 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
102 write
!(f
, "{}/{}", self.addr
, self.mask
)
106 fn mask_limit(addr
: &IpAddr
) -> usize {
114 /// Possible errors that might occur when parsing FQDNs.
115 #[derive(Debug, Eq, PartialEq)]
116 pub enum FqdnParseError
{
123 impl fmt
::Display
for FqdnParseError
{
124 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
125 use FqdnParseError
::*;
127 MissingHostname
=> write
!(f
, "missing hostname part"),
128 NumericHostname
=> write
!(f
, "hostname cannot be purely numeric"),
129 InvalidPart(part
) => write
!(
131 "FQDN must only consist of alphanumeric characters and dashes. Invalid part: '{part}'",
133 TooLong(len
) => write
!(f
, "FQDN too long: {len} > {}", Fqdn
::MAX_LENGTH
),
138 /// A type for safely representing fully-qualified domain names (FQDNs).
140 /// It considers following RFCs:
141 /// https://www.ietf.org/rfc/rfc952.txt (sec. "ASSUMPTIONS", 1.)
142 /// https://www.ietf.org/rfc/rfc1035.txt (sec. 2.3. "Conventions")
143 /// https://www.ietf.org/rfc/rfc1123.txt (sec. 2.1. "Host Names and Numbers")
144 /// https://www.ietf.org/rfc/rfc3492.txt
145 /// https://www.ietf.org/rfc/rfc4343.txt
147 /// .. and applies some restriction given by Debian, e.g. 253 instead of 255
148 /// maximum total length and maximum 63 characters per label.
149 /// https://manpages.debian.org/stable/manpages/hostname.7.en.html
152 /// - It enforces the restriction as per Bugzilla #1054, in that
153 /// purely numeric hostnames are not allowed - against RFC1123 sec. 2.1.
155 /// Some terminology:
156 /// - "label" - a single part of a FQDN, e.g. <label>.<label>.<tld>
157 #[derive(Clone, Debug, Eq)]
163 /// Maximum length of a single label of the FQDN
164 const MAX_LABEL_LENGTH
: usize = 63;
165 /// Maximum total length of the FQDN
166 const MAX_LENGTH
: usize = 253;
168 pub fn from(fqdn
: &str) -> Result
<Self, FqdnParseError
> {
169 if fqdn
.len() > Self::MAX_LENGTH
{
170 return Err(FqdnParseError
::TooLong(fqdn
.len()));
175 .map(ToOwned
::to_owned
)
176 .collect
::<Vec
<String
>>();
179 if !Self::validate_single(part
) {
180 return Err(FqdnParseError
::InvalidPart(part
.clone()));
185 Err(FqdnParseError
::MissingHostname
)
186 } else if parts
[0].chars().all(|c
| c
.is_ascii_digit()) {
187 // Do not allow a purely numeric hostname, see:
188 // https://bugzilla.proxmox.com/show_bug.cgi?id=1054
189 Err(FqdnParseError
::NumericHostname
)
195 pub fn host(&self) -> Option
<&str> {
196 self.has_host().then_some(&self.parts
[0])
199 pub fn domain(&self) -> String
{
200 let parts
= if self.has_host() {
209 /// Checks whether the FQDN has a hostname associated with it, i.e. is has more than 1 part.
210 fn has_host(&self) -> bool
{
214 fn validate_single(s
: &String
) -> bool
{
216 && s
.len() <= Self::MAX_LABEL_LENGTH
217 // First character must be alphanumeric
220 .map(|c
| c
.is_ascii_alphanumeric())
222 // .. last character as well,
225 .map(|c
| c
.is_ascii_alphanumeric())
227 // and anything between must be alphanumeric or -
230 .take(s
.len().saturating_sub(2))
231 .all(|c
| c
.is_ascii_alphanumeric() || c
== '
-'
)
235 impl FromStr
for Fqdn
{
236 type Err
= FqdnParseError
;
238 fn from_str(value
: &str) -> Result
<Self, Self::Err
> {
243 impl fmt
::Display
for Fqdn
{
244 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
245 write
!(f
, "{}", self.parts
.join("."))
249 impl<'de
> Deserialize
<'de
> for Fqdn
{
250 fn deserialize
<D
>(deserializer
: D
) -> Result
<Self, D
::Error
>
252 D
: serde
::Deserializer
<'de
>,
254 let s
: String
= Deserialize
::deserialize(deserializer
)?
;
256 .map_err(|_
| serde
::de
::Error
::custom("invalid FQDN"))
260 impl PartialEq
for Fqdn
{
261 // Case-insensitive comparison, as per RFC 952 "ASSUMPTIONS", RFC 1035 sec. 2.3.3. "Character
262 // Case" and RFC 4343 as a whole
263 fn eq(&self, other
: &Self) -> bool
{
264 if self.parts
.len() != other
.parts
.len() {
270 .zip(other
.parts
.iter())
271 .all(|(a
, b
)| a
.to_lowercase() == b
.to_lowercase())
280 fn fqdn_construct() {
281 use FqdnParseError
::*;
282 assert
!(Fqdn
::from("foo.example.com").is_ok());
283 assert
!(Fqdn
::from("foo-bar.com").is_ok());
284 assert
!(Fqdn
::from("a-b.com").is_ok());
286 assert_eq
!(Fqdn
::from("foo"), Err(MissingHostname
));
288 assert_eq
!(Fqdn
::from("-foo.com"), Err(InvalidPart("-foo".to_owned())));
289 assert_eq
!(Fqdn
::from("foo-.com"), Err(InvalidPart("foo-".to_owned())));
290 assert_eq
!(Fqdn
::from("foo.com-"), Err(InvalidPart("com-".to_owned())));
291 assert_eq
!(Fqdn
::from("-o-.com"), Err(InvalidPart("-o-".to_owned())));
293 // https://bugzilla.proxmox.com/show_bug.cgi?id=1054
294 assert_eq
!(Fqdn
::from("123.com"), Err(NumericHostname
));
295 assert
!(Fqdn
::from("foo123.com").is_ok());
296 assert
!(Fqdn
::from("123foo.com").is_ok());
298 assert
!(Fqdn
::from(&format
!("{}.com", "a".repeat(63))).is_ok());
300 Fqdn
::from(&format
!("{}.com", "a".repeat(250))),
304 Fqdn
::from(&format
!("{}.com", "a".repeat(64))),
305 Err(InvalidPart("a".repeat(64))),
308 // https://bugzilla.proxmox.com/show_bug.cgi?id=5230
310 Fqdn
::from("123@foo.com"),
311 Err(InvalidPart("123@foo".to_owned()))
317 let fqdn
= Fqdn
::from("pve.example.com").unwrap();
318 assert_eq
!(fqdn
.host().unwrap(), "pve");
319 assert_eq
!(fqdn
.domain(), "example.com");
322 &["pve".to_owned(), "example".to_owned(), "com".to_owned()]
329 Fqdn
::from("foo.example.com").unwrap().to_string(),
336 assert_eq
!(Fqdn
::from("example.com"), Fqdn
::from("example.com"));
337 assert_eq
!(Fqdn
::from("example.com"), Fqdn
::from("ExAmPle.Com"));
338 assert_eq
!(Fqdn
::from("ExAmPle.Com"), Fqdn
::from("example.com"));
339 assert_ne
!(Fqdn
::from("subdomain.ExAmPle.Com"), Fqdn
::from("example.com"));
340 assert_ne
!(Fqdn
::from("foo.com"), Fqdn
::from("bar.com"));
341 assert_ne
!(Fqdn
::from("example.com"), Fqdn
::from("example.net"));