Release 1.0.0

This commit is contained in:
2026-11-18 00:31:29 +03:00
commit 8562456249
118 changed files with 62491 additions and 0 deletions
+365
View File
@@ -0,0 +1,365 @@
from pathlib import Path
import subprocess
import yaml
class Config:
def __init__(self):
# Путь к конфигурационному файлу
config_file = (
Path(__file__).parent.parent
/
"config"
/
"config.yaml"
)
# Загрузка YAML
with open(
config_file,
"r"
) as file:
self.cfg = yaml.safe_load(file)
self._interface = None
# -----------------------------
# GPS
# -----------------------------
@property
def gps_source(self):
gps = self.cfg["gps"]
return gps.get(
"source",
"gpsrelay"
)
@property
def gpsrelay_host(self):
gps = self.cfg["gps"]
if "gpsrelay" in gps:
return gps["gpsrelay"]["host"]
return gps["host"]
@property
def gpsrelay_port(self):
gps = self.cfg["gps"]
if "gpsrelay" in gps:
return gps["gpsrelay"]["port"]
return gps["port"]
@property
def gnss_device(self):
gnss = self.cfg["gps"]["gnss"]
handler = gnss["handler"]
return gnss[handler]["device"]
@property
def gnss_at_device(self):
return self.cfg["gps"]["gnss"]["modem"]["at_device"]
@property
def gnss_handler(self):
return self.cfg["gps"]["gnss"]["handler"]
# -----------------------------
# Database
# -----------------------------
@property
def database(self):
return self.cfg["database"]["file"]
@property
def vendor_database(self):
return (
Path(__file__).parent.parent
/
self.cfg["vendor"]["database"]
)
@property
def vendor_sources(self):
return self.cfg["vendor"]["sources"]
# -----------------------------
# WiFi
# -----------------------------
@property
def interface(self):
if self._interface is None:
raise RuntimeError(
"WiFi interface is not selected."
)
return self._interface
def select_interface(self):
result = subprocess.run(
[
"sudo",
"-n",
"iw",
"dev"
],
capture_output=True,
text=True
)
interfaces = []
current = None
for line in result.stdout.splitlines():
line = line.strip()
if line.startswith("Interface"):
current = line.split()[1]
elif (
line.startswith("type")
and
current
):
if "monitor" in line or "managed" in line:
interfaces.append(
current
)
current = None
if not interfaces:
raise RuntimeError(
"No WiFi interface found."
)
iwlist = subprocess.run(
[
"sudo",
"-n",
"iw",
"list"
],
capture_output=True,
text=True
).stdout
if "monitor" not in iwlist.lower():
raise RuntimeError(
"No adapter supports monitor mode."
)
import os
requested_interface = os.environ.get(
"WIFI_INTERFACE"
)
if requested_interface:
if requested_interface in interfaces:
self._interface = (
requested_interface
)
return self._interface
raise RuntimeError(
f"WiFi interface '{requested_interface}' "
"is not available."
)
if len(interfaces) == 1:
self._interface = interfaces[0]
return self._interface
print()
print(
"Available WiFi interfaces:"
)
print()
for index, iface in enumerate(
interfaces,
start=1
):
print(
f"{index}) {iface}"
)
print()
while True:
try:
value = int(
input(
"Select interface: "
)
)
if (
1
<= value
<= len(interfaces)
):
self._interface = (
interfaces[value - 1]
)
return self._interface
except Exception:
pass
print(
"Invalid selection."
)
@property
def wifi_enable_2_4ghz(self):
return self.cfg["wifi"]["enable_2_4ghz"]
@property
def wifi_channels_2_4ghz(self):
return self.cfg["wifi"]["channels_2_4ghz"]
@property
def wifi_enable_5ghz(self):
return self.cfg["wifi"]["enable_5ghz"]
@property
def wifi_channels_5ghz(self):
return self.cfg["wifi"]["channels_5ghz"]
@property
def wifi_enable_6ghz(self):
return self.cfg["wifi"]["enable_6ghz"]
@property
def wifi_channels_6ghz(self):
return self.cfg["wifi"]["channels_6ghz"]
@property
def wifi_filtermode(self):
return self.cfg["wifi"]["filtermode"]
@property
def wifi_extra_args(self):
return self.cfg["wifi"]["extra_args"]
# -----------------------------
# Tools
# -----------------------------
@property
def hcxdumptool(self):
return (
Path(__file__).parent.parent
/
"bin"
/
"hcxdumptool"
)
@property
def hcxpcapngtool(self):
return (
Path(__file__).parent.parent
/
"bin"
/
"hcxpcapngtool"
)
# -----------------------------
# Capture
# -----------------------------
@property
def capture_directory(self):
return self.cfg["captures"]["directory"]
# -----------------------------
# Status
# -----------------------------
@property
def status_interval(self):
return self.cfg["status"]["interval"]
+1980
View File
File diff suppressed because it is too large Load Diff
+284
View File
@@ -0,0 +1,284 @@
import os
import subprocess
import logging
import sqlite3
import csv
class EnvironmentChecker:
"""
Проверка окружения проекта.
Проверяются:
- наличие необходимых каталогов;
- наличие бинарных файлов;
- права на выполнение;
- версия hcxdumptool;
- наличие базы производителей.
Основная база проекта не проверяется,
так как она может быть создана автоматически
при первом запуске.
"""
def __init__(
self,
config
):
self.config = config
self.log = logging.getLogger(
"environment"
)
# ---------------------------------------------------------
# Главная проверка
# ---------------------------------------------------------
def check(self):
self.log.info(
"Checking application environment..."
)
self.check_binary(
self.config.hcxdumptool,
"hcxdumptool"
)
self.check_binary(
self.config.hcxpcapngtool,
"hcxpcapngtool"
)
self.check_hcxdumptool_version()
vendor_database_ok = self.check_vendor_database()
if vendor_database_ok:
self.log.info(
"Environment OK"
)
else:
self.log.warning(
"Environment checks completed; vendor lookup unavailable"
)
# ---------------------------------------------------------
# Проверка бинарника
# ---------------------------------------------------------
def check_binary(
self,
path,
name
):
if not path.exists():
raise RuntimeError(
f"{name} not found:\n\n{path}"
)
if not path.is_file():
raise RuntimeError(
f"{name} is not a file:\n\n{path}"
)
if not os.access(
path,
os.X_OK
):
raise RuntimeError(
f"{name} is not executable:\n\n"
f"{path}\n\n"
f"Run:\n"
f"chmod +x {path}"
)
self.log.info(
f"{name}: OK"
)
# ---------------------------------------------------------
# Проверка версии hcxdumptool
# ---------------------------------------------------------
def check_hcxdumptool_version(self):
result = subprocess.run(
[
str(
self.config.hcxdumptool
),
"--help"
],
capture_output=True,
text=True
)
output = (
result.stdout
+
result.stderr
)
if "7." not in output:
raise RuntimeError(
"Unsupported hcxdumptool version.\n"
"Version 7.x is required."
)
self.log.info(
"hcxdumptool version: OK"
)
# ---------------------------------------------------------
# Проверка базы производителей
# ---------------------------------------------------------
def check_vendor_database(self):
database = self.config.vendor_database
if not database.exists():
self.log.warning(
"Vendor database not found: %s",
database
)
return False
if database.stat().st_size == 0:
self.log.warning(
"Vendor database is empty: %s",
database
)
return False
connection = None
try:
connection = sqlite3.connect(
f"{database.resolve().as_uri()}?mode=ro",
uri=True
)
cursor = connection.cursor()
cursor.execute(
"SELECT name FROM sqlite_master "
"WHERE type='table' "
"AND name='oui'"
)
if cursor.fetchone() is None:
raise RuntimeError(
"oui table not found"
)
cursor.execute(
"SELECT COUNT(*) FROM oui"
)
records = cursor.fetchone()[0]
if records < 50000:
raise RuntimeError(
f"Only {records} records"
)
cursor.execute(
"SELECT name FROM sqlite_master "
"WHERE type='table' "
"AND name='metadata'"
)
if cursor.fetchone() is None:
raise RuntimeError(
"metadata table not found"
)
cursor.execute(
"SELECT value "
"FROM metadata "
"WHERE key='import_status'"
)
row = cursor.fetchone()
if row is None or row[0] != "ok":
raise RuntimeError(
"Invalid import_status"
)
self.log.info(
"Vendor database: OK (%s records)",
records
)
return True
except sqlite3.Error as error:
self.log.warning(
"Vendor database is invalid: %s",
error
)
return False
except RuntimeError as error:
self.log.warning(
"Vendor database is invalid: %s",
error
)
return False
finally:
if connection is not None:
connection.close()
+480
View File
@@ -0,0 +1,480 @@
import socket
import threading
import select
import os
import termios
import logging
import subprocess
import pynmea2
from datetime import datetime, timezone
from models import GPSData
class GPSRelaySource:
def __init__(self, host, port):
self.host = host
self.port = port
self.socket = None
def open(self):
self.socket = socket.create_connection(
(
self.host,
self.port
)
)
return self.socket.makefile()
def close(self):
if self.socket:
self.socket.close()
class GpsdSource:
def __init__(self, host="127.0.0.1", port=2947):
self.host = host
self.port = port
self.socket = None
def open(self):
self.socket = socket.create_connection(
(
self.host,
self.port
)
)
file = self.socket.makefile()
file.readline()
self.socket.sendall(
b'?WATCH={"enable":true,"json":false,"nmea":true};\n'
)
return file
def close(self):
if self.socket:
self.socket.close()
class SerialSource:
def __init__(self, device):
self.device = device
self.fd = None
self.lock = threading.Lock()
def open(self):
self.fd = os.open(
self.device,
os.O_RDWR | os.O_NOCTTY
)
attributes = termios.tcgetattr(
self.fd
)
attributes[0] = 0
attributes[1] = 0
attributes[2] = (
termios.CLOCAL |
termios.CREAD |
termios.CS8
)
attributes[3] = 0
attributes[4] = termios.B9600
attributes[5] = termios.B9600
attributes[6][
termios.VMIN
] = 0
attributes[6][
termios.VTIME
] = 5
termios.tcsetattr(
self.fd,
termios.TCSANOW,
attributes
)
return self
def readline(self):
with self.lock:
buffer = b""
while True:
ready, _, _ = select.select(
[self.fd],
[],
[],
0.5
)
if not ready:
return ""
data = os.read(
self.fd,
1
)
if not data:
return ""
buffer += data
if data == b"\n":
return buffer.decode(
errors="replace"
)
def close(self):
with self.lock:
if self.fd is not None:
os.close(
self.fd
)
self.fd = None
class ModemGNSSSource:
def __init__(
self,
device,
at_device
):
self.device = device
self.at_device = at_device
self.serial = SerialSource(
device
)
def send_at(self, command):
result = subprocess.run(
[
"sudo",
"-n",
"atinout",
"-",
self.at_device,
"-"
],
input=command + "\r\n",
text=True,
capture_output=True,
timeout=10
)
if result.returncode != 0:
raise RuntimeError(
"AT command failed: "
+ result.stderr.strip()
)
return result.stdout
def ensure_gnss_enabled(self):
response = self.send_at(
"AT+QGPS?"
)
if "+QGPS: 1" not in response:
self.send_at(
"AT+QGPS=1"
)
response = self.send_at(
"AT+QGPS?"
)
if "+QGPS: 1" not in response:
raise RuntimeError(
"GNSS did not start."
)
def open(self):
self.ensure_gnss_enabled()
return self.serial.open()
def readline(self):
return self.serial.readline()
def close(self):
self.serial.close()
def create_gps_source(cfg):
if cfg.gps_source == "gpsrelay":
return GPSRelaySource(
cfg.gpsrelay_host,
cfg.gpsrelay_port
)
if cfg.gps_source == "gnss":
if cfg.gnss_handler == "gpsd":
return GpsdSource()
if cfg.gnss_handler == "modem":
return ModemGNSSSource(
cfg.gnss_device,
cfg.gnss_at_device
)
if cfg.gnss_handler == "direct":
return SerialSource(
cfg.gnss_device
)
raise ValueError(
f"Unknown GNSS handler: {cfg.gnss_handler}"
)
raise ValueError(
f"Unknown GPS source: {cfg.gps_source}"
)
def parse_nmea(
line,
received
):
if not line.startswith("$"):
return None
try:
msg = pynmea2.parse(
line
)
except Exception:
return None
message_type = getattr(
msg,
"sentence_type",
""
)
if message_type == "RMC":
if msg.status != "A":
return None
speed = float(
msg.spd_over_grnd or 0
)
elif message_type == "GNS":
mode = getattr(
msg,
"mode_indicator",
""
)
if not mode or mode[0] == "N":
return None
speed = 0
else:
return None
try:
return GPSData(
latitude=msg.latitude,
longitude=msg.longitude,
speed=speed,
timestamp=received,
valid=True
)
except (TypeError, ValueError):
return None
class GPSManager:
def __init__(self, source, session):
self.source = source
self.session = session
self.current = None
self.running = False
self.thread = None
self.log = logging.getLogger("gps")
def start(self):
self.running = True
self.thread = threading.Thread(
target=self.worker,
daemon=True
)
self.thread.start()
def parse_nmea(
self,
line,
received
):
gps = parse_nmea(
line,
received
)
if gps is None:
return
self.current = gps
self.session.update_gps(
gps
)
def worker(self):
file = None
try:
file = self.source.open()
self.log.info(
"GPS connection established"
)
with open(
self.session.gps_file,
"a"
) as gps_log:
while self.running:
if hasattr(
self.source,
"readline"
):
line = self.source.readline()
else:
line = file.readline()
if not line:
continue
received = datetime.now(
timezone.utc
)
gps_log.write(
f"{received.isoformat().replace('+00:00', 'Z')};{line}"
)
gps_log.flush()
self.session.add_nmea()
self.parse_nmea(
line,
received
)
except Exception as error:
self.log.error(
f"GPS error: {error}"
)
finally:
self.source.close()
def get(self):
return self.current
def stop(self):
self.running = False
self.source.close()
+350
View File
@@ -0,0 +1,350 @@
import threading
import time
from datetime import datetime, timezone
from gps import create_gps_source, parse_nmea
class GPSTestService:
def __init__(
self,
cfg,
callback=None
):
self.cfg = cfg
self.callback = callback
self.source = None
self.source_lock = threading.Lock()
self.thread = None
self.stop_event = threading.Event()
self.running = False
self.state = "READY"
self.nmea_received = False
self.fix_received = False
self.nmea_count = 0
self.fix_count = 0
self.latitude = None
self.longitude = None
self.error = None
def emit(self, message):
if self.callback:
self.callback(message)
def start(self):
if (
self.thread is not None
and
self.thread.is_alive()
):
return False
self.stop_event.clear()
self.running = True
self.state = "STARTING"
self.nmea_received = False
self.fix_received = False
self.nmea_count = 0
self.fix_count = 0
self.latitude = None
self.longitude = None
self.error = None
self.thread = threading.Thread(
target=self.worker,
daemon=True
)
self.thread.start()
return True
def stop(self):
self.stop_event.set()
with self.source_lock:
source = self.source
if source is None:
return
connection = getattr(
source,
"socket",
None
)
if connection is not None:
try:
connection.shutdown(2)
except OSError:
pass
try:
source.close()
except Exception as error:
self.emit(
f"[GPS TEST] Stop close error: {error}"
)
def worker(self):
source = None
file = None
try:
self.emit(
"[GPS TEST] Starting GPS test "
"from saved configuration."
)
source = create_gps_source(
self.cfg
)
with self.source_lock:
self.source = source
if self.stop_event.is_set():
return
self.emit(
"[GPS TEST] Connecting to GPS source..."
)
file = source.open()
if self.stop_event.is_set():
return
self.state = "CONNECTED"
self.emit(
"[GPS TEST] GPS source connected. "
"Waiting for NMEA..."
)
last_no_fix_message = 0
while not self.stop_event.is_set():
if hasattr(
source,
"readline"
):
line = source.readline()
else:
line = file.readline()
if not line:
if self.stop_event.wait(0.1):
break
continue
self.nmea_count += 1
self.nmea_received = True
if self.state == "CONNECTED":
self.state = "NMEA"
self.emit(
"[GPS TEST] NMEA received. "
"Waiting for valid FIX..."
)
received = datetime.now(
timezone.utc
)
gps = parse_nmea(
line,
received
)
if gps is not None:
first_fix = not self.fix_received
self.fix_count += 1
self.fix_received = True
self.state = "FIX"
self.latitude = gps.latitude
self.longitude = gps.longitude
self.emit(
"[GPS TEST] FIX received: "
f"lat={gps.latitude:.6f} "
f"lon={gps.longitude:.6f}"
)
if first_fix:
self.emit(
"[GPS TEST] GPS is ready "
"for scanning."
)
elif self.fix_count % 10 == 0:
self.emit(
"[GPS TEST] GPS is ready "
"for scanning. "
f"FIX: lat={gps.latitude:.6f} "
f"lon={gps.longitude:.6f}"
)
elif (
self.nmea_received
and
not self.fix_received
and
self.nmea_count % 10 == 0
and
time.monotonic() - last_no_fix_message >= 5
):
last_no_fix_message = (
time.monotonic()
)
self.emit(
"[GPS TEST] GPS is not ready: "
"NMEA received, but no valid FIX yet. "
f"NMEA: {self.nmea_count}"
)
except Exception as error:
if not self.stop_event.is_set():
self.state = "ERROR"
self.error = str(error)
self.emit(
f"[GPS TEST] GPS source error: {error}"
)
finally:
if file is not None:
try:
file.close()
except Exception as error:
self.emit(
f"[GPS TEST] File close error: {error}"
)
if source is not None:
try:
source.close()
except Exception as error:
self.emit(
f"[GPS TEST] Close error: {error}"
)
with self.source_lock:
if self.source is source:
self.source = None
self.running = False
if self.state != "ERROR":
self.state = "STOPPED"
self.emit(
"[GPS TEST] Test stopped."
)
def run_gps_test(cfg):
def output(message):
print(
message,
flush=True
)
service = GPSTestService(
cfg,
callback=output
)
service.start()
try:
while service.running:
time.sleep(0.2)
except KeyboardInterrupt:
print(
"[GPS TEST] Test interrupted by user.",
flush=True
)
if service.fix_received:
print(
"[GPS TEST] Result: "
"GPS is ready for scanning.",
flush=True
)
print(
"[GPS TEST] Last position: "
f"lat={service.latitude:.6f} "
f"lon={service.longitude:.6f}",
flush=True
)
else:
print(
"[GPS TEST] Result: "
"GPS is not ready for scanning.",
flush=True
)
service.stop()
while service.running:
time.sleep(0.1)
return 0 if service.fix_received else 1
+986
View File
@@ -0,0 +1,986 @@
import argparse
import getpass
import json
import os
import shutil
import signal
import socket
import stat
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from tileserver_config import load_tileserver_config
TILESERVER_CONFIG_DATA = load_tileserver_config(PROJECT_ROOT)
UNIT_NAME = "wifi-gps-mapper"
APP_HOST = "127.0.0.1"
APP_PORT = 5000
TILE_HOST = TILESERVER_CONFIG_DATA["host"]
TILE_PORT = TILESERVER_CONFIG_DATA["port"]
TILE_STYLE_URL = TILESERVER_CONFIG_DATA["style_url"]
TILESERVER_DIR = TILESERVER_CONFIG_DATA["directory"]
TILESERVER_ENTRY = TILESERVER_CONFIG_DATA["entry"]
TILESERVER_CONFIG = TILESERVER_CONFIG_DATA["config"]
TILESERVER_CONFIG_PATH = TILESERVER_CONFIG_DATA["config_path"]
STARTUP_TIMEOUT = 30
POLL_INTERVAL = 0.5
AUTH_SOCKET_PATH = Path(
os.environ.get(
"XDG_RUNTIME_DIR",
f"/run/user/{os.getuid()}"
)
) / "wifi-gps-mapper-auth.sock"
class LifecycleError(RuntimeError):
pass
def log(message):
print(
f"[WiFi GPS Mapper] {message}",
flush=True
)
def project_python():
return PROJECT_ROOT / "venv" / "bin" / "python"
def style_is_available(timeout=2):
try:
request = urllib.request.Request(
TILE_STYLE_URL,
headers={"Accept": "application/json"}
)
with urllib.request.urlopen(
request,
timeout=timeout
) as response:
if response.status != 200:
return False
content_type = response.headers.get(
"Content-Type",
""
)
payload = json.loads(
response.read().decode("utf-8")
)
return (
isinstance(payload, dict)
and "version" in payload
and (
"sources" in payload
or "layers" in payload
)
)
except (
OSError,
ValueError,
urllib.error.URLError
):
return False
def port_is_open(host, port):
with socket.socket(
socket.AF_INET,
socket.SOCK_STREAM
) as connection:
connection.settimeout(0.5)
return connection.connect_ex(
(host, port)
) == 0
def start_tileserver():
if style_is_available():
log(
"TileServer уже работает. "
"Используется внешний экземпляр."
)
return None
if port_is_open(TILE_HOST, TILE_PORT):
raise LifecycleError(
f"Порт {TILE_PORT} занят, но ожидаемый "
f"стиль {TILESERVER_CONFIG_DATA['style']} недоступен. "
"Чужой процесс не будет остановлен."
)
node = shutil.which("node")
if node is None:
raise LifecycleError(
"Node.js не найден в PATH."
)
if not TILESERVER_ENTRY.is_file():
raise LifecycleError(
f"Не найден TileServer entry point: "
f"{TILESERVER_ENTRY}"
)
config_path = TILESERVER_CONFIG_PATH
if not config_path.is_file():
raise LifecycleError(
f"Не найден TileServer config: {config_path}"
)
command = [
node,
str(TILESERVER_ENTRY),
"--config",
TILESERVER_CONFIG,
"--bind",
TILE_HOST,
"--port",
str(TILE_PORT)
]
log("Запускается TileServer...")
process = subprocess.Popen(
command,
cwd=TILESERVER_DIR,
stdin=subprocess.DEVNULL
)
deadline = time.monotonic() + STARTUP_TIMEOUT
while time.monotonic() < deadline:
if process.poll() is not None:
raise LifecycleError(
"TileServer завершился во время запуска "
f"(код {process.returncode})."
)
if style_is_available():
log(
f"TileServer запущен, PID {process.pid}."
)
return process
time.sleep(POLL_INTERVAL)
process.terminate()
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
raise LifecycleError(
"TileServer не стал доступен за "
f"{STARTUP_TIMEOUT} секунд."
)
def stop_owned_tileserver(process):
if process is None or process.poll() is not None:
return
log("Останавливается принадлежащий менеджеру TileServer.")
process.terminate()
try:
process.wait(timeout=10)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
def wait_for_scanner(app_module):
notified = False
while True:
with app_module.scanner_lock:
starting = app_module.scanner_starting
network_active = app_module.network_action_active
process = app_module.scanner_process
reader = app_module.scanner_output_thread
running = (
process is not None
and process.poll() is None
)
if not starting and not network_active and not running:
break
if not notified:
log(
"Ожидание завершения сканера или сетевой операции. "
"Если сканер работает, останови его кнопкой "
"Stop в веб-интерфейсе."
)
notified = True
time.sleep(POLL_INTERVAL)
if process is not None:
process.wait()
if reader is not None and reader is not threading.current_thread():
reader.join()
log("Сканер и поток чтения его вывода завершены.")
def stop_gps_test(app_module):
with app_module.gps_test_lock:
service = app_module.gps_test_service
if service is None:
return
thread = service.thread
if thread is None or not thread.is_alive():
return
log("Останавливается GPS-тест.")
service.stop()
if thread is not threading.current_thread():
thread.join()
log("GPS-тест завершён.")
def join_background_threads(app_module):
for name in (
"vendor_update_thread",
"vendor_recalc_thread"
):
thread = getattr(app_module, name, None)
if thread is None or thread is threading.current_thread():
continue
if thread.is_alive():
log(f"Ожидание фоновой задачи: {name}.")
thread.join()
log("Фоновые задачи завершены.")
def receive_sudo_authentication(shutdown_event):
runtime_dir = AUTH_SOCKET_PATH.parent
if not runtime_dir.is_dir():
raise LifecycleError(
f"Не найден runtime-каталог: {runtime_dir}"
)
if AUTH_SOCKET_PATH.exists() or AUTH_SOCKET_PATH.is_symlink():
try:
socket_info = AUTH_SOCKET_PATH.lstat()
except OSError as error:
raise LifecycleError(
f"Не удалось проверить Unix-сокет: {error}"
) from error
if (
not stat.S_ISSOCK(socket_info.st_mode)
or socket_info.st_uid != os.getuid()
):
raise LifecycleError(
f"Путь занят посторонним объектом: {AUTH_SOCKET_PATH}"
)
AUTH_SOCKET_PATH.unlink()
auth_socket = socket.socket(
socket.AF_UNIX,
socket.SOCK_STREAM
)
try:
auth_socket.bind(str(AUTH_SOCKET_PATH))
AUTH_SOCKET_PATH.chmod(0o600)
auth_socket.listen(1)
auth_deadline = time.monotonic() + STARTUP_TIMEOUT + 60
auth_socket.settimeout(POLL_INTERVAL)
log("Ожидание sudo-аутентификации от CLI...")
while True:
if shutdown_event.is_set():
raise LifecycleError(
"Ожидание sudo-аутентификации прервано остановкой."
)
if time.monotonic() >= auth_deadline:
raise LifecycleError(
"Не получен пароль sudo за отведённое время."
)
try:
connection, _ = auth_socket.accept()
break
except socket.timeout:
continue
with connection:
connection.settimeout(10)
password = bytearray()
while True:
chunk = connection.recv(1024)
if not chunk:
break
password.extend(chunk)
if len(password) > 4096:
raise LifecycleError(
"Получен недопустимо длинный пароль."
)
if not password:
connection.sendall(b"AUTH_FAILED")
raise LifecycleError(
"Получен пустой пароль sudo."
)
result = subprocess.run(
["sudo", "-S", "-p", "", "-v"],
input=bytes(password) + b"\n",
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
check=False
)
for index in range(len(password)):
password[index] = 0
if result.returncode != 0:
connection.sendall(b"AUTH_FAILED")
raise LifecycleError(
"sudo-аутентификация не пройдена."
)
connection.sendall(b"AUTH_OK")
log("sudo-аутентификация успешно пройдена.")
except socket.timeout as error:
raise LifecycleError(
"Не получен пароль sudo за отведённое время."
) from error
finally:
auth_socket.close()
try:
socket_info = AUTH_SOCKET_PATH.lstat()
if (
stat.S_ISSOCK(socket_info.st_mode)
and socket_info.st_uid == os.getuid()
):
AUTH_SOCKET_PATH.unlink()
except FileNotFoundError:
pass
def send_sudo_authentication():
deadline = time.monotonic() + STARTUP_TIMEOUT
connection = None
while connection is None:
if not unit_is_active():
raise LifecycleError(
"Менеджер завершился до подключения CLI. "
"Проверь журнал: "
f"journalctl --user -u {UNIT_NAME}.service"
)
if time.monotonic() >= deadline:
raise LifecycleError(
"Не удалось подключиться к сокету "
"sudo-аутентификации."
)
candidate = socket.socket(
socket.AF_UNIX,
socket.SOCK_STREAM
)
try:
candidate.settimeout(POLL_INTERVAL)
candidate.connect(str(AUTH_SOCKET_PATH))
connection = candidate
except OSError:
candidate.close()
time.sleep(POLL_INTERVAL)
password = ""
try:
password = getpass.getpass("Введите пароль sudo: ")
connection.settimeout(10)
connection.sendall(password.encode("utf-8") + b"\n")
password = ""
connection.shutdown(socket.SHUT_WR)
response = connection.recv(32)
finally:
password = ""
connection.close()
if response != b"AUTH_OK":
raise LifecycleError(
"Менеджер отклонил sudo-аутентификацию."
)
def run_server():
os.chdir(PROJECT_ROOT)
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
src_path = str(PROJECT_ROOT / "src")
if src_path not in sys.path:
sys.path.insert(0, src_path)
tileserver_process = None
server = None
server_thread = None
app_module = None
shutdown_event = threading.Event()
shutdown_started = False
def request_shutdown(signum, frame):
nonlocal shutdown_started
if shutdown_started:
return
shutdown_started = True
log("Получен сигнал завершения.")
if app_module is not None:
app_module.request_lifecycle.begin_shutdown()
shutdown_event.set()
signal.signal(signal.SIGTERM, request_shutdown)
signal.signal(signal.SIGINT, request_shutdown)
try:
receive_sudo_authentication(shutdown_event)
tileserver_process = start_tileserver()
from gui import app as app_module
if not app_module.check_sudo():
raise LifecycleError(
"sudo-аутентификация менеджера недоступна."
)
app_module.sudo_keepalive_stop_event.clear()
app_module.sudo_keepalive_thread = threading.Thread(
target=app_module.sudo_keepalive,
args=(app_module.sudo_keepalive_stop_event,),
name="sudo-keepalive",
daemon=True
)
app_module.sudo_keepalive_thread.start()
from werkzeug.serving import make_server
server = make_server(
APP_HOST,
APP_PORT,
app_module.app,
threaded=True
)
server_thread = threading.Thread(
target=server.serve_forever,
name="flask-server",
daemon=False
)
server_thread.start()
log(
f"Веб-интерфейс запущен: "
f"http://{APP_HOST}:{APP_PORT}"
)
shutdown_event.wait()
except Exception:
if app_module is not None:
app_module.request_lifecycle.begin_shutdown()
raise
finally:
if app_module is not None:
app_module.request_lifecycle.begin_shutdown()
log("Ожидание завершения активных HTTP-запросов.")
app_module.request_lifecycle.wait_for_drain()
stop_gps_test(app_module)
wait_for_scanner(app_module)
join_background_threads(app_module)
app_module.sudo_keepalive_stop_event.set()
keepalive = app_module.sudo_keepalive_thread
if (
keepalive is not None
and keepalive is not threading.current_thread()
):
keepalive.join()
if server is not None:
log("Остановка Flask-сервера.")
server.shutdown()
if server_thread is not None:
server_thread.join()
stop_owned_tileserver(tileserver_process)
log("Менеджер завершил работу.")
def run_sudo_validation():
try:
result = subprocess.run(
["sudo", "-v"],
check=False
)
except OSError as error:
raise LifecycleError(
f"Не удалось запустить sudo: {error}"
) from error
if result.returncode != 0:
raise LifecycleError(
"Проверка sudo не пройдена."
)
def systemctl_user(*arguments, check=True):
command = [
"systemctl",
"--user",
*arguments
]
return subprocess.run(
command,
check=check,
text=True,
capture_output=True
)
def active_service_project():
result = systemctl_user(
"show",
f"{UNIT_NAME}.service",
"--property=WorkingDirectory",
"--value",
check=False
)
if result.returncode != 0:
return None
working_directory = result.stdout.strip()
if not working_directory:
return None
try:
return Path(working_directory).resolve()
except (OSError, RuntimeError):
return None
def unit_is_active():
result = systemctl_user(
"is-active",
"--quiet",
f"{UNIT_NAME}.service",
check=False
)
return result.returncode == 0
def start_service():
if unit_is_active():
active_project = active_service_project()
if active_project is None:
raise LifecycleError(
"Сервис уже активен, но не удалось определить "
"каталог проекта. Второй экземпляр не будет запущен."
)
if active_project == PROJECT_ROOT:
log("Менеджер уже запущен из текущего проекта.")
else:
log(
"Менеджер уже запущен из другого проекта: "
f"{active_project}. Второй экземпляр не запущен."
)
return 0
if port_is_open(APP_HOST, APP_PORT):
raise LifecycleError(
f"Порт приложения {APP_PORT} занят. "
"Чужой процесс не будет остановлен."
)
python = project_python()
if not python.is_file():
raise LifecycleError(
f"Не найден Python виртуального окружения: {python}"
)
command = [
"systemd-run",
"--user",
f"--unit={UNIT_NAME}",
"--service-type=exec",
"--property=KillMode=process",
"--collect",
f"--working-directory={PROJECT_ROOT}",
str(python),
str(PROJECT_ROOT / "src" / "lifecycle_manager.py"),
"--serve"
]
subprocess.run(
command,
check=True
)
send_sudo_authentication()
deadline = time.monotonic() + STARTUP_TIMEOUT
while time.monotonic() < deadline:
if not unit_is_active():
raise LifecycleError(
"Сервис завершился во время запуска. "
"Проверь журнал: "
f"journalctl --user -u {UNIT_NAME}.service"
)
try:
with urllib.request.urlopen(
f"http://{APP_HOST}:{APP_PORT}/api/status",
timeout=1
) as response:
if response.status == 200:
log(
f"Приложение запущено: "
f"http://{APP_HOST}:{APP_PORT}"
)
return 0
except OSError:
pass
time.sleep(POLL_INTERVAL)
raise LifecycleError(
"Приложение не ответило за время запуска. "
f"Проверь journalctl --user -u {UNIT_NAME}.service"
)
def stop_service():
if not unit_is_active():
log("Менеджер не запущен.")
return 0
active_project = active_service_project()
if active_project is None:
raise LifecycleError(
"Не удалось определить проект работающего сервиса. "
"Остановка отменена."
)
if active_project != PROJECT_ROOT:
raise LifecycleError(
f"Сервис запущен из другого проекта: {active_project}. "
f"Остановка из {PROJECT_ROOT} отменена."
)
run_sudo_validation()
systemctl_user(
"kill",
"--kill-whom=main",
"--signal=SIGTERM",
f"{UNIT_NAME}.service"
)
log(
"Запрошено штатное завершение. "
"Если сканер активен, останови его в веб-интерфейсе."
)
notified = False
while unit_is_active():
if not notified:
log(
"Ожидание завершения приложения и фоновых задач..."
)
notified = True
time.sleep(1)
log("Сервис остановлен.")
return 0
def show_status():
active = unit_is_active()
print(
"Application:",
"RUNNING" if active else "STOPPED"
)
if active:
active_project = active_service_project()
print(
"Active project:",
active_project if active_project is not None else "UNKNOWN"
)
if active:
try:
with urllib.request.urlopen(
f"http://{APP_HOST}:{APP_PORT}/api/status",
timeout=2
) as response:
data = json.loads(
response.read().decode("utf-8")
)
scanner = data.get("status", {})
gps = data.get("gps_test", {})
scanner_running = scanner.get("running", False)
scanner_health = scanner.get("health", "unknown")
scanner_pid = scanner.get("pid")
if scanner_running:
scanner_state = (
f"RUNNING (PID {scanner_pid}, "
f"health: {scanner_health})"
)
else:
scanner_state = (
f"STOPPED (health: {scanner_health})"
)
print("Scanner:", scanner_state)
print(
"GPS test:",
gps.get("state", "unknown")
)
print(
"Network action:",
"BUSY" if data.get("network_actions_busy") else "IDLE"
)
except Exception as error:
print(f"Application API: unavailable ({error})")
print(
"TileServer:",
"AVAILABLE" if style_is_available() else "UNAVAILABLE"
)
if active:
result = systemctl_user(
"show",
f"{UNIT_NAME}.service",
"--property=MainPID",
"--property=ActiveState",
check=False
)
if result.returncode == 0:
print(result.stdout.strip())
def install():
python = project_python()
if not python.is_file():
raise LifecycleError(
f"Не найдено виртуальное окружение: {python}"
)
if shutil.which("systemd-run") is None:
raise LifecycleError("Не найден systemd-run.")
if shutil.which("systemctl") is None:
raise LifecycleError("Не найден systemctl.")
if shutil.which("sudo") is None:
raise LifecycleError("Не найден sudo.")
if shutil.which("node") is None:
raise LifecycleError("Не найден Node.js.")
if not TILESERVER_ENTRY.is_file():
raise LifecycleError(
f"Не найден TileServer entry point: {TILESERVER_ENTRY}"
)
if not TILESERVER_CONFIG_PATH.is_file():
raise LifecycleError(
"Не найден TileServer config: "
f"{TILESERVER_CONFIG_PATH}"
)
check = subprocess.run(
[
str(python),
"-c",
"import flask, werkzeug"
],
check=False
)
if check.returncode != 0:
raise LifecycleError(
"Flask или Werkzeug недоступны в venv."
)
cli_path = PROJECT_ROOT / "wifi-gps-mapper"
if not cli_path.is_file():
raise LifecycleError(
f"Не найден CLI-файл: {cli_path}"
)
cli_path.chmod(
cli_path.stat().st_mode | 0o111
)
systemctl_user("show-environment")
log("Проверка окружения пройдена.")
log(f"CLI: {cli_path}")
log("TileServer не устанавливался и не изменялся.")
def main():
parser = argparse.ArgumentParser(
prog="wifi-gps-mapper"
)
parser.add_argument(
"--serve",
action="store_true",
help=argparse.SUPPRESS
)
parser.add_argument(
"command",
nargs="?",
choices=(
"install",
"start",
"status",
"stop",
"restart"
)
)
args = parser.parse_args()
try:
if args.serve:
run_server()
return 0
if args.command == "install":
install()
return 0
if args.command == "start":
return start_service()
if args.command == "status":
show_status()
return 0
if args.command == "stop":
return stop_service()
if args.command == "restart":
stop_service()
return start_service()
parser.print_help()
return 2
except (
LifecycleError,
subprocess.CalledProcessError,
OSError
) as error:
print(
f"Ошибка: {error}",
file=sys.stderr
)
return 1
if __name__ == "__main__":
raise SystemExit(main())
+47
View File
@@ -0,0 +1,47 @@
import logging
from pathlib import Path
from logging_config import (
LOG_DATE_FORMAT,
LOG_FORMAT,
UTCFormatter,
)
def setup_logger():
Path(
"logs"
).mkdir(
exist_ok=True
)
file_handler = logging.FileHandler(
"logs/project.log"
)
console_handler = logging.StreamHandler()
for handler in (
file_handler,
console_handler,
):
handler.setFormatter(
UTCFormatter(
LOG_FORMAT,
datefmt=LOG_DATE_FORMAT,
)
)
logging.basicConfig(
level=logging.INFO,
handlers=[
file_handler,
console_handler,
],
)
return logging.getLogger(
"project-wifi"
)
+16
View File
@@ -0,0 +1,16 @@
import logging
import time
LOG_FORMAT = (
"%(asctime)s.%(msecs)03dZ "
"[%(levelname)s] "
"%(name)s: "
"%(message)s"
)
LOG_DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"
class UTCFormatter(logging.Formatter):
converter = staticmethod(time.gmtime)
+496
View File
@@ -0,0 +1,496 @@
import signal
import sys
import time
import logging
from config import Config
from database import Database
from gps import GPSManager, create_gps_source
from gps_test import run_gps_test
from logger import setup_logger
from network import NetworkManagerControl
from wifi import WiFiManager
from session import Session
from environment import EnvironmentChecker
from sudo import SudoChecker
# ============================================================
# Инициализация
# ============================================================
cfg = Config()
if "--gps-test" in sys.argv:
sudo_checker = SudoChecker()
sudo_checker.check()
sys.exit(
run_gps_test(
cfg
)
)
logger = setup_logger()
logger.info(
"Project started"
)
# ============================================================
# Проверка окружения
# ============================================================
try:
environment = EnvironmentChecker(
cfg
)
environment.check()
sudo_checker = SudoChecker()
sudo_checker.check()
cfg.select_interface()
logger.info(
f"WiFi interface: {cfg.interface}"
)
except KeyboardInterrupt:
logger.info(
"Startup cancelled"
)
sys.exit(0)
# ============================================================
# Network
# ============================================================
network = NetworkManagerControl(
cfg.interface
)
wifi = None
gps = None
session = None
db = None
parser = None
session_id = None
network_prepared = False
shutdown_requested = False
scanner_state = "READY"
def set_scanner_state(state):
global scanner_state
if scanner_state == state:
return
scanner_state = state
print(
f"ScannerState: {state}",
flush=True
)
def shutdown(signum=None, frame=None):
global shutdown_requested
global network_prepared
if shutdown_requested:
return
shutdown_requested = True
set_scanner_state(
"STOPPED"
)
logger.info(
"Shutdown requested"
)
try:
if wifi:
wifi.stop()
except Exception as error:
logger.error(
f"WiFi stop error: {error}"
)
try:
if parser and session:
parser.parse(
session,
session_id
)
except Exception as error:
logger.error(
f"Parser error: {error}"
)
try:
if gps:
gps.stop()
except Exception as error:
logger.error(
f"GPS stop error: {error}"
)
try:
if (db and session_id is not None):
db.flush_observations()
db.finalize_session(
session_id
)
db.commit()
except Exception as error:
logger.error(
f"Database finalize error: {error}"
)
try:
if network_prepared:
network.restore()
except Exception as error:
logger.error(
f"Network restore error: {error}"
)
try:
if db:
db.close()
except Exception:
pass
logger.info(
"Project stopped"
)
sys.exit(0)
signal.signal(
signal.SIGINT,
shutdown
)
signal.signal(
signal.SIGTERM,
shutdown
)
from parser import CaptureParser
# ============================================================
# Подготовка оборудования
# ============================================================
try:
network_prepared = True
network.prepare()
# ============================================================
# Сессия
# ============================================================
session = Session(
cfg.capture_directory
)
logger.info(
f"Session directory: {session.path}"
)
logger.info(
f"Capture file: {session.capture_file}"
)
logger.info(
f"GPS track: {session.gps_file}"
)
# ============================================================
# Database
# ============================================================
db = Database(
cfg.database
)
logger.info(
"SQLite initialized"
)
parser = CaptureParser(
cfg,
db
)
session_id = db.create_session(
str(session.capture_file)
)
session.id = session_id
wifi = WiFiManager(
cfg,
session,
cfg.interface
)
gps_source = create_gps_source(
cfg
)
gps = GPSManager(
gps_source,
session
)
wifi.start()
gps.start()
set_scanner_state(
"ACTIVE"
)
except KeyboardInterrupt:
logger.info(
"Startup cancelled"
)
shutdown()
except Exception as error:
logger.error(
f"Startup error: {error}"
)
shutdown()
# ============================================================
# Главный цикл
# ============================================================
last_status = 0
last_capture_size = 0
capture_stall_count = 0
last_sudo_keepalive = time.time()
sudo_keepalive_interval = 60
while True:
now = time.time()
if (
now - last_sudo_keepalive
>= sudo_keepalive_interval
):
if sudo_checker.refresh():
logger.debug(
"Sudo keepalive: OK"
)
else:
logger.warning(
"WARNING: sudo keepalive failed"
)
last_sudo_keepalive = now
if wifi and wifi.process:
return_code = wifi.process.poll()
if return_code is not None:
if return_code == 0:
logger.info(
"hcxdumptool finished"
)
else:
logger.error(
f"hcxdumptool exited with code {return_code}"
)
shutdown()
if ( now - last_status >= cfg.status_interval ):
capture_bytes = 0
try:
capture_bytes = ( session.capture_file.stat().st_size )
except Exception:
pass
#
# контроль роста capture.pcapng
#
if last_capture_size:
if capture_bytes <= last_capture_size:
capture_stall_count += 1
else:
capture_stall_count = 0
last_capture_size = capture_bytes
capture_size = ( capture_bytes / 1024 )
capture_text = ( f"{capture_size:.1f}KB")
pid = "-"
if wifi and wifi.process:
pid = wifi.process.pid
gps_data = session.current_gps
if gps_data:
logger.info(
"Status: "
f"elapsed={session.elapsed()}s "
f"nmea={session.nmea_messages} "
f"gps={session.gps_positions} "
f"lat={gps_data.latitude:.6f} "
f"lon={gps_data.longitude:.6f} "
f"capture={capture_text} "
f"pid={pid}"
)
else:
logger.info(
"Status: "
f"elapsed={session.elapsed()}s "
f"nmea={session.nmea_messages} "
f"gps={session.gps_positions} "
f"capture={capture_text} "
f"pid={pid} "
"gps=no signal"
)
last_status = now
if capture_stall_count >= 3:
logger.warning(
"WARNING: capture file is not growing"
)
set_scanner_state(
"WARNING"
)
else:
set_scanner_state(
"ACTIVE"
)
time.sleep(1)
+11
View File
@@ -0,0 +1,11 @@
from dataclasses import dataclass
from datetime import datetime
@dataclass
class GPSData:
latitude: float
longitude: float
speed: float
timestamp: datetime
valid: bool
+210
View File
@@ -0,0 +1,210 @@
import logging
import subprocess
class NetworkManagerControl:
def __init__(self, interface):
self.interface = interface
self.log = logging.getLogger(
"network"
)
self.restore_networkmanager = False
self.restore_wpa = False
def _run(self, command):
subprocess.run(
[
"sudo",
"-n"
]
+
command,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
def _is_active(self, service):
result = subprocess.run(
[
"systemctl",
"is-active",
service
],
capture_output=True,
text=True
)
return (
result.stdout.strip()
==
"active"
)
def prepare(self):
self.restore_networkmanager = self._is_active(
"NetworkManager"
)
self.restore_wpa = self._is_active(
"wpa_supplicant"
)
self.log.info(
f"NetworkManager : {'running' if self.restore_networkmanager else 'stopped'}"
)
self.log.info(
f"wpa_supplicant : {'running' if self.restore_wpa else 'stopped'}"
)
if self.restore_networkmanager:
self._run(
[
"systemctl",
"stop",
"NetworkManager"
]
)
if self.restore_wpa:
self._run(
[
"systemctl",
"stop",
"wpa_supplicant"
]
)
self.log.info(
"Network services stopped"
)
def restore(self):
self.log.info(
"Restoring WiFi interface"
)
self._run(
[
"ip",
"link",
"set",
self.interface,
"down"
]
)
self._run(
[
"iw",
"dev",
self.interface,
"set",
"type",
"managed"
]
)
self._run(
[
"ip",
"link",
"set",
self.interface,
"up"
]
)
self.log.info(
"WiFi interface restored to managed mode"
)
if self.restore_wpa:
self._run(
[
"systemctl",
"start",
"wpa_supplicant"
]
)
if self.restore_networkmanager:
self._run(
[
"systemctl",
"start",
"NetworkManager"
]
)
if self.restore_networkmanager:
self._run(
[
"nmcli",
"device",
"set",
self.interface,
"managed",
"yes"
]
)
self._run(
[
"nmcli",
"device",
"connect",
self.interface
]
)
self.log.info(
"Network services restored"
)
+1236
View File
File diff suppressed because it is too large Load Diff
+220
View File
@@ -0,0 +1,220 @@
import threading
import time
class RequestLifecycleMiddleware:
ALLOWED_DURING_SHUTDOWN = {
("GET", "/"),
("HEAD", "/"),
("GET", "/api/status"),
("GET", "/api/gps-test"),
("POST", "/scanner/stop"),
("POST", "/gps-test/stop"),
}
UNTRACKED_DURING_SHUTDOWN = {
("GET", "/"),
("HEAD", "/"),
("GET", "/api/status"),
("GET", "/api/gps-test"),
}
STATIC_PREFIXES = (
"/static/",
"/reports/static/",
)
def __init__(self, application):
self.application = application
self._condition = threading.Condition()
self._shutdown_requested = False
self._active_requests = 0
@property
def shutdown_requested(self):
with self._condition:
return self._shutdown_requested
@property
def active_requests(self):
with self._condition:
return self._active_requests
def begin_shutdown(self):
with self._condition:
self._shutdown_requested = True
self._condition.notify_all()
def wait_for_drain(self, timeout=None):
deadline = (
None
if timeout is None
else time.monotonic() + timeout
)
with self._condition:
while self._active_requests:
remaining = (
None
if deadline is None
else deadline - time.monotonic()
)
if remaining is not None and remaining <= 0:
return False
self._condition.wait(remaining)
return True
def _is_allowed_during_shutdown(self, method, path):
if (method, path) in self.ALLOWED_DURING_SHUTDOWN:
return True
if method not in ("GET", "HEAD"):
return False
return any(
path.startswith(prefix)
for prefix in self.STATIC_PREFIXES
)
def _release_request(self):
with self._condition:
self._active_requests -= 1
self._condition.notify_all()
def __call__(self, environ, start_response):
method = environ.get("REQUEST_METHOD", "GET").upper()
path = environ.get("PATH_INFO", "/")
track_request = True
with self._condition:
if self._shutdown_requested:
if not self._is_allowed_during_shutdown(
method,
path
):
body = b"Application is shutting down.\n"
start_response(
"503 Service Unavailable",
[
("Content-Type", "text/plain; charset=utf-8"),
("Content-Length", str(len(body))),
("Retry-After", "5"),
("Cache-Control", "no-store"),
]
)
return [body]
if (
(method, path) in self.UNTRACKED_DURING_SHUTDOWN
or (
method in ("GET", "HEAD")
and any(
path.startswith(prefix)
for prefix in self.STATIC_PREFIXES
)
)
):
track_request = False
if track_request:
self._active_requests += 1
if not track_request:
return self.application(
environ,
start_response
)
try:
response = self.application(
environ,
start_response
)
except BaseException:
self._release_request()
raise
return _TrackedIterable(
response,
self._release_request
)
class _TrackedIterable:
def __init__(self, iterable, release):
self._iterable = iterable
self._iterator = iter(iterable)
self._release = release
self._closed = False
def __iter__(self):
return self
def __next__(self):
try:
return next(self._iterator)
except BaseException:
self.close()
raise
def close(self):
if self._closed:
return
self._closed = True
try:
close = getattr(
self._iterable,
"close",
None
)
if close is not None:
close()
finally:
self._release()
+277
View File
@@ -0,0 +1,277 @@
from datetime import datetime, timezone
from pathlib import Path
class Session:
"""
Управление текущей сессией захвата.
Одна сессия содержит:
- pcapng захват
- GPS трек
- результаты парсинга
- hashcat файлы
Все данные одной поездки находятся
внутри одного каталога.
"""
def __init__(
self,
directory
):
#
# Время запуска
#
self.start_time = datetime.now(
timezone.utc
)
#
# Каталог сессии
#
name = self.start_time.strftime(
"%Y%m%d_%H%M%S"
)
self.path = (
Path(directory) / name
)
self.path.mkdir(
parents=True,
exist_ok=True
)
# =====================================================
# Основной захват
# =====================================================
self.capture_file = (
self.path /
"capture.pcapng"
)
# =====================================================
# GPS
# =====================================================
self.gps_file = (
self.path /
"gps_track.nmea"
)
# =====================================================
# Результаты hcxpcapngtool
# =====================================================
#
# Список точек доступа
#
self.access_points_file = (
self.path /
"access_points.csv"
)
#
# Hashcat формат
#
# WPA-PBKDF2-PMKID+EAPOL
#
self.handshakes_file = (
self.path /
"handshakes.22000"
)
#
# ESSID список
#
self.essid_file = (
self.path /
"essid.txt"
)
#
# Identity список
#
self.identity_file = (
self.path /
"identities.txt"
)
#
# Лог работы парсера
#
self.parser_log = (
self.path /
"parser.log"
)
# =====================================================
# Статистика текущей сессии
# =====================================================
#
# Все NMEA сообщения
#
self.nmea_messages = 0
#
# Валидные GPS позиции
#
self.gps_positions = 0
#
# Последняя координата
#
self.current_gps = None
@classmethod
def from_existing(
cls,
path
):
"""
Открывает уже существующую
сессию из каталога captures.
"""
obj = cls.__new__(cls)
obj.start_time = datetime.now(
timezone.utc
)
obj.path = Path(path)
obj.capture_file = (
obj.path /
"capture.pcapng"
)
obj.gps_file = (
obj.path /
"gps_track.nmea"
)
obj.access_points_file = (
obj.path /
"access_points.csv"
)
obj.handshakes_file = (
obj.path /
"handshakes.22000"
)
obj.essid_file = (
obj.path /
"essid.txt"
)
obj.identity_file = (
obj.path /
"identities.txt"
)
obj.parser_log = (
obj.path /
"parser.log"
)
obj.nmea_messages = 0
obj.gps_positions = 0
obj.current_gps = None
return obj
# =========================================================
# Время работы
# =========================================================
def elapsed(
self
):
return int(
(
datetime.now(
timezone.utc
)
-
self.start_time
).total_seconds()
)
# =========================================================
# GPS статистика
# =========================================================
def add_nmea(self):
"""
Увеличить счетчик
полученных NMEA сообщений.
"""
self.nmea_messages += 1
def update_gps(
self,
gps
):
"""
Обновить последнюю GPS координату.
"""
self.current_gps = gps
self.gps_positions += 1
+77
View File
@@ -0,0 +1,77 @@
import logging
import subprocess
import sys
class SudoChecker:
def __init__(self):
self.log = logging.getLogger(
"sudo"
)
def check(self):
self.log.info(
"Checking sudo..."
)
try:
result = subprocess.run(
[
"sudo",
"-n",
"-v"
]
)
if result.returncode != 0:
result = subprocess.run(
[
"sudo",
"-v"
]
)
except KeyboardInterrupt:
self.log.error(
"Sudo authentication cancelled."
)
raise SystemExit(1)
if result.returncode != 0:
self.log.error(
"Sudo authentication is not available."
)
raise SystemExit(1)
self.log.info(
"Sudo: OK"
)
def refresh(self):
try:
result = subprocess.run(
[
"sudo",
"-n",
"-v"
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
except Exception:
return False
return result.returncode == 0
+105
View File
@@ -0,0 +1,105 @@
"""
Shared TileServer configuration loader.
"""
import os
from pathlib import Path
import yaml
DEFAULT_ENTRY = "node_modules/tileserver-gl-light/src/main.js"
DEFAULT_CONFIG = "config.json"
DEFAULT_STYLE = "server-map"
def load_tileserver_config(project_root):
project_root = Path(project_root).expanduser().resolve()
config_file = project_root / "config" / "config.yaml"
try:
with config_file.open("r", encoding="utf-8") as file:
application_config = yaml.safe_load(file) or {}
except (OSError, yaml.YAMLError) as error:
raise RuntimeError(
f"Не удалось загрузить конфигурацию {config_file}: {error}"
) from error
if not isinstance(application_config, dict):
raise RuntimeError(
"Корень config/config.yaml должен быть YAML-объектом."
)
section = application_config.get("tileserver", {})
if not isinstance(section, dict):
raise RuntimeError(
"Раздел tileserver в config/config.yaml должен быть YAML-объектом."
)
directory_value = os.environ.get(
"WIFI_GPS_TILESERVER_DIR",
section.get("directory", "map-server")
)
directory = Path(directory_value).expanduser()
if "WIFI_GPS_TILESERVER_DIR" not in os.environ and not directory.is_absolute():
directory = project_root / directory
directory = directory.resolve()
entry_from_environment = "WIFI_GPS_TILESERVER_ENTRY" in os.environ
entry_value = os.environ.get(
"WIFI_GPS_TILESERVER_ENTRY",
section.get("entry", DEFAULT_ENTRY)
)
entry = Path(entry_value).expanduser()
if not entry.is_absolute() and not entry_from_environment:
entry = directory / entry
config_value = os.environ.get(
"WIFI_GPS_TILESERVER_CONFIG",
section.get("config", DEFAULT_CONFIG)
)
config = Path(config_value).expanduser()
config_path = config if config.is_absolute() else directory / config
host = str(section.get("host", "127.0.0.1")).strip()
try:
port = int(
os.environ.get(
"WIFI_GPS_TILESERVER_PORT",
section.get("port", 8080)
)
)
except (TypeError, ValueError) as error:
raise RuntimeError("Некорректный порт TileServer.") from error
if not host:
raise RuntimeError("Не задан host для TileServer.")
if not 1 <= port <= 65535:
raise RuntimeError(f"Некорректный порт TileServer: {port}")
style = str(section.get("style", DEFAULT_STYLE)).strip().strip("/")
if not style:
raise RuntimeError("Не задан style для TileServer.")
return {
"host": host,
"port": port,
"directory": directory,
"entry": entry,
"config": str(config),
"config_path": config_path,
"style": style,
"style_url": (
f"http://{host}:{port}/styles/{style}/style.json"
),
}
+714
View File
@@ -0,0 +1,714 @@
import sqlite3
from pathlib import Path
class VendorResolver:
def __init__(
self,
database,
writable=False
):
self.db_path = Path(database)
self.writable = writable
if writable:
self.db_path.parent.mkdir(
parents=True,
exist_ok=True
)
self.conn = sqlite3.connect(
self.db_path
)
self.create_tables()
else:
self.conn = sqlite3.connect(
f"{self.db_path.resolve().as_uri()}?mode=ro",
uri=True
)
self.conn.execute(
"SELECT 1 FROM oui LIMIT 0"
)
# =====================================================
# Создание структуры
# =====================================================
def create_tables(self):
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS oui
(
prefix TEXT PRIMARY KEY,
vendor TEXT NOT NULL,
confidence TEXT NOT NULL,
prefix_length INTEGER NOT NULL
)
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS metadata
(
key TEXT PRIMARY KEY,
value TEXT NOT NULL
)
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS metadata
(
key TEXT PRIMARY KEY,
value TEXT
)
"""
)
self.conn.execute(
"""
CREATE INDEX IF NOT EXISTS idx_prefix
ON oui(prefix)
"""
)
self.conn.execute(
"""
CREATE TABLE IF NOT EXISTS metadata
(
key TEXT PRIMARY KEY,
value TEXT
)
"""
)
self.conn.commit()
# =====================================================
# Определение производителя
# =====================================================
def lookup(
self,
mac
):
if not mac:
return None
mac = self.normalize(
mac
)
for length in (
9,
7,
6
):
prefix = mac[:length]
cursor = self.conn.execute(
"""
SELECT vendor
FROM oui
WHERE prefix=?
""",
(
prefix,
)
)
row = cursor.fetchone()
if row:
return row[0]
return "Unknown"
# =====================================================
# Добавление производителя
# =====================================================
def add_vendor(
self,
prefix,
vendor,
confidence="IEEE"
):
prefix = self.normalize(prefix)
if not prefix:
return False
prefix_length = len(prefix)
if prefix_length not in (6,7,9):
return False
self.conn.execute(
"""
INSERT OR REPLACE INTO oui
(
prefix,
vendor,
confidence,
prefix_length
)
VALUES (?,?,?,?)
""",
(
prefix,
vendor,
confidence,
prefix_length
)
)
return True
# =====================================================
# Сохранение изменений
# =====================================================
def commit(self):
self.conn.commit()
# =====================================================
# Количество записей
# =====================================================
def count(self):
cursor = self.conn.execute(
"SELECT COUNT(*) FROM oui"
)
return cursor.fetchone()[0]
# =====================================================
# Metadata
# =====================================================
def get_metadata(
self,
key,
default=None
):
cursor = self.conn.execute(
"""
SELECT value
FROM metadata
WHERE key=?
""",
(
key,
)
)
row = cursor.fetchone()
if row:
return row[0]
return default
def set_metadata(
self,
key,
value
):
self.conn.execute(
"""
INSERT OR REPLACE INTO metadata
(
key,
value
)
VALUES (?,?)
""",
(
key,
str(value)
)
)
# =====================================================
# Получить значение metadata
# =====================================================
def get_metadata(
self,
key
):
cursor = self.conn.execute(
"""
SELECT value
FROM metadata
WHERE key=?
""",
(
key,
)
)
row = cursor.fetchone()
if row:
return row[0]
return None
# =====================================================
# Сохранение metadata
# =====================================================
def set_metadata(
self,
key,
value
):
self.conn.execute(
"""
INSERT OR REPLACE INTO metadata
(
key,
value
)
VALUES (?,?)
""",
(
key,
str(value)
)
)
# =====================================================
# Записать значение metadata
# =====================================================
def set_metadata(
self,
key,
value
):
self.conn.execute(
"""
INSERT OR REPLACE INTO metadata
(
key,
value
)
VALUES
(
?,
?
)
""",
(
key,
str(value)
)
)
# =====================================================
# Удаление metadata
# =====================================================
def delete_metadata(
self,
key
):
self.conn.execute(
"""
DELETE
FROM metadata
WHERE key=?
""",
(
key,
)
)
# =====================================================
# Есть ли база производителей
# =====================================================
def has_database(self):
cursor = self.conn.execute(
"""
SELECT COUNT(*)
FROM oui
"""
)
return cursor.fetchone()[0] > 0
# =====================================================
# Требуется обновление
# =====================================================
def update_available(self):
value = self.get_metadata(
"update_available"
)
return value == "1"
# =====================================================
# Получение параметра metadata
# =====================================================
def get_metadata(
self,
key
):
cursor = self.conn.execute(
"""
SELECT value
FROM metadata
WHERE key=?
""",
(
key,
)
)
row = cursor.fetchone()
if row:
return row[0]
return None
# =====================================================
# Запись параметра metadata
# =====================================================
def set_metadata(
self,
key,
value
):
self.conn.execute(
"""
INSERT OR REPLACE INTO metadata
(
key,
value
)
VALUES
(
?,
?
)
""",
(
key,
str(value)
)
)
# =====================================================
# Получение всех параметров metadata
# =====================================================
def get_all_metadata(
self
):
cursor = self.conn.execute(
"""
SELECT
key,
value
FROM metadata
"""
)
result = {}
for row in cursor.fetchall():
result[
row[0]
] = row[1]
return result
# =====================================================
# Удаление параметра metadata
# =====================================================
def delete_metadata(
self,
key
):
self.conn.execute(
"""
DELETE
FROM metadata
WHERE key=?
""",
(
key,
)
)
# =====================================================
# Проверка metadata
# =====================================================
def has_metadata(
self,
key
):
cursor = self.conn.execute(
"""
SELECT 1
FROM metadata
WHERE key=?
LIMIT 1
""",
(
key,
)
)
return cursor.fetchone() is not None
# =====================================================
# Приведение MAC
# =====================================================
def normalize(
self,
mac
):
if not mac:
return None
mac = mac.replace(
":",
""
)
mac = mac.replace(
"-",
""
)
mac = mac.replace(
".",
""
)
mac = mac.upper()
return mac
# =====================================================
# Получение metadata
# =====================================================
def get_metadata(
self,
key,
default=None
):
cursor = self.conn.execute(
"""
SELECT value
FROM metadata
WHERE key=?
""",
(
key,
)
)
row = cursor.fetchone()
if row:
return row[0]
return default
# =====================================================
# Закрытие
# =====================================================
def close(self):
self.conn.close()
File diff suppressed because it is too large Load Diff
+194
View File
@@ -0,0 +1,194 @@
import logging
import subprocess
import signal
import shlex
class WiFiManager:
def __init__(
self,
config,
session,
interface
):
self.config = config
self.session = session
self.interface = interface
self.process = None
self.log = logging.getLogger(
"wifi"
)
cmd = [
"sudo",
"-n",
str(self.config.hcxdumptool),
"-i",
self.interface,
"-w",
str(self.session.capture_file),
]
#
# Каналы WiFi
#
# Каналы собираются отдельно для каждого
# включённого диапазона.
#
# a - диапазон 2.4 GHz
# b - диапазон 5 GHz
# c - диапазон 6 GHz
#
channels = []
if self.config.wifi_enable_2_4ghz:
if self.config.wifi_channels_2_4ghz:
channels.append(
self.config.wifi_channels_2_4ghz
)
if self.config.wifi_enable_5ghz:
if self.config.wifi_channels_5ghz:
channels.append(
self.config.wifi_channels_5ghz
)
if self.config.wifi_enable_6ghz:
if self.config.wifi_channels_6ghz:
channels.append(
self.config.wifi_channels_6ghz
)
if channels:
cmd.extend(
[
"-c",
",".join(channels)
]
)
#
# Дополнительные параметры
#
# Берутся из config.yaml
#
# Позволяют добавлять новые ключи
# без изменения программы
#
if self.config.wifi_extra_args:
cmd.extend(
shlex.split(
self.config.wifi_extra_args
)
)
self.cmd = cmd
def start(self):
if self.process is not None:
return
self.log.info(
"Starting hcxdumptool"
)
self.log.debug(
"Command: %s",
" ".join(self.cmd)
)
self.process = subprocess.Popen(
self.cmd
)
self.log.info(
"hcxdumptool started, pid=%s",
self.process.pid
)
def stop(self):
if not self.process:
return
self.log.info(
"Stopping hcxdumptool"
)
self.process.send_signal(
signal.SIGTERM
)
try:
self.process.wait(
timeout=10
)
self.log.info(
"hcxdumptool stopped with code %s",
self.process.returncode
)
except subprocess.TimeoutExpired:
self.log.warning(
"hcxdumptool did not stop, killing..."
)
self.process.kill()
self.process.wait(
timeout=5
)
self.process = None
File diff suppressed because it is too large Load Diff
+94
View File
@@ -0,0 +1,94 @@
from pathlib import Path
class WiFiInterfaceDetector:
def detect(self):
interfaces = []
network_directory = Path(
"/sys/class/net"
)
for interface in sorted(
network_directory.iterdir()
):
wireless_directory = (
interface
/
"wireless"
)
if wireless_directory.exists():
interfaces.append(
interface.name
)
if not interfaces:
raise RuntimeError(
"No WiFi interfaces found."
)
if len(interfaces) == 1:
return interfaces[0]
print()
print(
"Available WiFi interfaces:"
)
print()
for index, interface in enumerate(
interfaces,
start=1
):
print(
f"{index}. {interface}"
)
print()
while True:
answer = input(
"Select interface: "
)
try:
number = int(
answer
)
except ValueError:
continue
if (
1
<=
number
<=
len(interfaces)
):
return interfaces[
number - 1
]
+2731
View File
File diff suppressed because it is too large Load Diff