357 lines
12 KiB
Python
357 lines
12 KiB
Python
from __future__ import annotations
|
|
|
|
import ipaddress
|
|
import json
|
|
import os
|
|
import re
|
|
import select
|
|
import socket
|
|
import subprocess
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
try:
|
|
import termios
|
|
except ModuleNotFoundError: # pragma: no cover - Windows import fallback
|
|
termios = None # type: ignore[assignment]
|
|
|
|
_MAC_HEX_RE = re.compile(r"^[0-9A-Fa-f]{12}$")
|
|
_SERIAL_PORT_RE = re.compile(r"^(?:/dev/tty(?:USB|ACM|AMA|S|THS|XRUSB)[A-Za-z0-9._/-]*|COM\d+)$", re.IGNORECASE)
|
|
_WOL_IGNORED_IFACE_PREFIXES = ("docker", "br-", "veth", "virbr", "lxc", "wg", "tailscale")
|
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
WOL_DEVICES_FILE = BASE_DIR / "config" / "wol_devices.json"
|
|
|
|
|
|
def normalize_mac_address(value: str) -> str:
|
|
cleaned = re.sub(r"[^0-9A-Fa-f]", "", (value or "").strip())
|
|
if not _MAC_HEX_RE.fullmatch(cleaned):
|
|
raise ValueError("Invalid MAC address")
|
|
return ":".join(cleaned.upper()[i : i + 2] for i in range(0, 12, 2))
|
|
|
|
|
|
def _magic_packet(mac: str) -> bytes:
|
|
compact = mac.replace(":", "")
|
|
return bytes.fromhex("FF" * 6 + compact * 16)
|
|
|
|
|
|
def send_wake_on_lan(mac: str, broadcast: str = "255.255.255.255", port: int = 9) -> dict[str, Any]:
|
|
normalized = normalize_mac_address(mac)
|
|
target = (broadcast or "255.255.255.255").strip()
|
|
try:
|
|
ipaddress.IPv4Address(target)
|
|
except ValueError as exc:
|
|
raise ValueError("Broadcast must be an IPv4 address") from exc
|
|
try:
|
|
resolved_port = int(port)
|
|
except (TypeError, ValueError) as exc:
|
|
raise ValueError("Port must be between 1 and 65535") from exc
|
|
if not 1 <= resolved_port <= 65535:
|
|
raise ValueError("Port must be between 1 and 65535")
|
|
|
|
packet = _magic_packet(normalized)
|
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
try:
|
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
|
sent = sock.sendto(packet, (target, resolved_port))
|
|
finally:
|
|
sock.close()
|
|
|
|
return {
|
|
"message": f"Wake-on-LAN packet sent to {normalized} via {target}:{resolved_port}",
|
|
"mac": normalized,
|
|
"broadcast": target,
|
|
"port": resolved_port,
|
|
"bytes": sent,
|
|
}
|
|
|
|
|
|
def _wol_store_path(base_dir: Path | None = None) -> Path:
|
|
root = base_dir or BASE_DIR
|
|
return root / "config" / "wol_devices.json"
|
|
|
|
|
|
def _load_wol_devices(base_dir: Path | None = None) -> list[dict[str, Any]]:
|
|
path = _wol_store_path(base_dir)
|
|
try:
|
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
except (OSError, json.JSONDecodeError):
|
|
return []
|
|
if not isinstance(data, list):
|
|
return []
|
|
out: list[dict[str, Any]] = []
|
|
for item in data:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
mac = str(item.get("mac") or "").strip()
|
|
try:
|
|
norm = normalize_mac_address(mac)
|
|
except ValueError:
|
|
continue
|
|
out.append(
|
|
{
|
|
"id": norm,
|
|
"name": str(item.get("name") or item.get("ip") or norm).strip(),
|
|
"mac": norm,
|
|
"ip": str(item.get("ip") or "").strip(),
|
|
"reachable": bool(item.get("reachable")),
|
|
"source": str(item.get("source") or "manual"),
|
|
"last_seen": float(item.get("last_seen") or 0),
|
|
"updated_at": float(item.get("updated_at") or 0),
|
|
}
|
|
)
|
|
return sorted(out, key=lambda item: (not item.get("reachable"), item.get("name") or item["mac"]))
|
|
|
|
|
|
def _save_wol_devices(devices: list[dict[str, Any]], base_dir: Path | None = None) -> None:
|
|
path = _wol_store_path(base_dir)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
path.write_text(json.dumps(devices, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
try:
|
|
path.chmod(0o666)
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def _run_text(args: list[str], timeout: float = 3.0) -> str:
|
|
try:
|
|
completed = subprocess.run(args, text=True, capture_output=True, timeout=timeout, check=False)
|
|
except (OSError, subprocess.SubprocessError):
|
|
return ""
|
|
return completed.stdout or ""
|
|
|
|
|
|
def _wol_probe_networks() -> list[ipaddress.IPv4Network]:
|
|
raw = (os.environ.get("WOL_PROBE_CIDR") or "").strip()
|
|
networks: list[ipaddress.IPv4Network] = []
|
|
for item in re.split(r"[,;\s]+", raw):
|
|
if not item:
|
|
continue
|
|
try:
|
|
network = ipaddress.ip_network(item, strict=False)
|
|
except ValueError:
|
|
continue
|
|
if isinstance(network, ipaddress.IPv4Network):
|
|
networks.append(network)
|
|
return networks
|
|
|
|
|
|
def _wol_ip_allowed(ip: ipaddress.IPv4Address, networks: list[ipaddress.IPv4Network]) -> bool:
|
|
if ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_unspecified:
|
|
return False
|
|
if networks:
|
|
return any(ip in network for network in networks)
|
|
return True
|
|
|
|
|
|
def _wol_iface_allowed(iface: str) -> bool:
|
|
name = (iface or "").strip().lower()
|
|
if not name:
|
|
return True
|
|
return not name.startswith(_WOL_IGNORED_IFACE_PREFIXES)
|
|
|
|
|
|
def _ip_neigh_devices() -> list[dict[str, Any]]:
|
|
raw = _run_text(["ip", "neigh", "show"], timeout=2.5)
|
|
devices: list[dict[str, Any]] = []
|
|
networks = _wol_probe_networks()
|
|
for line in raw.splitlines():
|
|
parts = line.split()
|
|
if len(parts) < 5 or "lladdr" not in parts:
|
|
continue
|
|
ip = parts[0]
|
|
iface = parts[parts.index("dev") + 1] if "dev" in parts and parts.index("dev") + 1 < len(parts) else ""
|
|
if not _wol_iface_allowed(iface):
|
|
continue
|
|
try:
|
|
ip_obj = ipaddress.IPv4Address(ip)
|
|
except ValueError:
|
|
continue
|
|
if not _wol_ip_allowed(ip_obj, networks):
|
|
continue
|
|
mac = parts[parts.index("lladdr") + 1]
|
|
try:
|
|
norm = normalize_mac_address(mac)
|
|
except ValueError:
|
|
continue
|
|
state = parts[-1].lower()
|
|
if state in {"failed", "incomplete"}:
|
|
continue
|
|
devices.append(
|
|
{
|
|
"id": norm,
|
|
"name": ip,
|
|
"ip": ip,
|
|
"mac": norm,
|
|
"reachable": state in {"reachable", "stale", "delay", "probe", "permanent"},
|
|
"source": "neigh",
|
|
"last_seen": time.time(),
|
|
"updated_at": time.time(),
|
|
}
|
|
)
|
|
return devices
|
|
|
|
|
|
def _ping_host(ip: str, timeout: float = 1.0) -> bool:
|
|
try:
|
|
ipaddress.IPv4Address(ip)
|
|
except ValueError:
|
|
return False
|
|
try:
|
|
completed = subprocess.run(
|
|
["ping", "-c", "1", "-W", str(max(1, int(timeout))), ip],
|
|
stdout=subprocess.DEVNULL,
|
|
stderr=subprocess.DEVNULL,
|
|
check=False,
|
|
)
|
|
except OSError:
|
|
return False
|
|
return completed.returncode == 0
|
|
|
|
|
|
def list_wol_devices(base_dir: Path | None = None) -> list[dict[str, Any]]:
|
|
return _load_wol_devices(base_dir)
|
|
|
|
|
|
def probe_wol_devices(base_dir: Path | None = None) -> dict[str, Any]:
|
|
now = time.time()
|
|
existing = {item["mac"]: item for item in _load_wol_devices(base_dir)}
|
|
seen: set[str] = set()
|
|
for item in list(existing.values()):
|
|
ip = str(item.get("ip") or "").strip()
|
|
if ip:
|
|
reachable = _ping_host(ip)
|
|
item["reachable"] = reachable
|
|
item["updated_at"] = now
|
|
if reachable:
|
|
item["last_seen"] = now
|
|
for item in _ip_neigh_devices():
|
|
seen.add(item["mac"])
|
|
current = existing.get(item["mac"], {})
|
|
merged = {**item, **{k: v for k, v in current.items() if k in {"name", "source"} and v}}
|
|
if current.get("name") and current.get("name") != current.get("ip"):
|
|
merged["name"] = current["name"]
|
|
if current.get("source") == "manual":
|
|
merged["source"] = "manual"
|
|
existing[item["mac"]] = merged
|
|
devices = [
|
|
item
|
|
for item in existing.values()
|
|
if item.get("source") == "manual" or item["mac"] in seen
|
|
]
|
|
devices = sorted(devices, key=lambda item: (not item.get("reachable"), item.get("name") or item["mac"]))
|
|
_save_wol_devices(devices, base_dir)
|
|
return {"devices": devices, "count": len(devices), "probed_at": now}
|
|
|
|
|
|
def upsert_wol_device(name: str, mac: str, ip: str = "", base_dir: Path | None = None) -> dict[str, Any]:
|
|
norm = normalize_mac_address(mac)
|
|
ip_value = (ip or "").strip()
|
|
if ip_value:
|
|
try:
|
|
ipaddress.IPv4Address(ip_value)
|
|
except ValueError as exc:
|
|
raise ValueError("Device IP must be an IPv4 address") from exc
|
|
devices = {item["mac"]: item for item in _load_wol_devices(base_dir)}
|
|
now = time.time()
|
|
current = devices.get(norm, {})
|
|
devices[norm] = {
|
|
"id": norm,
|
|
"name": (name or ip_value or norm).strip(),
|
|
"mac": norm,
|
|
"ip": ip_value,
|
|
"reachable": bool(current.get("reachable")),
|
|
"source": "manual",
|
|
"last_seen": float(current.get("last_seen") or 0),
|
|
"updated_at": now,
|
|
}
|
|
out = sorted(devices.values(), key=lambda item: (not item.get("reachable"), item.get("name") or item["mac"]))
|
|
_save_wol_devices(out, base_dir)
|
|
return devices[norm]
|
|
|
|
|
|
def delete_wol_device(mac: str, base_dir: Path | None = None) -> dict[str, Any]:
|
|
norm = normalize_mac_address(mac)
|
|
devices = [item for item in _load_wol_devices(base_dir) if item["mac"] != norm]
|
|
_save_wol_devices(devices, base_dir)
|
|
return {"message": "Device removed", "mac": norm, "devices": devices}
|
|
|
|
|
|
def list_serial_ports() -> list[dict[str, Any]]:
|
|
patterns = ["/dev/ttyUSB*", "/dev/ttyACM*", "/dev/ttyAMA*", "/dev/ttyTHS*", "/dev/ttyXRUSB*", "/dev/ttyS*"]
|
|
ports: list[dict[str, Any]] = []
|
|
seen: set[str] = set()
|
|
for pattern in patterns:
|
|
for path in sorted(Path("/").glob(pattern.lstrip("/"))):
|
|
raw = "/" + path.as_posix().lstrip("/")
|
|
if raw in seen:
|
|
continue
|
|
seen.add(raw)
|
|
name = ""
|
|
try:
|
|
name = (Path("/sys/class/tty") / Path(raw).name / "device" / "product").read_text(encoding="utf-8", errors="ignore").strip()
|
|
except OSError:
|
|
pass
|
|
ports.append({"path": raw, "label": f"{Path(raw).name} {name}".strip(), "name": name})
|
|
return ports
|
|
|
|
|
|
def _baud_constant(baudrate: int) -> int:
|
|
if termios is None:
|
|
raise RuntimeError("Serial control requires Linux termios support")
|
|
mapping = {
|
|
9600: termios.B9600,
|
|
19200: termios.B19200,
|
|
38400: termios.B38400,
|
|
57600: termios.B57600,
|
|
115200: termios.B115200,
|
|
}
|
|
if hasattr(termios, "B230400"):
|
|
mapping[230400] = termios.B230400
|
|
return mapping.get(int(baudrate), termios.B115200)
|
|
|
|
|
|
def send_serial_command(port: str, command: str, baudrate: int = 115200, timeout: float = 2.0, append_crlf: bool = True) -> dict[str, Any]:
|
|
if termios is None:
|
|
raise RuntimeError("Serial control requires Linux termios support")
|
|
target = (port or "").strip()
|
|
if not _SERIAL_PORT_RE.fullmatch(target):
|
|
raise ValueError("Unsupported serial port path")
|
|
if not command:
|
|
raise ValueError("Serial command is empty")
|
|
baud = _baud_constant(int(baudrate))
|
|
fd = os.open(target, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
|
|
old_attrs = termios.tcgetattr(fd)
|
|
try:
|
|
attrs = termios.tcgetattr(fd)
|
|
attrs[0] = 0
|
|
attrs[1] = 0
|
|
attrs[2] = termios.CLOCAL | termios.CREAD | termios.CS8
|
|
attrs[3] = 0
|
|
attrs[4] = baud
|
|
attrs[5] = baud
|
|
termios.tcsetattr(fd, termios.TCSANOW, attrs)
|
|
payload = command.encode("utf-8", "replace")
|
|
if append_crlf:
|
|
payload += b"\r\n"
|
|
os.write(fd, payload)
|
|
chunks: list[bytes] = []
|
|
deadline = time.time() + max(0.2, min(float(timeout), 10.0))
|
|
while time.time() < deadline:
|
|
remaining = max(0.05, deadline - time.time())
|
|
readable, _, _ = select.select([fd], [], [], remaining)
|
|
if not readable:
|
|
continue
|
|
try:
|
|
chunk = os.read(fd, 4096)
|
|
except BlockingIOError:
|
|
continue
|
|
if not chunk:
|
|
break
|
|
chunks.append(chunk)
|
|
text = b"".join(chunks).decode("utf-8", "replace")
|
|
return {"port": target, "baudrate": int(baudrate), "command": command, "response": text, "bytes": len(payload)}
|
|
finally:
|
|
termios.tcsetattr(fd, termios.TCSANOW, old_attrs)
|
|
os.close(fd)
|