1686 lines
52 KiB
Python
1686 lines
52 KiB
Python
import logging
|
|
import math
|
|
import queue
|
|
import threading
|
|
import time
|
|
|
|
from datetime import datetime, timezone
|
|
|
|
from reports.database import close as close_database
|
|
from reports.database import connect as connect_database
|
|
|
|
from auto_gps import AutoGPSService
|
|
from wifi_connection import (
|
|
APNotFoundError,
|
|
NetworkCleanupError,
|
|
NetworkCommandError,
|
|
NetworkRestoreError,
|
|
WiFiConnectionError
|
|
)
|
|
|
|
|
|
logger = logging.getLogger(
|
|
"wifi-gps-mapper.auto-verification"
|
|
)
|
|
|
|
|
|
def _utc_now():
|
|
return datetime.now(
|
|
timezone.utc
|
|
).isoformat(timespec="seconds")
|
|
|
|
|
|
def _distance_meters(lat1, lon1, lat2, lon2):
|
|
radius = 6371000.0
|
|
|
|
lat1 = math.radians(float(lat1))
|
|
lon1 = math.radians(float(lon1))
|
|
lat2 = math.radians(float(lat2))
|
|
lon2 = math.radians(float(lon2))
|
|
|
|
delta_lat = lat2 - lat1
|
|
delta_lon = lon2 - lon1
|
|
|
|
value = (
|
|
math.sin(delta_lat / 2) ** 2
|
|
+ math.cos(lat1)
|
|
* math.cos(lat2)
|
|
* math.sin(delta_lon / 2) ** 2
|
|
)
|
|
|
|
return radius * 2 * math.atan2(
|
|
math.sqrt(value),
|
|
math.sqrt(max(0.0, 1.0 - value))
|
|
)
|
|
|
|
|
|
def _is_invalid_password(result):
|
|
if result.get("success"):
|
|
return False
|
|
|
|
text = " ".join(
|
|
str(result.get(key) or "")
|
|
for key in (
|
|
"error",
|
|
"error_stdout",
|
|
"error_stderr"
|
|
)
|
|
).lower()
|
|
|
|
markers = (
|
|
"incorrect password",
|
|
"wrong password",
|
|
"password is incorrect",
|
|
"secrets were required",
|
|
"no secrets",
|
|
"secret was required",
|
|
"802-11-wireless-security.psk",
|
|
"4-way handshake",
|
|
"four-way handshake",
|
|
"authentication failed",
|
|
"invalid psk"
|
|
)
|
|
|
|
return any(
|
|
marker in text
|
|
for marker in markers
|
|
)
|
|
|
|
|
|
class AutoWiFiVerificationService:
|
|
|
|
def __init__(
|
|
self,
|
|
settings,
|
|
interface,
|
|
wifi_connection_service,
|
|
callback=None,
|
|
acquire_network_owner=None,
|
|
release_network_owner=None,
|
|
gps_service=None
|
|
):
|
|
self.settings = dict(settings or {})
|
|
self.interface = interface
|
|
self.wifi_connection_service = wifi_connection_service
|
|
self.callback = callback
|
|
self.acquire_network_owner = acquire_network_owner
|
|
self.release_network_owner = release_network_owner
|
|
self.network_owner_acquired = False
|
|
self.start_lock = threading.Lock()
|
|
|
|
self.radius_m = int(
|
|
self.settings.get("radius_m", 500)
|
|
)
|
|
|
|
self.queue_retry_passes = int(
|
|
self.settings.get(
|
|
"queue_retry_passes",
|
|
2
|
|
)
|
|
)
|
|
|
|
self._gps_fix_condition = threading.Condition()
|
|
self._gps_fix_generation = 0
|
|
self._gps_fix_consumed_generation = 0
|
|
|
|
self._radius_update_lock = threading.Lock()
|
|
self._pending_radius_update = None
|
|
self._radius_update_event = threading.Event()
|
|
|
|
self.manage_gps_service = gps_service is None
|
|
|
|
if gps_service is None:
|
|
self.gps_service = AutoGPSService(
|
|
self.settings,
|
|
callback=self._gps_callback,
|
|
position_callback=self._gps_fix_callback
|
|
)
|
|
else:
|
|
self.gps_service = gps_service
|
|
|
|
self.stop_event = threading.Event()
|
|
self.thread = None
|
|
|
|
self.lock = threading.RLock()
|
|
|
|
self.running = False
|
|
self.state = "STOPPED"
|
|
self.error = None
|
|
|
|
self.session_id = None
|
|
|
|
self.access_points_total = 0
|
|
self.attempts_total = 0
|
|
self.success_count = 0
|
|
self.invalid_password_count = 0
|
|
self.technical_error_count = 0
|
|
|
|
self.current_bssid = None
|
|
self.current_essid = None
|
|
|
|
self._bssid_states = {}
|
|
self._missing_scan_bssids = set()
|
|
|
|
# Отдельные счётчики результатов попыток.
|
|
self.ap_not_found_count = 0
|
|
self.connection_timeout_count = 0
|
|
self.network_error_count = 0
|
|
self.unknown_error_count = 0
|
|
|
|
# Только безопасные снимки для интерфейса.
|
|
self.monitor_candidates = []
|
|
self.monitor_queue = []
|
|
self.monitor_active = None
|
|
self.monitor_events = []
|
|
self.monitor_event_limit = 100
|
|
|
|
self._notify()
|
|
|
|
def _gps_callback(self, status):
|
|
self._notify()
|
|
|
|
def _gps_fix_callback(self, gps):
|
|
with self._gps_fix_condition:
|
|
self._gps_fix_generation += 1
|
|
self._gps_fix_condition.notify_all()
|
|
|
|
def request_radius_update(self, radius_m):
|
|
if type(radius_m) is not int or radius_m not in (50, 75, 100, 125, 150, 175, 200, 250, 350, 500):
|
|
raise ValueError("Invalid verification radius.")
|
|
|
|
with self._radius_update_lock:
|
|
with self._gps_fix_condition:
|
|
after_generation = self._gps_fix_generation
|
|
self._pending_radius_update = {
|
|
"radius_m": radius_m,
|
|
"after_generation": after_generation
|
|
}
|
|
self._radius_update_event.set()
|
|
self._gps_fix_condition.notify_all()
|
|
|
|
return True
|
|
|
|
def _notify(self):
|
|
if self.callback is None:
|
|
return
|
|
|
|
try:
|
|
self.callback(
|
|
self.get_status()
|
|
)
|
|
except Exception:
|
|
logger.exception(
|
|
"Auto Wi-Fi verification callback failed."
|
|
)
|
|
|
|
def _add_monitor_event(self, event, message, level="info"):
|
|
item = {
|
|
"timestamp": _utc_now(),
|
|
"event": event,
|
|
"message": message,
|
|
"level": level
|
|
}
|
|
|
|
with self.lock:
|
|
self.monitor_events.append(item)
|
|
self.monitor_events = self.monitor_events[
|
|
-self.monitor_event_limit:
|
|
]
|
|
|
|
def _update_monitor_candidates(self, candidates):
|
|
with self.lock:
|
|
strengths = {
|
|
candidate["bssid"].lower(): candidate.get("strength")
|
|
for candidate in self.monitor_candidates
|
|
}
|
|
|
|
snapshot = []
|
|
|
|
for access_point in candidates:
|
|
bssid = access_point["bssid"]
|
|
|
|
snapshot.append({
|
|
"bssid": bssid,
|
|
"essid": access_point["essid"],
|
|
"distance": (
|
|
round(float(access_point["distance"]), 1)
|
|
if access_point.get("distance") is not None
|
|
else None
|
|
),
|
|
"strength": strengths.get(bssid.lower())
|
|
})
|
|
|
|
self.monitor_candidates = sorted(
|
|
snapshot,
|
|
key=lambda candidate: (
|
|
candidate["strength"] is None,
|
|
-(candidate["strength"] or 0)
|
|
)
|
|
)
|
|
|
|
def _update_monitor_signal(self, scan_results):
|
|
strengths = {
|
|
access_point.bssid.lower(): getattr(
|
|
access_point,
|
|
"strength",
|
|
None
|
|
)
|
|
for access_point in scan_results
|
|
}
|
|
|
|
with self.lock:
|
|
for candidate in self.monitor_candidates:
|
|
strength = strengths.get(
|
|
candidate["bssid"].lower()
|
|
)
|
|
|
|
candidate["strength"] = (
|
|
strength
|
|
if isinstance(strength, int)
|
|
and 0 <= strength <= 100
|
|
else None
|
|
)
|
|
|
|
self.monitor_candidates.sort(
|
|
key=lambda candidate: (
|
|
candidate["strength"] is None,
|
|
-(candidate["strength"] or 0)
|
|
)
|
|
)
|
|
|
|
def _update_monitor_queue(self, work_queue):
|
|
grouped = {}
|
|
|
|
for job in work_queue:
|
|
bssid = job[1]
|
|
key = bssid.lower()
|
|
|
|
if key not in grouped:
|
|
grouped[key] = {
|
|
"bssid": bssid,
|
|
"essid": job[2]
|
|
}
|
|
|
|
snapshot = list(grouped.values())
|
|
|
|
with self.lock:
|
|
self.monitor_queue = snapshot
|
|
|
|
def _set_monitor_active(self, job=None):
|
|
snapshot = None
|
|
|
|
if job is not None:
|
|
snapshot = {
|
|
"bssid": job[1],
|
|
"essid": job[2]
|
|
}
|
|
|
|
with self.lock:
|
|
self.monitor_active = snapshot
|
|
|
|
def get_status(self):
|
|
with self.lock:
|
|
gps_status = self.gps_service.get_status()
|
|
|
|
return {
|
|
"running": self.running,
|
|
"state": self.state,
|
|
"error": self.error,
|
|
"session_id": self.session_id,
|
|
"interface": self.interface,
|
|
"radius_m": self.radius_m,
|
|
"gps": gps_status,
|
|
"access_points_total": self.access_points_total,
|
|
"attempts_total": self.attempts_total,
|
|
"success_count": self.success_count,
|
|
"invalid_password_count": self.invalid_password_count,
|
|
"technical_error_count": self.technical_error_count,
|
|
"monitor_statistics": {
|
|
"SUCCESS": self.success_count,
|
|
"AP_NOT_FOUND": self.ap_not_found_count,
|
|
"INVALID_PASSWORD": self.invalid_password_count,
|
|
"CONNECTION_TIMEOUT": self.connection_timeout_count,
|
|
"NETWORK_ERROR": self.network_error_count,
|
|
"UNKNOWN_ERROR": self.unknown_error_count
|
|
},
|
|
"monitor_candidates": [
|
|
dict(item)
|
|
for item in self.monitor_candidates
|
|
],
|
|
"monitor_queue": [
|
|
dict(item)
|
|
for item in self.monitor_queue
|
|
],
|
|
"monitor_active": (
|
|
dict(self.monitor_active)
|
|
if self.monitor_active is not None
|
|
else None
|
|
),
|
|
"monitor_events": [
|
|
dict(item)
|
|
for item in self.monitor_events
|
|
],
|
|
"current_bssid": self.current_bssid,
|
|
"current_essid": self.current_essid
|
|
}
|
|
|
|
def start(self):
|
|
with self.start_lock:
|
|
with self.lock:
|
|
if self.running:
|
|
return False
|
|
|
|
if self.thread and self.thread.is_alive():
|
|
return False
|
|
|
|
if self.acquire_network_owner is not None:
|
|
acquired, error = self.acquire_network_owner(
|
|
"AUTO_WIFI_VERIFY"
|
|
)
|
|
|
|
if not acquired:
|
|
self._set_state("BUSY", error)
|
|
return False
|
|
|
|
with self.lock:
|
|
self.network_owner_acquired = True
|
|
|
|
try:
|
|
gps_generation = 0
|
|
|
|
if not self.manage_gps_service:
|
|
gps_status = self.gps_service.get_status()
|
|
|
|
if (
|
|
gps_status.get("has_fresh_fix")
|
|
and gps_status.get("latitude") is not None
|
|
and gps_status.get("longitude") is not None
|
|
):
|
|
gps_generation = 1
|
|
|
|
with self._radius_update_lock:
|
|
self._pending_radius_update = None
|
|
self._radius_update_event.clear()
|
|
|
|
with self.lock:
|
|
self.stop_event.clear()
|
|
|
|
with self._gps_fix_condition:
|
|
self._gps_fix_generation = gps_generation
|
|
self._gps_fix_consumed_generation = 0
|
|
|
|
self._bssid_states.clear()
|
|
self._missing_scan_bssids.clear()
|
|
self.running = True
|
|
self.state = "WAITING_GPS"
|
|
self.error = None
|
|
|
|
self.thread = threading.Thread(
|
|
target=self._worker,
|
|
name="auto-wifi-verification",
|
|
daemon=True
|
|
)
|
|
|
|
self.thread.start()
|
|
|
|
except Exception:
|
|
try:
|
|
self._release_network_owner()
|
|
except Exception:
|
|
logger.exception(
|
|
"Failed to release AUTO_WIFI_VERIFY "
|
|
"network owner after startup error."
|
|
)
|
|
|
|
with self.lock:
|
|
self.running = False
|
|
self.thread = None
|
|
|
|
raise
|
|
|
|
self._notify()
|
|
return True
|
|
|
|
def _release_network_owner(self):
|
|
with self.lock:
|
|
acquired = self.network_owner_acquired
|
|
|
|
if not acquired:
|
|
return
|
|
|
|
if self.release_network_owner is None:
|
|
raise RuntimeError(
|
|
"AUTO_WIFI_VERIFY network owner cannot be released: "
|
|
"release callback is not configured."
|
|
)
|
|
|
|
self.release_network_owner("AUTO_WIFI_VERIFY")
|
|
|
|
with self.lock:
|
|
self.network_owner_acquired = False
|
|
|
|
def stop(self, wait=True):
|
|
self.stop_event.set()
|
|
|
|
with self._gps_fix_condition:
|
|
self._gps_fix_condition.notify_all()
|
|
|
|
if self.manage_gps_service:
|
|
try:
|
|
self.gps_service.stop()
|
|
except Exception:
|
|
logger.exception(
|
|
"Failed to stop Auto GPS service."
|
|
)
|
|
|
|
thread = self.thread
|
|
|
|
if (
|
|
wait
|
|
and thread
|
|
and thread.is_alive()
|
|
and thread is not threading.current_thread()
|
|
):
|
|
thread.join(timeout=15)
|
|
|
|
self._notify()
|
|
|
|
def _set_state(self, state, error=None):
|
|
with self.lock:
|
|
previous_state = self.state
|
|
self.state = state
|
|
self.error = error
|
|
|
|
if previous_state != state:
|
|
self._add_monitor_event(
|
|
"STATE",
|
|
f"Состояние сервиса: {state}",
|
|
"error" if state == "ERROR" else "info"
|
|
)
|
|
|
|
self._notify()
|
|
|
|
def _increment(self, field):
|
|
with self.lock:
|
|
setattr(
|
|
self,
|
|
field,
|
|
getattr(self, field) + 1
|
|
)
|
|
|
|
def _create_session(self, connection):
|
|
cursor = connection.execute(
|
|
"""
|
|
INSERT INTO wifi_verification_sessions (
|
|
started_at,
|
|
status,
|
|
radius_m,
|
|
interface_name,
|
|
access_points_total,
|
|
attempts_total,
|
|
success_count,
|
|
invalid_password_count,
|
|
technical_error_count
|
|
)
|
|
VALUES (?, 'RUNNING', ?, ?, 0, 0, 0, 0, 0)
|
|
""",
|
|
(
|
|
_utc_now(),
|
|
self.radius_m,
|
|
self.interface
|
|
)
|
|
)
|
|
|
|
connection.commit()
|
|
|
|
self.session_id = cursor.lastrowid
|
|
|
|
def _update_session(self, connection, status):
|
|
if self.session_id is None:
|
|
return
|
|
|
|
with self.lock:
|
|
values = (
|
|
self.access_points_total,
|
|
self.attempts_total,
|
|
self.success_count,
|
|
self.invalid_password_count,
|
|
self.technical_error_count
|
|
)
|
|
|
|
connection.execute(
|
|
"""
|
|
UPDATE wifi_verification_sessions
|
|
SET
|
|
finished_at = ?,
|
|
status = ?,
|
|
access_points_total = ?,
|
|
attempts_total = ?,
|
|
success_count = ?,
|
|
invalid_password_count = ?,
|
|
technical_error_count = ?
|
|
WHERE id = ?
|
|
""",
|
|
(
|
|
_utc_now(),
|
|
status,
|
|
*values,
|
|
self.session_id
|
|
)
|
|
)
|
|
|
|
connection.commit()
|
|
|
|
def _record_attempt(
|
|
self,
|
|
connection,
|
|
credential_id,
|
|
bssid,
|
|
status,
|
|
error_code=None,
|
|
error_message=None
|
|
):
|
|
connection.execute(
|
|
"""
|
|
INSERT INTO wifi_verification_attempts (
|
|
credential_id,
|
|
session_id,
|
|
verification_mode,
|
|
status,
|
|
started_at,
|
|
finished_at,
|
|
interface_name,
|
|
bssid,
|
|
error_code,
|
|
error_message
|
|
)
|
|
VALUES (?, ?, 'AUTO', ?, ?, ?, ?, ?, ?, ?)
|
|
""",
|
|
(
|
|
credential_id,
|
|
self.session_id,
|
|
status,
|
|
_utc_now(),
|
|
_utc_now(),
|
|
self.interface,
|
|
bssid,
|
|
error_code,
|
|
error_message
|
|
)
|
|
)
|
|
|
|
connection.commit()
|
|
|
|
self._increment("attempts_total")
|
|
|
|
if status == "SUCCESS":
|
|
self._increment("success_count")
|
|
elif status == "AP_NOT_FOUND":
|
|
self._increment("ap_not_found_count")
|
|
elif status == "INVALID_PASSWORD":
|
|
self._increment("invalid_password_count")
|
|
elif status == "CONNECTION_TIMEOUT":
|
|
self._increment("technical_error_count")
|
|
self._increment("connection_timeout_count")
|
|
elif status == "NETWORK_ERROR":
|
|
self._increment("technical_error_count")
|
|
self._increment("network_error_count")
|
|
elif status == "UNKNOWN_ERROR":
|
|
self._increment("technical_error_count")
|
|
self._increment("unknown_error_count")
|
|
|
|
self._add_monitor_event(
|
|
"ATTEMPT_RESULT",
|
|
f"Результат проверки: {status}",
|
|
"success" if status == "SUCCESS" else (
|
|
"error" if status not in (
|
|
"INVALID_PASSWORD",
|
|
) else "warning"
|
|
)
|
|
)
|
|
|
|
self._update_session_counters(connection)
|
|
|
|
def _update_session_counters(self, connection):
|
|
if self.session_id is None:
|
|
return
|
|
|
|
with self.lock:
|
|
values = (
|
|
self.attempts_total,
|
|
self.success_count,
|
|
self.invalid_password_count,
|
|
self.technical_error_count
|
|
)
|
|
|
|
connection.execute(
|
|
"""
|
|
UPDATE wifi_verification_sessions
|
|
SET
|
|
attempts_total = ?,
|
|
success_count = ?,
|
|
invalid_password_count = ?,
|
|
technical_error_count = ?
|
|
WHERE id = ?
|
|
""",
|
|
(
|
|
*values,
|
|
self.session_id
|
|
)
|
|
)
|
|
|
|
connection.commit()
|
|
|
|
def _get_gps_fix(self):
|
|
status = self.gps_service.get_status()
|
|
|
|
if not status.get("has_fresh_fix"):
|
|
return None
|
|
|
|
latitude = status.get("latitude")
|
|
longitude = status.get("longitude")
|
|
|
|
if latitude is None or longitude is None:
|
|
return None
|
|
|
|
return (
|
|
float(latitude),
|
|
float(longitude)
|
|
)
|
|
|
|
def _wait_for_gps(self):
|
|
self._set_state("WAITING_GPS")
|
|
|
|
while not self.stop_event.is_set():
|
|
with self._gps_fix_condition:
|
|
while (
|
|
not self.stop_event.is_set()
|
|
and self._gps_fix_generation
|
|
<= self._gps_fix_consumed_generation
|
|
):
|
|
self._gps_fix_condition.wait()
|
|
|
|
if self.stop_event.is_set():
|
|
return None
|
|
|
|
self._gps_fix_consumed_generation = (
|
|
self._gps_fix_generation
|
|
)
|
|
|
|
fix = self._get_gps_fix()
|
|
|
|
if fix is not None:
|
|
return fix
|
|
|
|
return None
|
|
|
|
def _get_candidates(self, connection, fix):
|
|
rows = connection.execute(
|
|
"""
|
|
SELECT
|
|
ap.id AS access_point_id,
|
|
ap.bssid,
|
|
ap.essid,
|
|
ap.last_latitude,
|
|
ap.last_longitude,
|
|
MIN(c.id) AS credential_id,
|
|
c.password
|
|
FROM access_points ap
|
|
INNER JOIN credentials c
|
|
ON c.access_point_id = ap.id
|
|
WHERE
|
|
c.password IS NOT NULL
|
|
AND c.password != ''
|
|
AND ap.last_latitude IS NOT NULL
|
|
AND ap.last_longitude IS NOT NULL
|
|
AND NOT EXISTS (
|
|
SELECT 1
|
|
FROM credentials verified_c
|
|
WHERE
|
|
verified_c.access_point_id = ap.id
|
|
AND verified_c.password COLLATE BINARY =
|
|
c.password COLLATE BINARY
|
|
AND verified_c.verified = 1
|
|
)
|
|
AND NOT EXISTS (
|
|
SELECT 1
|
|
FROM credentials history_c
|
|
INNER JOIN wifi_verification_attempts attempt
|
|
ON attempt.credential_id = history_c.id
|
|
WHERE
|
|
history_c.access_point_id = ap.id
|
|
AND history_c.password COLLATE BINARY =
|
|
c.password COLLATE BINARY
|
|
AND attempt.status = 'INVALID_PASSWORD'
|
|
AND attempt.id = (
|
|
SELECT MAX(latest_attempt.id)
|
|
FROM credentials latest_c
|
|
INNER JOIN wifi_verification_attempts latest_attempt
|
|
ON latest_attempt.credential_id = latest_c.id
|
|
WHERE
|
|
latest_c.access_point_id = ap.id
|
|
AND latest_c.password COLLATE BINARY =
|
|
c.password COLLATE BINARY
|
|
)
|
|
)
|
|
GROUP BY
|
|
ap.id,
|
|
ap.bssid,
|
|
ap.essid,
|
|
ap.last_latitude,
|
|
ap.last_longitude,
|
|
c.password COLLATE BINARY
|
|
ORDER BY ap.id, MIN(c.id)
|
|
"""
|
|
).fetchall()
|
|
|
|
grouped = {}
|
|
|
|
for row in rows:
|
|
distance = _distance_meters(
|
|
fix[0],
|
|
fix[1],
|
|
row["last_latitude"],
|
|
row["last_longitude"]
|
|
)
|
|
|
|
if distance > self.radius_m:
|
|
continue
|
|
|
|
bssid = row["bssid"].lower()
|
|
|
|
if bssid not in grouped:
|
|
grouped[bssid] = {
|
|
"access_point_id": row["access_point_id"],
|
|
"bssid": row["bssid"],
|
|
"essid": row["essid"],
|
|
"distance": distance,
|
|
"credentials": []
|
|
}
|
|
|
|
grouped[bssid]["credentials"].append(
|
|
{
|
|
"credential_id": row["credential_id"],
|
|
"password": row["password"]
|
|
}
|
|
)
|
|
|
|
return sorted(
|
|
grouped.values(),
|
|
key=lambda item: item["distance"]
|
|
)
|
|
|
|
def _apply_pending_radius_update(self, connection, work_queue):
|
|
while not self.stop_event.is_set():
|
|
with self._radius_update_lock:
|
|
command = self._pending_radius_update
|
|
|
|
if command is None:
|
|
return False
|
|
|
|
self._set_state("WAITING_GPS")
|
|
|
|
while not self.stop_event.is_set():
|
|
with self._radius_update_lock:
|
|
command = self._pending_radius_update
|
|
|
|
if command is None:
|
|
return False
|
|
|
|
after_generation = command["after_generation"]
|
|
|
|
with self._gps_fix_condition:
|
|
generation = self._gps_fix_generation
|
|
|
|
if generation <= after_generation:
|
|
self._gps_fix_condition.wait()
|
|
continue
|
|
|
|
self._gps_fix_consumed_generation = max(
|
|
self._gps_fix_consumed_generation,
|
|
generation
|
|
)
|
|
|
|
fix = self._get_gps_fix()
|
|
|
|
if fix is None:
|
|
with self._radius_update_lock:
|
|
if self._pending_radius_update is command:
|
|
command["after_generation"] = generation
|
|
|
|
continue
|
|
|
|
with self._radius_update_lock:
|
|
if self._pending_radius_update is not command:
|
|
break
|
|
|
|
radius_m = command["radius_m"]
|
|
|
|
with self.lock:
|
|
self.radius_m = radius_m
|
|
|
|
candidates = self._get_candidates(
|
|
connection,
|
|
fix
|
|
)
|
|
|
|
candidate_credentials = {
|
|
access_point["bssid"].lower(): {
|
|
credential["credential_id"]
|
|
for credential in access_point["credentials"]
|
|
}
|
|
for access_point in candidates
|
|
}
|
|
|
|
queued_ids = set()
|
|
filtered_queue = []
|
|
|
|
for job in work_queue:
|
|
bssid_key = job[1].lower()
|
|
credential_id = job[3]["credential_id"]
|
|
state = self._bssid_states.get(bssid_key)
|
|
|
|
if (
|
|
bssid_key not in candidate_credentials
|
|
or state is None
|
|
or state["status"] == "VERIFIED"
|
|
or credential_id not in candidate_credentials[bssid_key]
|
|
or credential_id in state["processed_credentials"]
|
|
or (bssid_key, credential_id) in queued_ids
|
|
):
|
|
continue
|
|
|
|
filtered_queue.append(job)
|
|
queued_ids.add((bssid_key, credential_id))
|
|
|
|
work_queue[:] = filtered_queue
|
|
|
|
for access_point in candidates:
|
|
bssid = access_point["bssid"]
|
|
bssid_key = bssid.lower()
|
|
|
|
if bssid_key in self._missing_scan_bssids:
|
|
continue
|
|
|
|
state = self._bssid_states.setdefault(
|
|
bssid_key,
|
|
{
|
|
"status": "NEW",
|
|
"processed_credentials": set()
|
|
}
|
|
)
|
|
|
|
if state["status"] == "VERIFIED":
|
|
continue
|
|
|
|
processed_ids = state["processed_credentials"]
|
|
|
|
for credential in access_point["credentials"]:
|
|
credential_id = credential["credential_id"]
|
|
|
|
if credential_id in processed_ids:
|
|
continue
|
|
|
|
if (bssid_key, credential_id) in queued_ids:
|
|
continue
|
|
|
|
work_queue.append(
|
|
(
|
|
access_point["access_point_id"],
|
|
bssid,
|
|
access_point["essid"],
|
|
credential,
|
|
0
|
|
)
|
|
)
|
|
|
|
queued_ids.add((bssid_key, credential_id))
|
|
|
|
for bssid_key, state in self._bssid_states.items():
|
|
if state["status"] == "VERIFIED":
|
|
continue
|
|
|
|
has_jobs = any(
|
|
job[1].lower() == bssid_key
|
|
for job in work_queue
|
|
)
|
|
|
|
state["status"] = (
|
|
"QUEUED" if has_jobs else "COMPLETED"
|
|
)
|
|
|
|
with self.lock:
|
|
self.access_points_total = len(candidates)
|
|
|
|
self._update_monitor_candidates(candidates)
|
|
self._update_monitor_queue(work_queue)
|
|
|
|
self._pending_radius_update = None
|
|
self._radius_update_event.clear()
|
|
|
|
self._add_monitor_event(
|
|
"RADIUS_UPDATED",
|
|
(
|
|
f"Радиус проверки обновлён: {radius_m} м; "
|
|
f"кандидатов: {len(candidates)}"
|
|
)
|
|
)
|
|
|
|
return True
|
|
|
|
if self.stop_event.is_set():
|
|
return False
|
|
|
|
return False
|
|
|
|
def _verify_password(
|
|
self,
|
|
connection,
|
|
access_point,
|
|
credential
|
|
):
|
|
credential_id = credential["credential_id"]
|
|
bssid = access_point["bssid"]
|
|
password = credential["password"]
|
|
|
|
try:
|
|
result = self.wifi_connection_service.verify(
|
|
self.interface,
|
|
bssid,
|
|
password,
|
|
restore_connection=True,
|
|
keep_profile=False,
|
|
access_point=access_point["scan_result"]
|
|
)
|
|
|
|
except APNotFoundError as error:
|
|
self._record_attempt(
|
|
connection,
|
|
credential_id,
|
|
bssid,
|
|
"AP_NOT_FOUND",
|
|
"AP_NOT_FOUND",
|
|
str(error)
|
|
)
|
|
return "AP_NOT_FOUND"
|
|
|
|
except (NetworkRestoreError, NetworkCleanupError):
|
|
raise
|
|
|
|
except NetworkCommandError as error:
|
|
status = (
|
|
"CONNECTION_TIMEOUT"
|
|
if error.timed_out
|
|
else "NETWORK_ERROR"
|
|
)
|
|
|
|
self._record_attempt(
|
|
connection,
|
|
credential_id,
|
|
bssid,
|
|
status,
|
|
type(error).__name__,
|
|
str(error)
|
|
)
|
|
return "TECHNICAL_ERROR"
|
|
|
|
except WiFiConnectionError as error:
|
|
self._record_attempt(
|
|
connection,
|
|
credential_id,
|
|
bssid,
|
|
"UNKNOWN_ERROR",
|
|
type(error).__name__,
|
|
str(error)
|
|
)
|
|
return "TECHNICAL_ERROR"
|
|
|
|
if result.get("success"):
|
|
connection.execute(
|
|
"""
|
|
UPDATE credentials
|
|
SET verified = 0
|
|
WHERE
|
|
access_point_id = ?
|
|
AND password COLLATE BINARY != ? COLLATE BINARY
|
|
""",
|
|
(
|
|
access_point["access_point_id"],
|
|
password
|
|
)
|
|
)
|
|
connection.execute(
|
|
"""
|
|
UPDATE credentials
|
|
SET verified = 1
|
|
WHERE
|
|
access_point_id = ?
|
|
AND password COLLATE BINARY = ? COLLATE BINARY
|
|
""",
|
|
(
|
|
access_point["access_point_id"],
|
|
password
|
|
)
|
|
)
|
|
connection.commit()
|
|
|
|
self._record_attempt(
|
|
connection,
|
|
credential_id,
|
|
bssid,
|
|
"SUCCESS"
|
|
)
|
|
|
|
return "SUCCESS"
|
|
|
|
if result.get("error_type") == "APNotFoundError":
|
|
self._record_attempt(
|
|
connection,
|
|
credential_id,
|
|
bssid,
|
|
"AP_NOT_FOUND",
|
|
"AP_NOT_FOUND",
|
|
result.get("error")
|
|
)
|
|
return "AP_NOT_FOUND"
|
|
|
|
if _is_invalid_password(result):
|
|
self._record_attempt(
|
|
connection,
|
|
credential_id,
|
|
bssid,
|
|
"INVALID_PASSWORD",
|
|
result.get("error_type") or "INVALID_PASSWORD",
|
|
result.get("error")
|
|
)
|
|
return "INVALID_PASSWORD"
|
|
|
|
error_type = result.get("error_type") or "UNKNOWN_ERROR"
|
|
|
|
status = (
|
|
"CONNECTION_TIMEOUT"
|
|
if result.get("error_timed_out")
|
|
else "NETWORK_ERROR"
|
|
if error_type == "NetworkCommandError"
|
|
else "UNKNOWN_ERROR"
|
|
)
|
|
|
|
self._record_attempt(
|
|
connection,
|
|
credential_id,
|
|
bssid,
|
|
status,
|
|
error_type,
|
|
result.get("error")
|
|
)
|
|
|
|
return "TECHNICAL_ERROR"
|
|
|
|
def _process_access_point(
|
|
self,
|
|
connection,
|
|
access_point,
|
|
retry_queue,
|
|
scan_result=None
|
|
):
|
|
bssid = access_point["bssid"]
|
|
result = {
|
|
"processed_credentials": set(),
|
|
"verified": False,
|
|
"interrupted": False,
|
|
"ap_not_found": False
|
|
}
|
|
|
|
with self.lock:
|
|
self.current_bssid = bssid
|
|
self.current_essid = access_point["essid"]
|
|
|
|
self._notify()
|
|
|
|
if scan_result is None:
|
|
try:
|
|
scan_result = self.wifi_connection_service.get_access_point(
|
|
self.interface,
|
|
bssid
|
|
)
|
|
|
|
except APNotFoundError:
|
|
retry_queue[:] = [
|
|
job for job in retry_queue
|
|
if job[1].lower() != bssid.lower()
|
|
]
|
|
result["ap_not_found"] = True
|
|
return result
|
|
|
|
access_point["scan_result"] = scan_result
|
|
|
|
for credential in access_point["credentials"]:
|
|
if self.stop_event.is_set():
|
|
result["interrupted"] = True
|
|
return result
|
|
|
|
outcome = self._verify_password(
|
|
connection,
|
|
access_point,
|
|
credential
|
|
)
|
|
|
|
result["processed_credentials"].add(
|
|
credential["credential_id"]
|
|
)
|
|
|
|
if outcome == "AP_NOT_FOUND":
|
|
retry_queue[:] = [
|
|
job for job in retry_queue
|
|
if job[1].lower() != bssid.lower()
|
|
]
|
|
result["ap_not_found"] = True
|
|
break
|
|
|
|
if outcome == "SUCCESS":
|
|
result["verified"] = True
|
|
retry_queue[:] = [
|
|
job for job in retry_queue
|
|
if job[1].lower() != bssid.lower()
|
|
]
|
|
break
|
|
|
|
if outcome in ("INVALID_PASSWORD", "TECHNICAL_ERROR"):
|
|
retry_queue.append(
|
|
(
|
|
access_point["access_point_id"],
|
|
bssid,
|
|
access_point["essid"],
|
|
credential
|
|
)
|
|
)
|
|
|
|
self._notify()
|
|
|
|
return result
|
|
|
|
def _process_retry(
|
|
self,
|
|
connection,
|
|
job,
|
|
retry_queue,
|
|
scan_result=None
|
|
):
|
|
access_point_id, bssid, essid, credential = job[:4]
|
|
|
|
result = {
|
|
"verified": False,
|
|
"interrupted": False,
|
|
"ap_not_found": False
|
|
}
|
|
|
|
if scan_result is None:
|
|
try:
|
|
scan_result = self.wifi_connection_service.get_access_point(
|
|
self.interface,
|
|
bssid
|
|
)
|
|
except APNotFoundError:
|
|
retry_queue[:] = [
|
|
queued_job for queued_job in retry_queue
|
|
if queued_job[1].lower() != bssid.lower()
|
|
]
|
|
result["ap_not_found"] = True
|
|
return result
|
|
|
|
access_point = {
|
|
"access_point_id": access_point_id,
|
|
"bssid": bssid,
|
|
"essid": essid,
|
|
"scan_result": scan_result
|
|
}
|
|
|
|
if self.stop_event.is_set():
|
|
result["interrupted"] = True
|
|
return result
|
|
|
|
outcome = self._verify_password(
|
|
connection,
|
|
access_point,
|
|
credential
|
|
)
|
|
|
|
if outcome == "SUCCESS":
|
|
result["verified"] = True
|
|
|
|
elif outcome == "AP_NOT_FOUND":
|
|
result["ap_not_found"] = True
|
|
retry_queue.append(job)
|
|
|
|
elif outcome in ("INVALID_PASSWORD", "TECHNICAL_ERROR"):
|
|
retry_queue.append(job)
|
|
|
|
self._notify()
|
|
|
|
return result
|
|
|
|
def _worker(self):
|
|
connection = None
|
|
final_status = "STOPPED"
|
|
|
|
try:
|
|
connection = connect_database()
|
|
|
|
self._create_session(
|
|
connection
|
|
)
|
|
|
|
if self.manage_gps_service:
|
|
self.gps_service.start()
|
|
|
|
# Единственная FIFO-очередь.
|
|
# Формат задания:
|
|
# (access_point_id, bssid, essid, credential, retry_count)
|
|
work_queue = []
|
|
|
|
self._update_monitor_queue(work_queue)
|
|
self._set_monitor_active()
|
|
self._add_monitor_event(
|
|
"SERVICE_STARTED",
|
|
"Сервис автоматической проверки запущен"
|
|
)
|
|
|
|
gps_refresh_deferred = False
|
|
|
|
while not self.stop_event.is_set():
|
|
if self._radius_update_event.is_set():
|
|
self._apply_pending_radius_update(
|
|
connection,
|
|
work_queue
|
|
)
|
|
continue
|
|
|
|
gps_update = False
|
|
|
|
# Забираем последнее необработанное GPS-поколение.
|
|
with self._gps_fix_condition:
|
|
if (
|
|
self._gps_fix_generation
|
|
> self._gps_fix_consumed_generation
|
|
):
|
|
self._gps_fix_consumed_generation = (
|
|
self._gps_fix_generation
|
|
)
|
|
gps_update = True
|
|
|
|
# GPS FIX добавляет новые задания.
|
|
# Потеря GPS не очищает существующую очередь.
|
|
if gps_update:
|
|
fix = self._get_gps_fix()
|
|
|
|
if fix is not None:
|
|
candidates = self._get_candidates(
|
|
connection,
|
|
fix
|
|
)
|
|
|
|
with self.lock:
|
|
self.access_points_total = len(candidates)
|
|
|
|
self._update_monitor_candidates(candidates)
|
|
self._add_monitor_event(
|
|
"CANDIDATES_REFRESHED",
|
|
f"Обновлён список кандидатов: {len(candidates)}"
|
|
)
|
|
|
|
for access_point in candidates:
|
|
bssid = access_point["bssid"]
|
|
bssid_key = bssid.lower()
|
|
|
|
if bssid_key in self._missing_scan_bssids:
|
|
continue
|
|
|
|
state = self._bssid_states.setdefault(
|
|
bssid_key,
|
|
{
|
|
"status": "NEW",
|
|
"processed_credentials": set()
|
|
}
|
|
)
|
|
|
|
if state["status"] == "VERIFIED":
|
|
continue
|
|
|
|
processed_ids = state[
|
|
"processed_credentials"
|
|
]
|
|
|
|
queued_ids = {
|
|
job[3]["credential_id"]
|
|
for job in work_queue
|
|
if job[1].lower() == bssid_key
|
|
}
|
|
|
|
for credential in access_point["credentials"]:
|
|
credential_id = credential["credential_id"]
|
|
|
|
if credential_id in processed_ids:
|
|
continue
|
|
|
|
if credential_id in queued_ids:
|
|
continue
|
|
|
|
work_queue.append(
|
|
(
|
|
access_point["access_point_id"],
|
|
bssid,
|
|
access_point["essid"],
|
|
credential,
|
|
0
|
|
)
|
|
)
|
|
|
|
queued_ids.add(credential_id)
|
|
|
|
self._update_monitor_queue(work_queue)
|
|
|
|
if self.stop_event.is_set():
|
|
break
|
|
|
|
# Пустая очередь — ожидаем новый GPS FIX.
|
|
if not work_queue:
|
|
self._set_state("WAITING_GPS")
|
|
|
|
with self._gps_fix_condition:
|
|
while (
|
|
not self.stop_event.is_set()
|
|
and not self._radius_update_event.is_set()
|
|
and self._gps_fix_generation
|
|
<= self._gps_fix_consumed_generation
|
|
):
|
|
self._gps_fix_condition.wait()
|
|
|
|
continue
|
|
|
|
self._set_state("RUNNING")
|
|
|
|
# Одна свежая общая радиосканировка на одну попытку.
|
|
scan_results = self.wifi_connection_service.get_access_points(
|
|
self.interface
|
|
)
|
|
|
|
visible_access_points = {
|
|
access_point.bssid.lower(): access_point
|
|
for access_point in scan_results
|
|
}
|
|
|
|
self._update_monitor_signal(scan_results)
|
|
|
|
gps_update_pending = False
|
|
|
|
with self._gps_fix_condition:
|
|
gps_update_pending = (
|
|
self._gps_fix_generation
|
|
> self._gps_fix_consumed_generation
|
|
)
|
|
|
|
if gps_update_pending and not gps_refresh_deferred:
|
|
gps_refresh_deferred = True
|
|
continue
|
|
|
|
# Удаляем задания и состояние только для отсутствующих BSSID.
|
|
missing_bssids = [
|
|
bssid_key
|
|
for bssid_key in self._bssid_states
|
|
if bssid_key not in visible_access_points
|
|
]
|
|
|
|
for bssid_key in missing_bssids:
|
|
del self._bssid_states[bssid_key]
|
|
|
|
self._missing_scan_bssids.update(missing_bssids)
|
|
self._missing_scan_bssids.difference_update(
|
|
visible_access_points
|
|
)
|
|
|
|
if missing_bssids:
|
|
work_queue = [
|
|
job for job in work_queue
|
|
if job[1].lower() not in missing_bssids
|
|
]
|
|
|
|
self._add_monitor_event(
|
|
"AP_MISSING_FROM_SCAN",
|
|
(
|
|
"Точки отсутствуют в радиосканировании, "
|
|
f"задания удалены: {len(missing_bssids)}"
|
|
),
|
|
"warning"
|
|
)
|
|
|
|
self._update_monitor_queue(work_queue)
|
|
|
|
if self.stop_event.is_set():
|
|
break
|
|
|
|
if not work_queue:
|
|
self._update_session_counters(connection)
|
|
continue
|
|
|
|
|
|
# Радиус имеет приоритет перед следующим заданием.
|
|
radius_update_pending = False
|
|
|
|
with self._radius_update_lock:
|
|
if self._pending_radius_update is not None:
|
|
radius_update_pending = True
|
|
else:
|
|
job = work_queue.pop(0)
|
|
gps_refresh_deferred = False
|
|
|
|
if radius_update_pending:
|
|
self._apply_pending_radius_update(
|
|
connection,
|
|
work_queue
|
|
)
|
|
continue
|
|
|
|
|
|
self._update_monitor_queue(work_queue)
|
|
self._set_monitor_active(job)
|
|
self._add_monitor_event(
|
|
"ATTEMPT_STARTED",
|
|
"Начата проверка точки доступа"
|
|
)
|
|
|
|
access_point_id, bssid, essid, credential, retry_count = job
|
|
|
|
bssid_key = bssid.lower()
|
|
credential_id = credential["credential_id"]
|
|
|
|
state = self._bssid_states.get(bssid_key)
|
|
scan_result = visible_access_points.get(bssid_key)
|
|
|
|
if state is None or scan_result is None:
|
|
self._set_monitor_active()
|
|
self._update_session_counters(connection)
|
|
continue
|
|
|
|
if state["status"] == "VERIFIED":
|
|
self._set_monitor_active()
|
|
continue
|
|
|
|
state["status"] = "CHECKING"
|
|
|
|
if self.stop_event.is_set():
|
|
break
|
|
|
|
# При ошибке _process_retry добавляет исходное задание
|
|
# в конец этой же очереди.
|
|
result = self._process_retry(
|
|
connection,
|
|
job,
|
|
work_queue,
|
|
scan_result=scan_result
|
|
) or {}
|
|
|
|
state = self._bssid_states.get(bssid_key)
|
|
|
|
if state is not None:
|
|
state["processed_credentials"].add(credential_id)
|
|
|
|
if result.get("verified"):
|
|
state = self._bssid_states.get(bssid_key)
|
|
|
|
if state is not None:
|
|
state["status"] = "VERIFIED"
|
|
|
|
# Успех прекращает проверку остальных паролей AP.
|
|
work_queue = [
|
|
queued_job for queued_job in work_queue
|
|
if queued_job[1].lower() != bssid_key
|
|
]
|
|
|
|
elif result.get("interrupted"):
|
|
break
|
|
|
|
else:
|
|
# Пересоздаём задание со следующим номером попытки.
|
|
retry_scheduled = (
|
|
bool(work_queue)
|
|
and work_queue[-1] == job
|
|
)
|
|
|
|
if retry_scheduled:
|
|
work_queue.pop()
|
|
|
|
if retry_count < self.queue_retry_passes:
|
|
work_queue.append(
|
|
(
|
|
access_point_id,
|
|
bssid,
|
|
essid,
|
|
credential,
|
|
retry_count + 1
|
|
)
|
|
)
|
|
|
|
state = self._bssid_states.get(bssid_key)
|
|
|
|
if state is not None:
|
|
has_jobs = any(
|
|
queued_job[1].lower() == bssid_key
|
|
for queued_job in work_queue
|
|
)
|
|
|
|
state["status"] = (
|
|
"QUEUED" if has_jobs else "COMPLETED"
|
|
)
|
|
|
|
self._set_monitor_active()
|
|
self._update_monitor_queue(work_queue)
|
|
|
|
if self.stop_event.is_set():
|
|
break
|
|
|
|
self._update_session_counters(connection)
|
|
|
|
final_status = "STOPPED"
|
|
|
|
|
|
except (NetworkRestoreError, NetworkCleanupError) as error:
|
|
final_status = "ERROR"
|
|
self._set_state(
|
|
"ERROR",
|
|
str(error)
|
|
)
|
|
logger.exception(
|
|
"Critical Wi-Fi restoration or cleanup error."
|
|
)
|
|
|
|
except Exception as error:
|
|
final_status = "ERROR"
|
|
self._set_state(
|
|
"ERROR",
|
|
str(error)
|
|
)
|
|
logger.exception(
|
|
"Auto Wi-Fi verification failed."
|
|
)
|
|
|
|
finally:
|
|
if self.manage_gps_service:
|
|
try:
|
|
self.gps_service.stop()
|
|
except Exception:
|
|
logger.exception(
|
|
"Failed to stop Auto GPS service."
|
|
)
|
|
|
|
cleanup_success = False
|
|
|
|
try:
|
|
self.wifi_connection_service.cleanup_auto_profiles(
|
|
self.interface,
|
|
None,
|
|
[]
|
|
)
|
|
cleanup_success = True
|
|
|
|
except Exception as error:
|
|
final_status = "ERROR"
|
|
self._set_state(
|
|
"ERROR",
|
|
str(error)
|
|
)
|
|
logger.exception(
|
|
"Failed to clean up Auto verification profiles."
|
|
)
|
|
|
|
if cleanup_success:
|
|
try:
|
|
self._release_network_owner()
|
|
|
|
except Exception as error:
|
|
final_status = "ERROR"
|
|
self._set_state(
|
|
"ERROR",
|
|
str(error)
|
|
)
|
|
logger.exception(
|
|
"Failed to release AUTO_WIFI_VERIFY network owner."
|
|
)
|
|
|
|
if connection is not None:
|
|
try:
|
|
self._update_session(
|
|
connection,
|
|
final_status
|
|
)
|
|
except Exception:
|
|
logger.exception(
|
|
"Failed to finalize verification session."
|
|
)
|
|
finally:
|
|
close_database(connection)
|
|
|
|
self._set_monitor_active()
|
|
self._update_monitor_queue([])
|
|
self._add_monitor_event(
|
|
"SERVICE_STOPPED",
|
|
(
|
|
"Сервис завершил работу с ошибкой"
|
|
if final_status == "ERROR"
|
|
else "Сервис автоматической проверки остановлен"
|
|
),
|
|
"error" if final_status == "ERROR" else "info"
|
|
)
|
|
|
|
with self.lock:
|
|
self.running = False
|
|
|
|
if self.state != "ERROR":
|
|
self.state = "STOPPED"
|
|
|
|
self.current_bssid = None
|
|
self.current_essid = None
|
|
self._bssid_states.clear()
|
|
self._missing_scan_bssids.clear()
|
|
|
|
self._notify()
|