643 lines
13 KiB
Python
643 lines
13 KiB
Python
|
|
import ipaddress
|
|
import json
|
|
import shutil
|
|
import subprocess
|
|
import xml.etree.ElementTree as ET
|
|
|
|
from pathlib import Path
|
|
|
|
import pynmea2
|
|
|
|
|
|
DEFAULT_PORT = 5000
|
|
|
|
IP_TIMEOUT_SECONDS = 5
|
|
NMAP_TIMEOUT_SECONDS = 35
|
|
NMEA_TIMEOUT_SECONDS = 5
|
|
|
|
MIN_VALID_NMEA_SENTENCES = 2
|
|
|
|
MAX_NETWORK_PREFIX_LENGTH = 16
|
|
MIN_NETWORK_PREFIX_LENGTH = 30
|
|
|
|
PRIVATE_IPV4_NETWORKS = (
|
|
ipaddress.ip_network("10.0.0.0/8"),
|
|
ipaddress.ip_network("172.16.0.0/12"),
|
|
ipaddress.ip_network("192.168.0.0/16"),
|
|
)
|
|
|
|
EXCLUDED_INTERFACE_PREFIXES = (
|
|
"lo",
|
|
"docker",
|
|
"br-",
|
|
"virbr",
|
|
"veth",
|
|
"tun",
|
|
"tap",
|
|
"wg",
|
|
"tailscale",
|
|
"podman",
|
|
"cni",
|
|
"flannel",
|
|
"zt",
|
|
"vmnet",
|
|
"vboxnet",
|
|
"dummy",
|
|
"ppp",
|
|
"sit",
|
|
"gre",
|
|
)
|
|
|
|
VALID_NMEA_TYPES = {
|
|
"GGA",
|
|
"GLL",
|
|
"GNS",
|
|
"GSA",
|
|
"GSV",
|
|
"RMC",
|
|
"VTG",
|
|
"ZDA",
|
|
}
|
|
|
|
|
|
class GPSRelayDiscoveryError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def _require_tools():
|
|
|
|
packages = {
|
|
"ip": "iproute2",
|
|
"nmap": "nmap",
|
|
"nc": "netcat-openbsd",
|
|
}
|
|
|
|
missing = [
|
|
f"{tool} (пакет {package})"
|
|
for tool, package in packages.items()
|
|
if shutil.which(tool) is None
|
|
]
|
|
|
|
if missing:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
"Для поиска GPSRelay необходимо установить:\n"
|
|
+ "\n".join(missing)
|
|
+ "\nУстановка: sudo apt install "
|
|
+ " ".join(
|
|
package
|
|
for tool, package in packages.items()
|
|
if shutil.which(tool) is None
|
|
)
|
|
)
|
|
|
|
|
|
def _is_physical_interface(interface):
|
|
|
|
device_path = (
|
|
Path("/sys/class/net")
|
|
/ interface
|
|
/ "device"
|
|
)
|
|
|
|
return device_path.exists()
|
|
|
|
|
|
def _is_excluded_interface(interface):
|
|
|
|
return interface.startswith(
|
|
EXCLUDED_INTERFACE_PREFIXES
|
|
)
|
|
|
|
|
|
def _interface_priority(interface):
|
|
|
|
if interface.startswith("enx"):
|
|
return 0
|
|
|
|
if interface.startswith((
|
|
"enp",
|
|
"eno",
|
|
"eth",
|
|
)):
|
|
return 1
|
|
|
|
if interface.startswith((
|
|
"wl",
|
|
"wlan",
|
|
)):
|
|
return 2
|
|
|
|
return 3
|
|
|
|
|
|
def _get_local_networks(ip_binary):
|
|
|
|
try:
|
|
|
|
result = subprocess.run(
|
|
[
|
|
ip_binary,
|
|
"-j",
|
|
"-4",
|
|
"addr",
|
|
"show"
|
|
],
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=IP_TIMEOUT_SECONDS,
|
|
check=True
|
|
)
|
|
|
|
except (
|
|
subprocess.SubprocessError,
|
|
OSError
|
|
) as error:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
f"Не удалось получить сетевые интерфейсы: {error}"
|
|
) from error
|
|
|
|
try:
|
|
|
|
interfaces = json.loads(
|
|
result.stdout
|
|
)
|
|
|
|
except json.JSONDecodeError as error:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
"Команда ip вернула некорректные данные."
|
|
) from error
|
|
|
|
networks = {}
|
|
|
|
for item in interfaces:
|
|
|
|
interface = item.get("ifname", "")
|
|
|
|
if not interface:
|
|
continue
|
|
|
|
if _is_excluded_interface(interface):
|
|
continue
|
|
|
|
if not _is_physical_interface(interface):
|
|
continue
|
|
|
|
flags = item.get("flags", [])
|
|
|
|
if "UP" not in flags:
|
|
continue
|
|
|
|
if item.get("operstate") == "DOWN":
|
|
continue
|
|
|
|
for address in item.get("addr_info", []):
|
|
|
|
if address.get("family") != "inet":
|
|
continue
|
|
|
|
if address.get("scope") != "global":
|
|
continue
|
|
|
|
local = address.get("local")
|
|
prefixlen = address.get("prefixlen")
|
|
|
|
try:
|
|
|
|
network = ipaddress.ip_interface(
|
|
f"{local}/{prefixlen}"
|
|
).network
|
|
|
|
except (
|
|
TypeError,
|
|
ValueError
|
|
):
|
|
continue
|
|
|
|
if not (
|
|
MAX_NETWORK_PREFIX_LENGTH
|
|
<= network.prefixlen
|
|
<= MIN_NETWORK_PREFIX_LENGTH
|
|
):
|
|
continue
|
|
|
|
if not any(
|
|
network.subnet_of(private_network)
|
|
for private_network in PRIVATE_IPV4_NETWORKS
|
|
):
|
|
continue
|
|
|
|
if (
|
|
network.network_address.is_loopback
|
|
or network.network_address.is_link_local
|
|
or network.network_address.is_multicast
|
|
):
|
|
continue
|
|
|
|
key = str(network)
|
|
|
|
candidate = {
|
|
"network": key,
|
|
"interface": interface,
|
|
"priority": _interface_priority(interface)
|
|
}
|
|
|
|
previous = networks.get(key)
|
|
|
|
if (
|
|
previous is None
|
|
or candidate["priority"] < previous["priority"]
|
|
):
|
|
networks[key] = candidate
|
|
|
|
return sorted(
|
|
networks.values(),
|
|
key=lambda item: (
|
|
item["priority"],
|
|
item["network"]
|
|
)
|
|
)
|
|
|
|
|
|
def _scan_network(
|
|
nmap_binary,
|
|
network,
|
|
port
|
|
):
|
|
|
|
command = [
|
|
nmap_binary,
|
|
"--unprivileged",
|
|
"-n",
|
|
"-Pn",
|
|
"-sT",
|
|
"-T4",
|
|
"--max-retries",
|
|
"1",
|
|
"--host-timeout",
|
|
"8s",
|
|
"--open",
|
|
"-p",
|
|
str(port),
|
|
"-oX",
|
|
"-",
|
|
network
|
|
]
|
|
|
|
try:
|
|
|
|
result = subprocess.run(
|
|
command,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=NMAP_TIMEOUT_SECONDS,
|
|
check=False
|
|
)
|
|
|
|
except subprocess.TimeoutExpired as error:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
f"Истекло время сканирования сети {network}."
|
|
) from error
|
|
|
|
except OSError as error:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
f"Не удалось запустить nmap: {error}"
|
|
) from error
|
|
|
|
if result.returncode != 0:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
f"Ошибка nmap при сканировании {network}: "
|
|
f"{result.stderr.strip()}"
|
|
)
|
|
|
|
try:
|
|
|
|
root = ET.fromstring(
|
|
result.stdout
|
|
)
|
|
|
|
except ET.ParseError as error:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
f"Не удалось разобрать результат nmap для {network}."
|
|
) from error
|
|
|
|
candidates = []
|
|
|
|
for host in root.findall("host"):
|
|
|
|
status = host.find("status")
|
|
|
|
if (
|
|
status is None
|
|
or status.get("state") != "up"
|
|
):
|
|
continue
|
|
|
|
ports = host.find("ports")
|
|
|
|
if ports is None:
|
|
continue
|
|
|
|
port_is_open = any(
|
|
item.get("portid") == str(port)
|
|
and item.find("state") is not None
|
|
and item.find("state").get("state") == "open"
|
|
for item in ports.findall("port")
|
|
)
|
|
|
|
if not port_is_open:
|
|
continue
|
|
|
|
address = next(
|
|
(
|
|
item.get("addr")
|
|
for item in host.findall("address")
|
|
if item.get("addrtype") == "ipv4"
|
|
),
|
|
None
|
|
)
|
|
|
|
if address is not None:
|
|
|
|
candidates.append(
|
|
address
|
|
)
|
|
|
|
return candidates
|
|
|
|
|
|
def _validate_nmea_stream(output):
|
|
|
|
if isinstance(output, bytes):
|
|
output = output.decode(
|
|
"ascii",
|
|
errors="replace"
|
|
)
|
|
|
|
valid_types = set()
|
|
valid_count = 0
|
|
total_count = 0
|
|
|
|
for line in output.splitlines():
|
|
|
|
line = line.strip()
|
|
|
|
if not line.startswith("$"):
|
|
continue
|
|
|
|
total_count += 1
|
|
|
|
try:
|
|
|
|
message = pynmea2.parse(
|
|
line,
|
|
check=True
|
|
)
|
|
|
|
except (
|
|
pynmea2.ParseError,
|
|
ValueError,
|
|
TypeError
|
|
):
|
|
continue
|
|
|
|
message_type = getattr(
|
|
message,
|
|
"sentence_type",
|
|
""
|
|
)
|
|
|
|
if message_type not in VALID_NMEA_TYPES:
|
|
continue
|
|
|
|
valid_count += 1
|
|
valid_types.add(message_type)
|
|
|
|
ratio = (
|
|
valid_count / total_count
|
|
if total_count
|
|
else 0
|
|
)
|
|
|
|
return {
|
|
"valid_count": valid_count,
|
|
"valid_types": valid_types,
|
|
"valid_ratio": ratio,
|
|
"total_count": total_count
|
|
}
|
|
|
|
|
|
def _test_candidate(
|
|
nc_binary,
|
|
host,
|
|
port
|
|
):
|
|
|
|
try:
|
|
|
|
result = subprocess.run(
|
|
[
|
|
nc_binary,
|
|
"-n",
|
|
host,
|
|
str(port)
|
|
],
|
|
capture_output=True,
|
|
timeout=NMEA_TIMEOUT_SECONDS,
|
|
check=False
|
|
)
|
|
|
|
output = result.stdout or b""
|
|
|
|
except subprocess.TimeoutExpired as error:
|
|
|
|
output = error.stdout or b""
|
|
|
|
except OSError:
|
|
|
|
return None
|
|
|
|
quality = _validate_nmea_stream(
|
|
output
|
|
)
|
|
|
|
if (
|
|
quality["valid_count"]
|
|
< MIN_VALID_NMEA_SENTENCES
|
|
):
|
|
return None
|
|
|
|
return quality
|
|
|
|
|
|
def discover_gpsrelay(port=DEFAULT_PORT):
|
|
|
|
if isinstance(port, bool):
|
|
raise GPSRelayDiscoveryError(
|
|
"Некорректный порт GPSRelay."
|
|
)
|
|
|
|
try:
|
|
|
|
port = int(port)
|
|
|
|
except (
|
|
TypeError,
|
|
ValueError
|
|
) as error:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
"Некорректный порт GPSRelay."
|
|
) from error
|
|
|
|
if not 1 <= port <= 65535:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
"Порт GPSRelay должен находиться в диапазоне 1–65535."
|
|
)
|
|
|
|
_require_tools()
|
|
|
|
ip_binary = shutil.which("ip")
|
|
nmap_binary = shutil.which("nmap")
|
|
nc_binary = shutil.which("nc")
|
|
|
|
networks = _get_local_networks(
|
|
ip_binary
|
|
)
|
|
|
|
if not networks:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
"Не найдены активные физические сетевые интерфейсы "
|
|
"с подходящими IPv4-подсетями."
|
|
)
|
|
|
|
discovered = []
|
|
scan_errors = []
|
|
|
|
for network in networks:
|
|
|
|
try:
|
|
|
|
hosts = _scan_network(
|
|
nmap_binary,
|
|
network["network"],
|
|
port
|
|
)
|
|
|
|
except GPSRelayDiscoveryError as error:
|
|
|
|
scan_errors.append(
|
|
str(error)
|
|
)
|
|
continue
|
|
|
|
for host in hosts:
|
|
|
|
discovered.append({
|
|
"host": host,
|
|
"port": port,
|
|
"interface": network["interface"],
|
|
"priority": network["priority"]
|
|
})
|
|
|
|
if scan_errors:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
"Не удалось полностью просканировать все локальные сети:\n"
|
|
+ "\n".join(scan_errors)
|
|
)
|
|
|
|
if not discovered:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
f"Устройства с открытым TCP-портом {port} "
|
|
"в локальных сетях не найдены."
|
|
)
|
|
|
|
verified = []
|
|
|
|
for candidate in discovered:
|
|
|
|
quality = _test_candidate(
|
|
nc_binary,
|
|
candidate["host"],
|
|
port
|
|
)
|
|
|
|
if quality is None:
|
|
continue
|
|
|
|
verified.append({
|
|
**candidate,
|
|
**quality
|
|
})
|
|
|
|
if not verified:
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
"Порт найден, но ни одно устройство не передаёт "
|
|
"достаточное количество корректных NMEA-предложений."
|
|
)
|
|
|
|
verified.sort(
|
|
key=lambda item: (
|
|
item["priority"],
|
|
-item["valid_count"],
|
|
-len(item["valid_types"]),
|
|
-item["valid_ratio"]
|
|
)
|
|
)
|
|
|
|
best = verified[0]
|
|
|
|
best_rank = (
|
|
best["priority"],
|
|
best["valid_count"],
|
|
len(best["valid_types"]),
|
|
best["valid_ratio"]
|
|
)
|
|
|
|
equally_suitable = [
|
|
item
|
|
for item in verified
|
|
if (
|
|
item["priority"],
|
|
item["valid_count"],
|
|
len(item["valid_types"]),
|
|
item["valid_ratio"]
|
|
) == best_rank
|
|
]
|
|
|
|
if len(equally_suitable) > 1:
|
|
|
|
hosts = ", ".join(
|
|
item["host"]
|
|
for item in equally_suitable
|
|
)
|
|
|
|
raise GPSRelayDiscoveryError(
|
|
"Обнаружено несколько равноценных GPSRelay: "
|
|
+ hosts
|
|
+ ". Автоматический выбор небезопасен."
|
|
)
|
|
|
|
return {
|
|
"host": best["host"],
|
|
"port": port,
|
|
"interface": best["interface"],
|
|
"valid_sentences": best["valid_count"],
|
|
"sentence_types": sorted(
|
|
best["valid_types"]
|
|
),
|
|
"candidate_count": len(verified)
|
|
}
|