614 lines
15 KiB
Python
614 lines
15 KiB
Python
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),
|
||
)
|