public inbox for pve-devel@lists.proxmox.com
 help / color / mirror / Atom feed
* [PATCH proxmox 0/4] network-types: add types for network interface names
@ 2026-11-12 17:10 Stefan Hanreich
  2026-11-12 17:10 ` [PATCH proxmox 1/4] network-types: add a type " Stefan Hanreich
                   ` (3 more replies)
  0 siblings, 4 replies; 6+ messages in thread
From: Stefan Hanreich @ 2026-11-12 17:10 UTC (permalink / raw)
  To: pve-devel

Network interface names are validated differently all over the stack:

* pve-iface of the Perl JSON schema, e.g. for the network
  configuration and the interfaces of firewall rules in PVE: letters,
  digits and '_' with an optional VLAN or alias suffix, up to 21
  characters
* pve-bridge-id and the names of container interfaces: [-_.\w\d]+
* the network API of PBS and PDM: the SAFE_ID format with up to 15
  characters
* the installers: pve-iface, up to 15 bytes, and no names reserved for
  bonds, VLANs and bridges
* SDN: VNet IDs of up to 8 letters and digits
* iproute2 and the kernel, whose rules also differ between iproute2
  versions

The pve-iface format accepts names that the kernel rejects, e.g.
longer than 15 bytes, but rejects names with a '-', which users have
asked for (bug #6366 [1]).

This series adds one type per kind of name to proxmox-network-types,
with explicit conversions between them:

* NetworkInterfaceName: names as accepted by the API, i.e. every name
  that the APIs of PVE, PBS and PDM accept and the kernel can use,
  plus a few that pve-iface rejects, e.g. with a '-'. It uses the
  format of the network API of PBS and PDM.
* NetworkInterfaceAltname: names or altnames, e.g. the interface of a
  firewall rule
* KernelNetworkInterfaceName and KernelNetworkInterfaceAltname: names
  as accepted by the kernel, stored as bytes
* LegacyNetworkInterfaceName: names validated by pve-iface, for
  reading existing configurations

The module documentation describes which type to use for what. The
firewall hardening series uses the API types for the interfaces of
firewall rules and guests.

The goal is to unify the validation of interface names with types that
respect all the quirks that exist, and to convert the places dealing
with interface names to them in follow-up series, starting with
proxmox-network-api and the new format in pve-iface.


Notes
=====

The kernel types store bytes, since the kernel stores names as bytes
that do not have to be valid UTF-8, so String is unsuited for them.
Also, not every valid UTF-8 string is a valid kernel name. 'ip -json'
prints names that are not valid UTF-8 unchanged, which serde_json only
accepts when deserializing into bytes.

The types follow the rules of the kernel instead of iproute2, whose
checks differ between versions: before 7.0, 'ip' rejected altnames
with whitespace or '/', and it still rejects the empty altname.

The kernel treats 0xa0 as whitespace, which is also a UTF-8
continuation byte, so it rejects some valid UTF-8 names as well, e.g.
ones containing U+00E0. A test checks the resulting rule against all
code points.

[1] https://bugzilla.proxmox.com/show_bug.cgi?id=6366


proxmox:

Stefan Hanreich (4):
  network-types: add a type for network interface names
  network-types: add a type for network interface altnames
  network-types: add types for names reported by the kernel
  network-types: add a type for names of existing configurations

 proxmox-network-types/Cargo.toml              |   4 +-
 proxmox-network-types/src/lib.rs              |   2 +
 .../src/network_interface.rs                  | 957 ++++++++++++++++++
 3 files changed, 962 insertions(+), 1 deletion(-)
 create mode 100644 proxmox-network-types/src/network_interface.rs


Summary over all repositories:
  3 files changed, 962 insertions(+), 1 deletions(-)

-- 
Generated by murpp 0.12.1




^ permalink raw reply	[flat|nested] 6+ messages in thread

* [PATCH proxmox 1/4] network-types: add a type for network interface names
  2026-11-12 17:10 [PATCH proxmox 0/4] network-types: add types for network interface names Stefan Hanreich
@ 2026-11-12 17:10 ` Stefan Hanreich
  2026-11-12 17:10 ` [PATCH proxmox 2/4] network-types: add a type for network interface altnames Stefan Hanreich
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 6+ messages in thread
From: Stefan Hanreich @ 2026-11-12 17:10 UTC (permalink / raw)
  To: pve-devel

There is no common type for network interface names yet, and the
pve-iface format of the Perl JSON schema even accepts names that the
kernel rejects, e.g. names longer than 15 bytes, while it rejects
names with a '-' (bug #6366 [1]).

NetworkInterfaceName accepts every name that the APIs of PVE, PBS and
PDM accept and the kernel can use, plus a few that pve-iface rejects:
names with a '-', names starting with a digit or '_', single-character
names and names with more than one or a non-numeric dotted suffix,
e.g. eth0.100.200. It uses the format of the network API of PBS and
PDM.

The api_string_type macro requires anyhow, so add it to the api-types
feature.

[1] https://bugzilla.proxmox.com/show_bug.cgi?id=6366

Signed-off-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 proxmox-network-types/Cargo.toml              |   4 +-
 proxmox-network-types/src/lib.rs              |   2 +
 .../src/network_interface.rs                  | 102 ++++++++++++++++++
 3 files changed, 107 insertions(+), 1 deletion(-)
 create mode 100644 proxmox-network-types/src/network_interface.rs

diff --git a/proxmox-network-types/Cargo.toml b/proxmox-network-types/Cargo.toml
index 1e1eacbf..b5ab5c5e 100644
--- a/proxmox-network-types/Cargo.toml
+++ b/proxmox-network-types/Cargo.toml
@@ -10,6 +10,7 @@ exclude.workspace = true
 rust-version.workspace = true
 
 [dependencies]
+anyhow = { workspace = true, optional = true }
 regex = { workspace = true, optional = true }
 serde = { workspace = true, features = [ "derive", "std" ] }
 serde_with = "3.8.1"
@@ -17,7 +18,8 @@ serde_plain.workspace = true
 thiserror.workspace = true
 
 proxmox-schema = { workspace = true, features = [ "api-macro", "api-types" ], optional = true}
+proxmox-serde = { workspace = true, optional = true }
 
 [features]
 default = []
-api-types = ["dep:proxmox-schema", "dep:regex"]
+api-types = ["dep:anyhow", "dep:proxmox-schema", "dep:proxmox-serde", "dep:regex"]
diff --git a/proxmox-network-types/src/lib.rs b/proxmox-network-types/src/lib.rs
index 6a5ddbf9..ebbabe76 100644
--- a/proxmox-network-types/src/lib.rs
+++ b/proxmox-network-types/src/lib.rs
@@ -9,3 +9,5 @@ pub use ip_address::*;
 
 pub mod mac_address;
 pub use mac_address::*;
+
+pub mod network_interface;
diff --git a/proxmox-network-types/src/network_interface.rs b/proxmox-network-types/src/network_interface.rs
new file mode 100644
index 00000000..24972058
--- /dev/null
+++ b/proxmox-network-types/src/network_interface.rs
@@ -0,0 +1,102 @@
+//! Types for network interface names.
+//!
+//! The API, the kernel and existing configurations accept different names, so each kind of name
+//! has its own type, with explicit conversions between them. The API types are in `api_types` and
+//! require the `api-types` feature.
+//!
+//! # Which type to use
+//!
+//! * `api_types::NetworkInterfaceName`: names in the API and in configuration files, and names
+//!   that are created or passed to `ip`. Not for values that can also be altnames, and not for
+//!   reading names from the kernel, which can be outside of the API format.
+
+/// API types for network interface names.
+///
+/// [`NetworkInterfaceName`](api_types::NetworkInterfaceName) is the name of a network interface
+/// as accepted by the API. It is meant for every network interface that our stack creates,
+/// configures or references:
+///
+/// ```
+/// # use proxmox_network_types::network_interface::api_types::NetworkInterfaceName;
+/// let name: NetworkInterfaceName = "uplink-0".parse().unwrap();
+/// assert_eq!(name.as_str(), "uplink-0");
+///
+/// assert!("veth999999999i31".parse::<NetworkInterfaceName>().is_err());
+/// ```
+#[cfg(feature = "api-types")]
+pub mod api_types {
+    use proxmox_schema::{api, api_string_type, api_types::SAFE_ID_FORMAT};
+
+    /// The size of the kernel buffer for network interface names, including the terminating NUL.
+    const IFNAMSIZ: usize = 16;
+
+    api_string_type! {
+        #[api(format: &SAFE_ID_FORMAT, min_length: 1, max_length: IFNAMSIZ - 1)]
+        /// The name of a network interface.
+        ///
+        /// Uses the format of other names in the API, limited to the 15 bytes the kernel allows
+        /// for interface names. Every such name is valid for the kernel.
+        #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
+        #[repr(transparent)]
+        pub struct NetworkInterfaceName(String);
+    }
+
+    proxmox_serde::forward_deserialize_to_from_str!(NetworkInterfaceName);
+    proxmox_serde::forward_serialize_to_display!(NetworkInterfaceName);
+
+    #[cfg(test)]
+    mod tests {
+        use super::*;
+
+        #[test]
+        fn parse_network_interface_name() {
+            for name in [
+                "eth0",
+                "vmbr0",
+                "bond0.100",
+                "eth0.100.200",
+                "uplink-0",
+                "0eth",
+                "_eth0",
+                "a",
+                "tap100i0",
+                // 15 bytes is the longest name the kernel accepts
+                "abcdefghijklmno",
+            ] {
+                let parsed: NetworkInterfaceName = name.parse().expect(name);
+                assert_eq!(parsed.as_str(), name);
+                assert_eq!(parsed.to_string(), name);
+            }
+
+            for name in [
+                "",
+                ".",
+                "..",
+                ".eth0",
+                "-eth0",
+                "eth 0",
+                "eth0/1",
+                "eth0:1",
+                "eth\u{e9}",
+                "abcdefghijklmnop",
+                "veth999999999i31",
+            ] {
+                assert!(name.parse::<NetworkInterfaceName>().is_err(), "{name:?}");
+            }
+        }
+
+        #[test]
+        fn deserialize_network_interface_name() {
+            let name: NetworkInterfaceName = serde_plain::from_str("eth0").expect("valid name");
+            assert_eq!(name.as_str(), "eth0");
+            assert_eq!(serde_plain::to_string(&name).expect("serializable"), "eth0");
+
+            for name in ["eth:0", "abcdefghijklmnop"] {
+                assert!(
+                    serde_plain::from_str::<NetworkInterfaceName>(name).is_err(),
+                    "{name:?}"
+                );
+            }
+        }
+    }
+}
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 6+ messages in thread

* [PATCH proxmox 2/4] network-types: add a type for network interface altnames
  2026-11-12 17:10 [PATCH proxmox 0/4] network-types: add types for network interface names Stefan Hanreich
  2026-11-12 17:10 ` [PATCH proxmox 1/4] network-types: add a type " Stefan Hanreich
@ 2026-11-12 17:10 ` Stefan Hanreich
  2026-11-12 17:10 ` [PATCH proxmox 3/4] network-types: add types for names reported by the kernel Stefan Hanreich
  2026-11-12 17:11 ` [PATCH proxmox 4/4] network-types: add a type for names of existing configurations Stefan Hanreich
  3 siblings, 0 replies; 6+ messages in thread
From: Stefan Hanreich @ 2026-11-12 17:10 UTC (permalink / raw)
  To: pve-devel

Altnames can be up to 127 bytes long, so places that accept either a
name or an altname, like the interface of a firewall rule, cannot use
NetworkInterfaceName.

NetworkInterfaceAltname uses the same format with the length limit of
altnames. Every name is a valid altname as well, so add a conversion
from NetworkInterfaceName.

Signed-off-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 .../src/network_interface.rs                  | 80 +++++++++++++++++++
 1 file changed, 80 insertions(+)

diff --git a/proxmox-network-types/src/network_interface.rs b/proxmox-network-types/src/network_interface.rs
index 24972058..fa6d2e37 100644
--- a/proxmox-network-types/src/network_interface.rs
+++ b/proxmox-network-types/src/network_interface.rs
@@ -9,6 +9,10 @@
 //! * `api_types::NetworkInterfaceName`: names in the API and in configuration files, and names
 //!   that are created or passed to `ip`. Not for values that can also be altnames, and not for
 //!   reading names from the kernel, which can be outside of the API format.
+//!
+//! * `api_types::NetworkInterfaceAltname`: values that can be a name or an altname, e.g. the
+//!   interface of a firewall rule. Resolve it to the name where only names work, e.g. for
+//!   `iifname` in nftables.
 
 /// API types for network interface names.
 ///
@@ -23,6 +27,21 @@
 ///
 /// assert!("veth999999999i31".parse::<NetworkInterfaceName>().is_err());
 /// ```
+///
+/// Values that are either the name or an altname of a network interface, e.g. the interface of a
+/// firewall rule, are represented by
+/// [`NetworkInterfaceAltname`](api_types::NetworkInterfaceAltname):
+///
+/// ```
+/// # use proxmox_network_types::network_interface::api_types::{
+/// #     NetworkInterfaceAltname, NetworkInterfaceName,
+/// # };
+/// let altname: NetworkInterfaceAltname = "enx0123456789abcd".parse().unwrap();
+/// assert_eq!(altname.as_str(), "enx0123456789abcd");
+///
+/// let name: NetworkInterfaceName = "eth0".parse().unwrap();
+/// assert_eq!(NetworkInterfaceAltname::from(name).as_str(), "eth0");
+/// ```
 #[cfg(feature = "api-types")]
 pub mod api_types {
     use proxmox_schema::{api, api_string_type, api_types::SAFE_ID_FORMAT};
@@ -30,6 +49,9 @@ pub mod api_types {
     /// The size of the kernel buffer for network interface names, including the terminating NUL.
     const IFNAMSIZ: usize = 16;
 
+    /// The size of the kernel buffer for altnames, including the terminating NUL.
+    const ALTIFNAMSIZ: usize = 128;
+
     api_string_type! {
         #[api(format: &SAFE_ID_FORMAT, min_length: 1, max_length: IFNAMSIZ - 1)]
         /// The name of a network interface.
@@ -44,6 +66,27 @@ pub mod api_types {
     proxmox_serde::forward_deserialize_to_from_str!(NetworkInterfaceName);
     proxmox_serde::forward_serialize_to_display!(NetworkInterfaceName);
 
+    api_string_type! {
+        #[api(format: &SAFE_ID_FORMAT, min_length: 1, max_length: ALTIFNAMSIZ - 1)]
+        /// The name or an alternative name (altname) of a network interface.
+        ///
+        /// Same format as network interface names, but with the altname limit of 127 bytes. It
+        /// has to be resolved to the name of the interface where only names are accepted.
+        #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
+        #[repr(transparent)]
+        pub struct NetworkInterfaceAltname(String);
+    }
+
+    proxmox_serde::forward_deserialize_to_from_str!(NetworkInterfaceAltname);
+    proxmox_serde::forward_serialize_to_display!(NetworkInterfaceAltname);
+
+    impl From<NetworkInterfaceName> for NetworkInterfaceAltname {
+        fn from(name: NetworkInterfaceName) -> Self {
+            // SAFETY: both schemas use the same format, and names are shorter than altnames
+            unsafe { Self::from_string_unchecked(name.into_string()) }
+        }
+    }
+
     #[cfg(test)]
     mod tests {
         use super::*;
@@ -98,5 +141,42 @@ pub mod api_types {
                 );
             }
         }
+
+        #[test]
+        fn parse_network_interface_altname() {
+            let longest = "a".repeat(ALTIFNAMSIZ - 1);
+
+            for name in [
+                "eth0",
+                "bond0.100",
+                "uplink-a",
+                "abcdefghijklmnop",
+                "enx0123456789abcd",
+                longest.as_str(),
+            ] {
+                let parsed: NetworkInterfaceAltname = name.parse().expect(name);
+                assert_eq!(parsed.as_str(), name);
+                assert_eq!(parsed.to_string(), name);
+            }
+
+            let too_long = "a".repeat(ALTIFNAMSIZ);
+
+            for name in ["", ".", "-eth0", "eth 0", "eth0:1", too_long.as_str()] {
+                assert!(name.parse::<NetworkInterfaceAltname>().is_err(), "{name:?}");
+            }
+        }
+
+        #[test]
+        fn deserialize_network_interface_altname() {
+            let name: NetworkInterfaceAltname =
+                serde_plain::from_str("abcdefghijklmnop").expect("valid altname");
+            assert_eq!(name.as_str(), "abcdefghijklmnop");
+            assert_eq!(
+                serde_plain::to_string(&name).expect("serializable"),
+                "abcdefghijklmnop"
+            );
+
+            assert!(serde_plain::from_str::<NetworkInterfaceAltname>("eth0:1").is_err());
+        }
     }
 }
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 6+ messages in thread

* [PATCH proxmox 3/4] network-types: add types for names reported by the kernel
  2026-11-12 17:10 [PATCH proxmox 0/4] network-types: add types for network interface names Stefan Hanreich
  2026-11-12 17:10 ` [PATCH proxmox 1/4] network-types: add a type " Stefan Hanreich
  2026-11-12 17:10 ` [PATCH proxmox 2/4] network-types: add a type for network interface altnames Stefan Hanreich
@ 2026-11-12 17:10 ` Stefan Hanreich
  2026-11-12 17:11 ` [PATCH proxmox 4/4] network-types: add a type for names of existing configurations Stefan Hanreich
  3 siblings, 0 replies; 6+ messages in thread
From: Stefan Hanreich @ 2026-11-12 17:10 UTC (permalink / raw)
  To: pve-devel

The kernel accepts a lot more names than the API: any byte except
'/', ':', NUL and whitespace, and altnames are only limited in length.
So names read from the kernel, e.g. via 'ip link', cannot always be
represented by the API types.

KernelNetworkInterfaceName and KernelNetworkInterfaceAltname accept
exactly what the kernel accepts. This includes treating 0xa0 as
whitespace, which also rejects some valid UTF-8 names, e.g. ones
containing U+00E0.

Names do not have to be valid UTF-8, so the types store bytes.
'ip -json' prints such names unchanged, which only deserializes into
bytes, not into a String. The types follow the kernel instead of
iproute2, since 'ip' reports names unchanged, but its own checks
differ between versions: before 7.0 it rejected altnames with
whitespace, which was dropped since the kernel has no such
restriction. Names that are created or passed to 'ip' should use the
API types instead.

The checks are the ones of net-next (v7.4-rc1): dev_valid_name() for
names, which is unchanged since Linux 4.17, and only the length for
altnames, which is unchanged since altnames were added in Linux 5.5.

Serializing a name that is not valid UTF-8 fails, since it cannot be
represented as a string, and replacing the invalid bytes would yield
the name of another interface. The types are not meant for API
parameters, so they have no API schema and do not require the
api-types feature.

In practice, our stack does not create names that are not valid UTF-8
anyway, the bytes are only needed to read what the kernel reports.

Signed-off-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 .../src/network_interface.rs                  | 665 +++++++++++++++++-
 1 file changed, 660 insertions(+), 5 deletions(-)

diff --git a/proxmox-network-types/src/network_interface.rs b/proxmox-network-types/src/network_interface.rs
index fa6d2e37..afa8af2f 100644
--- a/proxmox-network-types/src/network_interface.rs
+++ b/proxmox-network-types/src/network_interface.rs
@@ -13,6 +13,330 @@
 //! * `api_types::NetworkInterfaceAltname`: values that can be a name or an altname, e.g. the
 //!   interface of a firewall rule. Resolve it to the name where only names work, e.g. for
 //!   `iifname` in nftables.
+//!
+//! * [`KernelNetworkInterfaceName`] and [`KernelNetworkInterfaceAltname`]: names read from the
+//!   kernel, e.g. via netlink or `ip -json link`. Deserialize them into these types instead of
+//!   `String`, since they do not have to be valid UTF-8, and convert them into the API types one
+//!   by one. Not for the API or configuration files, and not for names passed to `ip`, which
+//!   rejects some altnames that the kernel accepts.
+
+use std::cmp::Ordering;
+use std::fmt;
+use std::hash::{Hash, Hasher};
+use std::str::{FromStr, Utf8Error};
+
+use serde::{Deserialize, Deserializer, Serialize, Serializer, de, ser};
+use thiserror::Error;
+
+/// The size of the kernel buffer for network interface names, including the terminating NUL.
+const IFNAMSIZ: usize = 16;
+
+/// The size of the kernel buffer for altnames, including the terminating NUL.
+const ALTIFNAMSIZ: usize = 128;
+
+/// Errors for names and altnames that the kernel does not accept.
+#[derive(Error, Debug, Clone, PartialEq, Eq)]
+pub enum KernelNameError {
+    /// The name is empty.
+    #[error("the name must not be empty")]
+    Empty,
+    /// The name is longer than the kernel accepts.
+    #[error("the name must have at most {max} bytes, it has {len} bytes")]
+    TooLong {
+        /// The length of the name in bytes.
+        len: usize,
+        /// The maximum length in bytes.
+        max: usize,
+    },
+    /// The name is `.` or `..`, which the kernel reserves since names are used as directory names.
+    #[error("the name must not be '.' or '..'")]
+    Reserved,
+    /// The name contains a byte that the kernel rejects.
+    #[error("the name must not contain the byte {0:#04x}")]
+    InvalidByte(u8),
+}
+
+/// Returns whether the kernel treats `byte` as whitespace.
+///
+/// This includes `0xa0` (no-break space in Latin-1), which is also a UTF-8 continuation byte. So
+/// the kernel rejects every code point whose UTF-8 encoding has a 6-bit group of `0x20`, e.g.
+/// U+00E0 (`0xc3 0xa0`).
+fn is_kernel_space(byte: u8) -> bool {
+    matches!(byte, b'\t' | b'\n' | 0x0b | 0x0c | b'\r' | b' ' | 0xa0)
+}
+
+/// Checks a network interface name like `dev_valid_name()` of the kernel.
+fn check_kernel_name(name: &[u8]) -> Result<(), KernelNameError> {
+    if name.is_empty() {
+        return Err(KernelNameError::Empty);
+    }
+
+    if name.len() >= IFNAMSIZ {
+        return Err(KernelNameError::TooLong {
+            len: name.len(),
+            max: IFNAMSIZ - 1,
+        });
+    }
+
+    if name == b"." || name == b".." {
+        return Err(KernelNameError::Reserved);
+    }
+
+    match name
+        .iter()
+        .find(|byte| matches!(byte, b'\0' | b'/' | b':') || is_kernel_space(**byte))
+    {
+        Some(byte) => Err(KernelNameError::InvalidByte(*byte)),
+        None => Ok(()),
+    }
+}
+
+/// Checks an altname like the kernel, which only limits its length.
+fn check_kernel_altname(altname: &[u8]) -> Result<(), KernelNameError> {
+    if altname.len() >= ALTIFNAMSIZ {
+        return Err(KernelNameError::TooLong {
+            len: altname.len(),
+            max: ALTIFNAMSIZ - 1,
+        });
+    }
+
+    if altname.contains(&b'\0') {
+        return Err(KernelNameError::InvalidByte(b'\0'));
+    }
+
+    Ok(())
+}
+
+/// Implements the traits shared by the kernel name types. It only relies on `as_bytes()`,
+/// `TryFrom<&[u8]>` and `TryFrom<Vec<u8>>`, so it works for both storage layouts.
+macro_rules! kernel_name_impls {
+    ($type:ident, $kind:literal) => {
+        impl $type {
+            /// Returns the name as a string, if it is valid UTF-8.
+            pub fn to_str(&self) -> Result<&str, Utf8Error> {
+                std::str::from_utf8(self.as_bytes())
+            }
+        }
+
+        impl AsRef<[u8]> for $type {
+            fn as_ref(&self) -> &[u8] {
+                self.as_bytes()
+            }
+        }
+
+        impl PartialEq for $type {
+            fn eq(&self, other: &Self) -> bool {
+                self.as_bytes() == other.as_bytes()
+            }
+        }
+
+        impl Eq for $type {}
+
+        impl PartialOrd for $type {
+            fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+                Some(self.cmp(other))
+            }
+        }
+
+        impl Ord for $type {
+            fn cmp(&self, other: &Self) -> Ordering {
+                self.as_bytes().cmp(other.as_bytes())
+            }
+        }
+
+        impl Hash for $type {
+            fn hash<H: Hasher>(&self, state: &mut H) {
+                self.as_bytes().hash(state)
+            }
+        }
+
+        impl fmt::Debug for $type {
+            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                match self.to_str() {
+                    Ok(name) => f.debug_tuple(stringify!($type)).field(&name).finish(),
+                    Err(_) => f
+                        .debug_tuple(stringify!($type))
+                        .field(&format_args!("b\"{}\"", self.as_bytes().escape_ascii()))
+                        .finish(),
+                }
+            }
+        }
+
+        impl TryFrom<String> for $type {
+            type Error = KernelNameError;
+
+            fn try_from(name: String) -> Result<Self, Self::Error> {
+                Self::try_from(name.into_bytes())
+            }
+        }
+
+        impl FromStr for $type {
+            type Err = KernelNameError;
+
+            fn from_str(name: &str) -> Result<Self, Self::Err> {
+                Self::try_from(name.as_bytes())
+            }
+        }
+
+        impl Serialize for $type {
+            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
+                match self.to_str() {
+                    Ok(name) => serializer.serialize_str(name),
+                    Err(_) => Err(<S::Error as ser::Error>::custom(format_args!(
+                        "{self:?} is not valid UTF-8"
+                    ))),
+                }
+            }
+        }
+
+        impl<'de> Deserialize<'de> for $type {
+            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+                struct NameVisitor;
+
+                impl de::Visitor<'_> for NameVisitor {
+                    type Value = $type;
+
+                    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+                        write!(f, "a {} as a string or byte string", $kind)
+                    }
+
+                    fn visit_bytes<E: de::Error>(self, name: &[u8]) -> Result<$type, E> {
+                        $type::try_from(name).map_err(E::custom)
+                    }
+
+                    fn visit_byte_buf<E: de::Error>(self, name: Vec<u8>) -> Result<$type, E> {
+                        $type::try_from(name).map_err(E::custom)
+                    }
+
+                    fn visit_str<E: de::Error>(self, name: &str) -> Result<$type, E> {
+                        self.visit_bytes(name.as_bytes())
+                    }
+
+                    fn visit_string<E: de::Error>(self, name: String) -> Result<$type, E> {
+                        self.visit_byte_buf(name.into_bytes())
+                    }
+                }
+
+                // serde_json passes strings as raw bytes here, so names that are not valid UTF-8
+                // work as well
+                deserializer.deserialize_bytes(NameVisitor)
+            }
+        }
+    };
+}
+
+/// The name of a network interface as accepted by the kernel.
+///
+/// The kernel accepts names of 1 to 15 bytes, except `.` and `..`, without `/`, `:`, NUL and
+/// whitespace (including `0xa0`). Names do not have to be valid UTF-8, so this stores bytes.
+/// Every value of this type is accepted by the kernel. Unsafe code may rely on a name having 1 to
+/// 15 bytes and no NUL byte.
+///
+/// Serializing fails for names that are not valid UTF-8, since they cannot be represented as a
+/// string.
+///
+/// ```
+/// # use proxmox_network_types::network_interface::KernelNetworkInterfaceName;
+/// let name: KernelNetworkInterfaceName = "wg*mesh".parse().unwrap();
+/// assert_eq!(name.to_str(), Ok("wg*mesh"));
+///
+/// let name = KernelNetworkInterfaceName::try_from(&b"eth\xff"[..]).unwrap();
+/// assert!(name.to_str().is_err());
+/// assert_eq!(format!("{name:?}"), r#"KernelNetworkInterfaceName(b"eth\xff")"#);
+///
+/// assert!("eth:0".parse::<KernelNetworkInterfaceName>().is_err());
+/// ```
+#[derive(Clone, Copy)]
+pub struct KernelNetworkInterfaceName {
+    len: u8,
+    bytes: [u8; IFNAMSIZ - 1],
+}
+
+impl KernelNetworkInterfaceName {
+    /// # Safety
+    ///
+    /// `name` must pass `check_kernel_name()`.
+    unsafe fn from_bytes_unchecked(name: &[u8]) -> Self {
+        debug_assert_eq!(check_kernel_name(name), Ok(()));
+
+        let mut bytes = [0; IFNAMSIZ - 1];
+        bytes[..name.len()].copy_from_slice(name);
+
+        Self {
+            len: name.len() as u8,
+            bytes,
+        }
+    }
+
+    /// Returns the name as bytes, without the terminating NUL.
+    pub fn as_bytes(&self) -> &[u8] {
+        &self.bytes[..usize::from(self.len)]
+    }
+}
+
+impl TryFrom<&[u8]> for KernelNetworkInterfaceName {
+    type Error = KernelNameError;
+
+    fn try_from(name: &[u8]) -> Result<Self, Self::Error> {
+        check_kernel_name(name)?;
+        // SAFETY: checked above
+        Ok(unsafe { Self::from_bytes_unchecked(name) })
+    }
+}
+
+impl TryFrom<Vec<u8>> for KernelNetworkInterfaceName {
+    type Error = KernelNameError;
+
+    fn try_from(name: Vec<u8>) -> Result<Self, Self::Error> {
+        Self::try_from(name.as_slice())
+    }
+}
+
+kernel_name_impls!(KernelNetworkInterfaceName, "network interface name");
+
+/// An alternative name (altname) of a network interface as accepted by the kernel.
+///
+/// The kernel only limits altnames to 127 bytes, any byte except NUL is allowed. Every value of
+/// this type is accepted by the kernel. Unsafe code may rely on an altname having at most 127
+/// bytes and no NUL byte. Note that `ip` rejects the empty altname, and before iproute2 7.0 also
+/// altnames with whitespace or `/`.
+#[derive(Clone)]
+pub struct KernelNetworkInterfaceAltname(Box<[u8]>);
+
+impl KernelNetworkInterfaceAltname {
+    /// # Safety
+    ///
+    /// `altname` must pass `check_kernel_altname()`.
+    unsafe fn from_boxed_unchecked(altname: Box<[u8]>) -> Self {
+        debug_assert_eq!(check_kernel_altname(&altname), Ok(()));
+        Self(altname)
+    }
+
+    /// Returns the altname as bytes, without the terminating NUL.
+    pub fn as_bytes(&self) -> &[u8] {
+        &self.0
+    }
+}
+
+impl TryFrom<&[u8]> for KernelNetworkInterfaceAltname {
+    type Error = KernelNameError;
+
+    fn try_from(altname: &[u8]) -> Result<Self, Self::Error> {
+        check_kernel_altname(altname)?;
+        Ok(Self(altname.into()))
+    }
+}
+
+impl TryFrom<Vec<u8>> for KernelNetworkInterfaceAltname {
+    type Error = KernelNameError;
+
+    fn try_from(altname: Vec<u8>) -> Result<Self, Self::Error> {
+        check_kernel_altname(&altname)?;
+        Ok(Self(altname.into_boxed_slice()))
+    }
+}
+
+kernel_name_impls!(KernelNetworkInterfaceAltname, "altname");
 
 /// API types for network interface names.
 ///
