Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cec80c2b48 | ||
|
|
9682cc5b49 | ||
|
|
ab5c69b8c6 | ||
|
|
08bb7f5c45 |
+2
-2
@@ -60,7 +60,7 @@ wifi-gps-mapper-releases-build/
|
||||
Перед установкой необходимо:
|
||||
|
||||
1. Подготовить компьютер под управлением Debian/Linux.
|
||||
2. Скопировать на него релизную сборку WiFi GPS Mapper.
|
||||
2. Клонировать на него релизную сборку WiFi GPS Mapper.
|
||||
3. Убедиться, что пользователь имеет права на запись в каталог проекта.
|
||||
4. Обеспечить подключение к интернету для загрузки недостающих зависимостей и данных.
|
||||
5. Убедиться в наличии Python 3 и возможности создания виртуального окружения.
|
||||
@@ -78,7 +78,7 @@ wifi-gps-mapper-releases-build/
|
||||
Перейдите в каталог релизной сборки:
|
||||
|
||||
```bash
|
||||
cd ~/Projects/wifi-gps-mapper-releases-build
|
||||
cd ~/Projects/wifi-gps-mapper-releases
|
||||
```
|
||||
|
||||
Запустите установщик:
|
||||
|
||||
@@ -52,6 +52,23 @@ does not already exist.
|
||||
Local configuration, databases, captures and generated map data
|
||||
are not part of the source repository.
|
||||
|
||||
## Network scanning and connection verification
|
||||
|
||||
An active VPN connection may affect Wi-Fi scanning, local network
|
||||
reachability and Wi-Fi connection verification.
|
||||
|
||||
The application can detect active VPN connections managed by
|
||||
NetworkManager and display an advisory warning. VPN connections
|
||||
started outside NetworkManager may not be detected.
|
||||
|
||||
It is recommended to disable VPN connections while scanning Wi-Fi
|
||||
networks and performing Wi-Fi connection verification. Results
|
||||
cannot be guaranteed when a VPN is active.
|
||||
|
||||
The warning is advisory only. The application does not block user
|
||||
actions, disconnect VPN connections, modify VPN settings or attempt
|
||||
to restore a previous VPN state.
|
||||
|
||||
## License
|
||||
|
||||
WiFi GPS Mapper is distributed under the MIT License.
|
||||
|
||||
+1960
-178
File diff suppressed because it is too large
Load Diff
+1530
-1
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+83
-1
@@ -62,6 +62,82 @@ fail() {
|
||||
exit 1
|
||||
}
|
||||
|
||||
package_installed() {
|
||||
dpkg-query -W -f='${db:Status-Status}' "$1" 2>/dev/null | grep -qx installed
|
||||
}
|
||||
|
||||
install_gpsrelay_system_dependencies() {
|
||||
local -a packages=(iproute2 nmap netcat-openbsd)
|
||||
local -a commands=(ip nmap nc)
|
||||
local -a missing_packages=()
|
||||
local -a reinstall_packages=()
|
||||
local -a sudo_cmd=()
|
||||
local package executable
|
||||
local index
|
||||
|
||||
echo "Проверка системных зависимостей GPSRelay..."
|
||||
|
||||
for index in "${!packages[@]}"; do
|
||||
package="${packages[$index]}"
|
||||
executable="${commands[$index]}"
|
||||
|
||||
if command -v "$executable" >/dev/null 2>&1; then
|
||||
if package_installed "$package"; then
|
||||
echo "[OK] $executable доступна, пакет $package установлен."
|
||||
else
|
||||
echo "[OK] $executable доступна; пакет $package не зарегистрирован, установка не требуется."
|
||||
fi
|
||||
elif package_installed "$package"; then
|
||||
echo "[FIX] Пакет $package установлен, но команда $executable отсутствует."
|
||||
reinstall_packages+=("$package")
|
||||
else
|
||||
echo "[MISSING] Не найдена команда $executable (пакет $package)."
|
||||
missing_packages+=("$package")
|
||||
fi
|
||||
done
|
||||
|
||||
if (( ${#missing_packages[@]} == 0 && ${#reinstall_packages[@]} == 0 )); then
|
||||
echo "[OK] Все системные зависимости GPSRelay доступны."
|
||||
return 0
|
||||
fi
|
||||
|
||||
command -v apt-get >/dev/null 2>&1 ||
|
||||
fail "Для установки системных зависимостей GPSRelay требуется apt-get."
|
||||
|
||||
if (( EUID != 0 )); then
|
||||
command -v sudo >/dev/null 2>&1 ||
|
||||
fail "Для установки системных зависимостей GPSRelay необходим root или sudo."
|
||||
|
||||
sudo_cmd=(sudo)
|
||||
fi
|
||||
|
||||
log "ОБНОВЛЕНИЕ СПИСКА ПАКЕТОВ GPSRELAY"
|
||||
|
||||
"${sudo_cmd[@]}" apt-get update ||
|
||||
fail "Не удалось обновить список пакетов для GPSRelay."
|
||||
|
||||
if (( ${#missing_packages[@]} > 0 )); then
|
||||
log "УСТАНОВКА СИСТЕМНЫХ ЗАВИСИМОСТЕЙ GPSRELAY"
|
||||
|
||||
"${sudo_cmd[@]}" apt-get install -y "${missing_packages[@]}" ||
|
||||
fail "Не удалось установить системные зависимости GPSRelay."
|
||||
fi
|
||||
|
||||
if (( ${#reinstall_packages[@]} > 0 )); then
|
||||
log "ВОССТАНОВЛЕНИЕ СИСТЕМНЫХ ЗАВИСИМОСТЕЙ GPSRELAY"
|
||||
|
||||
"${sudo_cmd[@]}" apt-get install -y --reinstall "${reinstall_packages[@]}" ||
|
||||
fail "Не удалось восстановить системные зависимости GPSRelay."
|
||||
fi
|
||||
|
||||
for executable in "${commands[@]}"; do
|
||||
command -v "$executable" >/dev/null 2>&1 ||
|
||||
fail "После установки не найдена необходимая команда GPSRelay: $executable"
|
||||
|
||||
echo "[OK] Команда $executable доступна."
|
||||
done
|
||||
}
|
||||
|
||||
log "ПРОВЕРКА ФАЙЛОВ ПРОЕКТА"
|
||||
|
||||
[[ -f "$CONFIG_EXAMPLE" ]] || fail "Не найден $CONFIG_EXAMPLE"
|
||||
@@ -69,6 +145,9 @@ log "ПРОВЕРКА ФАЙЛОВ ПРОЕКТА"
|
||||
[[ -f "$PROJECT_ROOT/src/database.py" ]] || fail "Не найден src/database.py"
|
||||
[[ -f "$PROJECT_ROOT/cracklab/server/db/migrations.py" ]] || fail "Не найдены миграции CrackLab"
|
||||
|
||||
log "ПРОВЕРКА СИСТЕМНЫХ ЗАВИСИМОСТЕЙ GPSRELAY"
|
||||
install_gpsrelay_system_dependencies
|
||||
|
||||
log "ПОДГОТОВКА КАТАЛОГОВ ПРОЕКТА"
|
||||
|
||||
prepare_directory() {
|
||||
@@ -155,6 +234,7 @@ log "УСТАНОВКА PYTHON-ЗАВИСИМОСТЕЙ"
|
||||
"$PYTHON" -m pip install -r "$PROJECT_ROOT/requirements.txt"
|
||||
|
||||
"$PYTHON" -c "import flask, yaml, pynmea2, scapy"
|
||||
echo "[OK] Python-модуль pynmea2 доступен в виртуальном окружении."
|
||||
|
||||
log "ПОДГОТОВКА КОНФИГУРАЦИИ"
|
||||
|
||||
@@ -174,7 +254,7 @@ TMPDIR="$TMP_DIR" \
|
||||
"$PYTHON" - <<'PYTHON'
|
||||
from pathlib import Path
|
||||
|
||||
from database import Database
|
||||
from database import Database, migrate_wifi_verification_database
|
||||
from cracklab.server.db.migrations import migrate_database
|
||||
|
||||
database_path = Path("database/wifi.sqlite3")
|
||||
@@ -187,6 +267,8 @@ if not database_path.exists():
|
||||
else:
|
||||
print(f"Основная база уже существует: {database_path}")
|
||||
print("Повторная инициализация и миграции основной схемы пропущены.")
|
||||
migrate_wifi_verification_database(database_path)
|
||||
print("Схема Auto Verification проверена и обновлена при необходимости.")
|
||||
|
||||
applied = migrate_database(database_path)
|
||||
|
||||
|
||||
@@ -1224,6 +1224,22 @@ Time interval:
|
||||
—
|
||||
{esc(format_datetime(last_time))}
|
||||
|
||||
</div>
|
||||
"""
|
||||
|
||||
html += """
|
||||
<div class="access-points-verification-link">
|
||||
<a
|
||||
class="button access-points-verification-button"
|
||||
href="/reports/access-points/auto-verification"
|
||||
>
|
||||
<span class="access-points-verification-title">
|
||||
🛡 Auto Verification
|
||||
</span>
|
||||
<span class="access-points-verification-description">
|
||||
Сканирование точек доступа и автоматическая проверка найденных паролей
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
"""
|
||||
|
||||
|
||||
@@ -1505,16 +1505,20 @@ def render_wifi_connection_card(ap, credentials):
|
||||
);
|
||||
}}
|
||||
|
||||
if (data.wireguard_active) {{
|
||||
if (data.vpn_active) {{
|
||||
setWarning(
|
||||
"Обнаружено активное соединение WireGuard. "
|
||||
+ "При необходимости отключите VPN вручную. "
|
||||
+ "Приложение не изменяет состояние WireGuard."
|
||||
"Обнаружено активное VPN-подключение. "
|
||||
+ "Для надёжной проверки пароля и подключения "
|
||||
+ "рекомендуется временно отключить VPN. "
|
||||
+ "Продолжить можно, но успешная работа "
|
||||
+ "не гарантируется."
|
||||
);
|
||||
}} else if (data.wireguard_error) {{
|
||||
}} else if (data.vpn_error) {{
|
||||
setWarning(
|
||||
"Не удалось проверить состояние WireGuard: "
|
||||
+ data.wireguard_error
|
||||
"Не удалось достоверно определить состояние VPN. "
|
||||
+ "При активном VPN результат операции "
|
||||
+ "не гарантируется. "
|
||||
+ "Рекомендуется проверить состояние VPN вручную."
|
||||
);
|
||||
}}
|
||||
|
||||
@@ -1638,8 +1642,8 @@ def render_wifi_connection_card(ap, credentials):
|
||||
);
|
||||
}}
|
||||
|
||||
if (data.wireguard_warning) {{
|
||||
setWarning(data.wireguard_warning);
|
||||
if (data.vpn_warning) {{
|
||||
setWarning(data.vpn_warning);
|
||||
}}
|
||||
|
||||
}} catch (error) {{
|
||||
|
||||
@@ -0,0 +1,271 @@
|
||||
"""
|
||||
GeoJSON data for the Auto Wi-Fi Verification capture map.
|
||||
"""
|
||||
|
||||
import math
|
||||
import sqlite3
|
||||
from collections import defaultdict
|
||||
|
||||
from reports.database import close as close_database
|
||||
from reports.database import connect as connect_database
|
||||
from reports.map_popups import build_standard_popup
|
||||
|
||||
|
||||
TECHNICAL_STATUSES = {
|
||||
"CONNECTION_TIMEOUT",
|
||||
"NETWORK_ERROR",
|
||||
"UNKNOWN_ERROR",
|
||||
}
|
||||
|
||||
|
||||
def _valid_coordinates(latitude, longitude):
|
||||
try:
|
||||
latitude = float(latitude)
|
||||
longitude = float(longitude)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
if not math.isfinite(latitude) or not math.isfinite(longitude):
|
||||
return None
|
||||
|
||||
if not -90 <= latitude <= 90:
|
||||
return None
|
||||
|
||||
if not -180 <= longitude <= 180:
|
||||
return None
|
||||
|
||||
return latitude, longitude
|
||||
|
||||
|
||||
def _classify_access_point(credentials):
|
||||
"""
|
||||
Classify an AP using the latest attempt for each exact password.
|
||||
|
||||
Priority:
|
||||
green - any verified credential or successful attempt;
|
||||
red - every unique password has latest status INVALID_PASSWORD;
|
||||
orange - at least one latest status is a technical error;
|
||||
gray - all other cases.
|
||||
"""
|
||||
passwords = {}
|
||||
|
||||
for item in credentials:
|
||||
password = item["password"]
|
||||
state = passwords.setdefault(
|
||||
password,
|
||||
{
|
||||
"verified": False,
|
||||
"latest": None,
|
||||
"latest_order": None,
|
||||
},
|
||||
)
|
||||
|
||||
if item["verified"]:
|
||||
state["verified"] = True
|
||||
|
||||
if item["attempt_status"] == "SUCCESS":
|
||||
state["verified"] = True
|
||||
|
||||
if item["attempt_status"]:
|
||||
order = (
|
||||
item["attempt_started_at"] or "",
|
||||
item["attempt_id"] or 0,
|
||||
)
|
||||
if state["latest_order"] is None or order > state["latest_order"]:
|
||||
state["latest_order"] = order
|
||||
state["latest"] = item["attempt_status"]
|
||||
|
||||
if any(item["verified"] for item in passwords.values()):
|
||||
return "green"
|
||||
|
||||
latest_statuses = [
|
||||
item["latest"]
|
||||
for item in passwords.values()
|
||||
]
|
||||
|
||||
if latest_statuses and all(
|
||||
status == "INVALID_PASSWORD"
|
||||
for status in latest_statuses
|
||||
):
|
||||
return "red"
|
||||
|
||||
if any(
|
||||
status in TECHNICAL_STATUSES
|
||||
for status in latest_statuses
|
||||
):
|
||||
return "orange"
|
||||
|
||||
return "gray"
|
||||
|
||||
|
||||
def build_auto_verification_geojson():
|
||||
connection = connect_database()
|
||||
|
||||
try:
|
||||
connection.row_factory = sqlite3.Row
|
||||
|
||||
rows = connection.execute(
|
||||
"""
|
||||
SELECT
|
||||
ap.id AS access_point_id,
|
||||
ap.bssid,
|
||||
ap.essid,
|
||||
ap.vendor,
|
||||
ap.encryption,
|
||||
ap.cipher,
|
||||
ap.akm,
|
||||
ap.channel,
|
||||
ap.last_rssi,
|
||||
ap.last_seen,
|
||||
ap.last_latitude,
|
||||
ap.last_longitude,
|
||||
|
||||
c.id AS credential_id,
|
||||
c.password,
|
||||
c.source,
|
||||
c.verified,
|
||||
|
||||
a.id AS attempt_id,
|
||||
a.status AS attempt_status,
|
||||
a.started_at AS attempt_started_at
|
||||
|
||||
FROM access_points AS ap
|
||||
|
||||
INNER JOIN credentials AS c
|
||||
ON c.access_point_id = ap.id
|
||||
|
||||
LEFT JOIN wifi_verification_attempts AS a
|
||||
ON a.credential_id = c.id
|
||||
|
||||
WHERE
|
||||
c.password IS NOT NULL
|
||||
AND TRIM(c.password) <> ''
|
||||
AND ap.last_latitude IS NOT NULL
|
||||
AND ap.last_longitude IS NOT NULL
|
||||
|
||||
ORDER BY
|
||||
ap.id,
|
||||
c.id,
|
||||
a.started_at DESC,
|
||||
a.id DESC
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
finally:
|
||||
close_database(connection)
|
||||
|
||||
access_points = {}
|
||||
|
||||
for row in rows:
|
||||
ap_id = row["access_point_id"]
|
||||
|
||||
if ap_id not in access_points:
|
||||
coordinates = _valid_coordinates(
|
||||
row["last_latitude"],
|
||||
row["last_longitude"],
|
||||
)
|
||||
if coordinates is None:
|
||||
continue
|
||||
|
||||
access_points[ap_id] = {
|
||||
"row": row,
|
||||
"credentials": {},
|
||||
}
|
||||
|
||||
if ap_id not in access_points:
|
||||
continue
|
||||
|
||||
credential_id = row["credential_id"]
|
||||
credentials = access_points[ap_id]["credentials"]
|
||||
|
||||
if credential_id not in credentials:
|
||||
credentials[credential_id] = {
|
||||
"id": credential_id,
|
||||
"password": row["password"],
|
||||
"source": row["source"],
|
||||
"verified": bool(row["verified"]),
|
||||
"attempt_id": None,
|
||||
"attempt_status": None,
|
||||
"attempt_started_at": None,
|
||||
}
|
||||
|
||||
credential = credentials[credential_id]
|
||||
|
||||
if row["attempt_id"] is not None:
|
||||
order = (
|
||||
row["attempt_started_at"] or "",
|
||||
row["attempt_id"],
|
||||
)
|
||||
current_order = (
|
||||
credential["attempt_started_at"] or "",
|
||||
credential["attempt_id"] or 0,
|
||||
)
|
||||
|
||||
if credential["attempt_id"] is None or order > current_order:
|
||||
credential["attempt_id"] = row["attempt_id"]
|
||||
credential["attempt_status"] = row["attempt_status"]
|
||||
credential["attempt_started_at"] = row["attempt_started_at"]
|
||||
|
||||
features = []
|
||||
counts = {
|
||||
"green": 0,
|
||||
"red": 0,
|
||||
"orange": 0,
|
||||
"gray": 0,
|
||||
}
|
||||
|
||||
for item in access_points.values():
|
||||
row = item["row"]
|
||||
credentials = list(item["credentials"].values())
|
||||
|
||||
if not credentials:
|
||||
continue
|
||||
|
||||
coordinates = _valid_coordinates(
|
||||
row["last_latitude"],
|
||||
row["last_longitude"],
|
||||
)
|
||||
if coordinates is None:
|
||||
continue
|
||||
|
||||
latitude, longitude = coordinates
|
||||
status = _classify_access_point(credentials)
|
||||
|
||||
popup = build_standard_popup(
|
||||
essid=row["essid"],
|
||||
bssid=row["bssid"],
|
||||
vendor=row["vendor"],
|
||||
encryption=row["encryption"],
|
||||
cipher=row["cipher"],
|
||||
akm=row["akm"],
|
||||
channel=row["channel"],
|
||||
rssi=row["last_rssi"],
|
||||
passwords=credentials,
|
||||
handshakes=None,
|
||||
observed_at=row["last_seen"],
|
||||
latitude=latitude,
|
||||
longitude=longitude,
|
||||
)
|
||||
|
||||
features.append({
|
||||
"type": "Feature",
|
||||
"geometry": {
|
||||
"type": "Point",
|
||||
"coordinates": [longitude, latitude],
|
||||
},
|
||||
"properties": {
|
||||
"status": status,
|
||||
"popup": popup,
|
||||
"bssid": row["bssid"] or "",
|
||||
"essid": row["essid"] or "",
|
||||
},
|
||||
})
|
||||
|
||||
counts[status] += 1
|
||||
|
||||
return {
|
||||
"type": "FeatureCollection",
|
||||
"features": features,
|
||||
"counts": counts,
|
||||
"total": len(features),
|
||||
}
|
||||
@@ -64,6 +64,8 @@ from .sessions import (
|
||||
|
||||
)
|
||||
|
||||
from .recovery import recovery_block
|
||||
|
||||
# ============================================================
|
||||
# Helpers
|
||||
# ============================================================
|
||||
@@ -784,6 +786,14 @@ def generate_dashboard(
|
||||
|
||||
"""
|
||||
|
||||
# --------------------------------------------------------
|
||||
# Recovery
|
||||
# --------------------------------------------------------
|
||||
|
||||
html += recovery_block(
|
||||
conn
|
||||
)
|
||||
|
||||
# --------------------------------------------------------
|
||||
# Sessions
|
||||
# --------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from scapy.all import PcapNgReader
|
||||
|
||||
from .config import CAPTURES_DIR, get_timezone
|
||||
from .template import card
|
||||
from .utils import esc
|
||||
|
||||
|
||||
def _capture_duration_seconds(capture_file):
|
||||
reader = None
|
||||
first_timestamp = None
|
||||
last_timestamp = None
|
||||
|
||||
try:
|
||||
reader = PcapNgReader(str(capture_file))
|
||||
|
||||
for packet in reader:
|
||||
try:
|
||||
timestamp = float(packet.time)
|
||||
except (AttributeError, TypeError, ValueError, OverflowError):
|
||||
continue
|
||||
|
||||
if first_timestamp is None or timestamp < first_timestamp:
|
||||
first_timestamp = timestamp
|
||||
|
||||
if last_timestamp is None or timestamp > last_timestamp:
|
||||
last_timestamp = timestamp
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
finally:
|
||||
if reader is not None:
|
||||
reader.close()
|
||||
|
||||
if first_timestamp is None or last_timestamp is None:
|
||||
return 0
|
||||
|
||||
return max(0, last_timestamp - first_timestamp)
|
||||
|
||||
|
||||
def _has_recoverable_capture(session_dir):
|
||||
minimum_duration = MIN_RECOVERY_DURATION.total_seconds()
|
||||
|
||||
return (
|
||||
_capture_duration_seconds(
|
||||
session_dir / "capture.pcapng"
|
||||
) >= minimum_duration
|
||||
)
|
||||
|
||||
|
||||
MIN_RECOVERY_DURATION = timedelta(minutes=5)
|
||||
|
||||
|
||||
MIN_STALE_AGE = timedelta(minutes=15)
|
||||
|
||||
SESSION_FILES = (
|
||||
"capture.pcapng",
|
||||
"gps_track.nmea",
|
||||
"access_points.csv",
|
||||
"handshakes.22000",
|
||||
"essid.txt",
|
||||
"identities.txt",
|
||||
"parser.log",
|
||||
)
|
||||
|
||||
|
||||
def _utc_now(value=None):
|
||||
if value is None:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=timezone.utc)
|
||||
|
||||
return value.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _file_is_stale(path, now):
|
||||
try:
|
||||
modified = datetime.fromtimestamp(
|
||||
path.stat().st_mtime,
|
||||
timezone.utc,
|
||||
)
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
age = now - modified
|
||||
|
||||
return age >= MIN_STALE_AGE
|
||||
|
||||
|
||||
def _capture_is_interrupted(path, end_time, now):
|
||||
if end_time is not None:
|
||||
return False
|
||||
|
||||
try:
|
||||
if not path.is_file():
|
||||
return False
|
||||
|
||||
if path.stat().st_size <= 0:
|
||||
return False
|
||||
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
return _file_is_stale(path, now)
|
||||
|
||||
|
||||
def _resolve_session_directory(capture_file, captures_dir):
|
||||
if not capture_file:
|
||||
return None
|
||||
|
||||
root = Path(captures_dir).resolve()
|
||||
path = Path(capture_file)
|
||||
|
||||
if not path.is_absolute():
|
||||
path = root.parent / path
|
||||
|
||||
try:
|
||||
resolved = path.resolve()
|
||||
resolved.relative_to(root)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
|
||||
return resolved.parent
|
||||
|
||||
|
||||
def _parser_was_interrupted(parser_log):
|
||||
last_started = -1
|
||||
last_finished = -1
|
||||
|
||||
try:
|
||||
with parser_log.open(
|
||||
"r",
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
) as file:
|
||||
for index, line in enumerate(file):
|
||||
if "Parser started" in line:
|
||||
last_started = index
|
||||
|
||||
if "Parser finished" in line:
|
||||
last_finished = index
|
||||
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
return last_started >= 0 and last_started > last_finished
|
||||
|
||||
|
||||
def _parser_was_completed(parser_log):
|
||||
last_started = -1
|
||||
last_finished = -1
|
||||
|
||||
try:
|
||||
with parser_log.open(
|
||||
"r",
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
) as file:
|
||||
for index, line in enumerate(file):
|
||||
if "Parser started" in line:
|
||||
last_started = index
|
||||
|
||||
if "Parser finished" in line:
|
||||
last_finished = index
|
||||
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
return (
|
||||
last_started >= 0
|
||||
and last_finished > last_started
|
||||
)
|
||||
|
||||
|
||||
def _session_counts(conn, session_id):
|
||||
counts = {}
|
||||
|
||||
for name, table in (
|
||||
("gps", "gps_track"),
|
||||
("access_points", "access_point_observations"),
|
||||
("handshakes", "handshakes"),
|
||||
):
|
||||
row = conn.execute(
|
||||
f"""
|
||||
SELECT COUNT(*)
|
||||
FROM {table}
|
||||
WHERE session_id = ?
|
||||
""",
|
||||
(session_id,),
|
||||
).fetchone()
|
||||
|
||||
counts[name] = int(row[0])
|
||||
|
||||
return counts
|
||||
|
||||
|
||||
def _parse_datetime(value):
|
||||
if not value:
|
||||
return None
|
||||
|
||||
try:
|
||||
result = datetime.fromisoformat(
|
||||
str(value).replace("Z", "+00:00")
|
||||
)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
if result.tzinfo is None:
|
||||
return result.replace(tzinfo=timezone.utc)
|
||||
|
||||
return result.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _format_datetime(value, display_timezone):
|
||||
parsed = _parse_datetime(value)
|
||||
|
||||
if parsed is None:
|
||||
return "Неизвестно"
|
||||
|
||||
return parsed.astimezone(
|
||||
display_timezone
|
||||
).strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _collect_files(session_dir):
|
||||
result = []
|
||||
|
||||
for filename in SESSION_FILES:
|
||||
path = session_dir / filename
|
||||
|
||||
try:
|
||||
if not path.is_file():
|
||||
continue
|
||||
|
||||
size = path.stat().st_size
|
||||
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
result.append({
|
||||
"name": filename,
|
||||
"size": size,
|
||||
})
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _session_sources_are_stale(session_dir, now):
|
||||
source_paths = [
|
||||
session_dir / filename
|
||||
for filename in SESSION_FILES
|
||||
]
|
||||
|
||||
existing_paths = []
|
||||
|
||||
for source_path in source_paths:
|
||||
try:
|
||||
if source_path.is_file():
|
||||
existing_paths.append(source_path.stat().st_mtime)
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
if not existing_paths:
|
||||
return False
|
||||
|
||||
latest_modified = max(existing_paths)
|
||||
|
||||
modified = datetime.fromtimestamp(
|
||||
latest_modified,
|
||||
tz=timezone.utc,
|
||||
)
|
||||
|
||||
return now - modified >= MIN_STALE_AGE
|
||||
|
||||
|
||||
def find_recovery_candidates(
|
||||
conn,
|
||||
captures_dir=None,
|
||||
now=None,
|
||||
timezone_name=None,
|
||||
):
|
||||
now = _utc_now(now)
|
||||
|
||||
if captures_dir is None:
|
||||
captures_dir = CAPTURES_DIR
|
||||
|
||||
if timezone_name is None:
|
||||
timezone_name = get_timezone()
|
||||
|
||||
try:
|
||||
display_timezone = ZoneInfo(timezone_name)
|
||||
except (TypeError, ValueError):
|
||||
display_timezone = timezone.utc
|
||||
|
||||
rows = conn.execute("""
|
||||
SELECT
|
||||
id,
|
||||
start_time,
|
||||
end_time,
|
||||
capture_file
|
||||
FROM capture_sessions
|
||||
ORDER BY id DESC
|
||||
""").fetchall()
|
||||
|
||||
candidates = []
|
||||
known_session_dirs = set()
|
||||
|
||||
for row in rows:
|
||||
session_id = row[0]
|
||||
start_time = row[1]
|
||||
end_time = row[2]
|
||||
capture_file = row[3]
|
||||
|
||||
session_dir = _resolve_session_directory(
|
||||
capture_file,
|
||||
captures_dir,
|
||||
)
|
||||
|
||||
if session_dir is None or not session_dir.is_dir():
|
||||
continue
|
||||
|
||||
known_session_dirs.add(
|
||||
session_dir.resolve()
|
||||
)
|
||||
|
||||
capture_path = session_dir / "capture.pcapng"
|
||||
parser_log = session_dir / "parser.log"
|
||||
|
||||
if (
|
||||
parser_log.is_file()
|
||||
and _parser_was_completed(parser_log)
|
||||
):
|
||||
continue
|
||||
|
||||
capture_interrupted = _capture_is_interrupted(
|
||||
capture_path,
|
||||
end_time,
|
||||
now,
|
||||
)
|
||||
|
||||
parser_interrupted = (
|
||||
parser_log.is_file()
|
||||
and _file_is_stale(parser_log, now)
|
||||
and _parser_was_interrupted(parser_log)
|
||||
)
|
||||
|
||||
if not capture_interrupted and not parser_interrupted:
|
||||
continue
|
||||
|
||||
counts = _session_counts(
|
||||
conn,
|
||||
session_id,
|
||||
)
|
||||
|
||||
if not _has_recoverable_capture(session_dir):
|
||||
continue
|
||||
|
||||
reasons = []
|
||||
|
||||
if capture_interrupted:
|
||||
reasons.append(
|
||||
"Запись capture.pcapng не обновлялась более "
|
||||
"15 минут, а сессия в БД остаётся открытой."
|
||||
)
|
||||
|
||||
if parser_interrupted:
|
||||
reasons.append(
|
||||
"В parser.log обнаружен запуск парсера без "
|
||||
"последующего сообщения Parser finished; "
|
||||
"лог не обновлялся более 15 минут."
|
||||
)
|
||||
|
||||
files = _collect_files(session_dir)
|
||||
|
||||
candidates.append({
|
||||
"id": session_id,
|
||||
"start_time": _format_datetime(
|
||||
start_time,
|
||||
display_timezone,
|
||||
),
|
||||
"kind": (
|
||||
"capture_and_parser"
|
||||
if capture_interrupted and parser_interrupted
|
||||
else "capture"
|
||||
if capture_interrupted
|
||||
else "parser"
|
||||
),
|
||||
"counts": counts,
|
||||
"files": files,
|
||||
"reasons": reasons,
|
||||
"actions": (
|
||||
"Проверить целостность файлов захвата и "
|
||||
"оценить возможность завершения обработки поездки."
|
||||
if capture_interrupted
|
||||
else
|
||||
"В БД уже присутствуют результаты обработки. "
|
||||
"Сначала сверить их с исходными файлами; "
|
||||
"не запускать повторный парсинг без проверки."
|
||||
if any(counts.values())
|
||||
else
|
||||
"Проверить исходные файлы и оценить возможность "
|
||||
"повторного выполнения парсинга."
|
||||
),
|
||||
})
|
||||
|
||||
captures_root = Path(captures_dir).resolve()
|
||||
|
||||
try:
|
||||
session_directories = captures_root.iterdir()
|
||||
except OSError:
|
||||
session_directories = ()
|
||||
|
||||
for entry in session_directories:
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
|
||||
session_dir = entry.resolve()
|
||||
|
||||
if session_dir.parent != captures_root:
|
||||
continue
|
||||
|
||||
if session_dir in known_session_dirs:
|
||||
continue
|
||||
|
||||
try:
|
||||
start_time = datetime.strptime(
|
||||
session_dir.name,
|
||||
"%Y%m%d_%H%M%S",
|
||||
).replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
parser_log = session_dir / "parser.log"
|
||||
|
||||
if (
|
||||
parser_log.is_file()
|
||||
and _parser_was_completed(parser_log)
|
||||
):
|
||||
continue
|
||||
|
||||
if not _session_sources_are_stale(
|
||||
session_dir,
|
||||
now,
|
||||
):
|
||||
continue
|
||||
|
||||
if not _has_recoverable_capture(session_dir):
|
||||
continue
|
||||
|
||||
candidates.append({
|
||||
"id": None,
|
||||
"title": (
|
||||
f"Каталог {session_dir.name} "
|
||||
"(запись в БД отсутствует)"
|
||||
),
|
||||
"session_dir": str(session_dir),
|
||||
"start_time": _format_datetime(
|
||||
start_time.isoformat(),
|
||||
display_timezone,
|
||||
),
|
||||
"kind": "capture",
|
||||
"counts": {
|
||||
"gps": 0,
|
||||
"access_points": 0,
|
||||
"handshakes": 0,
|
||||
},
|
||||
"files": _collect_files(session_dir),
|
||||
"reasons": [
|
||||
"Найдены исходные файлы поездки, "
|
||||
"которые не обновлялись более 15 минут. "
|
||||
"Запись этой поездки в capture_sessions отсутствует."
|
||||
],
|
||||
"actions": (
|
||||
"Проверить исходные файлы и восстановить "
|
||||
"запись поездки в базе данных."
|
||||
),
|
||||
})
|
||||
|
||||
return candidates
|
||||
|
||||
|
||||
def recovery_block(conn):
|
||||
candidates = find_recovery_candidates(conn)
|
||||
|
||||
if not candidates:
|
||||
return ""
|
||||
|
||||
html = []
|
||||
|
||||
for candidate in candidates:
|
||||
counts = candidate["counts"]
|
||||
|
||||
title = candidate.get(
|
||||
"title",
|
||||
f"Поездка #{candidate['id']}",
|
||||
)
|
||||
|
||||
files_html = "".join(
|
||||
"<li>{} — {} байт</li>".format(
|
||||
esc(item["name"]),
|
||||
item["size"],
|
||||
)
|
||||
for item in candidate["files"]
|
||||
)
|
||||
|
||||
reasons_html = "".join(
|
||||
"<li>{}</li>".format(esc(reason))
|
||||
for reason in candidate["reasons"]
|
||||
)
|
||||
|
||||
recovery_html = ""
|
||||
|
||||
if candidate.get("id") is None:
|
||||
|
||||
directory_name = Path(
|
||||
candidate["session_dir"]
|
||||
).name
|
||||
|
||||
recovery_html = f"""
|
||||
<form method="post"
|
||||
action="/reports/recovery/{esc(directory_name)}">
|
||||
<button type="submit" class="button">
|
||||
Восстановить поездку
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<p>
|
||||
Если восстановление не требуется, каталог можно удалить вручную:
|
||||
</p>
|
||||
|
||||
<p class="recovery-directory">
|
||||
<code>{esc(candidate["session_dir"])}</code>
|
||||
<button
|
||||
type="button"
|
||||
class="recovery-copy-button"
|
||||
data-copy-path="{esc(candidate["session_dir"])}"
|
||||
onclick="copyRecoveryPath(this)"
|
||||
title="Копировать путь"
|
||||
aria-label="Копировать путь"
|
||||
><svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="18"
|
||||
height="18"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1.8"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<rect x="8" y="8" width="13" height="13" rx="2"/>
|
||||
<path d="M16 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h3"/>
|
||||
</svg></button>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Удаление безвозвратно уничтожит файлы поездки.
|
||||
Приложение автоматически файлы не удаляет.
|
||||
</p>
|
||||
"""
|
||||
|
||||
html.append(f"""
|
||||
<div class="card">
|
||||
<h3>{esc(title)}</h3>
|
||||
|
||||
<p>
|
||||
<strong>Дата начала:</strong>
|
||||
{esc(candidate["start_time"])}
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<strong>Обнаружено:</strong>
|
||||
{esc(candidate["kind"])}
|
||||
</p>
|
||||
|
||||
<p><strong>Состояние данных в БД:</strong></p>
|
||||
<ul>
|
||||
<li>GPS: {counts["gps"]}</li>
|
||||
<li>Наблюдения точек доступа: {counts["access_points"]}</li>
|
||||
<li>Handshake: {counts["handshakes"]}</li>
|
||||
</ul>
|
||||
|
||||
<p><strong>Найденные файлы:</strong></p>
|
||||
<ul>
|
||||
{files_html}
|
||||
</ul>
|
||||
|
||||
<p><strong>Причины обнаружения:</strong></p>
|
||||
<ul>
|
||||
{reasons_html}
|
||||
</ul>
|
||||
|
||||
<p>
|
||||
<strong>Возможное дальнейшее действие:</strong>
|
||||
{esc(candidate["actions"])}
|
||||
</p>
|
||||
|
||||
{recovery_html}
|
||||
</div>
|
||||
""")
|
||||
|
||||
return card(
|
||||
"⚠️ Восстановление поездок",
|
||||
"\n".join(html),
|
||||
)
|
||||
+1
-1
@@ -1318,7 +1318,7 @@ def render_search_page(
|
||||
"search-map",
|
||||
|
||||
style:
|
||||
"{map_style}",
|
||||
{map_style},
|
||||
|
||||
center: [
|
||||
geojson.features[0]
|
||||
|
||||
@@ -286,6 +286,29 @@ a:hover {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.access-points-verification-link {
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.access-points-verification-button {
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 4px;
|
||||
padding: 12px 18px;
|
||||
}
|
||||
|
||||
.access-points-verification-title {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.access-points-verification-description {
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
|
||||
/* ============================================================
|
||||
Cards
|
||||
@@ -1893,3 +1916,32 @@ body .maplibregl-popup-close-button:hover {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.recovery-directory {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.recovery-directory code {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.recovery-copy-button {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 32px;
|
||||
min-height: 32px;
|
||||
padding: 4px 7px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.recovery-copy-button:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
@@ -199,6 +199,40 @@ function filterTable(id,value)
|
||||
}}
|
||||
}}
|
||||
|
||||
async function copyRecoveryPath(button)
|
||||
{{
|
||||
const path = button.dataset.copyPath;
|
||||
|
||||
if (!path)
|
||||
return;
|
||||
|
||||
const originalHTML = button.innerHTML;
|
||||
|
||||
try
|
||||
{{
|
||||
if (!navigator.clipboard || !navigator.clipboard.writeText)
|
||||
throw new Error("Clipboard API unavailable");
|
||||
|
||||
await navigator.clipboard.writeText(path);
|
||||
|
||||
button.textContent = "✓";
|
||||
|
||||
setTimeout(() =>
|
||||
{{
|
||||
button.innerHTML = originalHTML;
|
||||
}}, 1500);
|
||||
}}
|
||||
catch (error)
|
||||
{{
|
||||
button.textContent = "✕";
|
||||
|
||||
setTimeout(() =>
|
||||
{{
|
||||
button.innerHTML = originalHTML;
|
||||
}}, 2000);
|
||||
}}
|
||||
}}
|
||||
|
||||
async function copyMapCoordinates(button)
|
||||
{{
|
||||
const coordinates = button.dataset.coordinates;
|
||||
|
||||
@@ -580,11 +580,11 @@ map.on(
|
||||
);
|
||||
|
||||
if (
|
||||
data.wireguard_warning
|
||||
data.vpn_warning
|
||||
&& wifiConnectionWarning
|
||||
) {
|
||||
wifiConnectionWarning.textContent =
|
||||
data.wireguard_warning;
|
||||
data.vpn_warning;
|
||||
wifiConnectionWarning.hidden = false;
|
||||
}
|
||||
|
||||
@@ -856,16 +856,20 @@ def render_wifi_connections_page(conn, context=None):
|
||||
);
|
||||
}
|
||||
|
||||
if (data.wireguard_active) {
|
||||
if (data.vpn_active) {
|
||||
setWarning(
|
||||
"Обнаружено активное соединение WireGuard. "
|
||||
+ "При необходимости отключите VPN вручную. "
|
||||
+ "Приложение не изменяет состояние WireGuard."
|
||||
"Обнаружено активное VPN-подключение. "
|
||||
+ "Для надёжной проверки пароля и подключения "
|
||||
+ "рекомендуется временно отключить VPN. "
|
||||
+ "Продолжить можно, но успешная работа "
|
||||
+ "не гарантируется."
|
||||
);
|
||||
} else if (data.wireguard_error) {
|
||||
} else if (data.vpn_error) {
|
||||
setWarning(
|
||||
"Не удалось проверить состояние WireGuard: "
|
||||
+ data.wireguard_error
|
||||
"Не удалось достоверно определить состояние VPN. "
|
||||
+ "При активном VPN результат операции "
|
||||
+ "не гарантируется. "
|
||||
+ "Рекомендуется проверить состояние VPN вручную."
|
||||
);
|
||||
}
|
||||
document.dispatchEvent(
|
||||
|
||||
+647
@@ -0,0 +1,647 @@
|
||||
import logging
|
||||
import re
|
||||
import select
|
||||
import socket
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from pathlib import Path
|
||||
|
||||
from gps import GPSRelaySource, GpsdSource, parse_nmea
|
||||
from logging_config import (
|
||||
LOG_DATE_FORMAT,
|
||||
LOG_FORMAT,
|
||||
UTCFormatter,
|
||||
)
|
||||
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
POLL_INTERVAL_SECONDS = 0.5
|
||||
RECONNECT_DELAY_SECONDS = 2.0
|
||||
CONNECT_TIMEOUT_SECONDS = 3.0
|
||||
GPSD_GREETING_MAX_BYTES = 65536
|
||||
LOG_MAX_BYTES = 5 * 1024 * 1024
|
||||
LOG_BACKUP_COUNT = 3
|
||||
|
||||
|
||||
def _create_logger():
|
||||
logger = logging.getLogger(
|
||||
"wifi-gps-mapper.auto-verification"
|
||||
)
|
||||
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
|
||||
if not logger.handlers:
|
||||
log_dir = PROJECT_ROOT / "logs"
|
||||
log_dir.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True
|
||||
)
|
||||
|
||||
handler = RotatingFileHandler(
|
||||
log_dir / "auto-verification.log",
|
||||
maxBytes=LOG_MAX_BYTES,
|
||||
backupCount=LOG_BACKUP_COUNT,
|
||||
encoding="utf-8"
|
||||
)
|
||||
|
||||
handler.setFormatter(
|
||||
UTCFormatter(
|
||||
LOG_FORMAT,
|
||||
datefmt=LOG_DATE_FORMAT
|
||||
)
|
||||
)
|
||||
|
||||
logger.addHandler(handler)
|
||||
|
||||
return logger
|
||||
|
||||
|
||||
def _get_gpsd_port():
|
||||
"""Получает IPv4 TCP-порт из активной конфигурации gpsd.socket."""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"systemctl",
|
||||
"show",
|
||||
"gpsd.socket",
|
||||
"--property=Listen",
|
||||
"--value",
|
||||
],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=3,
|
||||
)
|
||||
except (OSError, subprocess.SubprocessError) as error:
|
||||
raise RuntimeError(
|
||||
f"Cannot read gpsd.socket configuration: {error}"
|
||||
) from error
|
||||
|
||||
ports = set()
|
||||
|
||||
for line in result.stdout.splitlines():
|
||||
endpoint = line.strip()
|
||||
|
||||
if "=" in endpoint:
|
||||
endpoint = endpoint.split("=", 1)[1].strip()
|
||||
|
||||
match = re.fullmatch(
|
||||
r"(?:127\.0\.0\.1|0\.0\.0\.0):(\d+)(?:\s+\(Stream\))?",
|
||||
endpoint,
|
||||
)
|
||||
|
||||
if match:
|
||||
port = int(match.group(1))
|
||||
|
||||
if not 1 <= port <= 65535:
|
||||
raise RuntimeError(
|
||||
f"Invalid GPSD TCP port: {port}"
|
||||
)
|
||||
|
||||
ports.add(port)
|
||||
|
||||
if not ports:
|
||||
raise RuntimeError(
|
||||
"No IPv4 TCP listener found in gpsd.socket"
|
||||
)
|
||||
|
||||
if len(ports) != 1:
|
||||
raise RuntimeError(
|
||||
"gpsd.socket has multiple different IPv4 TCP ports: "
|
||||
+ ", ".join(str(port) for port in sorted(ports))
|
||||
)
|
||||
|
||||
return ports.pop()
|
||||
|
||||
|
||||
logger = _create_logger()
|
||||
|
||||
|
||||
class AutoGPSService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings,
|
||||
callback=None,
|
||||
fix_callback=None,
|
||||
position_callback=None
|
||||
):
|
||||
self.settings = dict(settings or {})
|
||||
self.callback = callback
|
||||
self.fix_callback = fix_callback
|
||||
self.position_callback = position_callback
|
||||
|
||||
self.gps_source = self.settings.get("gps_source")
|
||||
|
||||
self.max_age_seconds = float(
|
||||
self.settings.get(
|
||||
"gnss_max_age_seconds",
|
||||
10
|
||||
)
|
||||
)
|
||||
|
||||
if self.max_age_seconds <= 0:
|
||||
raise ValueError(
|
||||
"gnss_max_age_seconds must be positive"
|
||||
)
|
||||
|
||||
if self.gps_source not in ("gpsd", "gpsrelay"):
|
||||
raise ValueError(
|
||||
"Auto GPS source must be 'gpsd' or 'gpsrelay'"
|
||||
)
|
||||
|
||||
if self.gps_source == "gpsrelay":
|
||||
host = self.settings.get("gpsrelay_host")
|
||||
port = self.settings.get("gpsrelay_port")
|
||||
|
||||
if not isinstance(host, str) or not host.strip():
|
||||
raise ValueError(
|
||||
"GPS Relay host is required"
|
||||
)
|
||||
|
||||
if (
|
||||
isinstance(port, bool)
|
||||
or not isinstance(port, int)
|
||||
or not 1 <= port <= 65535
|
||||
):
|
||||
raise ValueError(
|
||||
"GPS Relay port must be between 1 and 65535"
|
||||
)
|
||||
|
||||
self.thread = None
|
||||
self.stop_event = threading.Event()
|
||||
|
||||
self.source = None
|
||||
self.source_lock = threading.Lock()
|
||||
self.state_lock = threading.Lock()
|
||||
|
||||
self.running = False
|
||||
self.state = "READY"
|
||||
self.error = None
|
||||
|
||||
self.current_fix = None
|
||||
self.last_fix_monotonic = None
|
||||
self.connected_monotonic = None
|
||||
|
||||
def _emit(
|
||||
self,
|
||||
level,
|
||||
code,
|
||||
message
|
||||
):
|
||||
event = {
|
||||
"level": level,
|
||||
"code": code,
|
||||
"message": message,
|
||||
"state": self.state,
|
||||
"timestamp": datetime.now(
|
||||
timezone.utc
|
||||
).isoformat()
|
||||
}
|
||||
|
||||
log_method = getattr(
|
||||
logger,
|
||||
level.lower(),
|
||||
logger.info
|
||||
)
|
||||
|
||||
if code in (
|
||||
"GPS_STARTED",
|
||||
"GPS_CONNECTED",
|
||||
"GPS_CONNECTION_LOST",
|
||||
"GPS_SERVICE_ERROR",
|
||||
"GPS_STOPPED",
|
||||
):
|
||||
log_method(
|
||||
"%s: %s",
|
||||
code,
|
||||
message
|
||||
)
|
||||
|
||||
if self.callback is not None:
|
||||
try:
|
||||
self.callback(event)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Auto GPS callback failed"
|
||||
)
|
||||
|
||||
def _set_state(self, state):
|
||||
with self.state_lock:
|
||||
self.state = state
|
||||
|
||||
def _create_source(self):
|
||||
if self.gps_source == "gpsd":
|
||||
return GpsdSource(
|
||||
host="127.0.0.1",
|
||||
port=_get_gpsd_port()
|
||||
)
|
||||
|
||||
if self.gps_source == "gpsrelay":
|
||||
return GPSRelaySource(
|
||||
self.settings["gpsrelay_host"].strip(),
|
||||
self.settings["gpsrelay_port"]
|
||||
)
|
||||
|
||||
raise ValueError(
|
||||
f"Unsupported Auto GPS source: {self.gps_source}"
|
||||
)
|
||||
|
||||
def _open_source(self, source):
|
||||
# Поддержка тестовых источников с заранее созданным сокетом.
|
||||
if getattr(source, "socket", None) is not None:
|
||||
stream = source.open()
|
||||
return source.socket, stream, b""
|
||||
|
||||
connection = socket.create_connection(
|
||||
(source.host, source.port),
|
||||
timeout=CONNECT_TIMEOUT_SECONDS
|
||||
)
|
||||
|
||||
# Сохраняем сокет сразу после подключения, чтобы stop()
|
||||
# мог закрыть его во время дальнейшей инициализации.
|
||||
source.socket = connection
|
||||
connection.settimeout(CONNECT_TIMEOUT_SECONDS)
|
||||
|
||||
pending = b""
|
||||
|
||||
if self.gps_source == "gpsd":
|
||||
greeting = bytearray()
|
||||
|
||||
handshake_deadline = (
|
||||
time.monotonic() + CONNECT_TIMEOUT_SECONDS
|
||||
)
|
||||
|
||||
while b"\n" not in greeting:
|
||||
if self.stop_event.is_set():
|
||||
raise ConnectionError(
|
||||
"Auto GPS stopped during GPSD handshake"
|
||||
)
|
||||
|
||||
remaining = (
|
||||
handshake_deadline - time.monotonic()
|
||||
)
|
||||
|
||||
if remaining <= 0:
|
||||
raise TimeoutError(
|
||||
"GPSD handshake timed out"
|
||||
)
|
||||
|
||||
connection.settimeout(remaining)
|
||||
chunk = connection.recv(4096)
|
||||
|
||||
if not chunk:
|
||||
raise ConnectionError(
|
||||
"GPSD closed the connection during handshake"
|
||||
)
|
||||
|
||||
greeting.extend(chunk)
|
||||
|
||||
if len(greeting) > GPSD_GREETING_MAX_BYTES:
|
||||
raise ConnectionError(
|
||||
"GPSD greeting exceeds the allowed size"
|
||||
)
|
||||
|
||||
greeting_end = greeting.find(b"\n") + 1
|
||||
pending = bytes(greeting[greeting_end:])
|
||||
|
||||
connection.sendall(
|
||||
b'?WATCH={"enable":true,"json":false,"nmea":true};\n'
|
||||
)
|
||||
|
||||
connection.setblocking(False)
|
||||
|
||||
return connection, None, pending
|
||||
|
||||
def start(self):
|
||||
if (
|
||||
self.thread is not None
|
||||
and self.thread.is_alive()
|
||||
):
|
||||
return False
|
||||
|
||||
self.stop_event.clear()
|
||||
|
||||
with self.state_lock:
|
||||
self.running = True
|
||||
self.state = "STARTING"
|
||||
self.error = None
|
||||
self.current_fix = None
|
||||
self.last_fix_monotonic = None
|
||||
self.connected_monotonic = None
|
||||
|
||||
self.thread = threading.Thread(
|
||||
target=self.worker,
|
||||
name="auto-gps",
|
||||
daemon=True
|
||||
)
|
||||
|
||||
self.thread.start()
|
||||
|
||||
self._emit(
|
||||
"INFO",
|
||||
"GPS_STARTED",
|
||||
f"Auto GPS started with source: {self.gps_source}"
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
def stop(self):
|
||||
self.stop_event.set()
|
||||
|
||||
with self.source_lock:
|
||||
source = self.source
|
||||
|
||||
if source is not None:
|
||||
connection = getattr(
|
||||
source,
|
||||
"socket",
|
||||
None
|
||||
)
|
||||
|
||||
if connection is not None:
|
||||
try:
|
||||
connection.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
try:
|
||||
source.close()
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Auto GPS source close failed"
|
||||
)
|
||||
|
||||
def _set_fix(self, gps):
|
||||
now = time.monotonic()
|
||||
|
||||
with self.state_lock:
|
||||
had_fresh_fix = (
|
||||
self.current_fix is not None
|
||||
and self.last_fix_monotonic is not None
|
||||
and now - self.last_fix_monotonic
|
||||
<= self.max_age_seconds
|
||||
)
|
||||
|
||||
self.current_fix = gps
|
||||
self.last_fix_monotonic = now
|
||||
self.state = "FIX"
|
||||
self.error = None
|
||||
|
||||
if not had_fresh_fix:
|
||||
self._emit(
|
||||
"INFO",
|
||||
"GPS_FIX_RESTORED",
|
||||
"Auto GPS has a fresh valid FIX: "
|
||||
f"lat={gps.latitude:.6f}, "
|
||||
f"lon={gps.longitude:.6f}"
|
||||
)
|
||||
|
||||
if self.fix_callback is not None:
|
||||
try:
|
||||
self.fix_callback(gps)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Auto GPS FIX callback failed"
|
||||
)
|
||||
|
||||
if self.position_callback is not None:
|
||||
try:
|
||||
self.position_callback(gps)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Auto GPS position callback failed"
|
||||
)
|
||||
|
||||
def _check_fix_freshness(self):
|
||||
now = time.monotonic()
|
||||
|
||||
with self.state_lock:
|
||||
if self.state in ("STOPPED", "RECONNECTING"):
|
||||
return
|
||||
|
||||
reference = (
|
||||
self.last_fix_monotonic
|
||||
if self.last_fix_monotonic is not None
|
||||
else self.connected_monotonic
|
||||
)
|
||||
|
||||
if reference is None:
|
||||
return
|
||||
|
||||
age = now - reference
|
||||
|
||||
if age <= self.max_age_seconds:
|
||||
return
|
||||
|
||||
if self.state == "NO_FIX":
|
||||
return
|
||||
|
||||
self.current_fix = None
|
||||
self.state = "NO_FIX"
|
||||
|
||||
self._emit(
|
||||
"WARNING",
|
||||
"GPS_FIX_LOST",
|
||||
"Auto GPS has no fresh valid FIX. "
|
||||
f"Last valid position age: {age:.1f} seconds."
|
||||
)
|
||||
|
||||
def get_status(self):
|
||||
now = time.monotonic()
|
||||
|
||||
with self.state_lock:
|
||||
fix = self.current_fix
|
||||
last_fix = self.last_fix_monotonic
|
||||
state = self.state
|
||||
error = self.error
|
||||
|
||||
age = (
|
||||
now - last_fix
|
||||
if last_fix is not None
|
||||
else None
|
||||
)
|
||||
|
||||
fresh = (
|
||||
fix is not None
|
||||
and age is not None
|
||||
and age <= self.max_age_seconds
|
||||
and state == "FIX"
|
||||
)
|
||||
|
||||
return {
|
||||
"running": self.running,
|
||||
"source": self.gps_source,
|
||||
"state": state,
|
||||
"has_fresh_fix": fresh,
|
||||
"latitude": (
|
||||
fix.latitude
|
||||
if fresh
|
||||
else None
|
||||
),
|
||||
"longitude": (
|
||||
fix.longitude
|
||||
if fresh
|
||||
else None
|
||||
),
|
||||
"fix_age_seconds": age,
|
||||
"max_age_seconds": self.max_age_seconds,
|
||||
"error": error
|
||||
}
|
||||
|
||||
def worker(self):
|
||||
try:
|
||||
while not self.stop_event.is_set():
|
||||
source = None
|
||||
stream = None
|
||||
|
||||
try:
|
||||
source = self._create_source()
|
||||
|
||||
with self.source_lock:
|
||||
self.source = source
|
||||
|
||||
if self.stop_event.is_set():
|
||||
break
|
||||
|
||||
self._set_state("CONNECTING")
|
||||
|
||||
logger.info(
|
||||
"Connecting Auto GPS to %s",
|
||||
self.gps_source
|
||||
)
|
||||
|
||||
connection, stream, pending = self._open_source(
|
||||
source
|
||||
)
|
||||
|
||||
if self.stop_event.is_set():
|
||||
break
|
||||
|
||||
with self.state_lock:
|
||||
self.connected_monotonic = time.monotonic()
|
||||
self.state = "CONNECTED"
|
||||
self.error = None
|
||||
|
||||
self._emit(
|
||||
"INFO",
|
||||
"GPS_CONNECTED",
|
||||
f"Auto GPS connected to {self.gps_source}"
|
||||
)
|
||||
|
||||
while not self.stop_event.is_set():
|
||||
# Сначала обрабатываем уже полученные строки.
|
||||
# Это исключает зависимость от готовности сокета,
|
||||
# когда данные остались во внутреннем буфере.
|
||||
while b"\n" in pending:
|
||||
line, pending = pending.split(b"\n", 1)
|
||||
|
||||
gps = parse_nmea(
|
||||
line.decode("ascii", errors="replace").strip(),
|
||||
datetime.now(timezone.utc)
|
||||
)
|
||||
|
||||
if gps is not None:
|
||||
self._set_fix(gps)
|
||||
else:
|
||||
self._check_fix_freshness()
|
||||
|
||||
if len(pending) > GPSD_GREETING_MAX_BYTES:
|
||||
raise ConnectionError(
|
||||
"NMEA receive buffer exceeds the allowed size"
|
||||
)
|
||||
|
||||
readable, _, _ = select.select(
|
||||
[connection],
|
||||
[],
|
||||
[],
|
||||
POLL_INTERVAL_SECONDS
|
||||
)
|
||||
|
||||
if not readable:
|
||||
self._check_fix_freshness()
|
||||
continue
|
||||
|
||||
chunk = connection.recv(4096)
|
||||
|
||||
if not chunk:
|
||||
raise ConnectionError(
|
||||
"GPS source closed the NMEA stream"
|
||||
)
|
||||
|
||||
pending += chunk
|
||||
|
||||
except Exception as error:
|
||||
if self.stop_event.is_set():
|
||||
break
|
||||
|
||||
with self.state_lock:
|
||||
self.current_fix = None
|
||||
self.state = "RECONNECTING"
|
||||
self.error = str(error)
|
||||
|
||||
self._emit(
|
||||
"WARNING",
|
||||
"GPS_CONNECTION_LOST",
|
||||
"Auto GPS connection lost: "
|
||||
f"{error}. Reconnecting to the same source."
|
||||
)
|
||||
|
||||
finally:
|
||||
if stream is not None:
|
||||
try:
|
||||
stream.close()
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Auto GPS stream close failed"
|
||||
)
|
||||
|
||||
if source is not None:
|
||||
try:
|
||||
source.close()
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Auto GPS source close failed"
|
||||
)
|
||||
|
||||
with self.source_lock:
|
||||
if self.source is source:
|
||||
self.source = None
|
||||
|
||||
if not self.stop_event.is_set():
|
||||
self.stop_event.wait(
|
||||
RECONNECT_DELAY_SECONDS
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
with self.state_lock:
|
||||
self.error = str(error)
|
||||
self.state = "ERROR"
|
||||
|
||||
self._emit(
|
||||
"ERROR",
|
||||
"GPS_SERVICE_ERROR",
|
||||
f"Auto GPS service error: {error}"
|
||||
)
|
||||
|
||||
finally:
|
||||
with self.state_lock:
|
||||
self.current_fix = None
|
||||
self.running = False
|
||||
was_error = self.state == "ERROR"
|
||||
|
||||
if not was_error:
|
||||
self.state = "STOPPED"
|
||||
|
||||
if not was_error:
|
||||
self._emit(
|
||||
"INFO",
|
||||
"GPS_STOPPED",
|
||||
"Auto GPS service stopped"
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
+352
-4
@@ -7,6 +7,202 @@ from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def _migrate_wifi_verification(conn):
|
||||
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS wifi_verification_settings (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
|
||||
radius_options TEXT NOT NULL
|
||||
DEFAULT '[25,50,100,200,300]',
|
||||
|
||||
radius_m INTEGER NOT NULL DEFAULT 100
|
||||
CHECK (radius_m > 0),
|
||||
|
||||
gnss_max_age_seconds INTEGER NOT NULL DEFAULT 5
|
||||
CHECK (gnss_max_age_seconds > 0),
|
||||
|
||||
queue_retry_passes INTEGER NOT NULL DEFAULT 1
|
||||
CHECK (queue_retry_passes >= 0),
|
||||
|
||||
updated_at TEXT NOT NULL
|
||||
DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
|
||||
)
|
||||
""")
|
||||
|
||||
conn.execute("""
|
||||
INSERT OR IGNORE INTO wifi_verification_settings (
|
||||
id
|
||||
)
|
||||
VALUES (1)
|
||||
""")
|
||||
|
||||
columns = {
|
||||
row[1]
|
||||
for row in conn.execute(
|
||||
"PRAGMA table_info(wifi_verification_settings)"
|
||||
)
|
||||
}
|
||||
|
||||
if "retry_interval_seconds" in columns:
|
||||
conn.execute("""
|
||||
ALTER TABLE wifi_verification_settings
|
||||
DROP COLUMN retry_interval_seconds
|
||||
""")
|
||||
|
||||
if "gps_source" not in columns:
|
||||
|
||||
conn.execute("""
|
||||
ALTER TABLE wifi_verification_settings
|
||||
ADD COLUMN gps_source TEXT
|
||||
CHECK (gps_source IN ('gpsd', 'gpsrelay'))
|
||||
""")
|
||||
|
||||
columns = {
|
||||
row[1]
|
||||
for row in conn.execute(
|
||||
"PRAGMA table_info(wifi_verification_settings)"
|
||||
)
|
||||
}
|
||||
|
||||
if "gpsrelay_host" not in columns:
|
||||
|
||||
conn.execute("""
|
||||
ALTER TABLE wifi_verification_settings
|
||||
ADD COLUMN gpsrelay_host TEXT
|
||||
CHECK (
|
||||
gpsrelay_host IS NULL
|
||||
OR length(trim(gpsrelay_host)) > 0
|
||||
)
|
||||
""")
|
||||
|
||||
if "gpsrelay_port" not in columns:
|
||||
|
||||
conn.execute("""
|
||||
ALTER TABLE wifi_verification_settings
|
||||
ADD COLUMN gpsrelay_port INTEGER
|
||||
CHECK (
|
||||
gpsrelay_port IS NULL
|
||||
OR gpsrelay_port BETWEEN 1 AND 65535
|
||||
)
|
||||
""")
|
||||
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS wifi_verification_sessions (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
|
||||
started_at TEXT NOT NULL,
|
||||
|
||||
finished_at TEXT,
|
||||
|
||||
status TEXT NOT NULL
|
||||
CHECK (
|
||||
status IN (
|
||||
'RUNNING',
|
||||
'PAUSED_GNSS',
|
||||
'PAUSED_QUEUE',
|
||||
'STOPPED',
|
||||
'ERROR'
|
||||
)
|
||||
),
|
||||
|
||||
radius_m INTEGER NOT NULL,
|
||||
|
||||
interface_name TEXT NOT NULL,
|
||||
|
||||
access_points_total INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
attempts_total INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
success_count INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
invalid_password_count INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
technical_error_count INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
""")
|
||||
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS wifi_verification_attempts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
|
||||
credential_id INTEGER,
|
||||
|
||||
session_id INTEGER,
|
||||
|
||||
verification_mode TEXT NOT NULL
|
||||
CHECK (
|
||||
verification_mode IN ('MANUAL', 'AUTO')
|
||||
),
|
||||
|
||||
status TEXT NOT NULL
|
||||
CHECK (
|
||||
status IN (
|
||||
'SUCCESS',
|
||||
'INVALID_PASSWORD',
|
||||
'AP_NOT_FOUND',
|
||||
'CONNECTION_TIMEOUT',
|
||||
'NETWORK_ERROR',
|
||||
'UNKNOWN_ERROR',
|
||||
'CANCELLED'
|
||||
)
|
||||
),
|
||||
|
||||
started_at TEXT NOT NULL,
|
||||
|
||||
finished_at TEXT,
|
||||
|
||||
interface_name TEXT,
|
||||
|
||||
bssid TEXT,
|
||||
|
||||
error_code TEXT,
|
||||
|
||||
error_message TEXT,
|
||||
|
||||
FOREIGN KEY (credential_id)
|
||||
REFERENCES credentials(id)
|
||||
ON DELETE SET NULL,
|
||||
|
||||
FOREIGN KEY (session_id)
|
||||
REFERENCES wifi_verification_sessions(id)
|
||||
ON DELETE SET NULL
|
||||
)
|
||||
""")
|
||||
|
||||
conn.execute("""
|
||||
CREATE INDEX IF NOT EXISTS
|
||||
idx_wifi_verification_sessions_started
|
||||
ON wifi_verification_sessions(started_at)
|
||||
""")
|
||||
|
||||
conn.execute("""
|
||||
CREATE INDEX IF NOT EXISTS
|
||||
idx_wifi_verification_attempts_session
|
||||
ON wifi_verification_attempts(session_id, started_at)
|
||||
""")
|
||||
|
||||
conn.execute("""
|
||||
CREATE INDEX IF NOT EXISTS
|
||||
idx_wifi_verification_attempts_credential
|
||||
ON wifi_verification_attempts(credential_id, started_at)
|
||||
""")
|
||||
|
||||
|
||||
|
||||
def migrate_wifi_verification_database(db_path):
|
||||
"""Запускает только миграцию схемы Auto Verification."""
|
||||
conn = sqlite3.connect(db_path)
|
||||
try:
|
||||
_migrate_wifi_verification(conn)
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
class Database:
|
||||
|
||||
|
||||
@@ -384,6 +580,7 @@ class Database:
|
||||
|
||||
self.conn.commit()
|
||||
|
||||
|
||||
def _migrate_credentials_table(
|
||||
self
|
||||
):
|
||||
@@ -826,10 +1023,15 @@ class Database:
|
||||
|
||||
def create_session(
|
||||
self,
|
||||
capture_file
|
||||
capture_file,
|
||||
start_time=None
|
||||
):
|
||||
|
||||
|
||||
session_start = start_time or datetime.now(
|
||||
timezone.utc
|
||||
)
|
||||
|
||||
cursor = self.conn.execute(
|
||||
"""
|
||||
INSERT INTO capture_sessions
|
||||
@@ -842,9 +1044,7 @@ class Database:
|
||||
""",
|
||||
|
||||
(
|
||||
datetime.now(
|
||||
timezone.utc
|
||||
).isoformat().replace(
|
||||
session_start.isoformat().replace(
|
||||
"+00:00",
|
||||
"Z"
|
||||
),
|
||||
@@ -984,6 +1184,154 @@ class Database:
|
||||
return True
|
||||
|
||||
|
||||
# =========================================================
|
||||
# Wi-Fi verification settings
|
||||
# =========================================================
|
||||
|
||||
def get_wifi_verification_settings(self):
|
||||
|
||||
row = self.conn.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM wifi_verification_settings
|
||||
WHERE id=1
|
||||
"""
|
||||
).fetchone()
|
||||
|
||||
if row is None:
|
||||
return None
|
||||
|
||||
return dict(row)
|
||||
|
||||
def update_wifi_verification_settings(
|
||||
self,
|
||||
settings
|
||||
):
|
||||
|
||||
if not isinstance(settings, dict):
|
||||
raise ValueError("Настройки должны быть словарём.")
|
||||
|
||||
allowed = (
|
||||
"gps_source",
|
||||
"gpsrelay_host",
|
||||
"gpsrelay_port",
|
||||
"radius_options",
|
||||
"radius_m",
|
||||
"gnss_max_age_seconds",
|
||||
"queue_retry_passes"
|
||||
)
|
||||
|
||||
unknown = set(settings) - set(allowed)
|
||||
|
||||
if unknown:
|
||||
raise ValueError(
|
||||
"Неизвестные настройки: "
|
||||
+ ", ".join(sorted(unknown))
|
||||
)
|
||||
|
||||
if not settings:
|
||||
raise ValueError("Не переданы настройки для обновления.")
|
||||
|
||||
values = dict(settings)
|
||||
|
||||
if "gps_source" in values:
|
||||
if values["gps_source"] not in (None, "gpsd", "gpsrelay"):
|
||||
raise ValueError("Недопустимый источник GPS.")
|
||||
|
||||
if "gpsrelay_host" in values:
|
||||
host = values["gpsrelay_host"]
|
||||
|
||||
if host is not None:
|
||||
if not isinstance(host, str) or not host.strip():
|
||||
raise ValueError("Некорректный адрес GPS Relay.")
|
||||
|
||||
values["gpsrelay_host"] = host.strip()
|
||||
|
||||
if "gpsrelay_port" in values:
|
||||
port = values["gpsrelay_port"]
|
||||
|
||||
if port is not None:
|
||||
if (
|
||||
isinstance(port, bool)
|
||||
or not isinstance(port, int)
|
||||
or not 1 <= port <= 65535
|
||||
):
|
||||
raise ValueError("Порт GPS Relay должен быть от 1 до 65535.")
|
||||
|
||||
integer_limits = {
|
||||
"radius_m": 1,
|
||||
"gnss_max_age_seconds": 1,
|
||||
"queue_retry_passes": 0
|
||||
}
|
||||
|
||||
for name, minimum in integer_limits.items():
|
||||
if name not in values:
|
||||
continue
|
||||
|
||||
value = values[name]
|
||||
|
||||
if (
|
||||
isinstance(value, bool)
|
||||
or not isinstance(value, int)
|
||||
or value < minimum
|
||||
):
|
||||
raise ValueError(
|
||||
f"Некорректное значение настройки {name}."
|
||||
)
|
||||
|
||||
if "radius_options" in values:
|
||||
options = values["radius_options"]
|
||||
|
||||
if isinstance(options, str):
|
||||
try:
|
||||
options = json.loads(options)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("radius_options должен содержать JSON-массив.")
|
||||
|
||||
if (
|
||||
not isinstance(options, (list, tuple))
|
||||
or not options
|
||||
or any(
|
||||
isinstance(value, bool)
|
||||
or not isinstance(value, int)
|
||||
or value <= 0
|
||||
for value in options
|
||||
)
|
||||
or len(set(options)) != len(options)
|
||||
):
|
||||
raise ValueError("Некорректный список radius_options.")
|
||||
|
||||
values["radius_options"] = json.dumps(
|
||||
list(options),
|
||||
separators=(",", ":")
|
||||
)
|
||||
|
||||
assignments = [
|
||||
f"{name}=?"
|
||||
for name in allowed
|
||||
if name in values
|
||||
]
|
||||
|
||||
parameters = [
|
||||
values[name]
|
||||
for name in allowed
|
||||
if name in values
|
||||
]
|
||||
|
||||
self.conn.execute(
|
||||
f"""
|
||||
UPDATE wifi_verification_settings
|
||||
SET
|
||||
{", ".join(assignments)},
|
||||
updated_at=strftime('%Y-%m-%dT%H:%M:%fZ', 'now')
|
||||
WHERE id=1
|
||||
""",
|
||||
parameters
|
||||
)
|
||||
|
||||
return self.get_wifi_verification_settings()
|
||||
|
||||
|
||||
# =========================================================
|
||||
# Access points
|
||||
# =========================================================
|
||||
|
||||
@@ -0,0 +1,642 @@
|
||||
|
||||
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)
|
||||
}
|
||||
@@ -289,6 +289,63 @@ def wait_for_scanner(app_module):
|
||||
log("Сканер и поток чтения его вывода завершены.")
|
||||
|
||||
|
||||
def stop_auto_gps(app_module):
|
||||
with app_module.auto_gps_lock:
|
||||
service = app_module.auto_gps_service
|
||||
|
||||
if service is None:
|
||||
return
|
||||
|
||||
thread = service.thread
|
||||
|
||||
if thread is None or not thread.is_alive():
|
||||
return
|
||||
|
||||
log("Останавливается Auto GPS.")
|
||||
|
||||
service.stop()
|
||||
|
||||
if thread is not threading.current_thread():
|
||||
thread.join(timeout=5)
|
||||
|
||||
if thread.is_alive():
|
||||
log(
|
||||
"Предупреждение: поток Auto GPS не завершился "
|
||||
"за отведённое время."
|
||||
)
|
||||
else:
|
||||
log("Auto GPS завершён.")
|
||||
|
||||
|
||||
def stop_auto_wifi_verification(app_module):
|
||||
|
||||
with app_module.auto_wifi_verification_lock:
|
||||
service = app_module.auto_wifi_verification_service
|
||||
|
||||
if service is None:
|
||||
return
|
||||
|
||||
thread = service.thread
|
||||
|
||||
if thread is None or not thread.is_alive():
|
||||
return
|
||||
|
||||
log("Останавливается автоматическая проверка Wi-Fi.")
|
||||
|
||||
service.stop()
|
||||
|
||||
if thread is not threading.current_thread():
|
||||
thread.join(timeout=5)
|
||||
|
||||
if thread.is_alive():
|
||||
log(
|
||||
"Предупреждение: поток автоматической проверки Wi-Fi "
|
||||
"не завершился за отведённое время."
|
||||
)
|
||||
else:
|
||||
log("Автоматическая проверка Wi-Fi завершена.")
|
||||
|
||||
|
||||
def stop_gps_test(app_module):
|
||||
with app_module.gps_test_lock:
|
||||
service = app_module.gps_test_service
|
||||
@@ -502,6 +559,17 @@ def send_sudo_authentication():
|
||||
)
|
||||
|
||||
|
||||
def migrate_application_database(database_file=None):
|
||||
from database import migrate_wifi_verification_database
|
||||
|
||||
if database_file is None:
|
||||
from reports.config import DATABASE_FILE
|
||||
|
||||
database_file = DATABASE_FILE
|
||||
|
||||
migrate_wifi_verification_database(database_file)
|
||||
|
||||
|
||||
def run_server():
|
||||
os.chdir(PROJECT_ROOT)
|
||||
|
||||
@@ -540,6 +608,11 @@ def run_server():
|
||||
|
||||
try:
|
||||
receive_sudo_authentication(shutdown_event)
|
||||
|
||||
log("Проверка схемы базы данных Auto Verification.")
|
||||
migrate_application_database()
|
||||
log("Схема базы данных Auto Verification актуальна.")
|
||||
|
||||
tileserver_process = start_tileserver()
|
||||
|
||||
from gui import app as app_module
|
||||
@@ -597,6 +670,8 @@ def run_server():
|
||||
log("Ожидание завершения активных HTTP-запросов.")
|
||||
app_module.request_lifecycle.wait_for_drain()
|
||||
|
||||
stop_auto_wifi_verification(app_module)
|
||||
stop_auto_gps(app_module)
|
||||
stop_gps_test(app_module)
|
||||
wait_for_scanner(app_module)
|
||||
join_background_threads(app_module)
|
||||
@@ -799,9 +874,7 @@ def stop_service():
|
||||
run_sudo_validation()
|
||||
|
||||
systemctl_user(
|
||||
"kill",
|
||||
"--kill-whom=main",
|
||||
"--signal=SIGTERM",
|
||||
"stop",
|
||||
f"{UNIT_NAME}.service"
|
||||
)
|
||||
|
||||
|
||||
+46
-6
@@ -148,6 +148,8 @@ def shutdown(signum=None, frame=None):
|
||||
f"WiFi stop error: {error}"
|
||||
)
|
||||
|
||||
parser_succeeded = False
|
||||
|
||||
try:
|
||||
|
||||
if parser and session:
|
||||
@@ -157,6 +159,8 @@ def shutdown(signum=None, frame=None):
|
||||
session_id
|
||||
)
|
||||
|
||||
parser_succeeded = True
|
||||
|
||||
|
||||
except Exception as error:
|
||||
|
||||
@@ -179,17 +183,31 @@ def shutdown(signum=None, frame=None):
|
||||
|
||||
|
||||
|
||||
database_close_safe = True
|
||||
|
||||
try:
|
||||
|
||||
if (db and session_id is not None):
|
||||
|
||||
db.flush_observations()
|
||||
if parser_succeeded:
|
||||
|
||||
db.finalize_session(
|
||||
session_id
|
||||
)
|
||||
db.flush_observations()
|
||||
|
||||
db.commit()
|
||||
db.finalize_session(
|
||||
session_id
|
||||
)
|
||||
|
||||
db.commit()
|
||||
|
||||
else:
|
||||
|
||||
db.observation_buffer.clear()
|
||||
|
||||
db.rollback()
|
||||
|
||||
logger.warning(
|
||||
"Parser did not complete; session transaction rolled back"
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
|
||||
@@ -197,6 +215,22 @@ def shutdown(signum=None, frame=None):
|
||||
f"Database finalize error: {error}"
|
||||
)
|
||||
|
||||
if db:
|
||||
|
||||
try:
|
||||
|
||||
db.observation_buffer.clear()
|
||||
|
||||
db.rollback()
|
||||
|
||||
except Exception as rollback_error:
|
||||
|
||||
logger.error(
|
||||
f"Database rollback error: {rollback_error}"
|
||||
)
|
||||
|
||||
database_close_safe = False
|
||||
|
||||
|
||||
|
||||
try:
|
||||
@@ -218,7 +252,13 @@ def shutdown(signum=None, frame=None):
|
||||
|
||||
if db:
|
||||
|
||||
db.close()
|
||||
if database_close_safe:
|
||||
|
||||
db.close()
|
||||
|
||||
else:
|
||||
|
||||
db.conn.close()
|
||||
|
||||
|
||||
except Exception:
|
||||
|
||||
+13
-4
@@ -173,12 +173,21 @@ class Session:
|
||||
|
||||
obj = cls.__new__(cls)
|
||||
|
||||
obj.start_time = datetime.now(
|
||||
timezone.utc
|
||||
)
|
||||
|
||||
obj.path = Path(path)
|
||||
|
||||
try:
|
||||
obj.start_time = datetime.strptime(
|
||||
obj.path.name,
|
||||
"%Y%m%d_%H%M%S"
|
||||
).replace(
|
||||
tzinfo=timezone.utc
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise ValueError(
|
||||
"Invalid session directory timestamp: "
|
||||
f"{obj.path.name}"
|
||||
) from exc
|
||||
|
||||
obj.capture_file = (
|
||||
obj.path /
|
||||
"capture.pcapng"
|
||||
|
||||
+848
-94
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user