feat(windows): démarrage automatique, réseau et adresse MAC sous Windows
CI / Formatting, tests and builds (push) Successful in 2m46s

Suite de l'intégration système (#94):
- démarrage automatique par une valeur de la clé Run de l'utilisateur
  (HKCU, sans droits d'administrateur), même API que le fichier XDG;
  les tests écrivent sous une clé à eux, jamais dans la vraie;
- adresse MAC d'un client par la table des voisins (GetIpNetTable2);
- état d'une interface donné par Windows avec ses adresses;
- VPN: un adaptateur point à point ou nommé comme un tunnel (NetBird,
  WireGuard, Tailscale, OpenVPN, ZeroTier) n'est pas pris pour le
  réseau local, ni un commutateur virtuel (Hyper-V, WSL, VirtualBox);
- le nom d'interface accepte les noms Windows, espaces compris; un
  caractère de contrôle est refusé partout.

Tests passés sous Wine; reste à vérifier sur une machine Windows réelle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Guillaume ASSIERandClaude Opus 5.5 committed 2026-10-30 20:43:41 +01:00
1 parent 78954b90dc
commit 595bcf51a8
7 files changed
+525 -131

No files matched your search

+1
View File
@@ -25,6 +25,7 @@ tokio = { version = "1", features = ["sync"] }
windows-sys = { version = "0.61.2", features = [
"Win32_Foundation",
"Win32_NetworkManagement_IpHelper",
"Win32_NetworkManagement_Ndis",
"Win32_Networking_WinSock",
"Win32_System_Power",
"Win32_System_Registry",
+18 -119
View File
@@ -1,23 +1,26 @@
//! Autostart when the session opens, through the XDG mechanism.
//! Autostart when the session opens.
//!
//! A `.desktop` file in `~/.config/autostart`: every Linux desktop reads it,
//! with no service and no privilege. Enabling means writing it; disabling
//! means removing it. No other state: the setting and the file cannot drift
//! apart silently, since [`is_enabled`] rereads the file.
//! Linux: a `.desktop` file in `~/.config/autostart`, which every desktop
//! reads, with no service and no privilege. Windows (#94): a value under
//! `HKCU\Software\Microsoft\Windows\CurrentVersion\Run`, the same thing
//! for the Windows session. Enabling means writing it, disabling means
//! removing it. No other state: the setting and the entry cannot drift apart
//! silently, since [`is_enabled`] rereads the entry.
//!
//! [`directory`] says where the entry lives: a folder on Linux, a registry key
//! under `HKCU` on Windows. Tests pass their own.
use std::path::{Path, PathBuf};
/// File name, unique to the product.
pub const FILE_NAME: &str = "rustscreen.desktop";
#[cfg(not(windows))]
mod xdg;
#[cfg(not(windows))]
pub use xdg::{FILE_NAME, content, directory, is_enabled, refresh, set};
/// Where the file lives: `$XDG_CONFIG_HOME/autostart`, else `~/.config/autostart`.
pub fn directory() -> Option<PathBuf> {
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|config| config.join("autostart"))
}
#[cfg(windows)]
mod windows;
#[cfg(windows)]
pub use windows::{RUN_KEY, VALUE_NAME, content, directory, is_enabled, refresh, set};
/// The path to write in the file for `executable`, one that survives an
/// update (#32).
@@ -43,89 +46,10 @@ pub fn launcher(executable: &Path, path_var: Option<&std::ffi::OsStr>) -> PathBu
/// Name of the desktop application's command.
const COMMAND: &str = "rustscreen";
/// Rewrites the file if autostart is on and its content is stale: an update
/// may have moved the executable (#32). Off, nothing is written.
pub fn refresh(directory: &Path, executable: &Path, arguments: &str) -> std::io::Result<bool> {
let file = directory.join(FILE_NAME);
let Ok(current) = std::fs::read_to_string(&file) else {
return Ok(false);
};
let wanted = content(executable, arguments);
if current == wanted {
return Ok(false);
}
std::fs::write(file, wanted)?;
Ok(true)
}
/// The file content that launches `executable` (with its arguments).
pub fn content(executable: &Path, arguments: &str) -> String {
// A path with a space must be quoted (Desktop Entry specification, Exec
// key).
let path = executable.display().to_string();
let path = if path.contains(' ') {
format!("\"{}\"", path.replace('"', "\\\""))
} else {
path
};
let exec = if arguments.is_empty() {
path
} else {
format!("{path} {arguments}")
};
format!(
"[Desktop Entry]\n\
Type=Application\n\
Name=rustscreen\n\
Comment=Screen sharing over the local network\n\
Exec={exec}\n\
Terminal=false\n\
X-GNOME-Autostart-enabled=true\n"
)
}
/// Writes or removes the file in `directory`.
pub fn set(
directory: &Path,
enabled: bool,
executable: &Path,
arguments: &str,
) -> std::io::Result<()> {
let file = directory.join(FILE_NAME);
if enabled {
std::fs::create_dir_all(directory)?;
std::fs::write(file, content(executable, arguments))
} else {
match std::fs::remove_file(file) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
other => other,
}
}
}
pub fn is_enabled(directory: &Path) -> bool {
directory.join(FILE_NAME).is_file()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn enabling_writes_the_file_and_disabling_removes_it() {
let directory = std::env::temp_dir().join(format!("rs-autostart-{}", std::process::id()));
let exe = Path::new("/opt/rust screen/rustscreen-desktop");
set(&directory, true, exe, "--cache").unwrap();
assert!(is_enabled(&directory));
let text = std::fs::read_to_string(directory.join(FILE_NAME)).unwrap();
assert!(text.contains("Exec=\"/opt/rust screen/rustscreen-desktop\" --cache"));
set(&directory, false, exe, "").unwrap();
assert!(!is_enabled(&directory));
// Disabling twice is not an error.
set(&directory, false, exe, "").unwrap();
let _ = std::fs::remove_dir_all(&directory);
}
#[test]
fn a_nix_store_path_gives_way_to_the_profile_link() {
let profile = std::env::temp_dir().join(format!("rs-profile-{}", std::process::id()));
@@ -142,29 +66,4 @@ mod tests {
assert_eq!(launcher(usr, Some(&path)), usr);
let _ = std::fs::remove_dir_all(&profile);
}
#[test]
fn refreshing_rewrites_a_stale_file_only_when_enabled() {
let directory =
std::env::temp_dir().join(format!("rs-autostart-refresh-{}", std::process::id()));
let old = Path::new("/nix/store/old/bin/rustscreen");
let new = Path::new("/nix/store/new/bin/rustscreen");
assert!(
!refresh(&directory, new, "--autostarted").unwrap(),
"off: nothing written"
);
assert!(!is_enabled(&directory));
set(&directory, true, old, "--autostarted").unwrap();
assert!(refresh(&directory, new, "--autostarted").unwrap());
let text = std::fs::read_to_string(directory.join(FILE_NAME)).unwrap();
assert!(
text.contains("Exec=/nix/store/new/bin/rustscreen --autostarted"),
"{text}"
);
assert!(
!refresh(&directory, new, "--autostarted").unwrap(),
"already fresh"
);
let _ = std::fs::remove_dir_all(&directory);
}
}
+208
View File
@@ -0,0 +1,208 @@
//! Autostart on Windows: a value of the `Run` key of the current user.
//!
//! No administrator rights: `HKEY_CURRENT_USER` belongs to the user, and
//! Windows starts every command listed there when the session opens. Task
//! Manager shows it under "Startup apps", where the user can also turn it off.
use std::path::{Path, PathBuf};
use windows_sys::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS};
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, KEY_QUERY_VALUE, KEY_SET_VALUE, REG_OPTION_NON_VOLATILE, REG_SZ,
RRF_RT_REG_SZ, RegCloseKey, RegCreateKeyExW, RegDeleteValueW, RegGetValueW, RegSetValueExW,
};
/// The key Windows reads at logon, under `HKEY_CURRENT_USER`.
pub const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
/// The name of the value, unique to the product.
pub const VALUE_NAME: &str = "rustscreen";
/// Where the entry lives: the `Run` key, under `HKEY_CURRENT_USER`.
pub fn directory() -> Option<PathBuf> {
Some(PathBuf::from(RUN_KEY))
}
/// The command line Windows runs: the quoted executable, then the arguments.
pub fn content(executable: &Path, arguments: &str) -> String {
let path = format!("\"{}\"", executable.display());
if arguments.is_empty() {
path
} else {
format!("{path} {arguments}")
}
}
/// Rewrites the value if autostart is on and its command is stale: an update
/// may have moved the executable (#32). Off, nothing is written.
pub fn refresh(key: &Path, executable: &Path, arguments: &str) -> std::io::Result<bool> {
let Some(current) = read(key)? else {
return Ok(false);
};
let wanted = content(executable, arguments);
if current == wanted {
return Ok(false);
}
write(key, &wanted)?;
Ok(true)
}
/// Writes or removes the value under `key`.
pub fn set(key: &Path, enabled: bool, executable: &Path, arguments: &str) -> std::io::Result<()> {
if enabled {
write(key, &content(executable, arguments))
} else {
let handle = open(key)?;
let name = wide(VALUE_NAME);
// SAFETY: `handle` is open, `name` is NUL-terminated.
let status = unsafe { RegDeleteValueW(handle.0, name.as_ptr()) };
match status {
ERROR_SUCCESS | ERROR_FILE_NOT_FOUND => Ok(()),
error => Err(os_error(error)),
}
}
}
pub fn is_enabled(key: &Path) -> bool {
matches!(read(key), Ok(Some(_)))
}
/// An open key, closed on drop.
struct Key(HKEY);
impl Drop for Key {
fn drop(&mut self) {
// SAFETY: opened by `open`, closed once.
unsafe { RegCloseKey(self.0) };
}
}
/// Opens `key` under `HKEY_CURRENT_USER`, creating it if needed.
fn open(key: &Path) -> std::io::Result<Key> {
let subkey = wide(&key.to_string_lossy());
let mut handle: HKEY = std::ptr::null_mut();
// SAFETY: `subkey` is NUL-terminated, `handle` receives the key.
let status = unsafe {
RegCreateKeyExW(
HKEY_CURRENT_USER,
subkey.as_ptr(),
0,
std::ptr::null(),
REG_OPTION_NON_VOLATILE,
KEY_SET_VALUE | KEY_QUERY_VALUE,
std::ptr::null(),
&mut handle,
std::ptr::null_mut(),
)
};
if status != ERROR_SUCCESS {
return Err(os_error(status));
}
Ok(Key(handle))
}
fn write(key: &Path, command: &str) -> std::io::Result<()> {
let handle = open(key)?;
let name = wide(VALUE_NAME);
let data = wide(command);
// SAFETY: `data` holds `data.len()` UTF-16 units, terminator included,
// as REG_SZ wants.
let status = unsafe {
RegSetValueExW(
handle.0,
name.as_ptr(),
0,
REG_SZ,
data.as_ptr().cast(),
(data.len() * 2) as u32,
)
};
if status != ERROR_SUCCESS {
return Err(os_error(status));
}
Ok(())
}
/// The command of the value, `None` when there is none.
fn read(key: &Path) -> std::io::Result<Option<String>> {
let subkey = wide(&key.to_string_lossy());
let name = wide(VALUE_NAME);
// A command line, a path and a few arguments: 32 KiB is the limit of a
// command line on Windows.
let mut buffer = vec![0u16; 16 * 1024];
let mut size = (buffer.len() * 2) as u32;
// SAFETY: `buffer` holds `size` bytes; RegGetValueW NUL-terminates.
let status = unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
subkey.as_ptr(),
name.as_ptr(),
RRF_RT_REG_SZ,
std::ptr::null_mut(),
buffer.as_mut_ptr().cast(),
&mut size,
)
};
match status {
ERROR_SUCCESS => {
let units = (size as usize / 2).saturating_sub(1);
Ok(Some(String::from_utf16_lossy(&buffer[..units])))
}
ERROR_FILE_NOT_FOUND => Ok(None),
error => Err(os_error(error)),
}
}
fn wide(text: &str) -> Vec<u16> {
text.encode_utf16().chain(Some(0)).collect()
}
fn os_error(status: u32) -> std::io::Error {
std::io::Error::from_raw_os_error(status as i32)
}
#[cfg(test)]
mod tests {
use super::*;
/// A key of its own: the user's real `Run` key is never touched.
fn test_key(name: &str) -> PathBuf {
PathBuf::from(format!(
r"Software\rustscreen-tests\{name}-{}",
std::process::id()
))
}
#[test]
fn enabling_writes_the_value_and_disabling_removes_it() {
let key = test_key("set");
let exe = Path::new(r"C:\Program Files\rustscreen\rustscreen.exe");
set(&key, true, exe, "--autostarted").unwrap();
assert!(is_enabled(&key));
assert_eq!(
read(&key).unwrap().as_deref(),
Some(r#""C:\Program Files\rustscreen\rustscreen.exe" --autostarted"#)
);
set(&key, false, exe, "").unwrap();
assert!(!is_enabled(&key));
// Disabling twice is not an error.
set(&key, false, exe, "").unwrap();
}
#[test]
fn refreshing_rewrites_a_stale_value_only_when_enabled() {
let key = test_key("refresh");
let old = Path::new(r"C:\old\rustscreen.exe");
let new = Path::new(r"C:\new\rustscreen.exe");
assert!(
!refresh(&key, new, "--autostarted").unwrap(),
"off: nothing written"
);
set(&key, true, old, "--autostarted").unwrap();
assert!(refresh(&key, new, "--autostarted").unwrap());
assert!(
!refresh(&key, new, "--autostarted").unwrap(),
"already fresh"
);
set(&key, false, new, "").unwrap();
}
}
+124
View File
@@ -0,0 +1,124 @@
//! Autostart on Linux: the XDG `.desktop` file.
use std::path::{Path, PathBuf};
/// File name, unique to the product.
pub const FILE_NAME: &str = "rustscreen.desktop";
/// Where the file lives: `$XDG_CONFIG_HOME/autostart`, else `~/.config/autostart`.
pub fn directory() -> Option<PathBuf> {
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|p| p.is_absolute())
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
.map(|config| config.join("autostart"))
}
/// Rewrites the file if autostart is on and its content is stale: an update
/// may have moved the executable (#32). Off, nothing is written.
pub fn refresh(directory: &Path, executable: &Path, arguments: &str) -> std::io::Result<bool> {
let file = directory.join(FILE_NAME);
let Ok(current) = std::fs::read_to_string(&file) else {
return Ok(false);
};
let wanted = content(executable, arguments);
if current == wanted {
return Ok(false);
}
std::fs::write(file, wanted)?;
Ok(true)
}
/// The file content that launches `executable` (with its arguments).
pub fn content(executable: &Path, arguments: &str) -> String {
// A path with a space must be quoted (Desktop Entry specification, Exec
// key).
let path = executable.display().to_string();
let path = if path.contains(' ') {
format!("\"{}\"", path.replace('"', "\\\""))
} else {
path
};
let exec = if arguments.is_empty() {
path
} else {
format!("{path} {arguments}")
};
format!(
"[Desktop Entry]\n\
Type=Application\n\
Name=rustscreen\n\
Comment=Screen sharing over the local network\n\
Exec={exec}\n\
Terminal=false\n\
X-GNOME-Autostart-enabled=true\n"
)
}
/// Writes or removes the file in `directory`.
pub fn set(
directory: &Path,
enabled: bool,
executable: &Path,
arguments: &str,
) -> std::io::Result<()> {
let file = directory.join(FILE_NAME);
if enabled {
std::fs::create_dir_all(directory)?;
std::fs::write(file, content(executable, arguments))
} else {
match std::fs::remove_file(file) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
other => other,
}
}
}
pub fn is_enabled(directory: &Path) -> bool {
directory.join(FILE_NAME).is_file()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn enabling_writes_the_file_and_disabling_removes_it() {
let directory = std::env::temp_dir().join(format!("rs-autostart-{}", std::process::id()));
let exe = Path::new("/opt/rust screen/rustscreen-desktop");
set(&directory, true, exe, "--cache").unwrap();
assert!(is_enabled(&directory));
let text = std::fs::read_to_string(directory.join(FILE_NAME)).unwrap();
assert!(text.contains("Exec=\"/opt/rust screen/rustscreen-desktop\" --cache"));
set(&directory, false, exe, "").unwrap();
assert!(!is_enabled(&directory));
// Disabling twice is not an error.
set(&directory, false, exe, "").unwrap();
let _ = std::fs::remove_dir_all(&directory);
}
#[test]
fn refreshing_rewrites_a_stale_file_only_when_enabled() {
let directory =
std::env::temp_dir().join(format!("rs-autostart-refresh-{}", std::process::id()));
let old = Path::new("/nix/store/old/bin/rustscreen");
let new = Path::new("/nix/store/new/bin/rustscreen");
assert!(
!refresh(&directory, new, "--autostarted").unwrap(),
"off: nothing written"
);
assert!(!is_enabled(&directory));
set(&directory, true, old, "--autostarted").unwrap();
assert!(refresh(&directory, new, "--autostarted").unwrap());
let text = std::fs::read_to_string(directory.join(FILE_NAME)).unwrap();
assert!(
text.contains("Exec=/nix/store/new/bin/rustscreen --autostarted"),
"{text}"
);
assert!(
!refresh(&directory, new, "--autostarted").unwrap(),
"already fresh"
);
let _ = std::fs::remove_dir_all(&directory);
}
}
+77 -4
View File
@@ -50,14 +50,18 @@ pub fn interfaces() -> Vec<NetworkInterface> {
None => list.push(NetworkInterface {
name: interface.name.clone(),
addresses: vec![ip],
active: false,
// Windows gives the adapter's state with its addresses; Linux
// reads sysfs below, which also knows VPN links.
active: !cfg!(target_os = "linux") && oper_up(&interface.oper_status),
loopback: interface.is_loopback(),
}),
}
}
for interface in &mut list {
interface.addresses.sort_by_key(|ip| !ip.is_ipv4());
interface.active = is_up(link_state(&interface.name).as_deref());
if cfg!(target_os = "linux") {
interface.active = is_up(link_state(&interface.name).as_deref());
}
}
list.sort_by(|a, b| (a.loopback, &a.name).cmp(&(b.loopback, &b.name)));
list
@@ -75,6 +79,12 @@ fn link_state(name: &str) -> Option<String> {
.map(|s| s.trim().to_string())
}
/// The state an adapter reports outside Linux: the same rule as [`is_up`].
fn oper_up(status: &if_addrs::IfOperStatus) -> bool {
use if_addrs::IfOperStatus::{Dormant, Down, LowerLayerDown, NotPresent};
!matches!(status, Down | Dormant | LowerLayerDown | NotPresent)
}
/// `unknown` is the state of many virtual interfaces (VPN, tun) that work
/// nonetheless: only an interface explicitly `down` (or `dormant`,
/// `lowerlayerdown`) is considered cut off.
@@ -142,8 +152,61 @@ pub fn mac_address(ip: std::net::IpAddr) -> Option<String> {
std::net::IpAddr::V4(v4) => v4,
std::net::IpAddr::V6(v6) => v6.to_ipv4_mapped()?,
};
let table = std::fs::read_to_string("/proc/net/arp").ok()?;
mac_in_arp_table(&table, ip)
#[cfg(windows)]
return windows::neighbour_mac(ip);
#[cfg(not(windows))]
{
let table = std::fs::read_to_string("/proc/net/arp").ok()?;
mac_in_arp_table(&table, ip)
}
}
/// A hardware address as the interface shows it: lowercase, colon separated.
/// `None` for an empty or all-zero one (an incomplete neighbour).
pub fn format_mac(bytes: &[u8]) -> Option<String> {
(!bytes.is_empty() && bytes.iter().any(|b| *b != 0)).then(|| {
bytes
.iter()
.map(|b| format!("{b:02x}"))
.collect::<Vec<_>>()
.join(":")
})
}
#[cfg(windows)]
mod windows {
use std::net::Ipv4Addr;
use windows_sys::Win32::NetworkManagement::IpHelper::{
FreeMibTable, GetIpNetTable2, MIB_IPNET_TABLE2,
};
use windows_sys::Win32::Networking::WinSock::{AF_INET, NlnsIncomplete, NlnsUnreachable};
/// The neighbour table (`GetIpNetTable2`, what `arp -a` shows), IPv4.
pub(super) fn neighbour_mac(ip: Ipv4Addr) -> Option<String> {
let mut table: *mut MIB_IPNET_TABLE2 = std::ptr::null_mut();
// SAFETY: on success Windows allocates the table, freed below.
if unsafe { GetIpNetTable2(AF_INET, &mut table) } != 0 || table.is_null() {
return None;
}
// SAFETY: `NumEntries` rows follow the header, in the same block.
let rows = unsafe {
std::slice::from_raw_parts((*table).Table.as_ptr(), (*table).NumEntries as usize)
};
let found = rows.iter().find_map(|row| {
// SAFETY: AF_INET was asked for: every row is an IPv4 address,
// stored in network order.
let address = unsafe { row.Address.Ipv4.sin_addr.S_un.S_addr };
let usable = row.State != NlnsIncomplete && row.State != NlnsUnreachable;
let length = (row.PhysicalAddressLength as usize).min(row.PhysicalAddress.len());
(Ipv4Addr::from(address.to_ne_bytes()) == ip && usable)
.then(|| super::format_mac(&row.PhysicalAddress[..length]))
.flatten()
});
// SAFETY: allocated by GetIpNetTable2, freed once.
unsafe { FreeMibTable(table.cast()) };
found
}
}
/// The lookup in the text of `/proc/net/arp`: complete entries only (flag
@@ -174,6 +237,16 @@ IP address HW type Flags HW address Mask Device
192.168.100.40 0x1 0x0 34:5a:60:43:b3:33 * wlp0s20f3
";
#[test]
fn a_hardware_address_reads_like_the_linux_one() {
assert_eq!(
format_mac(&[0x1c, 0x83, 0x41, 0x41, 0xa3, 0xe8]).as_deref(),
Some("1c:83:41:41:a3:e8")
);
assert_eq!(format_mac(&[0; 6]), None);
assert_eq!(format_mac(&[]), None);
}
#[test]
fn a_complete_entry_gives_the_mac() {
assert_eq!(
+71 -4
View File
@@ -70,8 +70,8 @@ fn candidates() -> Vec<Candidate> {
.into_iter()
.filter(|i| !i.is_loopback())
.map(|i| Candidate {
tunnel: is_tunnel(&i.name),
physical: is_physical(&i.name),
tunnel: is_tunnel(&i.name, i.is_p2p()),
physical: is_physical(&i.name, i.is_p2p()),
address: i.ip(),
interface: i.name,
})
@@ -80,7 +80,13 @@ fn candidates() -> Vec<Candidate> {
/// Kernel link types of tunnels: `none` (tun, WireGuard), PPP, IP in IP, SIT,
/// GRE. A TAP device looks like Ethernet: its `tun_flags` gives it away.
fn is_tunnel(name: &str) -> bool {
///
/// Windows has no sysfs: PPP and tunnel adapters say so (`p2p`), and the
/// others (WireGuard, Wintun, TAP) are virtual adapters known by their name.
fn is_tunnel(name: &str, p2p: bool) -> bool {
if cfg!(windows) {
return p2p || windows_tunnel(name);
}
let sys = std::path::Path::new("/sys/class/net").join(name);
let link_type = std::fs::read_to_string(sys.join("type"))
.ok()
@@ -104,13 +110,46 @@ fn is_tunnel(name: &str) -> bool {
}
}
fn is_physical(name: &str) -> bool {
fn is_physical(name: &str, p2p: bool) -> bool {
if cfg!(windows) {
return !p2p && !windows_tunnel(name) && !windows_virtual(name);
}
std::path::Path::new("/sys/class/net")
.join(name)
.join("device")
.exists()
}
/// A Windows adapter of a VPN, by its friendly name (`NetBird`, `wg0`,
/// `Tailscale`, `OpenVPN TAP-Windows6`, `ZeroTier One [...]`).
fn windows_tunnel(name: &str) -> bool {
let name = name.to_lowercase();
[
"wireguard",
"wintun",
"tailscale",
"netbird",
"zerotier",
"openvpn",
"tap-windows",
"vpn",
]
.iter()
.any(|word| name.contains(word))
|| ["wg", "tun", "tap", "ppp"]
.iter()
.any(|prefix| name.starts_with(prefix))
}
/// A Windows adapter that is not a network card: virtual switches of Hyper-V
/// and WSL (`vEthernet (WSL)`), of VirtualBox and VMware, Bluetooth.
fn windows_virtual(name: &str) -> bool {
let name = name.to_lowercase();
["vethernet", "virtual", "vmware", "bluetooth", "loopback"]
.iter()
.any(|word| name.contains(word))
}
/// RFC 1918 only: 100.64.0.0/10, the carrier-grade NAT range that Tailscale
/// and NetBird use, is never taken for the LAN.
fn is_private_v4(ip: IpAddr) -> bool {
@@ -177,4 +216,32 @@ mod tests {
"{chosen} is a tunnel while a LAN exists"
);
}
#[test]
fn windows_adapters_are_told_apart_by_their_name() {
for vpn in [
"NetBird",
"wg0",
"Tailscale",
"OpenVPN TAP-Windows6",
"ZeroTier One [8056c2e21c]",
] {
assert!(windows_tunnel(vpn), "{vpn}");
}
for lan in [
"Wi-Fi",
"Ethernet",
"Ethernet 2",
"Connexion au réseau local",
] {
assert!(!windows_tunnel(lan) && !windows_virtual(lan), "{lan}");
}
for virtual_switch in [
"vEthernet (WSL)",
"VirtualBox Host-Only Network",
"VMware Network Adapter VMnet8",
] {
assert!(windows_virtual(virtual_switch), "{virtual_switch}");
}
}
}
+26 -4
View File
@@ -423,13 +423,19 @@ fn is_language_code(code: &str) -> bool {
&& parts.all(|p| (1..=8).contains(&p.len()) && p.bytes().all(|b| b.is_ascii_alphanumeric()))
}
/// An interface name as the kernel accepts them: at most 15 bytes, without
/// space or slash.
/// An interface name as the system accepts them: at most 15 bytes, without
/// space or slash, for the Linux kernel; a friendly name on Windows (`Wi-Fi`,
/// `Connexion au réseau local`), spaces included, at most 256 characters.
fn validate_interface(name: &str) -> Result<(), Notice> {
if name.is_empty() {
return Err(Notice::new("interface_empty", "empty interface name"));
}
if name.len() > 15 || name.contains(['/', ' ', '\t', '\n']) {
let invalid = if cfg!(windows) {
name.chars().count() > 256 || name.chars().any(char::is_control)
} else {
name.len() > 15 || name.contains(['/', ' ']) || name.chars().any(char::is_control)
};
if invalid {
return Err(Notice::new(
"interface_invalid",
format!("\"{name}\" is not an interface name"),
@@ -944,7 +950,8 @@ mod tests {
let bad = Settings {
port: 22,
limit: 0,
interface: Some("a b".into()),
// Invalid everywhere: a control character.
interface: Some("a\nb".into()),
..Settings::default()
};
let Err(StoreError::Rejected(rejections)) = store.save(&bad) else {
@@ -1041,3 +1048,18 @@ mod media_port_tests {
}
}
}
#[cfg(test)]
mod interface_tests {
use super::*;
#[test]
fn interface_names_follow_the_system() {
assert!(validate_interface("wlp0s20f3").is_ok());
assert!(validate_interface("").is_err());
assert!(validate_interface("eth\u{7}").is_err());
// A Windows friendly name: refused by the Linux kernel, not by Windows.
let windows = "Connexion au réseau local 2";
assert_eq!(validate_interface(windows).is_ok(), cfg!(windows));
}
}