4 Commits
23 changed files with 10009 additions and 3654 deletions
+17
View File
@@ -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.
+3
View File
@@ -112,6 +112,9 @@ reports:
# Количество последних сессий, отображаемых в соответствующих разделах.
recent_sessions_limit: 10
# Количество сессий на странице Capture Sessions по умолчанию.
sessions_page_limit: 20
# Настройки журналирования приложения.
logging:
# Уровень подробности журналов.
+1566 -183
View File
File diff suppressed because it is too large Load Diff
+1472
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+24 -1
View File
@@ -128,6 +128,27 @@ fi
PYTHON="$VENV_DIR/bin/python"
log "ПРОВЕРКА PIP"
if ! "$PYTHON" -m pip --version >/dev/null 2>&1; then
echo "pip отсутствует в виртуальном окружении. Восстанавливаем..."
if ! "$PYTHON" -m ensurepip --upgrade; then
echo "Не удалось восстановить pip через ensurepip."
install_python_venv_package
"$PYTHON" -m ensurepip --upgrade ||
fail "Не удалось восстановить pip даже после установки системного пакета."
fi
"$PYTHON" -m pip --version >/dev/null 2>&1 ||
fail "pip не найден после попытки восстановления."
echo "pip успешно восстановлен."
else
echo "pip уже установлен."
fi
log "УСТАНОВКА PYTHON-ЗАВИСИМОСТЕЙ"
"$PYTHON" -m pip install --upgrade pip
@@ -153,7 +174,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")
@@ -166,6 +187,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)
+16
View File
@@ -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>
"""
+13 -9
View File
@@ -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) {{
+271
View File
@@ -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),
}
+9
View File
@@ -56,6 +56,15 @@ RECENT_SESSIONS_LIMIT = REPORTS_CONFIG.get(
10
)
try:
SESSIONS_PAGE_LIMIT = int(
REPORTS_CONFIG.get("sessions_page_limit", 20)
)
if SESSIONS_PAGE_LIMIT <= 0:
raise ValueError
except (TypeError, ValueError):
SESSIONS_PAGE_LIMIT = 20
TIMEZONE = CONFIG.get("timezone", "Europe/Moscow")
@lru_cache(maxsize=1)
+171 -2
View File
@@ -20,6 +20,7 @@ from pathlib import Path
from .config import (
RECENT_SESSIONS_LIMIT,
SESSIONS_PAGE_LIMIT,
)
from .utils import (
@@ -63,6 +64,8 @@ from .sessions import (
)
from .recovery import recovery_block
# ============================================================
# Helpers
# ============================================================
@@ -792,6 +795,14 @@ def generate_dashboard(
context,
)
# --------------------------------------------------------
# Recovery
# --------------------------------------------------------
html += recovery_block(
conn
)
# --------------------------------------------------------
# Footer
# --------------------------------------------------------
@@ -807,8 +818,21 @@ def generate_dashboard(
def generate_capture_sessions(
conn,
context=None,
sessions_page_limit=None,
):
if sessions_page_limit is None:
display_limit = SESSIONS_PAGE_LIMIT
elif str(sessions_page_limit).lower() == "all":
display_limit = "all"
else:
try:
display_limit = int(sessions_page_limit)
if display_limit <= 0:
raise ValueError
except (TypeError, ValueError):
display_limit = SESSIONS_PAGE_LIMIT
sessions = all_sessions(
conn
)
@@ -957,7 +981,7 @@ Total sessions: <b>{len(sessions)}</b>
</article>
""")
html += """
html += f"""
<div class="session-list-toolbar">
@@ -981,12 +1005,40 @@ Total sessions: <b>{len(sessions)}</b>
↓
</button>
<label for="session-limit">
Show:
</label>
<select id="session-limit">
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="500">500</option>
<option value="all">All</option>
<option value="custom">Custom</option>
</select>
<input
type="number"
id="session-custom-limit"
min="1"
step="1"
placeholder="Number"
aria-label="Custom number of sessions"
style="width: 100px;"
>
<span id="session-count"></span>
</div>
<div
class="session-list"
id="session-list"
data-sort-direction="desc"
data-display-limit="{display_limit}"
data-default-limit="{SESSIONS_PAGE_LIMIT}"
>
"""
@@ -1002,13 +1054,83 @@ Total sessions: <b>{len(sessions)}</b>
const list = document.getElementById("session-list");
const sortSelect = document.getElementById("session-sort");
const directionButton = document.getElementById("session-sort-direction");
const limitSelect = document.getElementById("session-limit");
const customLimitInput = document.getElementById("session-custom-limit");
const sessionCount = document.getElementById("session-count");
if (!list || !sortSelect || !directionButton) {
if (
!list ||
!sortSelect ||
!directionButton ||
!limitSelect ||
!customLimitInput ||
!sessionCount
) {
return;
}
let descending = true;
const defaultLimit = Number(list.dataset.defaultLimit) || 20;
const initialLimit = list.dataset.displayLimit;
const predefinedLimits = ["10", "20", "50", "100", "500", "all"];
function getDisplayLimit() {
if (limitSelect.value === "all") {
return "all";
}
if (limitSelect.value === "custom") {
const value = Number(customLimitInput.value);
if (
!Number.isInteger(value) ||
value <= 0
) {
return defaultLimit;
}
return value;
}
return Number(limitSelect.value) || defaultLimit;
}
function updateUrl() {
const params = new URLSearchParams(window.location.search);
const limit = getDisplayLimit();
params.set("limit", String(limit));
const query = params.toString();
const newUrl = window.location.pathname +
(query ? "?" + query : "") +
window.location.hash;
window.history.replaceState({}, "", newUrl);
}
function applyDisplayLimit() {
const cards = Array.from(
list.querySelectorAll(".session-compact-card")
);
const limit = getDisplayLimit();
const visibleCount = limit === "all"
? cards.length
: Math.min(cards.length, limit);
cards.forEach(function (card, index) {
card.style.display = index >= visibleCount ? "none" : "";
});
sessionCount.textContent =
"Showing " + visibleCount + " of " + cards.length;
}
function sortSessions() {
const sortBy = sortSelect.value;
@@ -1071,6 +1193,8 @@ Total sessions: <b>{len(sessions)}</b>
directionButton.textContent = descending ? "↓" : "↑";
list.dataset.sortDirection = descending ? "desc" : "asc";
applyDisplayLimit();
}
sortSelect.addEventListener("change", function () {
@@ -1087,6 +1211,51 @@ Total sessions: <b>{len(sessions)}</b>
sortSessions();
});
limitSelect.addEventListener("change", function () {
if (limitSelect.value !== "custom") {
customLimitInput.value = "";
}
if (limitSelect.value === "custom") {
customLimitInput.focus();
}
applyDisplayLimit();
updateUrl();
});
customLimitInput.addEventListener("input", function () {
limitSelect.value = "custom";
const value = Number(customLimitInput.value);
if (
Number.isInteger(value) &&
value > 0
) {
applyDisplayLimit();
updateUrl();
} else {
applyDisplayLimit();
}
});
if (initialLimit === "all") {
limitSelect.value = "all";
} else if (predefinedLimits.includes(initialLimit)) {
limitSelect.value = initialLimit;
} else {
limitSelect.value = "custom";
customLimitInput.value = initialLimit;
}
sortSessions();
})();
+366
View File
@@ -0,0 +1,366 @@
from datetime import datetime, timedelta, timezone
from pathlib import Path
from zoneinfo import ZoneInfo
from .config import CAPTURES_DIR, get_timezone
from .template import card
from .utils import esc
MIN_STALE_AGE = timedelta(minutes=15)
MAX_STALE_AGE = timedelta(hours=24)
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 (
MIN_STALE_AGE <= age <= MAX_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 _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 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 = []
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
capture_path = session_dir / "capture.pcapng"
parser_log = session_dir / "parser.log"
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,
)
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
"Проверить исходные файлы и оценить возможность "
"повторного выполнения парсинга."
),
})
return candidates
def recovery_block(conn):
candidates = find_recovery_candidates(conn)
if not candidates:
return ""
html = []
for candidate in candidates:
counts = candidate["counts"]
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"]
)
html.append(f"""
<div class="card">
<h3>Поездка #{candidate["id"]}</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>
</div>
""")
return card(
"⚠️ Восстановление поездок",
"\n".join(html),
)
+1 -1
View File
@@ -1318,7 +1318,7 @@ def render_search_page(
"search-map",
style:
"{map_style}",
{map_style},
center: [
geojson.features[0]
+191 -2
View File
@@ -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
@@ -593,11 +616,13 @@ code {
margin-bottom: 18px;
}
.session-list-toolbar label {
.session-list-toolbar label,
.session-list-toolbar #session-count {
color: var(--muted);
}
.session-list-toolbar select {
.session-list-toolbar select,
.session-list-toolbar input[type="number"] {
background: var(--surface);
color: var(--text);
@@ -1727,3 +1752,167 @@ body .maplibregl-popup-close-button:hover {
cursor: pointer;
font-weight: 600;
}
/* ============================================================
WiFiTrip export selection
============================================================ */
.wifitrip-export-options {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 18px;
margin-top: 22px;
}
.wifitrip-export-mode {
min-width: 0;
padding: 16px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 9px;
transition:
border-color 0.15s ease,
background 0.15s ease;
}
.wifitrip-export-mode:has(.wifitrip-mode-tab input:checked) {
border-color: var(--accent);
background: var(--surface-light);
}
.wifitrip-mode-tab {
display: flex;
align-items: center;
gap: 10px;
min-height: 24px;
color: var(--muted);
font-size: 15px;
font-weight: 700;
cursor: pointer;
}
.wifitrip-mode-tab input {
position: absolute;
width: 1px;
height: 1px;
opacity: 0;
pointer-events: none;
}
.wifitrip-mode-tab span {
display: block;
width: 100%;
padding: 5px 0 12px;
border-bottom: 2px solid transparent;
transition:
color 0.15s ease,
border-color 0.15s ease;
}
.wifitrip-mode-tab input:checked + span {
color: var(--text);
border-bottom-color: var(--accent);
}
.wifitrip-mode-tab input:focus-visible + span {
outline: 2px solid var(--accent);
outline-offset: 4px;
}
.wifitrip-mode-content {
display: flex;
flex-direction: column;
gap: 9px;
margin-top: 16px;
}
.wifitrip-mode-content label {
color: var(--muted);
font-size: 13px;
}
.wifitrip-mode-content .session-list-toolbar label {
font-size: inherit;
}
.wifitrip-mode-content > select,
.wifitrip-mode-content input[type="date"] {
width: 100%;
min-height: 38px;
padding: 8px 12px;
background: var(--surface);
color: var(--text);
border: 1px solid var(--border);
border-radius: 7px;
font-family: "Bender", Arial, Helvetica, sans-serif;
font-size: 14px;
color-scheme: dark;
}
.wifitrip-mode-content select:focus,
.wifitrip-mode-content input[type="date"]:focus,
.wifitrip-mode-content input[type="number"]:focus {
outline: none;
border-color: var(--accent);
box-shadow: 0 0 0 2px rgba(105, 167, 255, 0.12);
}
.wifitrip-mode-content select:disabled,
.wifitrip-mode-content input[type="date"]:disabled,
.wifitrip-mode-content input[type="number"]:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.wifitrip-date-fields {
gap: 14px;
}
.wifitrip-date-fields > div {
display: flex;
flex-direction: column;
gap: 9px;
}
.wifitrip-export-footer {
display: flex;
flex-direction: column;
align-items: center;
gap: 14px;
margin-top: 24px;
text-align: center;
}
.wifitrip-export-footer p {
margin: 0;
color: var(--text);
font-weight: 700;
}
.wifitrip-export-footer .button {
min-width: 220px;
text-align: center;
}
.wifitrip-export-footer .button:disabled {
opacity: 0.45;
cursor: not-allowed;
}
@media (max-width: 700px) {
.wifitrip-export-options {
grid-template-columns: 1fr;
gap: 12px;
}
.wifitrip-export-mode {
padding: 14px;
}
.wifitrip-export-footer .button {
width: 100%;
}
}
+425 -25
View File
@@ -234,12 +234,6 @@ def render_trips_page(
page="trips",
)
session_count = conn.execute(
"""
SELECT COUNT(*) AS count
FROM capture_sessions
"""
).fetchone()["count"]
html = page_begin(
"Trips",
@@ -257,44 +251,450 @@ def render_trips_page(
)
html += """
<section class="card">
<h2>Export capture sessions</h2>
<h2>Экспорт поездок</h2>
<p>
Export all capture sessions into one
<code>.wifitrip</code> package.
Выберите поездки, которые нужно включить
в пакет <code>.wifitrip</code>.
</p>
<p>
The package contains logical session data:
GPS track, access-point observations,
handshakes and credentials. Physical capture
files are not included.
Пакет содержит данные поездок: GPS-треки,
наблюдения точек доступа и рукопожатия.
Файлы захвата и пароли не включаются.
</p>
<div class="stats-grid">
"""
html += _stat_card(
"Sessions available",
session_count,
)
html += """
</div>
<form
id="wifitrip-export-form"
method="get"
action="/reports/trips/export"
>
<button type="submit" class="button">
Export all sessions
<div class="wifitrip-export-options">
<div class="wifitrip-export-mode wifitrip-export-mode-active">
<label class="wifitrip-mode-tab">
<input
type="radio"
name="mode"
value="latest"
checked
>
<span>Последние поездки</span>
</label>
<div class="wifitrip-mode-content">
<div class="session-list-toolbar wifitrip-limit-toolbar">
<label for="wifitrip-limit">
Show:
</label>
<select
id="wifitrip-limit"
name="limit"
>
<option value="1" selected>1</option>
<option value="3">3</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
<option value="100">100</option>
<option value="custom">Custom</option>
<option value="all">All</option>
</select>
<input
type="number"
id="wifitrip-custom-limit"
name="custom_limit"
min="1"
max="1"
step="1"
value="1"
placeholder="Number"
aria-label="Custom number of trips"
style="width: 100px;"
disabled
>
<span id="wifitrip-limit-count"></span>
</div>
</div>
</div>
<div class="wifitrip-export-mode">
<label class="wifitrip-mode-tab">
<input
type="radio"
name="mode"
value="range"
>
<span>По диапазону дат</span>
</label>
<div
id="wifitrip-date-range"
class="wifitrip-mode-content wifitrip-date-fields"
>
<div>
<label for="wifitrip-date-from">
Начальная дата
</label>
<input
type="date"
id="wifitrip-date-from"
name="date_from"
disabled
>
</div>
<div>
<label for="wifitrip-date-to">
Конечная дата
</label>
<input
type="date"
id="wifitrip-date-to"
name="date_to"
disabled
>
</div>
</div>
</div>
</div>
<div class="wifitrip-export-footer">
<p
id="wifitrip-export-preview"
aria-live="polite"
>
Подсчёт поездок...
</p>
<button
type="submit"
id="wifitrip-export-button"
class="button"
disabled
>
Экспортировать поездки
</button>
</div>
</form>
<script>
(function () {
const form = document.getElementById(
"wifitrip-export-form"
);
const limitInput = document.getElementById(
"wifitrip-limit"
);
const customLimitInput = document.getElementById(
"wifitrip-custom-limit"
);
const limitCount = document.getElementById(
"wifitrip-limit-count"
);
const dateFromInput = document.getElementById(
"wifitrip-date-from"
);
const dateToInput = document.getElementById(
"wifitrip-date-to"
);
const preview = document.getElementById(
"wifitrip-export-preview"
);
const exportButton = document.getElementById(
"wifitrip-export-button"
);
if (
!form ||
!limitInput ||
!customLimitInput ||
!limitCount ||
!dateFromInput ||
!dateToInput ||
!preview ||
!exportButton
) {
return;
}
let previewRequest = 0;
let availableSessions = null;
function getMode() {
const selected = form.querySelector(
'input[name="mode"]:checked'
);
return selected ? selected.value : "latest";
}
function updateControls() {
const mode = getMode();
const isRange = mode === "range";
const isCustomLimit =
mode === "latest" && limitInput.value === "custom";
limitInput.disabled = mode !== "latest";
customLimitInput.disabled = mode !== "latest";
customLimitInput.required = isCustomLimit;
customLimitInput.max = String(
Math.max(1, availableSessions || 1)
);
const customOption = limitInput.querySelector(
'option[value="custom"]'
);
if (customOption) {
customOption.disabled = availableSessions === 0;
}
dateFromInput.disabled = !isRange;
dateToInput.disabled = !isRange;
dateFromInput.required = isRange;
dateToInput.required = isRange;
if (isRange && dateFromInput.value) {
dateToInput.min = dateFromInput.value;
} else {
dateToInput.removeAttribute("min");
}
if (isRange && dateToInput.value) {
dateFromInput.max = dateToInput.value;
} else {
dateFromInput.removeAttribute("max");
}
}
async function updatePreview() {
const requestId = ++previewRequest;
updateControls();
const mode = getMode();
const isCustomLimit =
mode === "latest" && limitInput.value === "custom";
if (isCustomLimit) {
const customLimit = Number(customLimitInput.value);
if (availableSessions === null) {
preview.textContent =
"Дождитесь получения количества поездок.";
exportButton.disabled = true;
return;
}
if (
!customLimitInput.value ||
!Number.isInteger(customLimit) ||
customLimit < 1 ||
customLimit > availableSessions
) {
preview.textContent =
"Введите целое число от 1 до " +
availableSessions + ".";
exportButton.disabled = true;
return;
}
}
if (
mode === "range" &&
(
!dateFromInput.value ||
!dateToInput.value
)
) {
preview.textContent =
"Укажите начальную и конечную даты.";
exportButton.disabled = true;
return;
}
if (
mode === "range" &&
dateFromInput.value > dateToInput.value
) {
preview.textContent =
"Начальная дата не может быть позже конечной.";
exportButton.disabled = true;
return;
}
const params = new URLSearchParams();
params.set("mode", mode);
if (mode === "latest") {
params.set(
"limit",
isCustomLimit
? customLimitInput.value
: limitInput.value
);
}
if (mode === "range") {
params.set("date_from", dateFromInput.value);
params.set("date_to", dateToInput.value);
}
preview.textContent = "Подсчёт поездок...";
exportButton.disabled = true;
try {
const response = await fetch(
"/reports/trips/preview?" + params.toString(),
{
headers: {
"Accept": "application/json"
}
}
);
const result = await response.json();
if (requestId !== previewRequest) {
return;
}
if (!response.ok) {
throw new Error(
result.error || "Не удалось подсчитать поездки."
);
}
const count = Number(result.count);
const availableCount = Number(result.available_count);
if (!Number.isInteger(count) || count < 0) {
throw new Error(
"Сервер вернул некорректное количество поездок."
);
}
if (
!Number.isInteger(availableCount) ||
availableCount < 0
) {
throw new Error(
"Сервер вернул некорректное общее количество поездок."
);
}
availableSessions = availableCount;
updateControls();
limitCount.textContent =
"Showing " + count + " of " + availableCount;
preview.textContent =
"Будет экспортировано поездок: " + count;
exportButton.disabled = count === 0;
} catch (error) {
if (requestId !== previewRequest) {
return;
}
limitCount.textContent = "";
preview.textContent =
"Ошибка подсчёта: " + error.message;
exportButton.disabled = true;
}
}
form.addEventListener(
"change",
function (event) {
if (event.target === limitInput) {
if (limitInput.value !== "custom") {
customLimitInput.value = "";
} else {
customLimitInput.focus();
}
}
updatePreview();
}
);
form.addEventListener(
"input",
function (event) {
if (event.target === customLimitInput) {
limitInput.value = "custom";
}
updatePreview();
}
);
form.addEventListener(
"submit",
function (event) {
if (
!form.reportValidity() ||
exportButton.disabled
) {
event.preventDefault();
return;
}
if (
getMode() === "latest" &&
limitInput.value === "custom"
) {
const submittedLimit = document.createElement(
"input"
);
submittedLimit.type = "hidden";
submittedLimit.name = "limit";
submittedLimit.value = customLimitInput.value;
limitInput.disabled = true;
form.appendChild(submittedLimit);
}
}
);
updatePreview();
})();
</script>
</section>
"""
+13 -9
View File
@@ -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(
+143 -532
View File
@@ -24,7 +24,7 @@ logger = logging.getLogger(__name__)
WIFITRIP_FORMAT = "wifitrip"
WIFITRIP_VERSION = 1
WIFITRIP_VERSION = 2
SESSION_HASH_VERSION = 1
REQUIRED_FILES = (
@@ -34,7 +34,6 @@ REQUIRED_FILES = (
"access_points.json",
"observations.json",
"handshakes.json",
"credentials.json",
)
SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
@@ -167,6 +166,12 @@ def _read_package(path):
"Archive contains duplicate file names."
)
if "credentials.json" in names:
raise WifitripError(
"Archive contains unsupported file: "
"credentials.json"
)
missing = [
name
for name in REQUIRED_FILES
@@ -212,7 +217,6 @@ def _validate_package(data):
access_points = data["access_points.json"]
observations = data["observations.json"]
handshakes = data["handshakes.json"]
credentials = data["credentials.json"]
_require_dict(
manifest,
@@ -238,10 +242,6 @@ def _validate_package(data):
handshakes,
"handshakes.json",
)
_require_list(
credentials,
"credentials.json",
)
if manifest.get("format") != WIFITRIP_FORMAT:
raise WifitripError(
@@ -659,97 +659,6 @@ def _validate_package(data):
f"handshakes.json[{index}].speed",
)
for index, credential in enumerate(
credentials
):
_require_dict(
credential,
f"credentials.json[{index}]",
)
session_hash = credential.get(
"session_hash"
)
bssid = credential.get(
"bssid"
)
handshake_key = credential.get(
"handshake_key"
)
_validate_hash(
session_hash,
f"credentials.json[{index}].session_hash",
)
_require_bssid(
bssid,
f"credentials.json[{index}].bssid",
)
if session_hash not in session_versions:
raise WifitripError(
"Credential references unknown session: "
f"{session_hash}"
)
if bssid not in ap_map:
raise WifitripError(
"Credential references unknown BSSID: "
f"{bssid}"
)
if handshake_key is not None:
_require_string(
handshake_key,
f"credentials.json[{index}].handshake_key",
)
if handshake_key not in handshake_keys.get(
session_hash,
set(),
):
raise WifitripError(
"Credential references unknown handshake_key: "
f"{session_hash}: {handshake_key}"
)
_require_string(
credential.get("password"),
f"credentials.json[{index}].password",
)
if not credential.get("password"):
raise WifitripError(
"Credential password must not be empty."
)
_require_string(
credential.get("source"),
f"credentials.json[{index}].source",
allow_none=True,
)
_require_string(
credential.get("created_at"),
f"credentials.json[{index}].created_at",
allow_none=True,
)
verified = credential.get(
"verified"
)
_require_integer(
verified,
f"credentials.json[{index}].verified",
allow_none=False,
)
if verified not in (0, 1):
raise WifitripError(
"Credential verified must be 0 or 1."
)
def _session_hash(conn, session_id):
@@ -891,7 +800,110 @@ def _zip_write_json(archive, filename, value):
)
def export_wifitrip(conn, output_path=None):
def select_wifitrip_session_ids(
conn,
mode="all",
limit=1,
date_from=None,
date_to=None,
):
if mode == "latest":
if str(limit).lower() == "all":
rows = conn.execute(
"""
SELECT id
FROM capture_sessions
ORDER BY start_time DESC, id DESC
"""
).fetchall()
else:
try:
limit = int(limit)
except (TypeError, ValueError):
raise WifitripError(
"Invalid session limit."
)
available_count = conn.execute(
"SELECT COUNT(*) FROM capture_sessions"
).fetchone()[0]
if limit < 1 or limit > available_count:
raise WifitripError(
"Session limit must be between 1 and "
f"{available_count}, or all."
)
rows = conn.execute(
"""
SELECT id
FROM capture_sessions
ORDER BY start_time DESC, id DESC
LIMIT ?
""",
(limit,),
).fetchall()
elif mode == "range":
try:
start_date = datetime.strptime(
date_from,
"%Y-%m-%d",
).date()
end_date = datetime.strptime(
date_to,
"%Y-%m-%d",
).date()
except (TypeError, ValueError):
raise WifitripError(
"A valid start and end date are required."
)
if start_date > end_date:
raise WifitripError(
"Start date must not be later than end date."
)
rows = conn.execute(
"""
SELECT id
FROM capture_sessions
WHERE substr(start_time, 1, 10)
BETWEEN ? AND ?
ORDER BY start_time DESC, id DESC
""",
(
start_date.isoformat(),
end_date.isoformat(),
),
).fetchall()
elif mode == "all":
rows = conn.execute(
"""
SELECT id
FROM capture_sessions
ORDER BY start_time DESC, id DESC
"""
).fetchall()
else:
raise WifitripError(
"Invalid session selection mode."
)
return [
row["id"]
for row in rows
]
def export_wifitrip(
conn,
output_path=None,
session_ids=None,
):
started = time.monotonic()
if output_path is None:
@@ -909,6 +921,7 @@ def export_wifitrip(conn, output_path=None):
exist_ok=True,
)
if session_ids is None:
sessions = conn.execute(
"""
SELECT
@@ -922,6 +935,34 @@ def export_wifitrip(conn, output_path=None):
"""
).fetchall()
else:
selected_ids = [
int(session_id)
for session_id in session_ids
]
if selected_ids:
placeholders = ",".join(
"?" for _ in selected_ids
)
sessions = conn.execute(
f"""
SELECT
id,
start_time,
end_time,
session_hash,
session_hash_version
FROM capture_sessions
WHERE id IN ({placeholders})
ORDER BY start_time DESC, id DESC
""",
selected_ids,
).fetchall()
else:
sessions = []
session_by_id = {}
exported_sessions = []
@@ -1118,7 +1159,6 @@ def export_wifitrip(conn, output_path=None):
session_ids,
).fetchall()
handshake_key_by_id = {}
handshake_records = {}
handshakes = []
@@ -1137,13 +1177,6 @@ def export_wifitrip(conn, output_path=None):
f"h{len(records) + 1:06d}"
)
handshake_key_by_id[
row["id"]
] = (
session_hash,
handshake_key,
)
records.append(
handshake_key
)
@@ -1163,111 +1196,6 @@ def export_wifitrip(conn, output_path=None):
}
)
session_ap_ids = {}
for row in observation_rows:
session_ap_ids.setdefault(
row["session_id"],
set(),
).add(
row["bssid"]
)
for row in handshake_rows:
session_ap_ids.setdefault(
row["session_id"],
set(),
).add(
row["bssid"]
)
credentials_rows = conn.execute(
"""
SELECT
credentials.id,
credentials.access_point_id,
credentials.handshake_id,
access_points.bssid,
credentials.password,
credentials.source,
credentials.created_at,
credentials.verified,
handshakes.session_id AS handshake_session_id
FROM credentials
JOIN access_points
ON access_points.id =
credentials.access_point_id
LEFT JOIN handshakes
ON handshakes.id =
credentials.handshake_id
ORDER BY credentials.id
"""
).fetchall()
credentials = []
for row in credentials_rows:
if row["handshake_session_id"] is not None:
session_id = row[
"handshake_session_id"
]
if session_id not in session_by_id:
continue
session_hash = session_by_id[
session_id
]["session_hash"]
handshake_ref = (
handshake_key_by_id.get(
row["handshake_id"]
)
)
handshake_key = (
handshake_ref[1]
if handshake_ref
else None
)
credentials.append(
{
"session_hash": session_hash,
"bssid": row["bssid"],
"handshake_key": handshake_key,
"password": row["password"],
"source": row["source"],
"created_at": row["created_at"],
"verified": row["verified"],
}
)
continue
for session_id, bssids in (
session_ap_ids.items()
):
if row["bssid"] not in bssids:
continue
if session_id not in session_by_id:
continue
credentials.append(
{
"session_hash": session_by_id[
session_id
]["session_hash"],
"bssid": row["bssid"],
"handshake_key": None,
"password": row["password"],
"source": row["source"],
"created_at": row["created_at"],
"verified": row["verified"],
}
)
bssids = set()
for observation in observations:
@@ -1280,11 +1208,6 @@ def export_wifitrip(conn, output_path=None):
handshake["bssid"]
)
for credential in credentials:
bssids.add(
credential["bssid"]
)
access_points = [
{
"bssid": bssid
@@ -1368,12 +1291,6 @@ def export_wifitrip(conn, output_path=None):
handshakes,
)
_zip_write_json(
archive,
"credentials.json",
credentials,
)
os.replace(
temporary_path,
output_path,
@@ -1408,9 +1325,6 @@ def export_wifitrip(conn, output_path=None):
"handshakes": len(
handshakes
),
"credentials": len(
credentials
),
"file": str(output_path),
"size": size,
"duration": duration,
@@ -1419,11 +1333,10 @@ def export_wifitrip(conn, output_path=None):
logger.info(
"Completed .wifitrip export: "
"sessions=%d observations=%d handshakes=%d "
"credentials=%d file=%s size=%d duration=%.3fs",
"file=%s size=%d duration=%.3fs",
result["sessions"],
result["observations"],
result["handshakes"],
result["credentials"],
output_path,
size,
duration,
@@ -1604,221 +1517,6 @@ def _session_id_by_hash(
return row["id"]
def _map_existing_handshake_ids(
conn,
session_id,
session_handshakes,
):
rows = conn.execute(
"""
SELECT
handshakes.id,
access_points.bssid,
handshakes.type,
handshakes.hash22000,
handshakes.message_pair,
handshakes.captured_at,
handshakes.latitude,
handshakes.longitude,
handshakes.speed
FROM handshakes
JOIN access_points
ON access_points.id =
handshakes.access_point_id
WHERE handshakes.session_id=?
ORDER BY handshakes.id
""",
(session_id,),
).fetchall()
if len(rows) != len(session_handshakes):
raise WifitripError(
"Existing session handshake count does not "
"match the .wifitrip package."
)
expected_keys = [
f"h{index:06d}"
for index in range(
1,
len(session_handshakes) + 1,
)
]
package_keys = {
handshake["handshake_key"]
for handshake in session_handshakes
}
if package_keys != set(expected_keys):
raise WifitripError(
"Existing session handshake keys do not "
"match the exported sequence."
)
fields = (
"bssid",
"type",
"hash22000",
"message_pair",
"captured_at",
"latitude",
"longitude",
"speed",
)
local_ids_by_signature = {}
for row in rows:
signature = tuple(
row[field]
for field in fields
)
local_ids_by_signature.setdefault(
signature,
[],
).append(row["id"])
signature_positions = {}
handshake_ids = {}
ordered_handshakes = sorted(
session_handshakes,
key=lambda handshake: (
handshake["handshake_key"]
),
)
for handshake in ordered_handshakes:
signature = tuple(
handshake[field]
for field in fields
)
local_ids = local_ids_by_signature.get(
signature,
)
position = signature_positions.get(
signature,
0,
)
if local_ids is None or position >= len(local_ids):
raise WifitripError(
"Existing session handshake mapping "
"does not match the .wifitrip package."
)
handshake_ids[
handshake["handshake_key"]
] = local_ids[position]
signature_positions[signature] = position + 1
return handshake_ids
def _import_session_credentials(
conn,
session_credentials,
ap_ids,
handshake_ids,
):
for credential in session_credentials:
access_point_id = ap_ids[
credential["bssid"]
]
handshake_id = None
if credential["handshake_key"] is not None:
handshake_id = handshake_ids[
credential["handshake_key"]
]
existing_verified = conn.execute(
"""
SELECT COALESCE(MAX(verified), 0)
FROM credentials
WHERE access_point_id=?
AND password=?
""",
(
access_point_id,
credential["password"],
),
).fetchone()[0]
effective_verified = int(
bool(existing_verified)
or bool(credential["verified"])
)
existing_credential = conn.execute(
"""
SELECT id
FROM credentials
WHERE access_point_id=?
AND handshake_id IS ?
AND password=?
LIMIT 1
""",
(
access_point_id,
handshake_id,
credential["password"],
),
).fetchone()
if existing_credential is None:
conn.execute(
"""
INSERT INTO credentials (
access_point_id,
handshake_id,
password,
source,
created_at,
verified
)
VALUES (?, ?, ?, ?, ?, ?)
""",
(
access_point_id,
handshake_id,
credential["password"],
credential["source"],
credential["created_at"],
effective_verified,
),
)
if effective_verified:
conn.execute(
"""
UPDATE credentials
SET verified=1
WHERE access_point_id=?
AND password=?
""",
(
access_point_id,
credential["password"],
),
)
conn.execute(
"""
UPDATE access_points
SET is_cracked=1
WHERE id=?
""",
(access_point_id,),
)
def import_wifitrip(conn, package_path):
started = time.monotonic()
@@ -1836,12 +1534,10 @@ def import_wifitrip(conn, package_path):
gps_tracks = package["gps_tracks.json"]
observations = package["observations.json"]
handshakes = package["handshakes.json"]
credentials = package["credentials.json"]
gps_by_session = {}
observations_by_session = {}
handshakes_by_session = {}
credentials_by_session = {}
for point in gps_tracks:
gps_by_session.setdefault(
@@ -1861,12 +1557,6 @@ def import_wifitrip(conn, package_path):
[],
).append(handshake)
for credential in credentials:
credentials_by_session.setdefault(
credential["session_hash"],
[],
).append(credential)
result = {
"file": str(package_path),
"sessions": len(sessions),
@@ -1917,62 +1607,11 @@ def import_wifitrip(conn, package_path):
f"calculated {calculated_hash}"
)
session_handshakes = (
handshakes_by_session.get(
session_hash,
[],
)
)
session_credentials = (
credentials_by_session.get(
session_hash,
[],
)
)
bssids = {
handshake["bssid"]
for handshake in session_handshakes
}
bssids.update(
credential["bssid"]
for credential in session_credentials
)
created_access_points = set()
ap_ids = {}
for bssid in sorted(bssids):
ap_ids[bssid] = (
_get_or_create_import_ap(
conn,
bssid,
created_access_points,
)
)
handshake_ids = (
_map_existing_handshake_ids(
conn,
existing_id,
session_handshakes,
)
)
_import_session_credentials(
conn,
session_credentials,
ap_ids,
handshake_ids,
)
conn.commit()
logger.info(
"Updated duplicate .wifitrip session "
"credentials: hash=%s local_id=%s",
"Validated duplicate .wifitrip session: "
"hash=%s local_id=%s",
session_hash,
existing_id,
)
@@ -2040,13 +1679,6 @@ def import_wifitrip(conn, package_path):
)
)
session_credentials = (
credentials_by_session.get(
session_hash,
[],
)
)
bssids = set()
for observation in session_observations:
@@ -2059,11 +1691,6 @@ def import_wifitrip(conn, package_path):
handshake["bssid"]
)
for credential in session_credentials:
bssids.add(
credential["bssid"]
)
for bssid in sorted(bssids):
ap_ids[bssid] = (
_get_or_create_import_ap(
@@ -2181,8 +1808,6 @@ def import_wifitrip(conn, package_path):
latest_observation,
)
handshake_ids = {}
for handshake in session_handshakes:
access_point_id = ap_ids[
handshake["bssid"]
@@ -2218,10 +1843,6 @@ def import_wifitrip(conn, package_path):
),
)
handshake_ids[
handshake["handshake_key"]
] = cursor.lastrowid
if handshake["type"] == "PMKID":
conn.execute(
"""
@@ -2255,13 +1876,6 @@ def import_wifitrip(conn, package_path):
f"calculated {calculated_hash}"
)
_import_session_credentials(
conn,
session_credentials,
ap_ids,
handshake_ids,
)
conn.commit()
result["imported"] += 1
@@ -2342,9 +1956,6 @@ def validate_wifitrip(package_path):
"handshakes": len(
package["handshakes.json"]
),
"credentials": len(
package["credentials.json"]
),
"session_hash_versions": manifest[
"session_hash_versions"
],
+636
View File
@@ -0,0 +1,636 @@
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
)
log_method(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
+351
View File
@@ -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:
@@ -382,8 +578,15 @@ class Database:
self._migrate_session_hash()
self._migrate_wifi_verification()
self.conn.commit()
def _migrate_wifi_verification(self):
_migrate_wifi_verification(self.conn)
def _migrate_credentials_table(
self
):
@@ -984,6 +1187,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
# =========================================================
+154 -38
View File
@@ -59,6 +59,42 @@ def log(message):
)
def colorize(message, color, stream=None):
stream = stream or sys.stdout
if "NO_COLOR" in os.environ or not stream.isatty():
return message
colors = {
"green": "\033[1;92m",
"yellow": "\033[1;93m",
"red": "\033[1;91m",
"reset": "\033[0m"
}
return f"{colors[color]}{message}{colors['reset']}"
def print_success(message):
print(colorize(message, "green"), flush=True)
def print_warning(message):
print(colorize(message, "yellow"), flush=True)
def print_error(message):
print(
colorize(message, "red", sys.stderr),
file=sys.stderr,
flush=True
)
def print_info(message):
print(message, flush=True)
def project_python():
return PROJECT_ROOT / "venv" / "bin" / "python"
@@ -253,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
@@ -561,6 +654,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)
@@ -663,9 +758,11 @@ def start_service():
)
if active_project == PROJECT_ROOT:
log("Менеджер уже запущен из текущего проекта.")
print_warning(
"Менеджер уже запущен из текущего проекта."
)
else:
log(
print_warning(
"Менеджер уже запущен из другого проекта: "
f"{active_project}. Второй экземпляр не запущен."
)
@@ -687,6 +784,7 @@ def start_service():
command = [
"systemd-run",
"--quiet",
"--user",
f"--unit={UNIT_NAME}",
"--service-type=exec",
@@ -700,7 +798,8 @@ def start_service():
subprocess.run(
command,
check=True
check=True,
stdout=subprocess.DEVNULL
)
send_sudo_authentication()
@@ -721,7 +820,7 @@ def start_service():
timeout=1
) as response:
if response.status == 200:
log(
print_success(
f"Приложение запущено: "
f"http://{APP_HOST}:{APP_PORT}"
)
@@ -739,7 +838,7 @@ def start_service():
def stop_service():
if not unit_is_active():
log("Менеджер не запущен.")
print_warning("Менеджер уже остановлен.")
return 0
active_project = active_service_project()
@@ -759,13 +858,11 @@ def stop_service():
run_sudo_validation()
systemctl_user(
"kill",
"--kill-whom=main",
"--signal=SIGTERM",
"stop",
f"{UNIT_NAME}.service"
)
log(
print_warning(
"Запрошено штатное завершение. "
"Если сканер активен, останови его в веб-интерфейсе."
)
@@ -774,33 +871,32 @@ def stop_service():
while unit_is_active():
if not notified:
log(
print_warning(
"Ожидание завершения приложения и фоновых задач..."
)
notified = True
time.sleep(1)
log("Сервис остановлен.")
print_success("Сервис успешно остановлен.")
return 0
def show_status():
active = unit_is_active()
print(
"Application:",
"RUNNING" if active else "STOPPED"
)
if active:
print_success("Application: RUNNING")
else:
print_error("Application: STOPPED")
if active:
active_project = active_service_project()
print(
"Active project:",
active_project if active_project is not None else "UNKNOWN"
print_info(
"Active project: "
f"{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",
@@ -827,23 +923,38 @@ def show_status():
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"
)
if scanner_health == "ACTIVE":
print_success(f"Scanner: {scanner_state}")
elif scanner_health in {"WARNING", "STOPPING"}:
print_warning(f"Scanner: {scanner_state}")
elif scanner_health == "STOPPED":
print_error(f"Scanner: {scanner_state}")
else:
print_info(f"Scanner: {scanner_state}")
gps_state = gps.get("state", "unknown")
if gps_state in {"FIX", "CONNECTED"}:
print_success(f"GPS test: {gps_state}")
elif gps_state in {"STARTING", "NMEA"}:
print_warning(f"GPS test: {gps_state}")
elif gps_state == "ERROR":
print_error(f"GPS test: {gps_state}")
else:
print_info(f"GPS test: {gps_state}")
if data.get("network_actions_busy"):
print_warning("Network action: BUSY")
else:
print_success("Network action: IDLE")
except Exception as error:
print(f"Application API: unavailable ({error})")
print_error(f"Application API: unavailable ({error})")
print(
"TileServer:",
"AVAILABLE" if style_is_available() else "UNAVAILABLE"
)
if style_is_available():
print_success("TileServer: AVAILABLE")
else:
print_error("TileServer: UNAVAILABLE")
if active:
result = systemctl_user(
@@ -855,7 +966,7 @@ def show_status():
)
if result.returncode == 0:
print(result.stdout.strip())
print_info(result.stdout.strip())
def install():
@@ -970,7 +1081,15 @@ def main():
return stop_service()
if args.command == "restart":
if unit_is_active():
print_info("Перезапуск: остановка сервиса.")
stop_service()
else:
print_warning(
"Сервис уже остановлен. Этап остановки пропущен."
)
print_info("Перезапуск: запуск сервиса.")
return start_service()
parser.print_help()
@@ -981,10 +1100,7 @@ def main():
subprocess.CalledProcessError,
OSError
) as error:
print(
f"Ошибка: {error}",
file=sys.stderr
)
print_error(f"Ошибка: {error}")
return 1
+620 -31
View File
@@ -27,20 +27,44 @@ class WiFiConnectionError(RuntimeError):
pass
class NetworkCommandError(WiFiConnectionError):
class APNotFoundError(WiFiConnectionError):
pass
class NetworkCommandError(WiFiConnectionError):
def __init__(
self,
message,
returncode=None,
stdout="",
stderr="",
timed_out=False
):
super().__init__(message)
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
self.timed_out = timed_out
class UnsupportedSecurityError(WiFiConnectionError):
pass
class NetworkRestoreError(WiFiConnectionError):
pass
class NetworkCleanupError(WiFiConnectionError):
pass
class PasswordFileCleanupError(WiFiConnectionError):
pass
@dataclass(frozen=True)
class AccessPoint:
bssid: str
@@ -49,6 +73,7 @@ class AccessPoint:
wpa_flags: int
rsn_flags: int
key_mgmt: str | None
strength: int | None = None
@property
def is_open(self):
@@ -125,8 +150,20 @@ class WiFiConnectionService:
except subprocess.TimeoutExpired as error:
stdout = error.stdout or error.output or ""
stderr = error.stderr or ""
if isinstance(stdout, bytes):
stdout = stdout.decode(errors="replace")
if isinstance(stderr, bytes):
stderr = stderr.decode(errors="replace")
raise NetworkCommandError(
"NetworkManager command timed out."
"NetworkManager command timed out.",
stdout=stdout,
stderr=stderr,
timed_out=True
) from error
except OSError as error:
@@ -145,7 +182,12 @@ class WiFiConnectionService:
f"Command exited with code {result.returncode}."
)
raise NetworkCommandError(message)
raise NetworkCommandError(
message,
returncode=result.returncode,
stdout=result.stdout,
stderr=result.stderr
)
return result.stdout.strip()
@@ -320,6 +362,39 @@ class WiFiConnectionService:
f"Invalid value for {property_name}."
) from error
def _get_byte_property(
self,
object_path,
property_name
):
parts = self._get_property(
object_path,
NM_ACCESS_POINT,
property_name
)
if len(parts) != 2 or parts[0] != "y":
raise WiFiConnectionError(
f"Unexpected D-Bus type for {property_name}."
)
try:
value = int(parts[1])
except ValueError as error:
raise WiFiConnectionError(
f"Invalid value for {property_name}."
) from error
if not 0 <= value <= 100:
raise WiFiConnectionError(
f"Value for {property_name} is outside the valid range."
)
return value
def _get_ssid(self, object_path):
parts = self._get_property(
@@ -406,20 +481,16 @@ class WiFiConnectionService:
"This access point does not advertise WPA Personal PSK or SAE security."
)
def get_access_point(
def get_access_points(
self,
interface,
bssid
interface
):
self._validate_interface(
interface
)
self._validate_bssid(
bssid
)
device_path = self._device_path(
interface
)
@@ -460,6 +531,8 @@ class WiFiConnectionService:
"Cannot parse NetworkManager access point list."
) from error
access_points = []
for object_path in paths:
ap_bssid_parts = self._get_property(
@@ -477,7 +550,12 @@ class WiFiConnectionService:
ap_bssid = ap_bssid_parts[1]
if ap_bssid.lower() != bssid.lower():
try:
self._validate_bssid(
ap_bssid
)
except WiFiConnectionError:
continue
flags = self._get_integer_property(
@@ -499,25 +577,60 @@ class WiFiConnectionService:
object_path
)
try:
key_mgmt = self._select_key_mgmt(
flags,
wpa_flags,
rsn_flags
)
return AccessPoint(
except UnsupportedSecurityError:
key_mgmt = None
try:
strength = self._get_byte_property(
object_path,
"Strength"
)
except WiFiConnectionError:
strength = None
access_points.append(
AccessPoint(
bssid=ap_bssid.upper(),
ssid=ssid,
flags=flags,
wpa_flags=wpa_flags,
rsn_flags=rsn_flags,
key_mgmt=key_mgmt
key_mgmt=key_mgmt,
strength=strength
)
)
raise WiFiConnectionError(
return access_points
def get_access_point(
self,
interface,
bssid
):
self._validate_bssid(
bssid
)
for access_point in self.get_access_points(interface):
if access_point.bssid.lower() == bssid.lower():
return access_point
raise APNotFoundError(
f"Access point {bssid} is not currently visible to NetworkManager."
)
def _get_active_connection_uuid(self, interface):
output = self._nmcli(
@@ -533,6 +646,292 @@ class WiFiConnectionService:
return output
def _list_connection_profiles(self):
output = self._nmcli(
"--terse",
"--escape",
"yes",
"--fields",
"NAME,UUID",
"connection",
"show"
)
profiles = []
for line in output.splitlines():
if not line:
continue
try:
name, profile_uuid = line.rsplit(":", 1)
except ValueError as error:
raise NetworkCleanupError(
"NetworkManager returned an invalid connection "
"profile entry."
) from error
if not name or not profile_uuid:
raise NetworkCleanupError(
"NetworkManager returned an incomplete connection "
"profile entry."
)
profiles.append(
(name, profile_uuid)
)
return profiles
def _list_connection_profile_uuids(self):
return {
profile_uuid
for _, profile_uuid in self._list_connection_profiles()
}
def capture_active_connection(self, interface):
self._validate_interface(
interface
)
connection_uuid = self._get_active_connection_uuid(
interface
)
if not connection_uuid:
return None
bssid = self._get_active_access_point_bssid(
interface
)
return {
"uuid": connection_uuid,
"bssid": bssid
}
def restore_active_connection(self, interface, saved_connection):
self._validate_interface(
interface
)
if saved_connection is None:
return False
if not isinstance(saved_connection, dict):
raise WiFiConnectionError(
"Invalid saved Wi-Fi connection."
)
connection_uuid = saved_connection.get("uuid")
bssid = saved_connection.get("bssid")
if not connection_uuid or not isinstance(connection_uuid, str):
raise WiFiConnectionError(
"Saved Wi-Fi connection UUID is missing."
)
self._validate_bssid(
bssid
)
try:
self._nmcli(
"connection",
"up",
"uuid",
connection_uuid,
"ifname",
interface,
"ap",
bssid,
timeout=90
)
except NetworkCommandError as error:
raise NetworkRestoreError(
"The previous Wi-Fi connection could not be restored: "
f"{error}"
) from error
return True
def cleanup_auto_profiles(
self,
interface,
saved_connection,
profile_uuids
):
self._validate_interface(
interface
)
if not isinstance(profile_uuids, (list, tuple)):
raise WiFiConnectionError(
"Invalid Auto verification profile list."
)
for profile_uuid in profile_uuids:
if (
not isinstance(profile_uuid, str)
or
not re.fullmatch(
r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-"
r"[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
r"[0-9a-fA-F]{12}",
profile_uuid
)
):
raise WiFiConnectionError(
"Invalid temporary NetworkManager profile UUID."
)
try:
profiles = self._list_connection_profiles()
except NetworkCommandError as error:
raise NetworkCleanupError(
"NetworkManager could not inspect connection profiles: "
f"{error}"
) from error
auto_profiles = [
(name, profile_uuid)
for name, profile_uuid in profiles
if name.startswith("wifi-gps-mapper-")
]
auto_profile_uuids = {
profile_uuid
for _, profile_uuid in auto_profiles
}
try:
for _ in range(len(auto_profile_uuids) + 1):
active_uuid = self._get_active_connection_uuid(
interface
)
if active_uuid not in auto_profile_uuids:
break
try:
self._nmcli(
"connection",
"down",
"uuid",
active_uuid
)
except NetworkCommandError:
pass
active_uuid_after = self._get_active_connection_uuid(
interface
)
if active_uuid_after == active_uuid:
raise NetworkCleanupError(
"The active Auto verification connection "
"could not be disconnected: "
f"{active_uuid}"
)
if active_uuid_after not in auto_profile_uuids:
break
else:
raise NetworkCleanupError(
"An Auto verification connection remains active "
"on the Wi-Fi interface."
)
except NetworkCommandError as error:
raise NetworkCleanupError(
"The active Wi-Fi connection state could not be verified: "
f"{error}"
) from error
cleanup_errors = []
for _, profile_uuid in auto_profiles:
try:
self._delete_profile(
profile_uuid
)
except NetworkCleanupError as error:
cleanup_errors.append(
f"{profile_uuid}: {error}"
)
try:
remaining_profiles = self._list_connection_profiles()
except NetworkCommandError as error:
raise NetworkCleanupError(
"The final Auto verification profile cleanup "
"could not be verified: "
f"{error}"
) from error
remaining_auto_profiles = [
(name, profile_uuid)
for name, profile_uuid in remaining_profiles
if name.startswith("wifi-gps-mapper-")
]
if remaining_auto_profiles:
remaining_uuids = [
profile_uuid
for _, profile_uuid in remaining_auto_profiles
]
details = "; ".join(cleanup_errors)
raise NetworkCleanupError(
"Auto verification profiles remain in NetworkManager: "
+ ", ".join(remaining_uuids)
+ (f". Cleanup errors: {details}" if details else "")
)
return {
"restored": False,
"deleted_profile_uuids": [
profile_uuid
for _, profile_uuid in auto_profiles
]
}
def _get_active_access_point_bssid(self, interface):
device_path = self._device_path(
@@ -628,6 +1027,33 @@ class WiFiConnectionService:
f"{cleanup_error}"
) from creation_error
try:
remaining_profiles = self._nmcli(
"--terse",
"--escape",
"yes",
"--fields",
"NAME",
"connection",
"show"
)
except NetworkCommandError as inspection_error:
raise NetworkCleanupError(
"NetworkManager deleted the temporary profile command "
"but its absence could not be verified: "
f"{inspection_error}"
) from creation_error
if profile_name in remaining_profiles.splitlines():
raise NetworkCleanupError(
"NetworkManager still reports the temporary profile "
f"after deletion: {profile_name}"
) from creation_error
raise creation_error
def _create_temporary_profile(
@@ -716,12 +1142,39 @@ class WiFiConnectionService:
except NetworkCommandError as cleanup_error:
raise WiFiConnectionError(
raise NetworkCleanupError(
"NetworkManager created a temporary profile, but its UUID "
"could not be obtained and the profile could not be deleted: "
f"{cleanup_error}"
) from error
try:
remaining_profiles = self._nmcli(
"--terse",
"--escape",
"yes",
"--fields",
"NAME",
"connection",
"show"
)
except NetworkCommandError as inspection_error:
raise NetworkCleanupError(
"NetworkManager deleted the temporary profile command "
"but its absence could not be verified: "
f"{inspection_error}"
) from error
if profile_name in remaining_profiles.splitlines():
raise NetworkCleanupError(
"NetworkManager still reports the temporary profile "
f"after deletion: {profile_name}"
) from error
raise
return output
@@ -785,7 +1238,7 @@ class WiFiConnectionService:
except OSError as cleanup_error:
raise NetworkCleanupError(
raise PasswordFileCleanupError(
"Could not prepare the temporary password file. "
"The file could not be deleted: "
f"{cleanup_error}"
@@ -866,14 +1319,14 @@ class WiFiConnectionService:
if operation_error:
raise NetworkCleanupError(
raise PasswordFileCleanupError(
"Wi-Fi activation failed: "
f"{operation_error}. "
"The temporary password file could not be deleted: "
f"{cleanup_error}"
) from operation_error
raise NetworkCleanupError(
raise PasswordFileCleanupError(
"The temporary password file could not be deleted: "
f"{cleanup_error}"
) from cleanup_error
@@ -886,6 +1339,24 @@ class WiFiConnectionService:
if not profile_uuid:
return
try:
existing_uuids = self._list_connection_profile_uuids()
except NetworkCommandError as error:
raise NetworkCleanupError(
"NetworkManager could not inspect connection profiles: "
f"{error}"
) from error
if profile_uuid not in existing_uuids:
return
delete_error = None
try:
self._nmcli(
"connection",
"delete",
@@ -893,6 +1364,36 @@ class WiFiConnectionService:
profile_uuid
)
except NetworkCommandError as error:
delete_error = error
try:
remaining_uuids = self._list_connection_profile_uuids()
except NetworkCommandError as error:
raise NetworkCleanupError(
"The temporary profile deletion could not be verified: "
f"{error}"
) from error
if profile_uuid not in remaining_uuids:
return
if delete_error:
raise NetworkCleanupError(
"NetworkManager could not delete the temporary profile: "
f"{delete_error}"
) from delete_error
raise NetworkCleanupError(
"NetworkManager still reports the temporary profile "
f"after deletion: {profile_uuid}"
)
def connect(
self,
interface,
@@ -936,7 +1437,7 @@ class WiFiConnectionService:
profile_uuid
)
except NetworkCommandError as cleanup_error:
except NetworkCleanupError as cleanup_error:
raise NetworkCleanupError(
"Wi-Fi connection failed: "
@@ -959,14 +1460,52 @@ class WiFiConnectionService:
self,
interface,
bssid,
password
password,
restore_connection=True,
keep_profile=False,
access_point=None
):
if (
not restore_connection
and not keep_profile
):
raise WiFiConnectionError(
"A verification without connection restoration "
"must retain a successful temporary profile."
)
if (
restore_connection
and keep_profile
):
raise WiFiConnectionError(
"A temporary profile cannot be retained "
"when restoring the previous connection."
)
if access_point is None:
access_point = self.get_access_point(
interface,
bssid
)
else:
self._validate_interface(interface)
self._validate_bssid(bssid)
if not isinstance(access_point, AccessPoint):
raise WiFiConnectionError(
"Invalid access point object."
)
if access_point.bssid.lower() != bssid.lower():
raise WiFiConnectionError(
"The supplied access point does not match the requested BSSID."
)
if access_point.is_open:
raise WiFiConnectionError(
"Open access points do not require password verification."
@@ -977,12 +1516,15 @@ class WiFiConnectionService:
"Password verification is not supported for this security type."
)
previous_uuid = None
previous_bssid = None
if restore_connection:
previous_uuid = self._get_active_connection_uuid(
interface
)
previous_bssid = None
if previous_uuid:
previous_bssid = self._get_active_access_point_bssid(
@@ -1019,10 +1561,31 @@ class WiFiConnectionService:
error
)
if isinstance(error, NetworkCommandError):
try:
self.get_access_point(
interface,
bssid
)
except APNotFoundError as scan_error:
operation_error = scan_error
error_message = str(
scan_error
)
except Exception:
pass
finally:
if profile_uuid:
if restore_connection:
try:
if previous_uuid:
@@ -1041,8 +1604,6 @@ class WiFiConnectionService:
else:
try:
self._nmcli(
"connection",
"down",
@@ -1056,11 +1617,10 @@ class WiFiConnectionService:
error
)
except NetworkCommandError as error:
restore_error = str(
error
)
if not (
success
and keep_profile
):
try:
@@ -1068,7 +1628,7 @@ class WiFiConnectionService:
profile_uuid
)
except NetworkCommandError as error:
except NetworkCleanupError as error:
cleanup_error = str(
error
@@ -1114,5 +1674,34 @@ class WiFiConnectionService:
"interface": interface,
"bssid": access_point.bssid,
"ssid": access_point.ssid,
"error": error_message
"error": error_message,
"error_type": (
type(operation_error).__name__
if operation_error else None
),
"error_code": getattr(
operation_error,
"returncode",
None
),
"error_timed_out": getattr(
operation_error,
"timed_out",
None
),
"error_stdout": getattr(
operation_error,
"stdout",
None
),
"error_stderr": getattr(
operation_error,
"stderr",
None
),
"profile_uuid": (
profile_uuid
if success and keep_profile
else None
)
}
-2731
View File
File diff suppressed because it is too large Load Diff