@@ -42,15 +366,26 @@
 /// let name: NetworkInterfaceName = "eth0".parse().unwrap();
 /// assert_eq!(NetworkInterfaceAltname::from(name).as_str(), "eth0");
 /// ```
+///
+/// The API types convert into the kernel types, the other way around fails for names outside of
+/// the API format:
+///
+/// ```
+/// # use proxmox_network_types::network_interface::KernelNetworkInterfaceName;
+/// # use proxmox_network_types::network_interface::api_types::NetworkInterfaceName;
+/// let kernel_name: KernelNetworkInterfaceName = "wg*mesh".parse().unwrap();
+/// assert!(NetworkInterfaceName::try_from(kernel_name).is_err());
+///
+/// let name: NetworkInterfaceName = "wg-mesh".parse().unwrap();
+/// assert_eq!(KernelNetworkInterfaceName::from(name).as_bytes(), b"wg-mesh");
+/// ```
 #[cfg(feature = "api-types")]
 pub mod api_types {
-    use proxmox_schema::{api, api_string_type, api_types::SAFE_ID_FORMAT};
+    use anyhow::{Context, Error};
 
-    /// The size of the kernel buffer for network interface names, including the terminating NUL.
-    const IFNAMSIZ: usize = 16;
+    use proxmox_schema::{ApiType, api, api_string_type, api_types::SAFE_ID_FORMAT};
 
-    /// The size of the kernel buffer for altnames, including the terminating NUL.
-    const ALTIFNAMSIZ: usize = 128;
+    use super::{ALTIFNAMSIZ, IFNAMSIZ, KernelNetworkInterfaceAltname, KernelNetworkInterfaceName};
 
     api_string_type! {
         #[api(format: &SAFE_ID_FORMAT, min_length: 1, max_length: IFNAMSIZ - 1)]
@@ -87,6 +422,51 @@ pub mod api_types {
         }
     }
 
+    impl From<NetworkInterfaceName> for KernelNetworkInterfaceName {
+        fn from(name: NetworkInterfaceName) -> Self {
+            // SAFETY: the API format is a subset of what the kernel accepts
+            unsafe { Self::from_bytes_unchecked(name.as_str().as_bytes()) }
+        }
+    }
+
+    impl From<NetworkInterfaceAltname> for KernelNetworkInterfaceAltname {
+        fn from(altname: NetworkInterfaceAltname) -> Self {
+            let altname = altname.into_string().into_bytes().into_boxed_slice();
+            // SAFETY: the API format is a subset of what the kernel accepts
+            unsafe { Self::from_boxed_unchecked(altname) }
+        }
+    }
+
+    impl TryFrom<KernelNetworkInterfaceName> for NetworkInterfaceName {
+        type Error = Error;
+
+        fn try_from(name: KernelNetworkInterfaceName) -> Result<Self, Self::Error> {
+            let name = name
+                .to_str()
+                .with_context(|| format!("{name:?} is not valid UTF-8"))?;
+            const { Self::API_SCHEMA.unwrap_string_schema() }.check_constraints(name)?;
+
+            // SAFETY: checked against the schema above
+            Ok(unsafe { Self::from_string_unchecked(name.to_string()) })
+        }
+    }
+
+    impl TryFrom<KernelNetworkInterfaceAltname> for NetworkInterfaceAltname {
+        type Error = Error;
+
+        fn try_from(altname: KernelNetworkInterfaceAltname) -> Result<Self, Self::Error> {
+            let name = altname
+                .to_str()
+                .with_context(|| format!("{altname:?} is not valid UTF-8"))?;
+            const { Self::API_SCHEMA.unwrap_string_schema() }.check_constraints(name)?;
+
+            // SAFETY: valid UTF-8 and checked against the schema above, this reuses the buffer
+            Ok(unsafe {
+                Self::from_string_unchecked(String::from_utf8_unchecked(altname.0.into_vec()))
+            })
+        }
+    }
+
     #[cfg(test)]
     mod tests {
         use super::*;
@@ -178,5 +558,280 @@ pub mod api_types {
 
             assert!(serde_plain::from_str::<NetworkInterfaceAltname>("eth0:1").is_err());
         }
+
+        // the unchecked conversions into the kernel types are checked by a debug assertion
+        #[test]
+        fn api_names_are_kernel_names() {
+            for name in ["a", "eth0", "_x-1.2", "abcdefghijklmno"] {
+                let name: NetworkInterfaceName = name.parse().expect(name);
+                let kernel_name = KernelNetworkInterfaceName::from(name.clone());
+                assert_eq!(kernel_name.as_bytes(), name.as_str().as_bytes());
+                assert_eq!(NetworkInterfaceName::try_from(kernel_name).ok(), Some(name));
+            }
+        }
+
+        #[test]
+        fn api_altnames_are_kernel_altnames() {
+            let longest = "a".repeat(ALTIFNAMSIZ - 1);
+
+            for altname in ["eth0", "enx0123456789abcd", longest.as_str()] {
+                let altname: NetworkInterfaceAltname = altname.parse().expect(altname);
+                let kernel_altname = KernelNetworkInterfaceAltname::from(altname.clone());
+                assert_eq!(kernel_altname.as_bytes(), altname.as_str().as_bytes());
+                assert_eq!(
+                    NetworkInterfaceAltname::try_from(kernel_altname).ok(),
+                    Some(altname)
+                );
+            }
+        }
+
+        #[test]
+        fn kernel_names_outside_of_the_api_format() {
+            for name in [
+                &b"-eth0"[..],
+                b"a*b",
+                b"ctl\x01x",
+                "abcdefghijklm\u{e9}".as_bytes(),
+                b"eth\xff",
+            ] {
+                let kernel_name = KernelNetworkInterfaceName::try_from(name).expect("kernel name");
+                assert!(
+                    NetworkInterfaceName::try_from(kernel_name).is_err(),
+                    "{kernel_name:?}"
+                );
+            }
+
+            for altname in [&b""[..], b"sp ace", b"a/b", b"a\xffb"] {
+                let kernel_altname =
+                    KernelNetworkInterfaceAltname::try_from(altname).expect("kernel altname");
+                assert!(
+                    NetworkInterfaceAltname::try_from(kernel_altname.clone()).is_err(),
+                    "{kernel_altname:?}"
+                );
+            }
+        }
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use serde::de::IntoDeserializer;
+    use serde::de::value::{BytesDeserializer, Error as ValueError};
+
+    use super::*;
+
+    #[test]
+    fn parse_kernel_network_interface_name() {
+        for name in [
+            &b"eth0"[..],
+            b"wg-mesh",
+            b"-eth0",
+            b"a*b",
+            b"a.b.c",
+            b"eth0.",
+            b"ctl\x01x",
+            // U+00E9 is 0xc3 0xa9, so the name has 15 bytes
+            "abcdefghijklm\u{e9}".as_bytes(),
+            // none of their bytes is 0xa0
+            "a\u{121}b".as_bytes(),
+            "a\u{840}b".as_bytes(),
+            "a\u{1f600}b".as_bytes(),
+            // names do not have to be valid UTF-8
+            b"eth\xff",
+            b"\xc3",
+        ] {
+            let parsed = KernelNetworkInterfaceName::try_from(name).expect("valid name");
+            assert_eq!(parsed.as_bytes(), name);
+            assert_eq!(
+                KernelNetworkInterfaceName::try_from(name.to_vec()),
+                Ok(parsed)
+            );
+        }
+
+        for name in [
+            &b""[..],
+            b".",
+            b"..",
+            b"eth0/1",
+            b"eth0:1",
+            b"eth 0",
+            b"eth0\t",
+            b"eth\0",
+            // the kernel treats 0xa0 as whitespace, U+00E0 is 0xc3 0xa0
+            "a\u{e0}b".as_bytes(),
+            b"a\xa0b",
+            "a\u{120}b".as_bytes(),
+            "a\u{160}b".as_bytes(),
+            "a\u{1e0}b".as_bytes(),
+            // 0xa0 can also be a middle byte, U+0800 is 0xe0 0xa0 0x80
+            "a\u{800}b".as_bytes(),
+            "a\u{10800}b".as_bytes(),
+            b"abcdefghijklmnop",
+            // 16 bytes, but only 15 characters
+            "abcdefghijklmn\u{e9}".as_bytes(),
+        ] {
+            assert!(
+                KernelNetworkInterfaceName::try_from(name).is_err(),
+                "{name:?}"
+            );
+        }
+
+        assert_eq!(
+            "eth0:1".parse::<KernelNetworkInterfaceName>(),
+            Err(KernelNameError::InvalidByte(b':'))
+        );
+        assert_eq!(
+            "abcdefghijklmnop".parse::<KernelNetworkInterfaceName>(),
+            Err(KernelNameError::TooLong { len: 16, max: 15 })
+        );
+    }
+
+    #[test]
+    fn kernel_rejects_code_points_with_a_group_of_0x20() {
+        // the rule described at is_kernel_space(), checked against every code point
+        for c in (0x80..=char::MAX as u32).filter_map(char::from_u32) {
+            let code_point = c as u32;
+
+            let groups = match c.len_utf8() {
+                2 => vec![code_point & 0x3f],
+                3 => vec![code_point & 0x3f, (code_point >> 6) & 0x3f],
+                _ => vec![
+                    code_point & 0x3f,
+                    (code_point >> 6) & 0x3f,
+                    (code_point >> 12) & 0x3f,
+                ],
+            };
+
+            let name = format!("a{c}");
+            assert_eq!(
+                name.parse::<KernelNetworkInterfaceName>().is_ok(),
+                !groups.contains(&0x20),
+                "U+{code_point:04X}"
+            );
+        }
+    }
+
+    #[test]
+    fn parse_kernel_network_interface_altname() {
+        let longest = "a".repeat(ALTIFNAMSIZ - 1);
+        // 63 times U+00E9 (2 bytes each) and one 'a' are 127 bytes
+        let longest_utf8 = format!("{}a", "\u{e9}".repeat(63));
+
+        for altname in [
+            &b""[..],
+            b"sp ace/x:y",
+            b"c\x01x",
+            "a\u{e0}b".as_bytes(),
+            b"a\xa0b",
+            b"a\xffb",
+            longest.as_bytes(),
+            longest_utf8.as_bytes(),
+        ] {
+            let parsed = KernelNetworkInterfaceAltname::try_from(altname).expect("valid altname");
+            assert_eq!(parsed.as_bytes(), altname);
+            assert_eq!(
+                KernelNetworkInterfaceAltname::try_from(altname.to_vec()),
+                Ok(parsed)
+            );
+        }
+
+        let too_long = "a".repeat(ALTIFNAMSIZ);
+        let too_long_utf8 = "\u{e9}".repeat(64);
+
+        for altname in [&b"a\0b"[..], too_long.as_bytes(), too_long_utf8.as_bytes()] {
+            assert!(
+                KernelNetworkInterfaceAltname::try_from(altname).is_err(),
+                "{altname:?}"
+            );
+        }
+    }
+
+    #[test]
+    fn debug_kernel_network_interface_name() {
+        for (name, debug) in [
+            (&b"eth0"[..], r#"KernelNetworkInterfaceName("eth0")"#),
+            (
+                "\u{e9}th0".as_bytes(),
+                "KernelNetworkInterfaceName(\"\u{e9}th0\")",
+            ),
+            (b"c\x01\\x", r#"KernelNetworkInterfaceName("c\u{1}\\x")"#),
+            (
+                "x\u{200b}y".as_bytes(),
+                r#"KernelNetworkInterfaceName("x\u{200b}y")"#,
+            ),
+            (b"eth\xff", r#"KernelNetworkInterfaceName(b"eth\xff")"#),
+        ] {
+            let name = KernelNetworkInterfaceName::try_from(name).expect("valid name");
+            assert_eq!(format!("{name:?}"), debug);
+        }
+    }
+
+    #[test]
+    fn compare_kernel_network_interface_names() {
+        let names: Vec<KernelNetworkInterfaceName> = ["b", "ab", "a", "eth1", "eth0"]
+            .into_iter()
+            .map(|name| name.parse().expect(name))
+            .collect();
+
+        let mut sorted = names.clone();
+        sorted.sort();
+        assert_eq!(
+            sorted
+                .iter()
+                .map(|name| name.as_bytes())
+                .collect::<Vec<_>>(),
+            [&b"a"[..], b"ab", b"b", b"eth0", b"eth1"]
+        );
+
+        let set: std::collections::HashSet<_> = names.iter().chain(&names).collect();
+        assert_eq!(set.len(), names.len());
+    }
+
+    #[test]
+    fn deserialize_kernel_network_interface_name() {
+        let name = KernelNetworkInterfaceName::deserialize(BytesDeserializer::<ValueError>::new(
+            b"eth\xff",
+        ))
+        .expect("valid name");
+        assert_eq!(name.as_bytes(), b"eth\xff");
+
+        let name = KernelNetworkInterfaceName::deserialize(
+            IntoDeserializer::<ValueError>::into_deserializer("c\u{1}x"),
+        )
+        .expect("valid name");
+        assert_eq!(name.as_bytes(), b"c\x01x");
+
+        assert!(
+            KernelNetworkInterfaceName::deserialize(BytesDeserializer::<ValueError>::new(b"eth:0"))
+                .is_err()
+        );
+
+        let altname = KernelNetworkInterfaceAltname::deserialize(
+            BytesDeserializer::<ValueError>::new(b"sp ace\xff"),
+        )
+        .expect("valid altname");
+        assert_eq!(altname.as_bytes(), b"sp ace\xff");
+    }
+
+    #[test]
+    fn serialize_kernel_network_interface_name() {
+        let name: KernelNetworkInterfaceName = "c\u{1}x".parse().expect("valid name");
+        assert_eq!(
+            serde_plain::to_string(&name).expect("serializable"),
+            "c\u{1}x"
+        );
+
+        let name = KernelNetworkInterfaceName::try_from(&b"eth\xff"[..]).expect("valid name");
+        assert!(serde_plain::to_string(&name).is_err());
+
+        let altname: KernelNetworkInterfaceAltname = "sp ace".parse().expect("valid altname");
+        assert_eq!(
+            serde_plain::to_string(&altname).expect("serializable"),
+            "sp ace"
+        );
+
+        let altname =
+            KernelNetworkInterfaceAltname::try_from(&b"a\xffb"[..]).expect("valid altname");
+        assert!(serde_plain::to_string(&altname).is_err());
     }
 }
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 6+ messages in thread

* [PATCH proxmox 4/4] network-types: add a type for names of existing configurations
  2026-11-12 17:10 [PATCH proxmox 0/4] network-types: add types for network interface names Stefan Hanreich
                   ` (2 preceding siblings ...)
  2026-11-12 17:10 ` [PATCH proxmox 3/4] network-types: add types for names reported by the kernel Stefan Hanreich
@ 2026-11-12 17:11 ` Stefan Hanreich
  2026-11-12 17:36   ` Stefan Hanreich
  3 siblings, 1 reply; 6+ messages in thread
From: Stefan Hanreich @ 2026-11-12 17:11 UTC (permalink / raw)
  To: pve-devel

Existing configurations can contain names that were validated by the
pve-iface format of the Perl JSON schema, which accepts names that the
API types reject, e.g. alias labels like eth0:1, which name an
address and not an interface, or names longer than 127 characters.

LegacyNetworkInterfaceName accepts exactly the pve-iface format, so
such configurations can still be read, and converts into the API
types. It uses the regex of pve-iface.

Signed-off-by: Stefan Hanreich <s.hanreich@proxmox.com>
---
 .../src/network_interface.rs                  | 122 +++++++++++++++++-
 1 file changed, 121 insertions(+), 1 deletion(-)

diff --git a/proxmox-network-types/src/network_interface.rs b/proxmox-network-types/src/network_interface.rs
index afa8af2f..6977beed 100644
--- a/proxmox-network-types/src/network_interface.rs
+++ b/proxmox-network-types/src/network_interface.rs
@@ -19,6 +19,10 @@
 //!   `String`, since they do not have to be valid UTF-8, and convert them into the API types one
 //!   by one. Not for the API or configuration files, and not for names passed to `ip`, which
 //!   rejects some altnames that the kernel accepts.
+//!
+//! * `api_types::LegacyNetworkInterfaceName`: only for reading names from configurations that
+//!   were validated by the `pve-iface` format. Convert them into the API types before using them,
+//!   since the format also accepts alias labels like `eth0:1` and names the kernel rejects.
 
 use std::cmp::Ordering;
 use std::fmt;
@@ -379,11 +383,28 @@ kernel_name_impls!(KernelNetworkInterfaceAltname, "altname");
 /// let name: NetworkInterfaceName = "wg-mesh".parse().unwrap();
 /// assert_eq!(KernelNetworkInterfaceName::from(name).as_bytes(), b"wg-mesh");
 /// ```
+///
+/// Names from configurations validated by the `pve-iface` format are represented by
+/// [`LegacyNetworkInterfaceName`](api_types::LegacyNetworkInterfaceName), which converts into the
+/// API types, except for e.g. alias labels:
+///
+/// ```
+/// # use proxmox_network_types::network_interface::api_types::{
+/// #     LegacyNetworkInterfaceName, NetworkInterfaceAltname, NetworkInterfaceName,
+/// # };
+/// let legacy: LegacyNetworkInterfaceName = "eth0:1".parse().unwrap();
+/// assert!(NetworkInterfaceAltname::try_from(legacy).is_err());
+///
+/// let legacy: LegacyNetworkInterfaceName = "eth0".parse().unwrap();
+/// assert_eq!(NetworkInterfaceName::try_from(legacy).unwrap().as_str(), "eth0");
+/// ```
 #[cfg(feature = "api-types")]
 pub mod api_types {
     use anyhow::{Context, Error};
 
-    use proxmox_schema::{ApiType, api, api_string_type, api_types::SAFE_ID_FORMAT};
+    use proxmox_schema::{
+        ApiStringFormat, ApiType, api, api_string_type, api_types::SAFE_ID_FORMAT, const_regex,
+    };
 
     use super::{ALTIFNAMSIZ, IFNAMSIZ, KernelNetworkInterfaceAltname, KernelNetworkInterfaceName};
 
@@ -467,6 +488,46 @@ pub mod api_types {
         }
     }
 
+    const_regex! {
+        /// The `pve-iface` format of the Perl JSON schema.
+        LEGACY_NETWORK_INTERFACE_NAME_REGEX = r"^(?i)[a-z][a-z0-9_]{1,20}([:\.]\d+)?$";
+    }
+
+    const LEGACY_NETWORK_INTERFACE_NAME_FORMAT: ApiStringFormat =
+        ApiStringFormat::Pattern(&LEGACY_NETWORK_INTERFACE_NAME_REGEX);
+
+    api_string_type! {
+        #[api(format: &LEGACY_NETWORK_INTERFACE_NAME_FORMAT)]
+        /// The name of a network interface in an existing configuration, as accepted by the
+        /// pve-iface format of the Perl JSON schema.
+        ///
+        /// This includes names that are not valid for the kernel, e.g. names longer than 15 bytes
+        /// and alias labels such as `eth0:1`. Convert it into a network interface name or altname
+        /// before using it.
+        #[derive(Debug, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
+        #[repr(transparent)]
+        pub struct LegacyNetworkInterfaceName(String);
+    }
+
+    proxmox_serde::forward_deserialize_to_from_str!(LegacyNetworkInterfaceName);
+    proxmox_serde::forward_serialize_to_display!(LegacyNetworkInterfaceName);
+
+    impl TryFrom<LegacyNetworkInterfaceName> for NetworkInterfaceName {
+        type Error = Error;
+
+        fn try_from(name: LegacyNetworkInterfaceName) -> Result<Self, Self::Error> {
+            Self::from_string(name.into_string())
+        }
+    }
+
+    impl TryFrom<LegacyNetworkInterfaceName> for NetworkInterfaceAltname {
+        type Error = Error;
+
+        fn try_from(name: LegacyNetworkInterfaceName) -> Result<Self, Self::Error> {
+            Self::from_string(name.into_string())
+        }
+    }
+
     #[cfg(test)]
     mod tests {
         use super::*;
@@ -610,6 +671,65 @@ pub mod api_types {
                 );
             }
         }
+
+        #[test]
+        fn parse_legacy_network_interface_name() {
+            for name in [
+                "eth0",
+                "ETH0",
+                "eth0:1",
+                "bond0.100",
+                "ab",
+                "abcdefghijklmnopqrstu",
+                "abcdefghijklmnopqrstu.4094",
+            ] {
+                let parsed: LegacyNetworkInterfaceName = name.parse().expect(name);
+                assert_eq!(parsed.as_str(), name);
+            }
+
+            for name in [
+                "",
+                "a",
+                "0eth",
+                "_eth0",
+                "eth-0",
+                "eth0.1.2",
+                "eth0.",
+                "eth0:a",
+                "abcdefghijklmnopqrstuv",
+            ] {
+                assert!(
+                    name.parse::<LegacyNetworkInterfaceName>().is_err(),
+                    "{name:?}"
+                );
+            }
+        }
+
+        #[test]
+        fn convert_legacy_network_interface_name() {
+            for (name, is_name, is_altname) in [
+                ("eth0", true, true),
+                ("ETH0", true, true),
+                ("bond0.100", true, true),
+                ("abcdefghijklmno", true, true),
+                ("abcdefghijklmnop", false, true),
+                ("abcdefghijklmnopqrstu.4094", false, true),
+                ("eth0:1", false, false),
+            ] {
+                let legacy: LegacyNetworkInterfaceName = name.parse().expect(name);
+
+                assert_eq!(
+                    NetworkInterfaceName::try_from(legacy.clone()).is_ok(),
+                    is_name,
+                    "{name:?}"
+                );
+                assert_eq!(
+                    NetworkInterfaceAltname::try_from(legacy).is_ok(),
+                    is_altname,
+                    "{name:?}"
+                );
+            }
+        }
     }
 }
 
-- 
2.47.3





^ permalink raw reply related	[flat|nested] 6+ messages in thread

* Re: [PATCH proxmox 4/4] network-types: add a type for names of existing configurations
  2026-11-12 17:11 ` [PATCH proxmox 4/4] network-types: add a type for names of existing configurations Stefan Hanreich
@ 2026-11-12 17:36   ` Stefan Hanreich
  0 siblings, 0 replies; 6+ messages in thread
From: Stefan Hanreich @ 2026-11-12 17:36 UTC (permalink / raw)
  To: pve-devel

On 11/12/26 6:11 PM, Stefan Hanreich wrote:
> Existing configurations can contain names that were validated by the
> pve-iface format of the Perl JSON schema, which accepts names that the
> API types reject, e.g. alias labels like eth0:1, which name an
> address and not an interface, or names longer than 127 characters.

This is meant to be 15 instead of 127.






^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2026-11-12 17:36 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-12 17:10 [PATCH proxmox 0/4] network-types: add types for network interface names Stefan Hanreich
2026-11-12 17:10 ` [PATCH proxmox 1/4] network-types: add a type " Stefan Hanreich
2026-11-12 17:10 ` [PATCH proxmox 2/4] network-types: add a type for network interface altnames Stefan Hanreich
2026-11-12 17:10 ` [PATCH proxmox 3/4] network-types: add types for names reported by the kernel Stefan Hanreich
2026-11-12 17:11 ` [PATCH proxmox 4/4] network-types: add a type for names of existing configurations Stefan Hanreich
2026-11-12 17:36   ` Stefan Hanreich

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal