Compare commits
56
Commits
edc93c7348
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ddafbb613b | ||
|
|
012f209303 | ||
|
|
52fef57721 | ||
|
|
2c621aa8f1 | ||
|
|
2755f6b383 | ||
|
|
6866e02d7a | ||
|
|
899f7436f4 | ||
|
|
2d34fd41fd | ||
|
|
c8aa152087 | ||
|
|
e850b691c2 | ||
|
|
5994d513c8 | ||
|
|
37a52f004e | ||
|
|
34857e8ed2 | ||
|
|
f7d78c0ea6 | ||
|
|
b50baedda4 | ||
|
|
7c44fb339e | ||
|
|
705fa62d2c | ||
|
|
267707e271 | ||
|
|
a4fda4dcdc | ||
|
|
dbecf7b34e | ||
|
|
9c8229517b | ||
|
|
c892a96064 | ||
|
|
9e35491e3c | ||
|
|
fbc709e750 | ||
|
|
32c9eea487 | ||
|
|
d9ebdf9a14 | ||
|
|
f9af674230 | ||
|
|
92ccd37846 | ||
|
|
bdf44b9a2e | ||
|
|
e512ecdd8c | ||
|
|
086cedeb1f | ||
|
|
ed83f4f9cc | ||
|
|
6fa7b772e6 | ||
|
|
c1a2b960e7 | ||
|
|
7468f6c0d3 | ||
|
|
b96a3dfe36 | ||
|
|
7e8d251210 | ||
|
|
a0be30dddb | ||
|
|
a9358fec17 | ||
|
|
22c3c8b9bb | ||
|
|
2c003062cb | ||
|
|
b8dd02f4fa | ||
|
|
6ff1922de6 | ||
|
|
104a23ab2d | ||
|
|
c8df4d72d1 | ||
|
|
d386e1593d | ||
|
|
e45b427c12 | ||
|
|
04a7f08d7d | ||
|
|
05f83fd186 | ||
|
|
d5594ace92 | ||
|
|
bbcb2c8920 | ||
|
|
ab59e68615 | ||
|
|
dd182e9e4e | ||
|
|
aba6633b1f | ||
|
|
bb9e16638e | ||
|
|
d519a34145 |
@@ -32,6 +32,7 @@ class _ValidatedPackage:
|
||||
hash_content: bytes
|
||||
job_bytes: bytes
|
||||
hash_path: str
|
||||
package_filename: str
|
||||
|
||||
|
||||
class JobPackageService:
|
||||
@@ -56,7 +57,7 @@ class JobPackageService:
|
||||
job_id = validated.job["job_id"]
|
||||
job_path = (
|
||||
self._paths.jobs
|
||||
/ package_path.stem
|
||||
/ job_id
|
||||
)
|
||||
|
||||
if job_path.exists():
|
||||
@@ -175,6 +176,7 @@ class JobPackageService:
|
||||
hash_content=hash_bytes,
|
||||
job_bytes=job_bytes,
|
||||
hash_path=hash_name,
|
||||
package_filename=package_path.name,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -954,6 +956,14 @@ class JobPackageService:
|
||||
package.hash_content
|
||||
)
|
||||
|
||||
(
|
||||
temporary_path
|
||||
/ "package_filename.txt"
|
||||
).write_text(
|
||||
package.package_filename,
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
initialize_state(
|
||||
temporary_path,
|
||||
package.job,
|
||||
|
||||
@@ -252,10 +252,34 @@ def create_result_package(
|
||||
|
||||
job_id = job["job_id"]
|
||||
|
||||
destination = (
|
||||
outbox / f"RESULT-{job_dir.name}.zip"
|
||||
package_filename_path = (
|
||||
job_dir / "package_filename.txt"
|
||||
)
|
||||
|
||||
result_filename = f"RESULT-{job_dir.name}.zip"
|
||||
|
||||
if package_filename_path.is_file():
|
||||
package_filename = (
|
||||
package_filename_path.read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
)
|
||||
|
||||
if (
|
||||
not package_filename.startswith("JOB-")
|
||||
or not package_filename.endswith(".zip")
|
||||
or Path(package_filename).name != package_filename
|
||||
):
|
||||
raise ResultPackageError(
|
||||
"Invalid original Job package filename."
|
||||
)
|
||||
|
||||
result_filename = (
|
||||
f"RESULT-{package_filename.removeprefix('JOB-')}"
|
||||
)
|
||||
|
||||
destination = outbox / result_filename
|
||||
|
||||
if destination.exists():
|
||||
raise ResultPackageError(
|
||||
f"Result package already exists: "
|
||||
@@ -263,7 +287,7 @@ def create_result_package(
|
||||
)
|
||||
|
||||
fd, temporary = tempfile.mkstemp(
|
||||
prefix=f".RESULT-{job_dir.name}.",
|
||||
prefix=f".{destination.stem}.",
|
||||
suffix=".zip.tmp",
|
||||
dir=str(outbox),
|
||||
)
|
||||
|
||||
+308
-51
@@ -64,6 +64,7 @@ from reports.wifitrip import (
|
||||
)
|
||||
from reports.session_page import render_session_page
|
||||
from reports.access_points import render_access_points_page
|
||||
from reports.wifi_connections import render_wifi_connections_page
|
||||
from reports.access_points_page import render_access_point_page
|
||||
from reports.template import ReportContext
|
||||
from reports.utils import format_datetime as format_report_datetime
|
||||
@@ -79,6 +80,7 @@ from logging_config import (
|
||||
LOG_FORMAT,
|
||||
UTCFormatter,
|
||||
)
|
||||
from request_lifecycle import RequestLifecycleMiddleware
|
||||
|
||||
app = Flask(
|
||||
__name__,
|
||||
@@ -90,6 +92,11 @@ app = Flask(
|
||||
)
|
||||
)
|
||||
|
||||
request_lifecycle = RequestLifecycleMiddleware(
|
||||
app.wsgi_app
|
||||
)
|
||||
app.wsgi_app = request_lifecycle
|
||||
|
||||
app.add_template_filter(
|
||||
format_report_datetime,
|
||||
"local_datetime"
|
||||
@@ -136,9 +143,13 @@ def wants_json_error():
|
||||
))
|
||||
or request.path in {
|
||||
"/reports/vendors/update",
|
||||
"/reports/vendors/recalculate",
|
||||
"/reports/search/data",
|
||||
"/reports/search/cracklab",
|
||||
}
|
||||
or request.path.startswith(
|
||||
"/reports/vendors/recalculate/status/"
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
@@ -286,18 +297,31 @@ scanner_output = deque(
|
||||
|
||||
scanner_lock = threading.Lock()
|
||||
|
||||
scanner_output_thread = None
|
||||
|
||||
vendor_previews = {}
|
||||
|
||||
vendor_preview_lock = threading.Lock()
|
||||
|
||||
vendor_update_job = None
|
||||
vendor_update_thread = None
|
||||
|
||||
vendor_update_lock = threading.Lock()
|
||||
|
||||
vendor_operation_lock = threading.Lock()
|
||||
|
||||
vendor_recalc_job = None
|
||||
vendor_recalc_thread = None
|
||||
|
||||
vendor_recalc_lock = threading.Lock()
|
||||
|
||||
gps_test_service = None
|
||||
|
||||
gps_test_lock = threading.Lock()
|
||||
|
||||
sudo_keepalive_stop_event = threading.Event()
|
||||
sudo_keepalive_thread = None
|
||||
|
||||
wifi_connection_service = WiFiConnectionService()
|
||||
|
||||
def check_sudo():
|
||||
@@ -324,13 +348,11 @@ def check_sudo():
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def sudo_keepalive():
|
||||
def sudo_keepalive(stop_event):
|
||||
|
||||
checker = SudoChecker()
|
||||
|
||||
while True:
|
||||
|
||||
time.sleep(60)
|
||||
while not stop_event.wait(60):
|
||||
|
||||
checker.refresh()
|
||||
|
||||
@@ -1367,6 +1389,13 @@ def render_report(
|
||||
finally:
|
||||
close_database(conn)
|
||||
|
||||
@app.route("/reports/wifi-connections/")
|
||||
def reports_wifi_connections():
|
||||
|
||||
return render_report(
|
||||
render_wifi_connections_page
|
||||
)
|
||||
|
||||
@app.route("/reports/vendors/")
|
||||
def reports_vendors():
|
||||
|
||||
@@ -1408,6 +1437,25 @@ def reports_vendors():
|
||||
preview = None
|
||||
token = None
|
||||
|
||||
recalc_job = None
|
||||
|
||||
recalc_job_id = request.args.get(
|
||||
"recalc_job_id"
|
||||
)
|
||||
|
||||
if recalc_job_id:
|
||||
|
||||
with vendor_recalc_lock:
|
||||
|
||||
if (
|
||||
vendor_recalc_job is not None
|
||||
and vendor_recalc_job["id"] == recalc_job_id
|
||||
):
|
||||
|
||||
recalc_job = dict(
|
||||
vendor_recalc_job
|
||||
)
|
||||
|
||||
if job_id:
|
||||
|
||||
with vendor_update_lock:
|
||||
@@ -1442,7 +1490,8 @@ def reports_vendors():
|
||||
service,
|
||||
preview,
|
||||
token,
|
||||
job=job
|
||||
job=job,
|
||||
recalc_job=recalc_job
|
||||
)
|
||||
|
||||
def _run_vendor_update(
|
||||
@@ -1544,6 +1593,7 @@ def _run_vendor_update(
|
||||
def reports_vendors_update():
|
||||
|
||||
global vendor_update_job
|
||||
global vendor_update_thread
|
||||
|
||||
config = read_config()
|
||||
|
||||
@@ -1607,7 +1657,9 @@ def reports_vendors_update():
|
||||
"service": service
|
||||
}
|
||||
|
||||
thread = threading.Thread(
|
||||
try:
|
||||
|
||||
vendor_update_thread = threading.Thread(
|
||||
target=_run_vendor_update,
|
||||
args=(
|
||||
job_id,
|
||||
@@ -1616,7 +1668,17 @@ def reports_vendors_update():
|
||||
daemon=True
|
||||
)
|
||||
|
||||
thread.start()
|
||||
vendor_update_thread.start()
|
||||
|
||||
except Exception as error:
|
||||
|
||||
vendor_update_job["status"] = "error"
|
||||
vendor_update_job["stage"] = "error"
|
||||
vendor_update_job["source"] = None
|
||||
vendor_update_job["message"] = None
|
||||
vendor_update_job["error"] = str(
|
||||
error
|
||||
)
|
||||
|
||||
job = dict(
|
||||
vendor_update_job
|
||||
@@ -1667,33 +1729,205 @@ def reports_vendors_update_status(
|
||||
}
|
||||
)
|
||||
|
||||
def _run_vendor_recalculation(
|
||||
job_id,
|
||||
service
|
||||
):
|
||||
|
||||
global vendor_recalc_job
|
||||
|
||||
def progress_callback(
|
||||
stage,
|
||||
source=None,
|
||||
message=None
|
||||
):
|
||||
|
||||
with vendor_recalc_lock:
|
||||
|
||||
if (
|
||||
vendor_recalc_job is None
|
||||
or vendor_recalc_job["id"] != job_id
|
||||
):
|
||||
return
|
||||
|
||||
vendor_recalc_job["stage"] = stage
|
||||
vendor_recalc_job["message"] = message
|
||||
|
||||
try:
|
||||
|
||||
with vendor_operation_lock:
|
||||
|
||||
progress_callback(
|
||||
"scanning",
|
||||
message="Пересчёт производителей точек доступа"
|
||||
)
|
||||
|
||||
result = service.recalculate_ap_vendors(
|
||||
progress_callback=progress_callback
|
||||
)
|
||||
|
||||
with vendor_recalc_lock:
|
||||
|
||||
if (
|
||||
vendor_recalc_job is not None
|
||||
and vendor_recalc_job["id"] == job_id
|
||||
):
|
||||
|
||||
vendor_recalc_job["status"] = "ready"
|
||||
vendor_recalc_job["stage"] = "ready"
|
||||
vendor_recalc_job["message"] = (
|
||||
"Пересчёт производителей завершён"
|
||||
)
|
||||
vendor_recalc_job["result"] = result
|
||||
vendor_recalc_job["error"] = None
|
||||
|
||||
except Exception as error:
|
||||
|
||||
with vendor_recalc_lock:
|
||||
|
||||
if (
|
||||
vendor_recalc_job is not None
|
||||
and vendor_recalc_job["id"] == job_id
|
||||
):
|
||||
|
||||
vendor_recalc_job["status"] = "error"
|
||||
vendor_recalc_job["stage"] = "error"
|
||||
vendor_recalc_job["message"] = None
|
||||
vendor_recalc_job["error"] = str(error)
|
||||
|
||||
|
||||
@app.route(
|
||||
"/reports/vendors/recalculate",
|
||||
methods=["POST"]
|
||||
)
|
||||
def reports_vendors_recalculate():
|
||||
|
||||
global vendor_recalc_job
|
||||
global vendor_recalc_thread
|
||||
|
||||
config = read_config()
|
||||
|
||||
if "_error" in config:
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"error": config["_error"]
|
||||
}
|
||||
), 500
|
||||
|
||||
vendor_config = config.get(
|
||||
"vendor",
|
||||
{}
|
||||
)
|
||||
|
||||
database_config = config.get(
|
||||
"database",
|
||||
{}
|
||||
)
|
||||
|
||||
service = VendorService(
|
||||
PROJECT_ROOT / vendor_config["database"],
|
||||
PROJECT_ROOT / database_config["file"],
|
||||
sources={}
|
||||
)
|
||||
|
||||
with vendor_recalc_lock:
|
||||
|
||||
if (
|
||||
vendor_recalc_job is not None
|
||||
and vendor_recalc_job["status"] == "running"
|
||||
):
|
||||
|
||||
job = dict(
|
||||
vendor_recalc_job
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
job_id = secrets.token_urlsafe(
|
||||
16
|
||||
)
|
||||
|
||||
vendor_recalc_job = {
|
||||
"id": job_id,
|
||||
"status": "running",
|
||||
"stage": "waiting",
|
||||
"message": "Ожидание доступа к базам данных",
|
||||
"error": None,
|
||||
"result": None
|
||||
}
|
||||
|
||||
try:
|
||||
|
||||
vendor_recalc_thread = threading.Thread(
|
||||
target=_run_vendor_recalculation,
|
||||
args=(
|
||||
job_id,
|
||||
service
|
||||
),
|
||||
daemon=True
|
||||
)
|
||||
|
||||
vendor_recalc_thread.start()
|
||||
|
||||
except Exception as error:
|
||||
|
||||
vendor_recalc_job["status"] = "error"
|
||||
vendor_recalc_job["stage"] = "error"
|
||||
vendor_recalc_job["message"] = None
|
||||
vendor_recalc_job["error"] = str(error)
|
||||
|
||||
job = dict(
|
||||
vendor_recalc_job
|
||||
)
|
||||
|
||||
return render_report(
|
||||
render_vendors_page,
|
||||
service,
|
||||
recalc_job=job
|
||||
)
|
||||
|
||||
|
||||
@app.route(
|
||||
"/reports/vendors/recalculate/status/<job_id>"
|
||||
)
|
||||
def reports_vendors_recalculate_status(
|
||||
job_id
|
||||
):
|
||||
|
||||
with vendor_recalc_lock:
|
||||
|
||||
if (
|
||||
vendor_recalc_job is None
|
||||
or vendor_recalc_job["id"] != job_id
|
||||
):
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"status": "missing",
|
||||
"error": "Vendor recalculation job is missing."
|
||||
}
|
||||
), 404
|
||||
|
||||
job = dict(
|
||||
vendor_recalc_job
|
||||
)
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"status": job["status"],
|
||||
"stage": job["stage"],
|
||||
"message": job["message"],
|
||||
"error": job["error"]
|
||||
}
|
||||
)
|
||||
|
||||
@app.route(
|
||||
"/reports/vendors/apply",
|
||||
methods=["POST"]
|
||||
)
|
||||
def reports_vendors_apply():
|
||||
|
||||
token = request.form.get(
|
||||
"token",
|
||||
""
|
||||
)
|
||||
|
||||
with vendor_preview_lock:
|
||||
|
||||
preview = vendor_previews.pop(
|
||||
token,
|
||||
None
|
||||
)
|
||||
|
||||
if preview is None:
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"error":
|
||||
"Vendor preview is missing or expired."
|
||||
}
|
||||
), 400
|
||||
|
||||
config = read_config()
|
||||
|
||||
if "_error" in config:
|
||||
@@ -1724,26 +1958,45 @@ def reports_vendors_apply():
|
||||
)
|
||||
)
|
||||
|
||||
selected = {
|
||||
"unknown_to_vendor":
|
||||
request.form.get(
|
||||
"unknown_to_vendor"
|
||||
) == "1",
|
||||
"vendor_to_vendor":
|
||||
request.form.get(
|
||||
"vendor_to_vendor"
|
||||
) == "1",
|
||||
"vendor_to_unknown":
|
||||
request.form.get(
|
||||
"vendor_to_unknown"
|
||||
) == "1"
|
||||
if not vendor_operation_lock.acquire(
|
||||
blocking=False
|
||||
):
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"error":
|
||||
"Another vendor database operation is running. "
|
||||
"Please try again later."
|
||||
}
|
||||
), 409
|
||||
|
||||
try:
|
||||
|
||||
token = request.form.get(
|
||||
"token",
|
||||
""
|
||||
)
|
||||
|
||||
with vendor_preview_lock:
|
||||
|
||||
preview = vendor_previews.pop(
|
||||
token,
|
||||
None
|
||||
)
|
||||
|
||||
if preview is None:
|
||||
|
||||
return jsonify(
|
||||
{
|
||||
"error":
|
||||
"Vendor preview is missing or expired."
|
||||
}
|
||||
), 400
|
||||
|
||||
try:
|
||||
|
||||
result = service.apply(
|
||||
preview,
|
||||
**selected
|
||||
preview
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
@@ -1763,15 +2016,17 @@ def reports_vendors_apply():
|
||||
message={
|
||||
"type": "success",
|
||||
"text": (
|
||||
"Update completed. "
|
||||
"OUI update completed. "
|
||||
f"OUI updated: "
|
||||
f"{'yes' if result['oui_updated'] else 'no'}. "
|
||||
f"WiFi AP records updated: "
|
||||
f"{result['wifi_updated']}."
|
||||
f"{'yes' if result['oui_updated'] else 'no'}."
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
finally:
|
||||
|
||||
vendor_operation_lock.release()
|
||||
|
||||
@app.route("/reports/")
|
||||
def reports_dashboard():
|
||||
|
||||
@@ -3144,6 +3399,7 @@ def config_save():
|
||||
def scanner_start():
|
||||
|
||||
global scanner_process
|
||||
global scanner_output_thread
|
||||
global scanner_health
|
||||
global scanner_stopped_at
|
||||
global scanner_starting
|
||||
@@ -3294,13 +3550,13 @@ def scanner_start():
|
||||
)
|
||||
|
||||
|
||||
thread = threading.Thread(
|
||||
scanner_output_thread = threading.Thread(
|
||||
target=read_scanner_output,
|
||||
args=(process,),
|
||||
daemon=True
|
||||
)
|
||||
|
||||
thread.start()
|
||||
scanner_output_thread.start()
|
||||
|
||||
|
||||
return redirect(
|
||||
@@ -3377,12 +3633,13 @@ if __name__ == "__main__":
|
||||
)
|
||||
|
||||
|
||||
thread = threading.Thread(
|
||||
sudo_keepalive_thread = threading.Thread(
|
||||
target=sudo_keepalive,
|
||||
args=(sudo_keepalive_stop_event,),
|
||||
daemon=True
|
||||
)
|
||||
|
||||
thread.start()
|
||||
sudo_keepalive_thread.start()
|
||||
|
||||
|
||||
logging.getLogger("werkzeug").disabled = True
|
||||
|
||||
@@ -12,6 +12,7 @@ from reports.utils import (
|
||||
format_datetime as format_report_datetime,
|
||||
)
|
||||
from reports.map_popups import build_standard_popup
|
||||
from reports.map_service import get_map_style_url
|
||||
|
||||
def esc(value):
|
||||
|
||||
@@ -408,7 +409,7 @@ const map = new maplibregl.Map({
|
||||
container: "map",
|
||||
|
||||
style:
|
||||
"http://127.0.0.1:8080/styles/server-map/style.json",
|
||||
__MAP_STYLE_URL__,
|
||||
|
||||
center: [
|
||||
30.32,
|
||||
@@ -1181,6 +1182,11 @@ window.setTimeout(
|
||||
marker_js,
|
||||
)
|
||||
|
||||
map_html = map_html.replace(
|
||||
"__MAP_STYLE_URL__",
|
||||
json.dumps(get_map_style_url()),
|
||||
)
|
||||
|
||||
return map_html
|
||||
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from reports.template import (
|
||||
page_end,
|
||||
)
|
||||
from reports.map_popups import build_standard_popup
|
||||
from reports.map_service import get_map_style_url
|
||||
|
||||
def esc(value):
|
||||
return html.escape("" if value is None else str(value), quote=True)
|
||||
@@ -932,7 +933,7 @@ def render_map(geojson, context, title):
|
||||
|
||||
const map = new maplibregl.Map({{
|
||||
container: "access-point-history-map",
|
||||
style: "http://127.0.0.1:8080/styles/server-map/style.json",
|
||||
style: {json.dumps(get_map_style_url())},
|
||||
center: [30.32, 59.93],
|
||||
zoom: 5
|
||||
}});
|
||||
@@ -1106,7 +1107,6 @@ def render_map(geojson, context, title):
|
||||
</script>
|
||||
"""
|
||||
|
||||
|
||||
def render_observation_table(observations):
|
||||
rows = []
|
||||
|
||||
@@ -1413,7 +1413,7 @@ def render_wifi_connection_card(ap, credentials):
|
||||
}});
|
||||
|
||||
interfaceSelect.disabled =
|
||||
busy || devices.length <= 1;
|
||||
busy || devices.filter(device => device.available).length <= 1;
|
||||
}}
|
||||
|
||||
async function loadInterfaces() {{
|
||||
@@ -1437,6 +1437,10 @@ def render_wifi_connection_card(ap, credentials):
|
||||
|
||||
devices = data.devices || [];
|
||||
|
||||
const availableDevices = devices.filter(
|
||||
device => device.available
|
||||
);
|
||||
|
||||
interfaceSelect.replaceChildren();
|
||||
|
||||
const placeholder = document.createElement(
|
||||
@@ -1469,12 +1473,12 @@ def render_wifi_connection_card(ap, credentials):
|
||||
interfaceSelect.appendChild(option);
|
||||
}});
|
||||
|
||||
if (
|
||||
if (availableDevices.length === 1) {{
|
||||
interfaceSelect.value = availableDevices[0].device;
|
||||
}} else if (
|
||||
data.selected_device
|
||||
&& devices.some(
|
||||
device =>
|
||||
device.device === data.selected_device
|
||||
&& device.available
|
||||
&& availableDevices.some(
|
||||
device => device.device === data.selected_device
|
||||
)
|
||||
) {{
|
||||
interfaceSelect.value = data.selected_device;
|
||||
@@ -1485,15 +1489,17 @@ def render_wifi_connection_card(ap, credentials):
|
||||
data.error || "Wi-Fi интерфейсы не найдены.",
|
||||
true
|
||||
);
|
||||
}} else if (
|
||||
devices.length === 1
|
||||
&& !devices[0].available
|
||||
) {{
|
||||
}} else if (!availableDevices.length) {{
|
||||
const reasons = devices
|
||||
.map(device => device.reason)
|
||||
.filter(Boolean);
|
||||
|
||||
setMessage(
|
||||
devices[0].reason || "Wi-Fi интерфейс недоступен.",
|
||||
reasons.join(" ")
|
||||
|| "Нет доступных Wi-Fi интерфейсов.",
|
||||
true
|
||||
);
|
||||
}} else if (devices.length > 1) {{
|
||||
}} else if (availableDevices.length > 1) {{
|
||||
setMessage(
|
||||
"Выберите интерфейс, через который выполнять операцию."
|
||||
);
|
||||
@@ -1657,7 +1663,6 @@ def render_wifi_connection_card(ap, credentials):
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def render_access_point_page(
|
||||
conn,
|
||||
bssid,
|
||||
|
||||
@@ -253,4 +253,3 @@ def main():
|
||||
if __name__ == "__main__":
|
||||
|
||||
main()
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""
|
||||
Centralized map service configuration.
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from src.tileserver_config import load_tileserver_config
|
||||
|
||||
|
||||
MAP_STYLE_URL = load_tileserver_config(PROJECT_ROOT)["style_url"]
|
||||
|
||||
|
||||
def get_map_style_url():
|
||||
return MAP_STYLE_URL
|
||||
+2
-5
@@ -15,10 +15,7 @@ from reports.utils import (
|
||||
format_datetime as format_report_datetime,
|
||||
)
|
||||
from reports.map_popups import build_standard_popup
|
||||
|
||||
MAP_STYLE_URL = (
|
||||
"http://127.0.0.1:8080/styles/server-map/style.json"
|
||||
)
|
||||
from reports.map_service import get_map_style_url
|
||||
|
||||
|
||||
# ============================================================
|
||||
@@ -2020,7 +2017,7 @@ def render_search_page(
|
||||
)
|
||||
).replace(
|
||||
"{map_style}",
|
||||
MAP_STYLE_URL
|
||||
json.dumps(get_map_style_url())
|
||||
)
|
||||
|
||||
html += page_end()
|
||||
|
||||
@@ -39,6 +39,7 @@ from reports.template import (
|
||||
ReportContext,
|
||||
)
|
||||
from reports.map_popups import build_standard_popup
|
||||
from reports.map_service import get_map_style_url
|
||||
|
||||
# ============================================================
|
||||
# Helpers
|
||||
@@ -865,7 +866,7 @@ const map = new maplibregl.Map({
|
||||
|
||||
style:
|
||||
|
||||
"http://127.0.0.1:8080/styles/server-map/style.json",
|
||||
__MAP_STYLE_URL__,
|
||||
|
||||
center: [
|
||||
|
||||
@@ -2672,6 +2673,11 @@ Session folder:
|
||||
|
||||
html += page_end()
|
||||
|
||||
html = html.replace(
|
||||
"__MAP_STYLE_URL__",
|
||||
json.dumps(get_map_style_url()),
|
||||
)
|
||||
|
||||
return html
|
||||
|
||||
|
||||
|
||||
@@ -1698,3 +1698,32 @@ body .maplibregl-popup-close-button:hover {
|
||||
.hashcat-preflight .stats-grid {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.wifi-connection-action {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.wifi-connection-action label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.wifi-connection-password {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.wifi-connection-button {
|
||||
padding: 8px 14px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: var(--green);
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
@@ -291,6 +291,9 @@ def encryption_statistics(conn):
|
||||
|
||||
FROM access_points
|
||||
|
||||
WHERE encryption IS NOT NULL
|
||||
AND TRIM(encryption) != ''
|
||||
|
||||
GROUP BY encryption
|
||||
|
||||
ORDER BY total DESC
|
||||
|
||||
@@ -302,6 +302,12 @@ def navigation(
|
||||
"/reports/access-points/",
|
||||
),
|
||||
|
||||
(
|
||||
"wifi_connections",
|
||||
"Wi-Fi Connections",
|
||||
"/reports/wifi-connections/",
|
||||
),
|
||||
|
||||
(
|
||||
"vendors",
|
||||
"Vendors",
|
||||
|
||||
+160
-201
@@ -517,13 +517,6 @@ def update_block(
|
||||
|
||||
oui = preview["oui"]
|
||||
build = preview["build"]
|
||||
ap = preview["ap"]
|
||||
|
||||
ap_total = (
|
||||
ap["unknown_to_vendor"]
|
||||
+ ap["vendor_to_vendor"]
|
||||
+ ap["vendor_to_unknown"]
|
||||
)
|
||||
|
||||
if oui["identical"]:
|
||||
|
||||
@@ -531,20 +524,6 @@ def update_block(
|
||||
<p>
|
||||
База OUI не изменилась. Обновление не требуется.
|
||||
</p>
|
||||
"""
|
||||
|
||||
elif ap_total == 0:
|
||||
|
||||
status_html = """
|
||||
<p>
|
||||
База OUI содержит изменения, но существующие записи
|
||||
AP не требуют изменения vendor.
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Обновление базы OUI можно применить отдельно.
|
||||
Оно обновит справочник для будущих определений vendor.
|
||||
</p>
|
||||
"""
|
||||
|
||||
else:
|
||||
@@ -552,8 +531,7 @@ AP не требуют изменения vendor.
|
||||
status_html = """
|
||||
<p>
|
||||
База OUI содержит изменения.
|
||||
Сначала проверьте изменения в справочнике, затем при
|
||||
необходимости выберите синхронизацию vendor у существующих AP.
|
||||
Проверьте результаты перед применением обновления.
|
||||
</p>
|
||||
"""
|
||||
|
||||
@@ -619,11 +597,7 @@ AP не требуют изменения vendor.
|
||||
|
||||
"""
|
||||
|
||||
if oui["identical"]:
|
||||
|
||||
pass
|
||||
|
||||
else:
|
||||
if not oui["identical"]:
|
||||
|
||||
html += f"""
|
||||
<form
|
||||
@@ -638,148 +612,6 @@ AP не требуют изменения vendor.
|
||||
value="{escape(token)}"
|
||||
>
|
||||
|
||||
"""
|
||||
|
||||
if ap_total > 0:
|
||||
|
||||
html += """
|
||||
<div class="vendor-sync">
|
||||
|
||||
<hr>
|
||||
|
||||
<h2>
|
||||
Синхронизация существующих AP
|
||||
</h2>
|
||||
|
||||
<p>
|
||||
Следующие параметры не изменяют саму базу OUI.
|
||||
Они определяют, какие изменения vendor применить
|
||||
к уже существующим записям WiFi AP.
|
||||
</p>
|
||||
|
||||
<table>
|
||||
|
||||
<tr>
|
||||
<th>Изменение vendor</th>
|
||||
<th>Количество</th>
|
||||
<th>Применить</th>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<strong>Unknown → Vendor</strong>
|
||||
|
||||
<details>
|
||||
<summary>Что это означает?</summary>
|
||||
<p>
|
||||
Заполнить поле vendor у существующих AP, для которых
|
||||
vendor сейчас неизвестен. Новое значение определяется
|
||||
по обновлённой базе OUI.
|
||||
</p>
|
||||
</details>
|
||||
|
||||
</td>
|
||||
<td>""" + str(ap["unknown_to_vendor"]) + """</td>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="unknown_to_vendor"
|
||||
value="1"
|
||||
checked
|
||||
onchange="updateVendorApplyCount()"
|
||||
>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<strong>Vendor → другой Vendor</strong>
|
||||
|
||||
<details>
|
||||
<summary>Что это означает?</summary>
|
||||
<p>
|
||||
Заменить текущее значение vendor, если обновлённая
|
||||
база OUI определяет тот же AP как принадлежащий
|
||||
другому vendor.
|
||||
</p>
|
||||
</details>
|
||||
|
||||
</td>
|
||||
<td>""" + str(ap["vendor_to_vendor"]) + """</td>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="vendor_to_vendor"
|
||||
value="1"
|
||||
onchange="updateVendorApplyCount()"
|
||||
>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td>
|
||||
<strong>Vendor → Unknown</strong>
|
||||
|
||||
<details>
|
||||
<summary>Что это означает?</summary>
|
||||
<p>
|
||||
Удалить текущее значение vendor, если обновлённая
|
||||
база OUI больше не позволяет определить vendor
|
||||
для данного AP.
|
||||
</p>
|
||||
</details>
|
||||
|
||||
</td>
|
||||
<td>""" + str(ap["vendor_to_unknown"]) + """</td>
|
||||
<td>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="vendor_to_unknown"
|
||||
value="1"
|
||||
onchange="updateVendorApplyCount()"
|
||||
>
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
</table>
|
||||
|
||||
<p>
|
||||
Выбрано изменений AP:
|
||||
<strong id="vendor-apply-count">""" + str(
|
||||
ap["unknown_to_vendor"]
|
||||
) + """</strong>
|
||||
</p>
|
||||
|
||||
<p>
|
||||
Синхронизация AP необязательна. Снятые категории
|
||||
не будут изменять существующие записи AP.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
"""
|
||||
|
||||
else:
|
||||
|
||||
html += """
|
||||
<div class="vendor-sync vendor-sync-empty">
|
||||
|
||||
<hr>
|
||||
|
||||
<h2>
|
||||
Синхронизация существующих AP
|
||||
</h2>
|
||||
|
||||
<p>
|
||||
Существующие записи AP не требуют изменения vendor.
|
||||
Для этого обновления синхронизация AP недоступна.
|
||||
</p>
|
||||
|
||||
</div>
|
||||
|
||||
"""
|
||||
|
||||
html += """
|
||||
<div class="vendor-actions">
|
||||
|
||||
<button type="submit" class="button">
|
||||
@@ -792,51 +624,173 @@ vendor сейчас неизвестен. Новое значение опред
|
||||
|
||||
"""
|
||||
|
||||
if ap_total > 0:
|
||||
return html
|
||||
|
||||
def recalculate_block(job=None):
|
||||
|
||||
html = """
|
||||
<div class="card">
|
||||
|
||||
<h2>
|
||||
Перерасчёт производителей точек доступа
|
||||
</h2>
|
||||
|
||||
<p>
|
||||
Операция проверяет все записи AP по установленной базе OUI.
|
||||
Она заполняет неизвестные значения, обновляет устаревшие
|
||||
названия производителей и очищает значения, которые больше
|
||||
не определяются.
|
||||
</p>
|
||||
"""
|
||||
|
||||
if job is None:
|
||||
|
||||
html += """
|
||||
<form
|
||||
method="POST"
|
||||
action="/reports/vendors/recalculate"
|
||||
onsubmit="return confirm('Запустить полный перерасчёт производителей всех точек доступа?');"
|
||||
>
|
||||
|
||||
<button type="submit" class="button">
|
||||
Пересчитать производителей AP
|
||||
</button>
|
||||
|
||||
</form>
|
||||
"""
|
||||
|
||||
elif job["status"] == "ready":
|
||||
|
||||
result = job["result"]
|
||||
|
||||
labels = (
|
||||
("total", "Всего точек доступа"),
|
||||
("checked", "Проверено"),
|
||||
("updated", "Изменено"),
|
||||
("filled", "Заполнено"),
|
||||
("refreshed", "Обновлено"),
|
||||
("cleared", "Очищено"),
|
||||
("unknown", "Неизвестный производитель"),
|
||||
("unchanged", "Без изменений")
|
||||
)
|
||||
|
||||
html += """
|
||||
<p>
|
||||
Перерасчёт завершён.
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Показатель</th>
|
||||
<th>Количество</th>
|
||||
</tr>
|
||||
"""
|
||||
|
||||
for key, label in labels:
|
||||
|
||||
html += f"""
|
||||
<tr>
|
||||
<td>{label}</td>
|
||||
<td>{result[key]}</td>
|
||||
</tr>
|
||||
"""
|
||||
|
||||
html += """
|
||||
</table>
|
||||
"""
|
||||
|
||||
elif job["status"] == "error":
|
||||
|
||||
html += f"""
|
||||
<p>
|
||||
Ошибка перерасчёта:
|
||||
</p>
|
||||
|
||||
<p>
|
||||
<strong>{escape(job["error"] or "Неизвестная ошибка")}</strong>
|
||||
</p>
|
||||
|
||||
<form
|
||||
method="POST"
|
||||
action="/reports/vendors/recalculate"
|
||||
>
|
||||
|
||||
<button type="submit" class="button">
|
||||
Повторить перерасчёт
|
||||
</button>
|
||||
|
||||
</form>
|
||||
"""
|
||||
|
||||
else:
|
||||
|
||||
html += f"""
|
||||
<p id="vendor-recalc-status">
|
||||
{escape(job["message"] or "Перерасчёт выполняется")}
|
||||
</p>
|
||||
|
||||
<script>
|
||||
function updateVendorApplyCount() {{
|
||||
(function() {{
|
||||
|
||||
let total = 0;
|
||||
const jobId = {job["id"]!r};
|
||||
|
||||
const fields = [
|
||||
[
|
||||
"unknown_to_vendor",
|
||||
{ap["unknown_to_vendor"]}
|
||||
],
|
||||
[
|
||||
"vendor_to_vendor",
|
||||
{ap["vendor_to_vendor"]}
|
||||
],
|
||||
[
|
||||
"vendor_to_unknown",
|
||||
{ap["vendor_to_unknown"]}
|
||||
]
|
||||
];
|
||||
|
||||
for (const field of fields) {{
|
||||
|
||||
const checkbox = document.querySelector(
|
||||
'input[name="' + field[0] + '"]'
|
||||
const statusElement = document.getElementById(
|
||||
"vendor-recalc-status"
|
||||
);
|
||||
|
||||
if (checkbox && checkbox.checked) {{
|
||||
total += field[1];
|
||||
}}
|
||||
async function checkStatus() {{
|
||||
|
||||
try {{
|
||||
|
||||
const response = await fetch(
|
||||
"/reports/vendors/recalculate/status/" + jobId
|
||||
);
|
||||
|
||||
if (!response.ok) {{
|
||||
|
||||
statusElement.textContent =
|
||||
"Не удалось получить статус задачи (HTTP " +
|
||||
response.status +
|
||||
")";
|
||||
|
||||
return;
|
||||
}}
|
||||
|
||||
document.getElementById(
|
||||
"vendor-apply-count"
|
||||
).textContent = total;
|
||||
}}
|
||||
const data = await response.json();
|
||||
|
||||
if (data.message) {{
|
||||
statusElement.textContent = data.message;
|
||||
}}
|
||||
|
||||
if (data.status === "ready" || data.status === "error") {{
|
||||
|
||||
window.location.href =
|
||||
"/reports/vendors/?recalc_job_id=" + jobId;
|
||||
|
||||
return;
|
||||
}}
|
||||
|
||||
}} catch (error) {{
|
||||
|
||||
statusElement.textContent = error.message;
|
||||
|
||||
}}
|
||||
|
||||
window.setTimeout(checkStatus, 1000);
|
||||
}}
|
||||
|
||||
window.setTimeout(checkStatus, 1000);
|
||||
|
||||
}})();
|
||||
</script>
|
||||
"""
|
||||
|
||||
html += """
|
||||
</div>
|
||||
"""
|
||||
|
||||
return html
|
||||
|
||||
|
||||
def render_vendors_page(
|
||||
conn,
|
||||
service,
|
||||
@@ -844,7 +798,8 @@ def render_vendors_page(
|
||||
token=None,
|
||||
message=None,
|
||||
context=None,
|
||||
job=None
|
||||
job=None,
|
||||
recalc_job=None
|
||||
):
|
||||
status = service.status()
|
||||
|
||||
@@ -896,6 +851,10 @@ def render_vendors_page(
|
||||
job
|
||||
)
|
||||
|
||||
html += recalculate_block(
|
||||
recalc_job
|
||||
)
|
||||
|
||||
html += page_end()
|
||||
|
||||
return html
|
||||
@@ -0,0 +1,937 @@
|
||||
|
||||
import html
|
||||
import json
|
||||
|
||||
from reports.access_points import (
|
||||
format_popup_datetime,
|
||||
load_access_points,
|
||||
)
|
||||
from reports.map_popups import build_standard_popup
|
||||
from reports.map_service import get_map_style_url
|
||||
from reports.template import (
|
||||
ReportContext,
|
||||
card,
|
||||
page_begin,
|
||||
page_end,
|
||||
)
|
||||
|
||||
|
||||
def verified_passwords(row):
|
||||
passwords = []
|
||||
seen = set()
|
||||
|
||||
for credential in row["passwords"]:
|
||||
password = credential.get("password")
|
||||
|
||||
if (
|
||||
not credential.get("verified")
|
||||
or not isinstance(password, str)
|
||||
or not password
|
||||
or password in seen
|
||||
):
|
||||
continue
|
||||
|
||||
seen.add(password)
|
||||
passwords.append(password)
|
||||
|
||||
return passwords
|
||||
|
||||
|
||||
def classify_access_points(observations):
|
||||
verified_wpa = []
|
||||
open_aps = []
|
||||
|
||||
for row in observations:
|
||||
latitude = row.get("latitude")
|
||||
longitude = row.get("longitude")
|
||||
|
||||
if latitude is None or longitude is None:
|
||||
continue
|
||||
|
||||
encryption = str(
|
||||
row.get("encryption") or ""
|
||||
).strip().upper()
|
||||
|
||||
if encryption == "OPEN":
|
||||
open_aps.append(row)
|
||||
elif verified_passwords(row):
|
||||
verified_wpa.append(row)
|
||||
|
||||
return verified_wpa, open_aps
|
||||
|
||||
|
||||
def build_connection_popup(row, is_open):
|
||||
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["rssi"],
|
||||
passwords=row["passwords"],
|
||||
handshakes=row["handshakes"],
|
||||
observed_at=format_popup_datetime(
|
||||
row["observed_at"]
|
||||
),
|
||||
latitude=row["latitude"],
|
||||
longitude=row["longitude"],
|
||||
access_point_url=(
|
||||
f"/reports/access-points/{row['bssid']}"
|
||||
),
|
||||
)
|
||||
|
||||
if is_open:
|
||||
connect_control = """
|
||||
<div class="wifi-connection-action">
|
||||
<button
|
||||
type="button"
|
||||
class="wifi-connection-button"
|
||||
data-wifi-connect
|
||||
data-bssid="{}"
|
||||
data-open="true"
|
||||
>
|
||||
Подключиться
|
||||
</button>
|
||||
</div>
|
||||
""".format(
|
||||
html.escape(str(row["bssid"]), quote=True)
|
||||
)
|
||||
|
||||
else:
|
||||
passwords = verified_passwords(row)
|
||||
|
||||
options = "".join(
|
||||
'<option value="{}">{}</option>'.format(
|
||||
html.escape(password, quote=True),
|
||||
html.escape(password),
|
||||
)
|
||||
for password in passwords
|
||||
)
|
||||
|
||||
connect_control = """
|
||||
<div class="wifi-connection-action">
|
||||
<label>
|
||||
Проверенный пароль:
|
||||
<select
|
||||
class="wifi-connection-password"
|
||||
data-wifi-password
|
||||
>
|
||||
{}
|
||||
</select>
|
||||
</label>
|
||||
<button
|
||||
type="button"
|
||||
class="wifi-connection-button"
|
||||
data-wifi-connect
|
||||
data-bssid="{}"
|
||||
data-open="false"
|
||||
>
|
||||
Подключиться
|
||||
</button>
|
||||
</div>
|
||||
""".format(
|
||||
options,
|
||||
html.escape(str(row["bssid"]), quote=True),
|
||||
)
|
||||
|
||||
return popup + connect_control
|
||||
|
||||
|
||||
def build_wifi_connections_marker_js(observations):
|
||||
verified_wpa, open_aps = classify_access_points(
|
||||
observations
|
||||
)
|
||||
|
||||
def make_features(rows, is_open):
|
||||
features = []
|
||||
|
||||
for row in rows:
|
||||
popup = build_connection_popup(
|
||||
row,
|
||||
is_open,
|
||||
)
|
||||
|
||||
features.append({
|
||||
"type": "Feature",
|
||||
"geometry": {
|
||||
"type": "Point",
|
||||
"coordinates": [
|
||||
float(row["longitude"]),
|
||||
float(row["latitude"]),
|
||||
],
|
||||
},
|
||||
"properties": {
|
||||
"popup": popup,
|
||||
},
|
||||
})
|
||||
|
||||
return features
|
||||
|
||||
return (
|
||||
"const verifiedWpaFeatures = "
|
||||
+ json.dumps(
|
||||
make_features(verified_wpa, False),
|
||||
ensure_ascii=False,
|
||||
)
|
||||
+ ";\n"
|
||||
+ "const openFeatures = "
|
||||
+ json.dumps(
|
||||
make_features(open_aps, True),
|
||||
ensure_ascii=False,
|
||||
)
|
||||
+ ";\n"
|
||||
)
|
||||
|
||||
|
||||
def render_wifi_connections_map(observations, context):
|
||||
marker_js = build_wifi_connections_marker_js(
|
||||
observations
|
||||
)
|
||||
|
||||
maplibre_css_url = context.asset_url(
|
||||
"maplibre/maplibre-gl.css"
|
||||
)
|
||||
|
||||
maplibre_js_url = context.asset_url(
|
||||
"maplibre/maplibre-gl.js"
|
||||
)
|
||||
|
||||
map_html = """
|
||||
<div id="map"></div>
|
||||
|
||||
<link
|
||||
rel="stylesheet"
|
||||
href="__MAPLIBRE_CSS_URL__"
|
||||
>
|
||||
|
||||
<script src="__MAPLIBRE_JS_URL__"></script>
|
||||
|
||||
<script>
|
||||
|
||||
__MARKER_JS__
|
||||
|
||||
const map = new maplibregl.Map({
|
||||
|
||||
container: "map",
|
||||
|
||||
style:
|
||||
__MAP_STYLE_URL__,
|
||||
|
||||
center: [
|
||||
30.32,
|
||||
59.93
|
||||
],
|
||||
|
||||
zoom: 5,
|
||||
|
||||
attributionControl: true
|
||||
|
||||
});
|
||||
|
||||
map.addControl(
|
||||
new maplibregl.NavigationControl(),
|
||||
"top-right"
|
||||
);
|
||||
|
||||
map.addControl(
|
||||
new maplibregl.ScaleControl({
|
||||
maxWidth: 120,
|
||||
unit: "metric"
|
||||
})
|
||||
);
|
||||
|
||||
map.on(
|
||||
"load",
|
||||
function()
|
||||
{
|
||||
|
||||
map.addSource(
|
||||
"verified-wpa",
|
||||
{
|
||||
type: "geojson",
|
||||
data: {
|
||||
type: "FeatureCollection",
|
||||
features: verifiedWpaFeatures
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
map.addSource(
|
||||
"open-aps",
|
||||
{
|
||||
type: "geojson",
|
||||
data: {
|
||||
type: "FeatureCollection",
|
||||
features: openFeatures
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
map.addLayer({
|
||||
|
||||
id: "verified-wpa-points",
|
||||
|
||||
type: "circle",
|
||||
|
||||
source: "verified-wpa",
|
||||
|
||||
paint: {
|
||||
|
||||
"circle-radius": 8,
|
||||
|
||||
"circle-color": "#43A047",
|
||||
|
||||
"circle-stroke-color": "#ffffff",
|
||||
|
||||
"circle-stroke-width": 1.5
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
map.addLayer({
|
||||
|
||||
id: "open-ap-points",
|
||||
|
||||
type: "circle",
|
||||
|
||||
source: "open-aps",
|
||||
|
||||
paint: {
|
||||
|
||||
"circle-radius": 8,
|
||||
|
||||
"circle-color": "#AB47BC",
|
||||
|
||||
"circle-stroke-color": "#ffffff",
|
||||
|
||||
"circle-stroke-width": 1.5
|
||||
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
const popupLayers = [
|
||||
"verified-wpa-points",
|
||||
"open-ap-points"
|
||||
];
|
||||
|
||||
popupLayers.forEach(
|
||||
function(layerId)
|
||||
{
|
||||
|
||||
map.on(
|
||||
"click",
|
||||
layerId,
|
||||
function(e)
|
||||
{
|
||||
|
||||
if(
|
||||
!e.features
|
||||
||
|
||||
!e.features.length
|
||||
)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
const feature = e.features[0];
|
||||
|
||||
if(
|
||||
!feature
|
||||
||
|
||||
!feature.properties
|
||||
)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
new maplibregl.Popup()
|
||||
.setLngLat(
|
||||
feature.geometry.coordinates
|
||||
)
|
||||
.setHTML(
|
||||
feature.properties.popup
|
||||
|| "<b>Access Point</b>"
|
||||
)
|
||||
.addTo(map);
|
||||
updateWifiConnectButtons();
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
map.on(
|
||||
"mouseenter",
|
||||
layerId,
|
||||
function()
|
||||
{
|
||||
map.getCanvas().style.cursor =
|
||||
"pointer";
|
||||
}
|
||||
);
|
||||
|
||||
map.on(
|
||||
"mouseleave",
|
||||
layerId,
|
||||
function()
|
||||
{
|
||||
map.getCanvas().style.cursor =
|
||||
"";
|
||||
}
|
||||
);
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
document.querySelectorAll(
|
||||
".session-map-controls input[data-layer]"
|
||||
).forEach(
|
||||
function(input)
|
||||
{
|
||||
|
||||
input.addEventListener(
|
||||
"change",
|
||||
function()
|
||||
{
|
||||
|
||||
const layerId =
|
||||
input.dataset.layer === "verified"
|
||||
? "verified-wpa-points"
|
||||
: "open-ap-points";
|
||||
|
||||
map.setLayoutProperty(
|
||||
layerId,
|
||||
"visibility",
|
||||
input.checked
|
||||
? "visible"
|
||||
: "none"
|
||||
);
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
let wifiConnectionBusy = false;
|
||||
|
||||
const wifiInterfaceSelect = document.getElementById(
|
||||
"wifi-connections-interface"
|
||||
);
|
||||
|
||||
const wifiConnectionMessage = document.getElementById(
|
||||
"wifi-connections-message"
|
||||
);
|
||||
|
||||
const wifiConnectionWarning = document.getElementById(
|
||||
"wifi-connections-warning"
|
||||
);
|
||||
|
||||
function setWifiConnectionMessage(text, isError = false) {
|
||||
if (!wifiConnectionMessage) {
|
||||
return;
|
||||
}
|
||||
|
||||
wifiConnectionMessage.textContent = text || "";
|
||||
wifiConnectionMessage.style.color = isError
|
||||
? "var(--red)"
|
||||
: "var(--muted)";
|
||||
}
|
||||
|
||||
function updateWifiConnectButtons() {
|
||||
const interfaceReady = Boolean(
|
||||
wifiInterfaceSelect
|
||||
&& wifiInterfaceSelect.value
|
||||
);
|
||||
|
||||
document.querySelectorAll(
|
||||
"[data-wifi-connect]"
|
||||
).forEach(function(button) {
|
||||
button.disabled =
|
||||
wifiConnectionBusy || !interfaceReady;
|
||||
});
|
||||
}
|
||||
|
||||
if (wifiInterfaceSelect) {
|
||||
wifiInterfaceSelect.addEventListener(
|
||||
"change",
|
||||
updateWifiConnectButtons
|
||||
);
|
||||
}
|
||||
|
||||
updateWifiConnectButtons();
|
||||
|
||||
document.addEventListener(
|
||||
"wifi-interfaces-loaded",
|
||||
updateWifiConnectButtons
|
||||
);
|
||||
|
||||
document.addEventListener(
|
||||
"click",
|
||||
async function(event) {
|
||||
const target = event.target;
|
||||
|
||||
if (!(target instanceof Element)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const button = target.closest(
|
||||
"[data-wifi-connect]"
|
||||
);
|
||||
|
||||
if (!button || wifiConnectionBusy) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const interfaceName = wifiInterfaceSelect
|
||||
? wifiInterfaceSelect.value
|
||||
: "";
|
||||
|
||||
if (!interfaceName) {
|
||||
setWifiConnectionMessage(
|
||||
"Выберите доступный Wi-Fi интерфейс.",
|
||||
true
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const bssid = button.dataset.bssid;
|
||||
const isOpen = button.dataset.open === "true";
|
||||
|
||||
if (!bssid) {
|
||||
setWifiConnectionMessage(
|
||||
"Не указан BSSID точки доступа.",
|
||||
true
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
let password = null;
|
||||
|
||||
if (!isOpen) {
|
||||
const action = button.closest(
|
||||
".wifi-connection-action"
|
||||
);
|
||||
|
||||
const passwordSelect = action
|
||||
? action.querySelector("[data-wifi-password]")
|
||||
: null;
|
||||
|
||||
password = passwordSelect
|
||||
? passwordSelect.value
|
||||
: "";
|
||||
|
||||
if (!password) {
|
||||
setWifiConnectionMessage(
|
||||
"Выберите проверенный пароль.",
|
||||
true
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
wifiConnectionBusy = true;
|
||||
updateWifiConnectButtons();
|
||||
|
||||
setWifiConnectionMessage(
|
||||
"Выполняется подключение к " + bssid + "..."
|
||||
);
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
interface: interfaceName,
|
||||
bssid: bssid
|
||||
};
|
||||
|
||||
if (!isOpen) {
|
||||
payload.password = password;
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
"/api/network/connect",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json"
|
||||
},
|
||||
body: JSON.stringify(payload)
|
||||
}
|
||||
);
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (
|
||||
!response.ok
|
||||
|| !data.ok
|
||||
|| data.success === false
|
||||
) {
|
||||
throw new Error(
|
||||
data.error || "Не удалось подключиться."
|
||||
);
|
||||
}
|
||||
|
||||
setWifiConnectionMessage(
|
||||
"Подключение успешно: "
|
||||
+ (data.ssid || bssid)
|
||||
);
|
||||
|
||||
if (
|
||||
data.wireguard_warning
|
||||
&& wifiConnectionWarning
|
||||
) {
|
||||
wifiConnectionWarning.textContent =
|
||||
data.wireguard_warning;
|
||||
wifiConnectionWarning.hidden = false;
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
setWifiConnectionMessage(
|
||||
error.message
|
||||
|| "Ошибка подключения к точке доступа.",
|
||||
true
|
||||
);
|
||||
|
||||
} finally {
|
||||
wifiConnectionBusy = false;
|
||||
updateWifiConnectButtons();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const allFeatures =
|
||||
verifiedWpaFeatures.concat(openFeatures);
|
||||
|
||||
if(allFeatures.length === 1)
|
||||
{
|
||||
|
||||
map.jumpTo({
|
||||
|
||||
center:
|
||||
allFeatures[0].geometry.coordinates,
|
||||
|
||||
zoom: 15
|
||||
|
||||
});
|
||||
|
||||
}
|
||||
else if(allFeatures.length > 1)
|
||||
{
|
||||
|
||||
const bounds =
|
||||
new maplibregl.LngLatBounds();
|
||||
|
||||
allFeatures.forEach(
|
||||
function(feature)
|
||||
{
|
||||
bounds.extend(
|
||||
feature.geometry.coordinates
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
map.fitBounds(
|
||||
bounds,
|
||||
{
|
||||
padding: 50,
|
||||
maxZoom: 15
|
||||
}
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
);
|
||||
|
||||
window.setTimeout(
|
||||
function()
|
||||
{
|
||||
map.resize();
|
||||
},
|
||||
100
|
||||
);
|
||||
|
||||
</script>
|
||||
"""
|
||||
|
||||
map_html = map_html.replace(
|
||||
"__MAPLIBRE_CSS_URL__",
|
||||
maplibre_css_url,
|
||||
)
|
||||
|
||||
map_html = map_html.replace(
|
||||
"__MAPLIBRE_JS_URL__",
|
||||
maplibre_js_url,
|
||||
)
|
||||
|
||||
map_html = map_html.replace(
|
||||
"__MARKER_JS__",
|
||||
marker_js,
|
||||
)
|
||||
|
||||
map_html = map_html.replace(
|
||||
"__MAP_STYLE_URL__",
|
||||
json.dumps(get_map_style_url()),
|
||||
)
|
||||
|
||||
return map_html
|
||||
|
||||
|
||||
def render_wifi_connections_page(conn, context=None):
|
||||
if context is None:
|
||||
context = ReportContext(
|
||||
mode="server"
|
||||
)
|
||||
|
||||
observations = load_access_points(conn)
|
||||
|
||||
verified_wpa, open_aps = classify_access_points(
|
||||
observations
|
||||
)
|
||||
|
||||
html = page_begin(
|
||||
"Wi-Fi Connections",
|
||||
active="wifi_connections",
|
||||
context=context,
|
||||
section_title="Reports",
|
||||
)
|
||||
|
||||
html += card(
|
||||
"Подключение к Wi-Fi",
|
||||
"""
|
||||
<div id="wifi-connections-controls">
|
||||
<div style="margin-bottom:14px;">
|
||||
<label for="wifi-connections-interface">
|
||||
<strong>Wi-Fi интерфейс:</strong>
|
||||
</label>
|
||||
|
||||
<select
|
||||
id="wifi-connections-interface"
|
||||
class="search"
|
||||
style="display:block;width:100%;max-width:400px;"
|
||||
disabled
|
||||
>
|
||||
<option value="">Загрузка интерфейсов...</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div
|
||||
id="wifi-connections-warning"
|
||||
role="status"
|
||||
hidden
|
||||
style="
|
||||
margin:12px 0;
|
||||
padding:12px;
|
||||
border:1px solid var(--yellow);
|
||||
border-radius:8px;
|
||||
line-height:1.5;
|
||||
"
|
||||
></div>
|
||||
|
||||
<div
|
||||
id="wifi-connections-message"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
style="margin:12px 0;"
|
||||
></div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
(function() {
|
||||
const root = document.getElementById(
|
||||
"wifi-connections-controls"
|
||||
);
|
||||
|
||||
if (!root) {
|
||||
return;
|
||||
}
|
||||
|
||||
const interfaceSelect = document.getElementById(
|
||||
"wifi-connections-interface"
|
||||
);
|
||||
|
||||
const message = document.getElementById(
|
||||
"wifi-connections-message"
|
||||
);
|
||||
|
||||
const warning = document.getElementById(
|
||||
"wifi-connections-warning"
|
||||
);
|
||||
|
||||
function setMessage(text, isError = false) {
|
||||
message.textContent = text || "";
|
||||
message.style.color = isError
|
||||
? "var(--red)"
|
||||
: "var(--muted)";
|
||||
}
|
||||
|
||||
function setWarning(text) {
|
||||
warning.textContent = text || "";
|
||||
warning.hidden = !text;
|
||||
}
|
||||
|
||||
async function loadInterfaces() {
|
||||
try {
|
||||
const response = await fetch(
|
||||
"/api/network/wifi-devices",
|
||||
{cache: "no-store"}
|
||||
);
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (!response.ok || !data.ok) {
|
||||
throw new Error(
|
||||
data.error
|
||||
|| "Не удалось получить Wi-Fi интерфейсы."
|
||||
);
|
||||
}
|
||||
|
||||
const devices = data.devices || [];
|
||||
|
||||
interfaceSelect.replaceChildren();
|
||||
|
||||
const placeholder = document.createElement("option");
|
||||
placeholder.value = "";
|
||||
placeholder.textContent = devices.length > 1
|
||||
? "Выберите Wi-Fi интерфейс"
|
||||
: "Нет доступных интерфейсов";
|
||||
|
||||
interfaceSelect.appendChild(placeholder);
|
||||
|
||||
devices.forEach(device => {
|
||||
const option = document.createElement("option");
|
||||
|
||||
option.value = device.device;
|
||||
option.textContent = device.available
|
||||
? device.device + " (" + device.state + ")"
|
||||
: device.device + " — " + (
|
||||
device.reason || device.state
|
||||
);
|
||||
|
||||
option.disabled = !device.available;
|
||||
interfaceSelect.appendChild(option);
|
||||
});
|
||||
|
||||
const availableDevices = devices.filter(
|
||||
device => device.available
|
||||
);
|
||||
|
||||
if (availableDevices.length === 1) {
|
||||
interfaceSelect.value =
|
||||
availableDevices[0].device;
|
||||
} else if (
|
||||
data.selected_device
|
||||
&& availableDevices.some(device =>
|
||||
device.device === data.selected_device
|
||||
)
|
||||
) {
|
||||
interfaceSelect.value = data.selected_device;
|
||||
}
|
||||
|
||||
interfaceSelect.disabled =
|
||||
availableDevices.length <= 1;
|
||||
|
||||
if (!devices.length) {
|
||||
setMessage(
|
||||
data.error || "Wi-Fi интерфейсы не найдены.",
|
||||
true
|
||||
);
|
||||
} else if (
|
||||
!devices.some(device => device.available)
|
||||
) {
|
||||
setMessage(
|
||||
devices.map(device =>
|
||||
device.device + ": " + (
|
||||
device.reason || device.state
|
||||
)
|
||||
).join("; "),
|
||||
true
|
||||
);
|
||||
} else if (availableDevices.length > 1) {
|
||||
setMessage(
|
||||
"Выберите доступный Wi-Fi интерфейс."
|
||||
);
|
||||
}
|
||||
|
||||
if (data.wireguard_active) {
|
||||
setWarning(
|
||||
"Обнаружено активное соединение WireGuard. "
|
||||
+ "При необходимости отключите VPN вручную. "
|
||||
+ "Приложение не изменяет состояние WireGuard."
|
||||
);
|
||||
} else if (data.wireguard_error) {
|
||||
setWarning(
|
||||
"Не удалось проверить состояние WireGuard: "
|
||||
+ data.wireguard_error
|
||||
);
|
||||
}
|
||||
document.dispatchEvent(
|
||||
new Event("wifi-interfaces-loaded")
|
||||
);
|
||||
|
||||
} catch (error) {
|
||||
interfaceSelect.disabled = true;
|
||||
setMessage(
|
||||
error.message
|
||||
|| "Ошибка получения Wi-Fi интерфейсов.",
|
||||
true
|
||||
);
|
||||
document.dispatchEvent(
|
||||
new Event("wifi-interfaces-loaded")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
loadInterfaces();
|
||||
})();
|
||||
</script>
|
||||
"""
|
||||
)
|
||||
|
||||
html += card(
|
||||
"""
|
||||
<span class="session-map-title">
|
||||
<span class="session-map-title-text">
|
||||
🗺 Wi-Fi Connections
|
||||
</span>
|
||||
|
||||
<span class="session-map-controls">
|
||||
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
data-layer="verified"
|
||||
checked
|
||||
>
|
||||
<span class="map-layer-dot map-layer-dot-handshake"></span>
|
||||
Verified WPA ({})
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<input
|
||||
type="checkbox"
|
||||
data-layer="open"
|
||||
checked
|
||||
>
|
||||
<span class="map-layer-dot map-layer-dot-open"></span>
|
||||
OPEN ({})
|
||||
</label>
|
||||
|
||||
</span>
|
||||
</span>
|
||||
""".format(
|
||||
len(verified_wpa),
|
||||
len(open_aps),
|
||||
),
|
||||
render_wifi_connections_map(
|
||||
observations,
|
||||
context,
|
||||
),
|
||||
)
|
||||
|
||||
html += page_end()
|
||||
|
||||
return html
|
||||
+12
-5
@@ -434,6 +434,7 @@ class Database:
|
||||
|
||||
if (
|
||||
"handshake_id" in column_names
|
||||
and "verified" in column_names
|
||||
and has_provenance_unique
|
||||
):
|
||||
return
|
||||
@@ -486,10 +487,16 @@ class Database:
|
||||
)
|
||||
""")
|
||||
|
||||
verified_expression = (
|
||||
"verified"
|
||||
if "verified" in column_names
|
||||
else "0"
|
||||
)
|
||||
|
||||
if "handshake_id" in column_names:
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
f"""
|
||||
INSERT INTO credentials
|
||||
(
|
||||
id,
|
||||
@@ -507,7 +514,7 @@ class Database:
|
||||
password,
|
||||
source,
|
||||
created_at,
|
||||
verified
|
||||
{verified_expression}
|
||||
FROM credentials_old
|
||||
"""
|
||||
)
|
||||
@@ -515,7 +522,7 @@ class Database:
|
||||
else:
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
f"""
|
||||
INSERT INTO credentials
|
||||
(
|
||||
id,
|
||||
@@ -531,7 +538,7 @@ class Database:
|
||||
password,
|
||||
source,
|
||||
created_at,
|
||||
verified
|
||||
{verified_expression}
|
||||
FROM credentials_old
|
||||
"""
|
||||
)
|
||||
@@ -879,7 +886,7 @@ class Database:
|
||||
"""
|
||||
UPDATE capture_sessions
|
||||
|
||||
SET end_time=?
|
||||
SET end_time=COALESCE(end_time, ?)
|
||||
|
||||
WHERE id=?
|
||||
""",
|
||||
|
||||
+57
-87
@@ -4,8 +4,6 @@ import logging
|
||||
import sqlite3
|
||||
import csv
|
||||
|
||||
from vendor_import import VendorImporter
|
||||
|
||||
class EnvironmentChecker:
|
||||
"""
|
||||
Проверка окружения проекта.
|
||||
@@ -63,14 +61,16 @@ class EnvironmentChecker:
|
||||
self.check_hcxdumptool_version()
|
||||
|
||||
|
||||
self.check_vendor_database()
|
||||
|
||||
vendor_database_ok = self.check_vendor_database()
|
||||
|
||||
if vendor_database_ok:
|
||||
self.log.info(
|
||||
"Environment OK"
|
||||
)
|
||||
|
||||
|
||||
else:
|
||||
self.log.warning(
|
||||
"Environment checks completed; vendor lookup unavailable"
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# Проверка бинарника
|
||||
@@ -174,30 +174,31 @@ class EnvironmentChecker:
|
||||
|
||||
database = self.config.vendor_database
|
||||
|
||||
rebuild = False
|
||||
|
||||
if not database.exists():
|
||||
|
||||
self.log.warning(
|
||||
"Vendor database not found"
|
||||
"Vendor database not found: %s",
|
||||
database
|
||||
)
|
||||
|
||||
rebuild = True
|
||||
return False
|
||||
|
||||
elif database.stat().st_size == 0:
|
||||
if database.stat().st_size == 0:
|
||||
|
||||
self.log.warning(
|
||||
"Vendor database is empty"
|
||||
"Vendor database is empty: %s",
|
||||
database
|
||||
)
|
||||
|
||||
rebuild = True
|
||||
return False
|
||||
|
||||
else:
|
||||
connection = None
|
||||
|
||||
try:
|
||||
|
||||
connection = sqlite3.connect(
|
||||
database
|
||||
f"{database.resolve().as_uri()}?mode=ro",
|
||||
uri=True
|
||||
)
|
||||
|
||||
cursor = connection.cursor()
|
||||
@@ -211,13 +212,11 @@ class EnvironmentChecker:
|
||||
if cursor.fetchone() is None:
|
||||
|
||||
raise RuntimeError(
|
||||
"vendors table not found"
|
||||
"oui table not found"
|
||||
)
|
||||
|
||||
cursor.execute(
|
||||
|
||||
"SELECT COUNT(*) FROM oui"
|
||||
|
||||
)
|
||||
|
||||
records = cursor.fetchone()[0]
|
||||
@@ -225,90 +224,61 @@ class EnvironmentChecker:
|
||||
if records < 50000:
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
f"Only {records} records"
|
||||
|
||||
)
|
||||
|
||||
cursor.execute(
|
||||
"SELECT name FROM sqlite_master "
|
||||
"WHERE type='table' "
|
||||
"AND name='metadata'"
|
||||
)
|
||||
|
||||
if cursor.fetchone() is None:
|
||||
|
||||
raise RuntimeError(
|
||||
"metadata table not found"
|
||||
)
|
||||
|
||||
cursor.execute(
|
||||
"SELECT value "
|
||||
"FROM metadata "
|
||||
"WHERE key='import_status'"
|
||||
|
||||
)
|
||||
|
||||
row = cursor.fetchone()
|
||||
|
||||
if (
|
||||
|
||||
row is None
|
||||
|
||||
or
|
||||
|
||||
row[0] != "ok"
|
||||
|
||||
):
|
||||
if row is None or row[0] != "ok":
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
"Invalid import_status"
|
||||
|
||||
)
|
||||
|
||||
self.log.info(
|
||||
"Vendor database: OK (%s records)",
|
||||
records
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
except sqlite3.Error as error:
|
||||
|
||||
self.log.warning(
|
||||
"Vendor database is invalid: %s",
|
||||
error
|
||||
)
|
||||
|
||||
return False
|
||||
|
||||
except RuntimeError as error:
|
||||
|
||||
self.log.warning(
|
||||
"Vendor database is invalid: %s",
|
||||
error
|
||||
)
|
||||
|
||||
return False
|
||||
|
||||
finally:
|
||||
|
||||
if connection is not None:
|
||||
connection.close()
|
||||
|
||||
self.log.info(
|
||||
|
||||
f"Vendor database: OK ({records} records)"
|
||||
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
except KeyboardInterrupt:
|
||||
|
||||
self.log.warning(
|
||||
"Download cancelled by user"
|
||||
)
|
||||
|
||||
raise
|
||||
|
||||
except Exception as error:
|
||||
|
||||
self.log.warning(
|
||||
|
||||
f"Vendor database is invalid: {error}"
|
||||
|
||||
)
|
||||
|
||||
rebuild = True
|
||||
|
||||
if rebuild:
|
||||
|
||||
database.unlink(
|
||||
missing_ok=True
|
||||
)
|
||||
|
||||
self.log.info(
|
||||
"Creating vendor database..."
|
||||
)
|
||||
|
||||
importer = VendorImporter(
|
||||
self.config
|
||||
)
|
||||
|
||||
importer.bootstrap()
|
||||
|
||||
if not database.exists():
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
"Unable to create vendor database."
|
||||
|
||||
)
|
||||
|
||||
self.log.info(
|
||||
"Vendor database created"
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,992 @@
|
||||
import argparse
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
from tileserver_config import load_tileserver_config
|
||||
from runtime_paths import get_node_path, get_runtime_env
|
||||
|
||||
TILESERVER_CONFIG_DATA = load_tileserver_config(PROJECT_ROOT)
|
||||
|
||||
UNIT_NAME = "wifi-gps-mapper"
|
||||
APP_HOST = "127.0.0.1"
|
||||
APP_PORT = 5000
|
||||
|
||||
TILE_HOST = TILESERVER_CONFIG_DATA["host"]
|
||||
TILE_PORT = TILESERVER_CONFIG_DATA["port"]
|
||||
TILE_STYLE_URL = TILESERVER_CONFIG_DATA["style_url"]
|
||||
|
||||
TILESERVER_DIR = TILESERVER_CONFIG_DATA["directory"]
|
||||
TILESERVER_ENTRY = TILESERVER_CONFIG_DATA["entry"]
|
||||
TILESERVER_CONFIG = TILESERVER_CONFIG_DATA["config"]
|
||||
TILESERVER_CONFIG_PATH = TILESERVER_CONFIG_DATA["config_path"]
|
||||
|
||||
STARTUP_TIMEOUT = 30
|
||||
POLL_INTERVAL = 0.5
|
||||
AUTH_SOCKET_PATH = Path(
|
||||
os.environ.get(
|
||||
"XDG_RUNTIME_DIR",
|
||||
f"/run/user/{os.getuid()}"
|
||||
)
|
||||
) / "wifi-gps-mapper-auth.sock"
|
||||
|
||||
|
||||
class LifecycleError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def log(message):
|
||||
print(
|
||||
f"[WiFi GPS Mapper] {message}",
|
||||
flush=True
|
||||
)
|
||||
|
||||
|
||||
def project_python():
|
||||
return PROJECT_ROOT / "venv" / "bin" / "python"
|
||||
|
||||
|
||||
def style_is_available(timeout=2):
|
||||
try:
|
||||
request = urllib.request.Request(
|
||||
TILE_STYLE_URL,
|
||||
headers={"Accept": "application/json"}
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(
|
||||
request,
|
||||
timeout=timeout
|
||||
) as response:
|
||||
if response.status != 200:
|
||||
return False
|
||||
|
||||
content_type = response.headers.get(
|
||||
"Content-Type",
|
||||
""
|
||||
)
|
||||
|
||||
payload = json.loads(
|
||||
response.read().decode("utf-8")
|
||||
)
|
||||
|
||||
return (
|
||||
isinstance(payload, dict)
|
||||
and "version" in payload
|
||||
and (
|
||||
"sources" in payload
|
||||
or "layers" in payload
|
||||
)
|
||||
)
|
||||
|
||||
except (
|
||||
OSError,
|
||||
ValueError,
|
||||
urllib.error.URLError
|
||||
):
|
||||
return False
|
||||
|
||||
|
||||
def port_is_open(host, port):
|
||||
with socket.socket(
|
||||
socket.AF_INET,
|
||||
socket.SOCK_STREAM
|
||||
) as connection:
|
||||
connection.settimeout(0.5)
|
||||
|
||||
return connection.connect_ex(
|
||||
(host, port)
|
||||
) == 0
|
||||
|
||||
|
||||
def start_tileserver():
|
||||
if style_is_available():
|
||||
log(
|
||||
"TileServer уже работает. "
|
||||
"Используется внешний экземпляр."
|
||||
)
|
||||
return None
|
||||
|
||||
if port_is_open(TILE_HOST, TILE_PORT):
|
||||
raise LifecycleError(
|
||||
f"Порт {TILE_PORT} занят, но ожидаемый "
|
||||
f"стиль {TILESERVER_CONFIG_DATA['style']} недоступен. "
|
||||
"Чужой процесс не будет остановлен."
|
||||
)
|
||||
|
||||
try:
|
||||
node = str(get_node_path())
|
||||
except FileNotFoundError as error:
|
||||
raise LifecycleError(
|
||||
"Локальный Node.js не найден."
|
||||
) from error
|
||||
|
||||
if not TILESERVER_ENTRY.is_file():
|
||||
raise LifecycleError(
|
||||
f"Не найден TileServer entry point: "
|
||||
f"{TILESERVER_ENTRY}"
|
||||
)
|
||||
|
||||
config_path = TILESERVER_CONFIG_PATH
|
||||
|
||||
if not config_path.is_file():
|
||||
raise LifecycleError(
|
||||
f"Не найден TileServer config: {config_path}"
|
||||
)
|
||||
|
||||
command = [
|
||||
node,
|
||||
str(TILESERVER_ENTRY),
|
||||
"--config",
|
||||
TILESERVER_CONFIG,
|
||||
"--bind",
|
||||
TILE_HOST,
|
||||
"--port",
|
||||
str(TILE_PORT)
|
||||
]
|
||||
|
||||
log("Запускается TileServer...")
|
||||
|
||||
process = subprocess.Popen(
|
||||
command,
|
||||
cwd=TILESERVER_DIR,
|
||||
stdin=subprocess.DEVNULL,
|
||||
env=get_runtime_env()
|
||||
)
|
||||
|
||||
deadline = time.monotonic() + STARTUP_TIMEOUT
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
if process.poll() is not None:
|
||||
raise LifecycleError(
|
||||
"TileServer завершился во время запуска "
|
||||
f"(код {process.returncode})."
|
||||
)
|
||||
|
||||
if style_is_available():
|
||||
log(
|
||||
f"TileServer запущен, PID {process.pid}."
|
||||
)
|
||||
return process
|
||||
|
||||
time.sleep(POLL_INTERVAL)
|
||||
|
||||
process.terminate()
|
||||
|
||||
try:
|
||||
process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
raise LifecycleError(
|
||||
"TileServer не стал доступен за "
|
||||
f"{STARTUP_TIMEOUT} секунд."
|
||||
)
|
||||
|
||||
|
||||
def stop_owned_tileserver(process):
|
||||
if process is None or process.poll() is not None:
|
||||
return
|
||||
|
||||
log("Останавливается принадлежащий менеджеру TileServer.")
|
||||
|
||||
process.terminate()
|
||||
|
||||
try:
|
||||
process.wait(timeout=10)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
|
||||
def wait_for_scanner(app_module):
|
||||
notified = False
|
||||
|
||||
while True:
|
||||
with app_module.scanner_lock:
|
||||
starting = app_module.scanner_starting
|
||||
network_active = app_module.network_action_active
|
||||
process = app_module.scanner_process
|
||||
reader = app_module.scanner_output_thread
|
||||
|
||||
running = (
|
||||
process is not None
|
||||
and process.poll() is None
|
||||
)
|
||||
|
||||
if not starting and not network_active and not running:
|
||||
break
|
||||
|
||||
if not notified:
|
||||
log(
|
||||
"Ожидание завершения сканера или сетевой операции. "
|
||||
"Если сканер работает, останови его кнопкой "
|
||||
"Stop в веб-интерфейсе."
|
||||
)
|
||||
notified = True
|
||||
|
||||
time.sleep(POLL_INTERVAL)
|
||||
|
||||
if process is not None:
|
||||
process.wait()
|
||||
|
||||
if reader is not None and reader is not threading.current_thread():
|
||||
reader.join()
|
||||
|
||||
log("Сканер и поток чтения его вывода завершены.")
|
||||
|
||||
|
||||
def stop_gps_test(app_module):
|
||||
with app_module.gps_test_lock:
|
||||
service = app_module.gps_test_service
|
||||
|
||||
if service is None:
|
||||
return
|
||||
|
||||
thread = service.thread
|
||||
|
||||
if thread is None or not thread.is_alive():
|
||||
return
|
||||
|
||||
log("Останавливается GPS-тест.")
|
||||
|
||||
service.stop()
|
||||
|
||||
if thread is not threading.current_thread():
|
||||
thread.join()
|
||||
|
||||
log("GPS-тест завершён.")
|
||||
|
||||
|
||||
def join_background_threads(app_module):
|
||||
for name in (
|
||||
"vendor_update_thread",
|
||||
"vendor_recalc_thread"
|
||||
):
|
||||
thread = getattr(app_module, name, None)
|
||||
|
||||
if thread is None or thread is threading.current_thread():
|
||||
continue
|
||||
|
||||
if thread.is_alive():
|
||||
log(f"Ожидание фоновой задачи: {name}.")
|
||||
thread.join()
|
||||
|
||||
log("Фоновые задачи завершены.")
|
||||
|
||||
|
||||
def receive_sudo_authentication(shutdown_event):
|
||||
runtime_dir = AUTH_SOCKET_PATH.parent
|
||||
|
||||
if not runtime_dir.is_dir():
|
||||
raise LifecycleError(
|
||||
f"Не найден runtime-каталог: {runtime_dir}"
|
||||
)
|
||||
|
||||
if AUTH_SOCKET_PATH.exists() or AUTH_SOCKET_PATH.is_symlink():
|
||||
try:
|
||||
socket_info = AUTH_SOCKET_PATH.lstat()
|
||||
except OSError as error:
|
||||
raise LifecycleError(
|
||||
f"Не удалось проверить Unix-сокет: {error}"
|
||||
) from error
|
||||
|
||||
if (
|
||||
not stat.S_ISSOCK(socket_info.st_mode)
|
||||
or socket_info.st_uid != os.getuid()
|
||||
):
|
||||
raise LifecycleError(
|
||||
f"Путь занят посторонним объектом: {AUTH_SOCKET_PATH}"
|
||||
)
|
||||
|
||||
AUTH_SOCKET_PATH.unlink()
|
||||
|
||||
auth_socket = socket.socket(
|
||||
socket.AF_UNIX,
|
||||
socket.SOCK_STREAM
|
||||
)
|
||||
|
||||
try:
|
||||
auth_socket.bind(str(AUTH_SOCKET_PATH))
|
||||
AUTH_SOCKET_PATH.chmod(0o600)
|
||||
auth_socket.listen(1)
|
||||
auth_deadline = time.monotonic() + STARTUP_TIMEOUT + 60
|
||||
auth_socket.settimeout(POLL_INTERVAL)
|
||||
|
||||
log("Ожидание sudo-аутентификации от CLI...")
|
||||
|
||||
while True:
|
||||
if shutdown_event.is_set():
|
||||
raise LifecycleError(
|
||||
"Ожидание sudo-аутентификации прервано остановкой."
|
||||
)
|
||||
|
||||
if time.monotonic() >= auth_deadline:
|
||||
raise LifecycleError(
|
||||
"Не получен пароль sudo за отведённое время."
|
||||
)
|
||||
|
||||
try:
|
||||
connection, _ = auth_socket.accept()
|
||||
break
|
||||
except socket.timeout:
|
||||
continue
|
||||
|
||||
with connection:
|
||||
connection.settimeout(10)
|
||||
password = bytearray()
|
||||
|
||||
while True:
|
||||
chunk = connection.recv(1024)
|
||||
|
||||
if not chunk:
|
||||
break
|
||||
|
||||
password.extend(chunk)
|
||||
|
||||
if len(password) > 4096:
|
||||
raise LifecycleError(
|
||||
"Получен недопустимо длинный пароль."
|
||||
)
|
||||
|
||||
if not password:
|
||||
connection.sendall(b"AUTH_FAILED")
|
||||
raise LifecycleError(
|
||||
"Получен пустой пароль sudo."
|
||||
)
|
||||
|
||||
result = subprocess.run(
|
||||
["sudo", "-S", "-p", "", "-v"],
|
||||
input=bytes(password) + b"\n",
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False
|
||||
)
|
||||
|
||||
for index in range(len(password)):
|
||||
password[index] = 0
|
||||
|
||||
if result.returncode != 0:
|
||||
connection.sendall(b"AUTH_FAILED")
|
||||
raise LifecycleError(
|
||||
"sudo-аутентификация не пройдена."
|
||||
)
|
||||
|
||||
connection.sendall(b"AUTH_OK")
|
||||
|
||||
log("sudo-аутентификация успешно пройдена.")
|
||||
|
||||
except socket.timeout as error:
|
||||
raise LifecycleError(
|
||||
"Не получен пароль sudo за отведённое время."
|
||||
) from error
|
||||
|
||||
finally:
|
||||
auth_socket.close()
|
||||
|
||||
try:
|
||||
socket_info = AUTH_SOCKET_PATH.lstat()
|
||||
|
||||
if (
|
||||
stat.S_ISSOCK(socket_info.st_mode)
|
||||
and socket_info.st_uid == os.getuid()
|
||||
):
|
||||
AUTH_SOCKET_PATH.unlink()
|
||||
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
|
||||
def send_sudo_authentication():
|
||||
deadline = time.monotonic() + STARTUP_TIMEOUT
|
||||
connection = None
|
||||
|
||||
while connection is None:
|
||||
if not unit_is_active():
|
||||
raise LifecycleError(
|
||||
"Менеджер завершился до подключения CLI. "
|
||||
"Проверь журнал: "
|
||||
f"journalctl --user -u {UNIT_NAME}.service"
|
||||
)
|
||||
|
||||
if time.monotonic() >= deadline:
|
||||
raise LifecycleError(
|
||||
"Не удалось подключиться к сокету "
|
||||
"sudo-аутентификации."
|
||||
)
|
||||
|
||||
candidate = socket.socket(
|
||||
socket.AF_UNIX,
|
||||
socket.SOCK_STREAM
|
||||
)
|
||||
|
||||
try:
|
||||
candidate.settimeout(POLL_INTERVAL)
|
||||
candidate.connect(str(AUTH_SOCKET_PATH))
|
||||
connection = candidate
|
||||
except OSError:
|
||||
candidate.close()
|
||||
time.sleep(POLL_INTERVAL)
|
||||
|
||||
password = ""
|
||||
|
||||
try:
|
||||
password = getpass.getpass("Введите пароль sudo: ")
|
||||
connection.settimeout(10)
|
||||
connection.sendall(password.encode("utf-8") + b"\n")
|
||||
password = ""
|
||||
connection.shutdown(socket.SHUT_WR)
|
||||
|
||||
response = connection.recv(32)
|
||||
|
||||
finally:
|
||||
password = ""
|
||||
connection.close()
|
||||
|
||||
if response != b"AUTH_OK":
|
||||
raise LifecycleError(
|
||||
"Менеджер отклонил sudo-аутентификацию."
|
||||
)
|
||||
|
||||
|
||||
def run_server():
|
||||
os.chdir(PROJECT_ROOT)
|
||||
|
||||
if str(PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(PROJECT_ROOT))
|
||||
|
||||
src_path = str(PROJECT_ROOT / "src")
|
||||
|
||||
if src_path not in sys.path:
|
||||
sys.path.insert(0, src_path)
|
||||
|
||||
tileserver_process = None
|
||||
server = None
|
||||
server_thread = None
|
||||
app_module = None
|
||||
|
||||
shutdown_event = threading.Event()
|
||||
shutdown_started = False
|
||||
|
||||
def request_shutdown(signum, frame):
|
||||
nonlocal shutdown_started
|
||||
|
||||
if shutdown_started:
|
||||
return
|
||||
|
||||
shutdown_started = True
|
||||
log("Получен сигнал завершения.")
|
||||
|
||||
if app_module is not None:
|
||||
app_module.request_lifecycle.begin_shutdown()
|
||||
|
||||
shutdown_event.set()
|
||||
|
||||
signal.signal(signal.SIGTERM, request_shutdown)
|
||||
signal.signal(signal.SIGINT, request_shutdown)
|
||||
|
||||
try:
|
||||
receive_sudo_authentication(shutdown_event)
|
||||
tileserver_process = start_tileserver()
|
||||
|
||||
from gui import app as app_module
|
||||
|
||||
if not app_module.check_sudo():
|
||||
raise LifecycleError(
|
||||
"sudo-аутентификация менеджера недоступна."
|
||||
)
|
||||
|
||||
app_module.sudo_keepalive_stop_event.clear()
|
||||
|
||||
app_module.sudo_keepalive_thread = threading.Thread(
|
||||
target=app_module.sudo_keepalive,
|
||||
args=(app_module.sudo_keepalive_stop_event,),
|
||||
name="sudo-keepalive",
|
||||
daemon=True
|
||||
)
|
||||
|
||||
app_module.sudo_keepalive_thread.start()
|
||||
|
||||
from werkzeug.serving import make_server
|
||||
|
||||
server = make_server(
|
||||
APP_HOST,
|
||||
APP_PORT,
|
||||
app_module.app,
|
||||
threaded=True
|
||||
)
|
||||
|
||||
server_thread = threading.Thread(
|
||||
target=server.serve_forever,
|
||||
name="flask-server",
|
||||
daemon=False
|
||||
)
|
||||
|
||||
server_thread.start()
|
||||
|
||||
log(
|
||||
f"Веб-интерфейс запущен: "
|
||||
f"http://{APP_HOST}:{APP_PORT}"
|
||||
)
|
||||
|
||||
shutdown_event.wait()
|
||||
|
||||
except Exception:
|
||||
if app_module is not None:
|
||||
app_module.request_lifecycle.begin_shutdown()
|
||||
|
||||
raise
|
||||
|
||||
finally:
|
||||
if app_module is not None:
|
||||
app_module.request_lifecycle.begin_shutdown()
|
||||
|
||||
log("Ожидание завершения активных HTTP-запросов.")
|
||||
app_module.request_lifecycle.wait_for_drain()
|
||||
|
||||
stop_gps_test(app_module)
|
||||
wait_for_scanner(app_module)
|
||||
join_background_threads(app_module)
|
||||
|
||||
app_module.sudo_keepalive_stop_event.set()
|
||||
|
||||
keepalive = app_module.sudo_keepalive_thread
|
||||
|
||||
if (
|
||||
keepalive is not None
|
||||
and keepalive is not threading.current_thread()
|
||||
):
|
||||
keepalive.join()
|
||||
|
||||
if server is not None:
|
||||
log("Остановка Flask-сервера.")
|
||||
server.shutdown()
|
||||
|
||||
if server_thread is not None:
|
||||
server_thread.join()
|
||||
|
||||
stop_owned_tileserver(tileserver_process)
|
||||
|
||||
log("Менеджер завершил работу.")
|
||||
|
||||
|
||||
def run_sudo_validation():
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["sudo", "-v"],
|
||||
check=False
|
||||
)
|
||||
except OSError as error:
|
||||
raise LifecycleError(
|
||||
f"Не удалось запустить sudo: {error}"
|
||||
) from error
|
||||
|
||||
if result.returncode != 0:
|
||||
raise LifecycleError(
|
||||
"Проверка sudo не пройдена."
|
||||
)
|
||||
|
||||
|
||||
def systemctl_user(*arguments, check=True):
|
||||
command = [
|
||||
"systemctl",
|
||||
"--user",
|
||||
*arguments
|
||||
]
|
||||
|
||||
return subprocess.run(
|
||||
command,
|
||||
check=check,
|
||||
text=True,
|
||||
capture_output=True
|
||||
)
|
||||
|
||||
def active_service_project():
|
||||
result = systemctl_user(
|
||||
"show",
|
||||
f"{UNIT_NAME}.service",
|
||||
"--property=WorkingDirectory",
|
||||
"--value",
|
||||
check=False
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
|
||||
working_directory = result.stdout.strip()
|
||||
|
||||
if not working_directory:
|
||||
return None
|
||||
|
||||
try:
|
||||
return Path(working_directory).resolve()
|
||||
except (OSError, RuntimeError):
|
||||
return None
|
||||
|
||||
|
||||
def unit_is_active():
|
||||
result = systemctl_user(
|
||||
"is-active",
|
||||
"--quiet",
|
||||
f"{UNIT_NAME}.service",
|
||||
check=False
|
||||
)
|
||||
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def start_service():
|
||||
if unit_is_active():
|
||||
active_project = active_service_project()
|
||||
|
||||
if active_project is None:
|
||||
raise LifecycleError(
|
||||
"Сервис уже активен, но не удалось определить "
|
||||
"каталог проекта. Второй экземпляр не будет запущен."
|
||||
)
|
||||
|
||||
if active_project == PROJECT_ROOT:
|
||||
log("Менеджер уже запущен из текущего проекта.")
|
||||
else:
|
||||
log(
|
||||
"Менеджер уже запущен из другого проекта: "
|
||||
f"{active_project}. Второй экземпляр не запущен."
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
if port_is_open(APP_HOST, APP_PORT):
|
||||
raise LifecycleError(
|
||||
f"Порт приложения {APP_PORT} занят. "
|
||||
"Чужой процесс не будет остановлен."
|
||||
)
|
||||
|
||||
python = project_python()
|
||||
|
||||
if not python.is_file():
|
||||
raise LifecycleError(
|
||||
f"Не найден Python виртуального окружения: {python}"
|
||||
)
|
||||
|
||||
command = [
|
||||
"systemd-run",
|
||||
"--user",
|
||||
f"--unit={UNIT_NAME}",
|
||||
"--service-type=exec",
|
||||
"--property=KillMode=process",
|
||||
"--collect",
|
||||
f"--working-directory={PROJECT_ROOT}",
|
||||
str(python),
|
||||
str(PROJECT_ROOT / "src" / "lifecycle_manager.py"),
|
||||
"--serve"
|
||||
]
|
||||
|
||||
subprocess.run(
|
||||
command,
|
||||
check=True
|
||||
)
|
||||
|
||||
send_sudo_authentication()
|
||||
|
||||
deadline = time.monotonic() + STARTUP_TIMEOUT
|
||||
|
||||
while time.monotonic() < deadline:
|
||||
if not unit_is_active():
|
||||
raise LifecycleError(
|
||||
"Сервис завершился во время запуска. "
|
||||
"Проверь журнал: "
|
||||
f"journalctl --user -u {UNIT_NAME}.service"
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
f"http://{APP_HOST}:{APP_PORT}/api/status",
|
||||
timeout=1
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
log(
|
||||
f"Приложение запущено: "
|
||||
f"http://{APP_HOST}:{APP_PORT}"
|
||||
)
|
||||
return 0
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
time.sleep(POLL_INTERVAL)
|
||||
|
||||
raise LifecycleError(
|
||||
"Приложение не ответило за время запуска. "
|
||||
f"Проверь journalctl --user -u {UNIT_NAME}.service"
|
||||
)
|
||||
|
||||
|
||||
def stop_service():
|
||||
if not unit_is_active():
|
||||
log("Менеджер не запущен.")
|
||||
return 0
|
||||
|
||||
active_project = active_service_project()
|
||||
|
||||
if active_project is None:
|
||||
raise LifecycleError(
|
||||
"Не удалось определить проект работающего сервиса. "
|
||||
"Остановка отменена."
|
||||
)
|
||||
|
||||
if active_project != PROJECT_ROOT:
|
||||
raise LifecycleError(
|
||||
f"Сервис запущен из другого проекта: {active_project}. "
|
||||
f"Остановка из {PROJECT_ROOT} отменена."
|
||||
)
|
||||
|
||||
run_sudo_validation()
|
||||
|
||||
systemctl_user(
|
||||
"kill",
|
||||
"--kill-whom=main",
|
||||
"--signal=SIGTERM",
|
||||
f"{UNIT_NAME}.service"
|
||||
)
|
||||
|
||||
log(
|
||||
"Запрошено штатное завершение. "
|
||||
"Если сканер активен, останови его в веб-интерфейсе."
|
||||
)
|
||||
|
||||
notified = False
|
||||
|
||||
while unit_is_active():
|
||||
if not notified:
|
||||
log(
|
||||
"Ожидание завершения приложения и фоновых задач..."
|
||||
)
|
||||
notified = True
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
log("Сервис остановлен.")
|
||||
return 0
|
||||
|
||||
|
||||
def show_status():
|
||||
active = unit_is_active()
|
||||
|
||||
print(
|
||||
"Application:",
|
||||
"RUNNING" if active else "STOPPED"
|
||||
)
|
||||
|
||||
if active:
|
||||
active_project = active_service_project()
|
||||
print(
|
||||
"Active project:",
|
||||
active_project if active_project is not None else "UNKNOWN"
|
||||
)
|
||||
|
||||
if active:
|
||||
try:
|
||||
with urllib.request.urlopen(
|
||||
f"http://{APP_HOST}:{APP_PORT}/api/status",
|
||||
timeout=2
|
||||
) as response:
|
||||
data = json.loads(
|
||||
response.read().decode("utf-8")
|
||||
)
|
||||
|
||||
scanner = data.get("status", {})
|
||||
gps = data.get("gps_test", {})
|
||||
|
||||
scanner_running = scanner.get("running", False)
|
||||
scanner_health = scanner.get("health", "unknown")
|
||||
scanner_pid = scanner.get("pid")
|
||||
|
||||
if scanner_running:
|
||||
scanner_state = (
|
||||
f"RUNNING (PID {scanner_pid}, "
|
||||
f"health: {scanner_health})"
|
||||
)
|
||||
else:
|
||||
scanner_state = (
|
||||
f"STOPPED (health: {scanner_health})"
|
||||
)
|
||||
|
||||
print("Scanner:", scanner_state)
|
||||
print(
|
||||
"GPS test:",
|
||||
gps.get("state", "unknown")
|
||||
)
|
||||
print(
|
||||
"Network action:",
|
||||
"BUSY" if data.get("network_actions_busy") else "IDLE"
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
print(f"Application API: unavailable ({error})")
|
||||
|
||||
print(
|
||||
"TileServer:",
|
||||
"AVAILABLE" if style_is_available() else "UNAVAILABLE"
|
||||
)
|
||||
|
||||
if active:
|
||||
result = systemctl_user(
|
||||
"show",
|
||||
f"{UNIT_NAME}.service",
|
||||
"--property=MainPID",
|
||||
"--property=ActiveState",
|
||||
check=False
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
print(result.stdout.strip())
|
||||
|
||||
|
||||
def install():
|
||||
python = project_python()
|
||||
|
||||
if not python.is_file():
|
||||
raise LifecycleError(
|
||||
f"Не найдено виртуальное окружение: {python}"
|
||||
)
|
||||
|
||||
if shutil.which("systemd-run") is None:
|
||||
raise LifecycleError("Не найден systemd-run.")
|
||||
|
||||
if shutil.which("systemctl") is None:
|
||||
raise LifecycleError("Не найден systemctl.")
|
||||
|
||||
if shutil.which("sudo") is None:
|
||||
raise LifecycleError("Не найден sudo.")
|
||||
|
||||
try:
|
||||
get_node_path()
|
||||
except FileNotFoundError as error:
|
||||
raise LifecycleError(
|
||||
"Локальный Node.js не найден."
|
||||
) from error
|
||||
|
||||
if not TILESERVER_ENTRY.is_file():
|
||||
raise LifecycleError(
|
||||
f"Не найден TileServer entry point: {TILESERVER_ENTRY}"
|
||||
)
|
||||
|
||||
if not TILESERVER_CONFIG_PATH.is_file():
|
||||
raise LifecycleError(
|
||||
"Не найден TileServer config: "
|
||||
f"{TILESERVER_CONFIG_PATH}"
|
||||
)
|
||||
|
||||
check = subprocess.run(
|
||||
[
|
||||
str(python),
|
||||
"-c",
|
||||
"import flask, werkzeug"
|
||||
],
|
||||
check=False
|
||||
)
|
||||
|
||||
if check.returncode != 0:
|
||||
raise LifecycleError(
|
||||
"Flask или Werkzeug недоступны в venv."
|
||||
)
|
||||
|
||||
cli_path = PROJECT_ROOT / "wifi-gps-mapper"
|
||||
|
||||
if not cli_path.is_file():
|
||||
raise LifecycleError(
|
||||
f"Не найден CLI-файл: {cli_path}"
|
||||
)
|
||||
|
||||
cli_path.chmod(
|
||||
cli_path.stat().st_mode | 0o111
|
||||
)
|
||||
|
||||
systemctl_user("show-environment")
|
||||
|
||||
log("Проверка окружения пройдена.")
|
||||
log(f"CLI: {cli_path}")
|
||||
log("TileServer не устанавливался и не изменялся.")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
prog="wifi-gps-mapper"
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--serve",
|
||||
action="store_true",
|
||||
help=argparse.SUPPRESS
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"command",
|
||||
nargs="?",
|
||||
choices=(
|
||||
"install",
|
||||
"start",
|
||||
"status",
|
||||
"stop",
|
||||
"restart"
|
||||
)
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
if args.serve:
|
||||
run_server()
|
||||
return 0
|
||||
|
||||
if args.command == "install":
|
||||
install()
|
||||
return 0
|
||||
|
||||
if args.command == "start":
|
||||
return start_service()
|
||||
|
||||
if args.command == "status":
|
||||
show_status()
|
||||
return 0
|
||||
|
||||
if args.command == "stop":
|
||||
return stop_service()
|
||||
|
||||
if args.command == "restart":
|
||||
stop_service()
|
||||
return start_service()
|
||||
|
||||
parser.print_help()
|
||||
return 2
|
||||
|
||||
except (
|
||||
LifecycleError,
|
||||
subprocess.CalledProcessError,
|
||||
OSError
|
||||
) as error:
|
||||
print(
|
||||
f"Ошибка: {error}",
|
||||
file=sys.stderr
|
||||
)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,229 +0,0 @@
|
||||
import csv
|
||||
import logging
|
||||
|
||||
|
||||
class OUIImporter:
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
resolver,
|
||||
files
|
||||
):
|
||||
|
||||
self.logger = logging.getLogger(
|
||||
"oui-import"
|
||||
)
|
||||
|
||||
self.resolver = resolver
|
||||
|
||||
self.files = files
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Импорт IEEE
|
||||
# =====================================================
|
||||
|
||||
def import_database(self):
|
||||
|
||||
|
||||
count = 0
|
||||
|
||||
skipped = 0
|
||||
|
||||
|
||||
stats = {
|
||||
|
||||
"MA-L": 0,
|
||||
|
||||
"MA-M": 0,
|
||||
|
||||
"MA-S": 0
|
||||
|
||||
}
|
||||
|
||||
|
||||
for filename in self.files:
|
||||
|
||||
|
||||
if not filename.exists():
|
||||
|
||||
self.logger.warning(
|
||||
f"{filename.name} not found"
|
||||
)
|
||||
|
||||
continue
|
||||
|
||||
|
||||
self.logger.info(
|
||||
f"Importing {filename.name}"
|
||||
)
|
||||
|
||||
|
||||
with open(
|
||||
|
||||
filename,
|
||||
|
||||
"r",
|
||||
|
||||
encoding="utf-8",
|
||||
|
||||
errors="ignore"
|
||||
|
||||
) as file:
|
||||
|
||||
|
||||
reader = csv.DictReader(
|
||||
file
|
||||
)
|
||||
|
||||
|
||||
for row in reader:
|
||||
|
||||
|
||||
registry = row.get(
|
||||
"Registry"
|
||||
)
|
||||
|
||||
assignment = row.get(
|
||||
"Assignment"
|
||||
)
|
||||
|
||||
organization = row.get(
|
||||
"Organization Name"
|
||||
)
|
||||
|
||||
|
||||
if not registry:
|
||||
|
||||
continue
|
||||
|
||||
|
||||
if registry not in stats:
|
||||
|
||||
continue
|
||||
|
||||
|
||||
if not assignment:
|
||||
|
||||
skipped += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
if not organization:
|
||||
|
||||
skipped += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
assignment = (
|
||||
|
||||
assignment
|
||||
|
||||
.replace(
|
||||
"-",
|
||||
""
|
||||
)
|
||||
|
||||
.replace(
|
||||
":",
|
||||
""
|
||||
)
|
||||
|
||||
.replace(
|
||||
".",
|
||||
""
|
||||
)
|
||||
|
||||
.strip()
|
||||
|
||||
.upper()
|
||||
|
||||
)
|
||||
|
||||
|
||||
if not all(
|
||||
|
||||
char in "0123456789ABCDEF"
|
||||
|
||||
for char in assignment
|
||||
|
||||
):
|
||||
|
||||
skipped += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
if len(
|
||||
assignment
|
||||
) not in (
|
||||
|
||||
6,
|
||||
|
||||
7,
|
||||
|
||||
9
|
||||
|
||||
):
|
||||
|
||||
skipped += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
result = self.resolver.add_vendor(
|
||||
|
||||
assignment,
|
||||
|
||||
organization.strip(),
|
||||
|
||||
registry
|
||||
|
||||
)
|
||||
|
||||
|
||||
if result:
|
||||
|
||||
count += 1
|
||||
|
||||
stats[
|
||||
registry
|
||||
] += 1
|
||||
|
||||
else:
|
||||
|
||||
skipped += 1
|
||||
|
||||
|
||||
self.resolver.commit()
|
||||
|
||||
|
||||
total = self.resolver.count()
|
||||
|
||||
|
||||
self.logger.info(
|
||||
f"Imported: {count}"
|
||||
)
|
||||
|
||||
self.logger.info(
|
||||
f"Skipped: {skipped}"
|
||||
)
|
||||
|
||||
self.logger.info(
|
||||
f"Database records: {total}"
|
||||
)
|
||||
|
||||
return {
|
||||
|
||||
"imported": count,
|
||||
|
||||
"skipped": skipped,
|
||||
|
||||
"total": total,
|
||||
|
||||
"stats": stats
|
||||
|
||||
}
|
||||
+36
-5
@@ -1,7 +1,7 @@
|
||||
import subprocess
|
||||
import logging
|
||||
import csv
|
||||
|
||||
import sqlite3
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import pynmea2
|
||||
from scapy.all import PcapNgReader
|
||||
@@ -30,9 +30,17 @@ class CaptureParser:
|
||||
#
|
||||
# Определение производителей
|
||||
#
|
||||
try:
|
||||
self.vendor = VendorResolver(
|
||||
self.config.vendor_database
|
||||
)
|
||||
except sqlite3.Error as exc:
|
||||
self.vendor = None
|
||||
|
||||
logging.getLogger("parser").warning(
|
||||
"OUI database unavailable: %s",
|
||||
exc
|
||||
)
|
||||
|
||||
self.log = logging.getLogger(
|
||||
"parser"
|
||||
@@ -323,8 +331,10 @@ class CaptureParser:
|
||||
timestamp
|
||||
)
|
||||
|
||||
vendor = self.vendor.lookup(
|
||||
row[2]
|
||||
vendor = (
|
||||
self.vendor.lookup(row[2])
|
||||
if self.vendor
|
||||
else "Unknown"
|
||||
)
|
||||
|
||||
|
||||
@@ -493,7 +503,22 @@ class CaptureParser:
|
||||
|
||||
|
||||
|
||||
# WPA*02*hash*APMAC*CLIENTMAC*ESSID*...
|
||||
hash_type = parts[1]
|
||||
|
||||
handshake_type = {
|
||||
"01": "PMKID",
|
||||
"02": "EAPOL"
|
||||
}.get(hash_type)
|
||||
|
||||
if handshake_type is None:
|
||||
|
||||
self.log.warning(
|
||||
"Unsupported WPA hash type: %s",
|
||||
hash_type
|
||||
)
|
||||
|
||||
continue
|
||||
|
||||
hash22000 = line
|
||||
|
||||
ap_bssid = self.normalize_mac(
|
||||
@@ -504,11 +529,17 @@ class CaptureParser:
|
||||
parts[4]
|
||||
)
|
||||
|
||||
if handshake_type == "EAPOL":
|
||||
|
||||
captured_at = self.find_handshake_time(
|
||||
ap_bssid,
|
||||
client_mac
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
captured_at = None
|
||||
|
||||
gps = self.gps_from_timestamp(
|
||||
captured_at
|
||||
)
|
||||
@@ -565,7 +596,7 @@ class CaptureParser:
|
||||
|
||||
|
||||
"type":
|
||||
"EAPOL",
|
||||
handshake_type,
|
||||
|
||||
|
||||
"hash22000":
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class RequestLifecycleMiddleware:
|
||||
|
||||
ALLOWED_DURING_SHUTDOWN = {
|
||||
("GET", "/"),
|
||||
("HEAD", "/"),
|
||||
("GET", "/api/status"),
|
||||
("GET", "/api/gps-test"),
|
||||
("POST", "/scanner/stop"),
|
||||
("POST", "/gps-test/stop"),
|
||||
}
|
||||
|
||||
UNTRACKED_DURING_SHUTDOWN = {
|
||||
("GET", "/"),
|
||||
("HEAD", "/"),
|
||||
("GET", "/api/status"),
|
||||
("GET", "/api/gps-test"),
|
||||
}
|
||||
|
||||
STATIC_PREFIXES = (
|
||||
"/static/",
|
||||
"/reports/static/",
|
||||
)
|
||||
|
||||
def __init__(self, application):
|
||||
|
||||
self.application = application
|
||||
|
||||
self._condition = threading.Condition()
|
||||
self._shutdown_requested = False
|
||||
self._active_requests = 0
|
||||
|
||||
@property
|
||||
def shutdown_requested(self):
|
||||
|
||||
with self._condition:
|
||||
|
||||
return self._shutdown_requested
|
||||
|
||||
@property
|
||||
def active_requests(self):
|
||||
|
||||
with self._condition:
|
||||
|
||||
return self._active_requests
|
||||
|
||||
def begin_shutdown(self):
|
||||
|
||||
with self._condition:
|
||||
|
||||
self._shutdown_requested = True
|
||||
|
||||
self._condition.notify_all()
|
||||
|
||||
def wait_for_drain(self, timeout=None):
|
||||
|
||||
deadline = (
|
||||
None
|
||||
if timeout is None
|
||||
else time.monotonic() + timeout
|
||||
)
|
||||
|
||||
with self._condition:
|
||||
|
||||
while self._active_requests:
|
||||
|
||||
remaining = (
|
||||
None
|
||||
if deadline is None
|
||||
else deadline - time.monotonic()
|
||||
)
|
||||
|
||||
if remaining is not None and remaining <= 0:
|
||||
return False
|
||||
|
||||
self._condition.wait(remaining)
|
||||
|
||||
return True
|
||||
|
||||
def _is_allowed_during_shutdown(self, method, path):
|
||||
|
||||
if (method, path) in self.ALLOWED_DURING_SHUTDOWN:
|
||||
return True
|
||||
|
||||
if method not in ("GET", "HEAD"):
|
||||
return False
|
||||
|
||||
return any(
|
||||
path.startswith(prefix)
|
||||
for prefix in self.STATIC_PREFIXES
|
||||
)
|
||||
|
||||
def _release_request(self):
|
||||
|
||||
with self._condition:
|
||||
|
||||
self._active_requests -= 1
|
||||
|
||||
self._condition.notify_all()
|
||||
|
||||
def __call__(self, environ, start_response):
|
||||
|
||||
method = environ.get("REQUEST_METHOD", "GET").upper()
|
||||
path = environ.get("PATH_INFO", "/")
|
||||
|
||||
track_request = True
|
||||
|
||||
with self._condition:
|
||||
|
||||
if self._shutdown_requested:
|
||||
|
||||
if not self._is_allowed_during_shutdown(
|
||||
method,
|
||||
path
|
||||
):
|
||||
|
||||
body = b"Application is shutting down.\n"
|
||||
|
||||
start_response(
|
||||
"503 Service Unavailable",
|
||||
[
|
||||
("Content-Type", "text/plain; charset=utf-8"),
|
||||
("Content-Length", str(len(body))),
|
||||
("Retry-After", "5"),
|
||||
("Cache-Control", "no-store"),
|
||||
]
|
||||
)
|
||||
|
||||
return [body]
|
||||
|
||||
if (
|
||||
(method, path) in self.UNTRACKED_DURING_SHUTDOWN
|
||||
or (
|
||||
method in ("GET", "HEAD")
|
||||
and any(
|
||||
path.startswith(prefix)
|
||||
for prefix in self.STATIC_PREFIXES
|
||||
)
|
||||
)
|
||||
):
|
||||
|
||||
track_request = False
|
||||
|
||||
if track_request:
|
||||
self._active_requests += 1
|
||||
|
||||
if not track_request:
|
||||
return self.application(
|
||||
environ,
|
||||
start_response
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
response = self.application(
|
||||
environ,
|
||||
start_response
|
||||
)
|
||||
|
||||
except BaseException:
|
||||
|
||||
self._release_request()
|
||||
|
||||
raise
|
||||
|
||||
return _TrackedIterable(
|
||||
response,
|
||||
self._release_request
|
||||
)
|
||||
|
||||
|
||||
class _TrackedIterable:
|
||||
|
||||
def __init__(self, iterable, release):
|
||||
|
||||
self._iterable = iterable
|
||||
self._iterator = iter(iterable)
|
||||
self._release = release
|
||||
self._closed = False
|
||||
|
||||
def __iter__(self):
|
||||
|
||||
return self
|
||||
|
||||
def __next__(self):
|
||||
|
||||
try:
|
||||
|
||||
return next(self._iterator)
|
||||
|
||||
except BaseException:
|
||||
|
||||
self.close()
|
||||
|
||||
raise
|
||||
|
||||
def close(self):
|
||||
|
||||
if self._closed:
|
||||
return
|
||||
|
||||
self._closed = True
|
||||
|
||||
try:
|
||||
|
||||
close = getattr(
|
||||
self._iterable,
|
||||
"close",
|
||||
None
|
||||
)
|
||||
|
||||
if close is not None:
|
||||
close()
|
||||
|
||||
finally:
|
||||
|
||||
self._release()
|
||||
@@ -0,0 +1,42 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
NODE_BIN_DIR = PROJECT_ROOT / "runtime" / "node" / "bin"
|
||||
|
||||
|
||||
def _runtime_executable(name):
|
||||
executable = NODE_BIN_DIR / name
|
||||
|
||||
if not executable.is_file() or not os.access(executable, os.X_OK):
|
||||
raise FileNotFoundError(
|
||||
f"Локальный исполняемый файл {name} не найден: {executable}"
|
||||
)
|
||||
|
||||
return executable
|
||||
|
||||
|
||||
def get_node_path():
|
||||
return _runtime_executable("node")
|
||||
|
||||
|
||||
def get_npm_path():
|
||||
return _runtime_executable("npm")
|
||||
|
||||
|
||||
def get_npx_path():
|
||||
return _runtime_executable("npx")
|
||||
|
||||
|
||||
def get_runtime_env():
|
||||
environment = os.environ.copy()
|
||||
current_path = environment.get("PATH", "")
|
||||
|
||||
environment["PATH"] = (
|
||||
f"{NODE_BIN_DIR}{os.pathsep}{current_path}"
|
||||
if current_path
|
||||
else str(NODE_BIN_DIR)
|
||||
)
|
||||
|
||||
return environment
|
||||
@@ -275,4 +275,3 @@ class Session:
|
||||
|
||||
|
||||
self.gps_positions += 1
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
Shared TileServer configuration loader.
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
DEFAULT_ENTRY = "node_modules/tileserver-gl-light/src/main.js"
|
||||
DEFAULT_CONFIG = "config.json"
|
||||
DEFAULT_STYLE = "server-map"
|
||||
|
||||
|
||||
def load_tileserver_config(project_root):
|
||||
project_root = Path(project_root).expanduser().resolve()
|
||||
config_file = project_root / "config" / "config.yaml"
|
||||
|
||||
try:
|
||||
with config_file.open("r", encoding="utf-8") as file:
|
||||
application_config = yaml.safe_load(file) or {}
|
||||
except (OSError, yaml.YAMLError) as error:
|
||||
raise RuntimeError(
|
||||
f"Не удалось загрузить конфигурацию {config_file}: {error}"
|
||||
) from error
|
||||
|
||||
if not isinstance(application_config, dict):
|
||||
raise RuntimeError(
|
||||
"Корень config/config.yaml должен быть YAML-объектом."
|
||||
)
|
||||
|
||||
section = application_config.get("tileserver", {})
|
||||
|
||||
if not isinstance(section, dict):
|
||||
raise RuntimeError(
|
||||
"Раздел tileserver в config/config.yaml должен быть YAML-объектом."
|
||||
)
|
||||
|
||||
directory_value = os.environ.get(
|
||||
"WIFI_GPS_TILESERVER_DIR",
|
||||
section.get("directory", "map-server")
|
||||
)
|
||||
|
||||
directory = Path(directory_value).expanduser()
|
||||
|
||||
if "WIFI_GPS_TILESERVER_DIR" not in os.environ and not directory.is_absolute():
|
||||
directory = project_root / directory
|
||||
|
||||
directory = directory.resolve()
|
||||
|
||||
entry_from_environment = "WIFI_GPS_TILESERVER_ENTRY" in os.environ
|
||||
entry_value = os.environ.get(
|
||||
"WIFI_GPS_TILESERVER_ENTRY",
|
||||
section.get("entry", DEFAULT_ENTRY)
|
||||
)
|
||||
|
||||
entry = Path(entry_value).expanduser()
|
||||
|
||||
if not entry.is_absolute() and not entry_from_environment:
|
||||
entry = directory / entry
|
||||
|
||||
config_value = os.environ.get(
|
||||
"WIFI_GPS_TILESERVER_CONFIG",
|
||||
section.get("config", DEFAULT_CONFIG)
|
||||
)
|
||||
|
||||
config = Path(config_value).expanduser()
|
||||
config_path = config if config.is_absolute() else directory / config
|
||||
|
||||
host = str(section.get("host", "127.0.0.1")).strip()
|
||||
|
||||
try:
|
||||
port = int(
|
||||
os.environ.get(
|
||||
"WIFI_GPS_TILESERVER_PORT",
|
||||
section.get("port", 8080)
|
||||
)
|
||||
)
|
||||
except (TypeError, ValueError) as error:
|
||||
raise RuntimeError("Некорректный порт TileServer.") from error
|
||||
|
||||
if not host:
|
||||
raise RuntimeError("Не задан host для TileServer.")
|
||||
|
||||
if not 1 <= port <= 65535:
|
||||
raise RuntimeError(f"Некорректный порт TileServer: {port}")
|
||||
|
||||
style = str(section.get("style", DEFAULT_STYLE)).strip().strip("/")
|
||||
|
||||
if not style:
|
||||
raise RuntimeError("Не задан style для TileServer.")
|
||||
|
||||
return {
|
||||
"host": host,
|
||||
"port": port,
|
||||
"directory": directory,
|
||||
"entry": entry,
|
||||
"config": str(config),
|
||||
"config_path": config_path,
|
||||
"style": style,
|
||||
"style_url": (
|
||||
f"http://{host}:{port}/styles/{style}/style.json"
|
||||
),
|
||||
}
|
||||
+14
-4
@@ -8,25 +8,35 @@ class VendorResolver:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database
|
||||
database,
|
||||
writable=False
|
||||
):
|
||||
|
||||
self.db_path = Path(database)
|
||||
self.writable = writable
|
||||
|
||||
|
||||
if writable:
|
||||
self.db_path.parent.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True
|
||||
)
|
||||
|
||||
|
||||
self.conn = sqlite3.connect(
|
||||
self.db_path
|
||||
)
|
||||
|
||||
|
||||
self.create_tables()
|
||||
|
||||
else:
|
||||
self.conn = sqlite3.connect(
|
||||
f"{self.db_path.resolve().as_uri()}?mode=ro",
|
||||
uri=True
|
||||
)
|
||||
|
||||
self.conn.execute(
|
||||
"SELECT 1 FROM oui LIMIT 0"
|
||||
)
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
|
||||
@@ -1,314 +0,0 @@
|
||||
import logging
|
||||
import urllib.request
|
||||
import datetime
|
||||
import time
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from vendor import VendorResolver
|
||||
from oui_import import OUIImporter
|
||||
|
||||
|
||||
PROJECT_ROOT = (
|
||||
Path(__file__).resolve().parent.parent
|
||||
)
|
||||
|
||||
|
||||
DATABASE_DIR = (
|
||||
PROJECT_ROOT
|
||||
/
|
||||
"database"
|
||||
)
|
||||
|
||||
|
||||
OUI_DATABASE = (
|
||||
DATABASE_DIR
|
||||
/
|
||||
"oui.sqlite"
|
||||
)
|
||||
|
||||
|
||||
HTTP_HEADERS = {
|
||||
|
||||
"User-Agent":
|
||||
|
||||
"Mozilla/5.0 (X11; Linux x86_64) "
|
||||
|
||||
"AppleWebKit/537.36 "
|
||||
|
||||
"(KHTML, like Gecko) "
|
||||
|
||||
"Chrome/138.0 Safari/537.36"
|
||||
|
||||
}
|
||||
|
||||
|
||||
DOWNLOAD_RETRIES = 3
|
||||
|
||||
DOWNLOAD_TIMEOUT = 60
|
||||
|
||||
CSV_FILES = {
|
||||
|
||||
"oui.csv": "oui",
|
||||
|
||||
"mam.csv": "mam",
|
||||
|
||||
"oui36.csv": "oui36",
|
||||
|
||||
}
|
||||
|
||||
|
||||
class VendorImporter:
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config
|
||||
):
|
||||
|
||||
self.config = config
|
||||
|
||||
self.log = logging.getLogger(
|
||||
"vendor_import"
|
||||
)
|
||||
|
||||
DATABASE_DIR.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# Загрузка IEEE CSV
|
||||
# ---------------------------------------------------------
|
||||
|
||||
def download_csv_files(self):
|
||||
|
||||
for filename, key in CSV_FILES.items():
|
||||
|
||||
url = self.config.vendor_sources[key]
|
||||
|
||||
destination = (
|
||||
DATABASE_DIR
|
||||
/
|
||||
filename
|
||||
)
|
||||
|
||||
success = False
|
||||
|
||||
for attempt in range(
|
||||
1,
|
||||
DOWNLOAD_RETRIES + 1
|
||||
):
|
||||
|
||||
self.log.info(
|
||||
|
||||
f"Downloading {filename} "
|
||||
|
||||
f"(attempt {attempt}/{DOWNLOAD_RETRIES})"
|
||||
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers=HTTP_HEADERS
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(
|
||||
request,
|
||||
timeout=DOWNLOAD_TIMEOUT
|
||||
) as response:
|
||||
|
||||
if response.status != 200:
|
||||
|
||||
raise RuntimeError(
|
||||
f"HTTP {response.status}"
|
||||
)
|
||||
|
||||
data = response.read()
|
||||
|
||||
if len(data) < 1000:
|
||||
|
||||
raise RuntimeError(
|
||||
"Downloaded file is too small"
|
||||
)
|
||||
|
||||
text = data.decode(
|
||||
"utf-8",
|
||||
errors="ignore"
|
||||
)
|
||||
|
||||
if "Assignment" not in text:
|
||||
|
||||
raise RuntimeError(
|
||||
"Invalid IEEE CSV"
|
||||
)
|
||||
|
||||
destination.write_bytes(
|
||||
data
|
||||
)
|
||||
|
||||
size = (
|
||||
destination.stat().st_size
|
||||
/ 1024
|
||||
/ 1024
|
||||
)
|
||||
|
||||
self.log.info(
|
||||
|
||||
f"{filename} downloaded "
|
||||
|
||||
f"({size:.2f} MB)"
|
||||
|
||||
)
|
||||
|
||||
success = True
|
||||
|
||||
break
|
||||
|
||||
except KeyboardInterrupt:
|
||||
|
||||
self.log.info(
|
||||
"CSV download cancelled"
|
||||
)
|
||||
|
||||
raise
|
||||
|
||||
except Exception as error:
|
||||
|
||||
self.log.warning(
|
||||
f"{filename}: {error}"
|
||||
)
|
||||
|
||||
if destination.exists():
|
||||
|
||||
destination.unlink()
|
||||
|
||||
if attempt < DOWNLOAD_RETRIES:
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
if not success:
|
||||
|
||||
raise RuntimeError(
|
||||
f"Unable to download {filename}"
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# Полное создание IEEE базы
|
||||
# ---------------------------------------------------------
|
||||
|
||||
def bootstrap(self):
|
||||
|
||||
OUI_DATABASE.unlink(
|
||||
missing_ok=True
|
||||
)
|
||||
|
||||
self.download_csv_files()
|
||||
|
||||
resolver = VendorResolver(
|
||||
OUI_DATABASE
|
||||
)
|
||||
|
||||
importer = OUIImporter(
|
||||
|
||||
resolver,
|
||||
|
||||
[
|
||||
DATABASE_DIR
|
||||
/
|
||||
filename
|
||||
|
||||
for filename
|
||||
|
||||
in CSV_FILES
|
||||
]
|
||||
|
||||
)
|
||||
|
||||
result = importer.import_database()
|
||||
|
||||
total = result["total"]
|
||||
|
||||
stats = result["stats"]
|
||||
|
||||
if (
|
||||
|
||||
stats["MA-L"] < 35000
|
||||
|
||||
or
|
||||
|
||||
stats["MA-M"] < 5000
|
||||
|
||||
or
|
||||
|
||||
stats["MA-S"] < 5000
|
||||
|
||||
):
|
||||
|
||||
resolver.close()
|
||||
|
||||
OUI_DATABASE.unlink(
|
||||
missing_ok=True
|
||||
)
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
"IEEE database verification failed.\n\n"
|
||||
|
||||
f"MA-L: {stats['MA-L']}\n"
|
||||
|
||||
f"MA-M: {stats['MA-M']}\n"
|
||||
|
||||
f"MA-S: {stats['MA-S']}"
|
||||
|
||||
)
|
||||
|
||||
resolver.set_metadata(
|
||||
|
||||
"last_import",
|
||||
datetime.datetime.now(
|
||||
datetime.timezone.utc
|
||||
).isoformat().replace(
|
||||
"+00:00",
|
||||
"Z"
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
resolver.set_metadata(
|
||||
|
||||
"records",
|
||||
|
||||
total
|
||||
|
||||
)
|
||||
|
||||
resolver.set_metadata(
|
||||
|
||||
"schema_version",
|
||||
|
||||
1
|
||||
|
||||
)
|
||||
|
||||
resolver.set_metadata(
|
||||
|
||||
"import_status",
|
||||
|
||||
"ok"
|
||||
|
||||
)
|
||||
|
||||
resolver.commit()
|
||||
|
||||
resolver.close()
|
||||
|
||||
self.log.info(
|
||||
|
||||
"IEEE database created: "
|
||||
|
||||
f"{total} records"
|
||||
|
||||
)
|
||||
+322
-98
@@ -214,10 +214,6 @@ class VendorService:
|
||||
candidate
|
||||
)
|
||||
|
||||
ap_impact = self._calculate_ap_impact(
|
||||
candidate
|
||||
)
|
||||
|
||||
progress(
|
||||
"ready",
|
||||
message="Обновление готово к применению"
|
||||
@@ -232,8 +228,7 @@ class VendorService:
|
||||
),
|
||||
"sources": downloaded,
|
||||
"build": build_stats,
|
||||
"oui": oui_diff,
|
||||
"ap": ap_impact
|
||||
"oui": oui_diff
|
||||
}
|
||||
|
||||
except Exception:
|
||||
@@ -1157,6 +1152,15 @@ class VendorService:
|
||||
.upper()
|
||||
)
|
||||
|
||||
if (
|
||||
len(normalized) != 12
|
||||
or any(
|
||||
character not in "0123456789ABCDEF"
|
||||
for character in normalized
|
||||
)
|
||||
):
|
||||
return None
|
||||
|
||||
for length in (
|
||||
9,
|
||||
7,
|
||||
@@ -1205,11 +1209,13 @@ class VendorService:
|
||||
"access_points table is missing"
|
||||
)
|
||||
|
||||
columns = {
|
||||
row[1]
|
||||
for row in conn.execute(
|
||||
column_info = conn.execute(
|
||||
"PRAGMA table_info(access_points)"
|
||||
).fetchall()
|
||||
|
||||
columns = {
|
||||
row[1]
|
||||
for row in column_info
|
||||
}
|
||||
|
||||
required = {
|
||||
@@ -1217,24 +1223,292 @@ class VendorService:
|
||||
"vendor"
|
||||
}
|
||||
|
||||
if not required.issubset(
|
||||
columns
|
||||
):
|
||||
primary_key_columns = [
|
||||
row
|
||||
for row in column_info
|
||||
if row[5] > 0
|
||||
]
|
||||
|
||||
id_column = next(
|
||||
(
|
||||
row
|
||||
for row in column_info
|
||||
if row[1] == "id"
|
||||
),
|
||||
None
|
||||
)
|
||||
|
||||
if (
|
||||
not required.issubset(columns)
|
||||
or id_column is None
|
||||
or str(id_column[2]).upper() != "INTEGER"
|
||||
or id_column[5] != 1
|
||||
or len(primary_key_columns) != 1
|
||||
):
|
||||
raise ValueError(
|
||||
"Invalid WiFi database schema"
|
||||
)
|
||||
|
||||
# ============================================================
|
||||
# Recalculate access point vendors
|
||||
# ============================================================
|
||||
|
||||
def recalculate_ap_vendors(
|
||||
self,
|
||||
progress_callback=None
|
||||
):
|
||||
|
||||
def progress(
|
||||
stage,
|
||||
message=None
|
||||
):
|
||||
|
||||
if progress_callback is not None:
|
||||
|
||||
progress_callback(
|
||||
stage,
|
||||
None,
|
||||
message
|
||||
)
|
||||
|
||||
if not self.vendor_database.is_file():
|
||||
|
||||
raise FileNotFoundError(
|
||||
f"OUI database not found: {self.vendor_database}"
|
||||
)
|
||||
|
||||
if not self.wifi_database.is_file():
|
||||
|
||||
raise FileNotFoundError(
|
||||
f"WiFi database not found: {self.wifi_database}"
|
||||
)
|
||||
|
||||
oui_conn = None
|
||||
wifi_conn = None
|
||||
|
||||
try:
|
||||
|
||||
oui_uri = (
|
||||
f"{self.vendor_database.resolve().as_uri()}"
|
||||
"?mode=ro"
|
||||
)
|
||||
|
||||
oui_conn = sqlite3.connect(
|
||||
oui_uri,
|
||||
uri=True,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
self._validate_schema(
|
||||
oui_conn
|
||||
)
|
||||
|
||||
wifi_conn = sqlite3.connect(
|
||||
self.wifi_database,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
self._validate_wifi_schema(
|
||||
wifi_conn
|
||||
)
|
||||
|
||||
wifi_conn.execute(
|
||||
"BEGIN IMMEDIATE"
|
||||
)
|
||||
|
||||
total = wifi_conn.execute(
|
||||
"""
|
||||
SELECT COUNT(*)
|
||||
FROM access_points
|
||||
"""
|
||||
).fetchone()[0]
|
||||
|
||||
stats = {
|
||||
"total": total,
|
||||
"checked": 0,
|
||||
"updated": 0,
|
||||
"filled": 0,
|
||||
"refreshed": 0,
|
||||
"cleared": 0,
|
||||
"unknown": 0,
|
||||
"unchanged": 0
|
||||
}
|
||||
|
||||
def iter_rows():
|
||||
|
||||
last_id = None
|
||||
|
||||
while True:
|
||||
|
||||
if last_id is None:
|
||||
|
||||
batch = wifi_conn.execute(
|
||||
"""
|
||||
SELECT
|
||||
id,
|
||||
bssid,
|
||||
vendor
|
||||
FROM access_points
|
||||
ORDER BY id
|
||||
LIMIT 1000
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
else:
|
||||
|
||||
batch = wifi_conn.execute(
|
||||
"""
|
||||
SELECT
|
||||
id,
|
||||
bssid,
|
||||
vendor
|
||||
FROM access_points
|
||||
WHERE id > ?
|
||||
ORDER BY id
|
||||
LIMIT 1000
|
||||
""",
|
||||
(
|
||||
last_id,
|
||||
)
|
||||
).fetchall()
|
||||
|
||||
if not batch:
|
||||
break
|
||||
|
||||
last_id = batch[-1][0]
|
||||
|
||||
yield from batch
|
||||
|
||||
placeholders = (
|
||||
None,
|
||||
"",
|
||||
"-",
|
||||
"Unknown"
|
||||
)
|
||||
|
||||
progress(
|
||||
"recalculating",
|
||||
f"Проверка точек доступа: {total}"
|
||||
)
|
||||
|
||||
progress_interval = max(
|
||||
1,
|
||||
total // 100
|
||||
)
|
||||
|
||||
def report_progress():
|
||||
|
||||
if (
|
||||
stats["checked"] % progress_interval == 0
|
||||
or stats["checked"] == total
|
||||
):
|
||||
|
||||
progress(
|
||||
"recalculating",
|
||||
(
|
||||
f"Проверено {stats['checked']} "
|
||||
f"из {total}"
|
||||
)
|
||||
)
|
||||
|
||||
for ap_id, bssid, current_vendor in iter_rows():
|
||||
|
||||
stats["checked"] += 1
|
||||
|
||||
new_vendor = self._lookup_vendor(
|
||||
oui_conn,
|
||||
bssid
|
||||
)
|
||||
|
||||
is_placeholder = (
|
||||
current_vendor in placeholders
|
||||
)
|
||||
|
||||
if new_vendor is None:
|
||||
|
||||
stats["unknown"] += 1
|
||||
|
||||
if is_placeholder:
|
||||
|
||||
stats["unchanged"] += 1
|
||||
report_progress()
|
||||
continue
|
||||
|
||||
desired_vendor = None
|
||||
|
||||
stats["cleared"] += 1
|
||||
|
||||
else:
|
||||
|
||||
desired_vendor = new_vendor
|
||||
|
||||
if current_vendor == desired_vendor:
|
||||
|
||||
stats["unchanged"] += 1
|
||||
report_progress()
|
||||
continue
|
||||
|
||||
if is_placeholder:
|
||||
|
||||
stats["filled"] += 1
|
||||
|
||||
else:
|
||||
|
||||
stats["refreshed"] += 1
|
||||
|
||||
wifi_conn.execute(
|
||||
"""
|
||||
UPDATE access_points
|
||||
SET vendor=?
|
||||
WHERE id=?
|
||||
""",
|
||||
(
|
||||
desired_vendor,
|
||||
ap_id
|
||||
)
|
||||
)
|
||||
|
||||
stats["updated"] += 1
|
||||
|
||||
report_progress()
|
||||
|
||||
progress(
|
||||
"committing",
|
||||
"Сохранение результатов"
|
||||
)
|
||||
|
||||
wifi_conn.commit()
|
||||
|
||||
progress(
|
||||
"ready",
|
||||
"Перерасчёт завершён"
|
||||
)
|
||||
|
||||
return stats
|
||||
|
||||
except Exception:
|
||||
|
||||
if wifi_conn is not None:
|
||||
|
||||
wifi_conn.rollback()
|
||||
|
||||
raise
|
||||
|
||||
finally:
|
||||
|
||||
if wifi_conn is not None:
|
||||
wifi_conn.close()
|
||||
|
||||
if oui_conn is not None:
|
||||
oui_conn.close()
|
||||
|
||||
# ============================================================
|
||||
# Apply
|
||||
# ============================================================
|
||||
|
||||
def apply(
|
||||
self,
|
||||
preview,
|
||||
unknown_to_vendor=True,
|
||||
vendor_to_vendor=False,
|
||||
vendor_to_unknown=False
|
||||
preview
|
||||
):
|
||||
|
||||
candidate = Path(
|
||||
@@ -1260,58 +1534,8 @@ class VendorService:
|
||||
"identical"
|
||||
]
|
||||
|
||||
selected = {
|
||||
"unknown_to_vendor":
|
||||
bool(
|
||||
unknown_to_vendor
|
||||
),
|
||||
"vendor_to_vendor":
|
||||
bool(
|
||||
vendor_to_vendor
|
||||
),
|
||||
"vendor_to_unknown":
|
||||
bool(
|
||||
vendor_to_unknown
|
||||
)
|
||||
}
|
||||
|
||||
selected_count = 0
|
||||
|
||||
if selected[
|
||||
"unknown_to_vendor"
|
||||
]:
|
||||
|
||||
selected_count += preview[
|
||||
"ap"
|
||||
][
|
||||
"unknown_to_vendor"
|
||||
]
|
||||
|
||||
if selected[
|
||||
"vendor_to_vendor"
|
||||
]:
|
||||
|
||||
selected_count += preview[
|
||||
"ap"
|
||||
][
|
||||
"vendor_to_vendor"
|
||||
]
|
||||
|
||||
if selected[
|
||||
"vendor_to_unknown"
|
||||
]:
|
||||
|
||||
selected_count += preview[
|
||||
"ap"
|
||||
][
|
||||
"vendor_to_unknown"
|
||||
]
|
||||
|
||||
result = {
|
||||
"oui_updated": False,
|
||||
"wifi_updated": 0,
|
||||
"selected": selected,
|
||||
"selected_count": selected_count
|
||||
"oui_updated": False
|
||||
}
|
||||
|
||||
try:
|
||||
@@ -1332,15 +1556,6 @@ class VendorService:
|
||||
"oui_updated"
|
||||
] = True
|
||||
|
||||
if selected_count:
|
||||
|
||||
result[
|
||||
"wifi_updated"
|
||||
] = self._apply_wifi_changes(
|
||||
preview,
|
||||
selected
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
finally:
|
||||
@@ -1524,6 +1739,35 @@ class VendorService:
|
||||
f"{database_type}-"
|
||||
)
|
||||
|
||||
timestamp = datetime.now(
|
||||
timezone.utc
|
||||
).strftime(
|
||||
"%Y%m%d-%H%M%S-%f"
|
||||
)
|
||||
|
||||
backup = (
|
||||
self.backup_directory
|
||||
/
|
||||
(
|
||||
f"{prefix}"
|
||||
f"{timestamp}"
|
||||
f".sqlite3"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
shutil.copy2(
|
||||
database,
|
||||
backup
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
backup.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
raise
|
||||
|
||||
backups = sorted(
|
||||
self.backup_directory.glob(
|
||||
f"{prefix}*.sqlite*"
|
||||
@@ -1532,32 +1776,12 @@ class VendorService:
|
||||
reverse=True
|
||||
)
|
||||
|
||||
while len(
|
||||
backups
|
||||
) >= self.BACKUP_LIMIT:
|
||||
|
||||
oldest = backups.pop()
|
||||
|
||||
for old_backup in backups[self.BACKUP_LIMIT:]:
|
||||
try:
|
||||
oldest.unlink()
|
||||
old_backup.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
backup = (
|
||||
self.backup_directory
|
||||
/
|
||||
(
|
||||
f"{prefix}"
|
||||
f"{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}"
|
||||
f".sqlite3"
|
||||
)
|
||||
)
|
||||
|
||||
shutil.copy2(
|
||||
database,
|
||||
backup
|
||||
)
|
||||
|
||||
return backup
|
||||
|
||||
# ============================================================
|
||||
|
||||
@@ -1,373 +0,0 @@
|
||||
import logging
|
||||
import urllib.request
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from vendor import VendorResolver
|
||||
from vendor_import import (
|
||||
VendorImporter,
|
||||
CSV_FILES
|
||||
)
|
||||
|
||||
|
||||
logger = logging.getLogger(
|
||||
"vendor-update"
|
||||
)
|
||||
|
||||
|
||||
class VendorUpdater:
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cfg
|
||||
):
|
||||
|
||||
self.cfg = cfg
|
||||
|
||||
|
||||
self.project_root = (
|
||||
|
||||
Path(__file__)
|
||||
|
||||
.resolve()
|
||||
|
||||
.parent
|
||||
|
||||
.parent
|
||||
|
||||
)
|
||||
|
||||
|
||||
self.database = (
|
||||
|
||||
self.project_root
|
||||
|
||||
/ "database"
|
||||
|
||||
/ "oui.sqlite"
|
||||
|
||||
)
|
||||
|
||||
|
||||
self.csv_files = [
|
||||
|
||||
self.project_root
|
||||
/ "database"
|
||||
/ filename
|
||||
|
||||
for filename
|
||||
|
||||
in CSV_FILES
|
||||
|
||||
]
|
||||
|
||||
# =====================================================
|
||||
# Проверка CSV
|
||||
# =====================================================
|
||||
|
||||
def csv_exists(
|
||||
self
|
||||
):
|
||||
|
||||
for file in self.csv_files:
|
||||
|
||||
if not file.exists():
|
||||
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
# =====================================================
|
||||
# Проверка базы
|
||||
# =====================================================
|
||||
|
||||
def database_exists(
|
||||
self
|
||||
):
|
||||
|
||||
return self.database.exists()
|
||||
|
||||
# =====================================================
|
||||
# Проверка metadata
|
||||
# =====================================================
|
||||
|
||||
def metadata_exists(
|
||||
self
|
||||
):
|
||||
|
||||
resolver = VendorResolver(
|
||||
self.database
|
||||
)
|
||||
|
||||
|
||||
result = resolver.has_metadata(
|
||||
"last_import"
|
||||
)
|
||||
|
||||
|
||||
resolver.close()
|
||||
|
||||
return result
|
||||
|
||||
# =====================================================
|
||||
# Создание базы IEEE
|
||||
# =====================================================
|
||||
|
||||
def create_database(
|
||||
self
|
||||
):
|
||||
|
||||
logger.info(
|
||||
"Creating IEEE OUI database..."
|
||||
)
|
||||
|
||||
|
||||
importer = VendorImporter(
|
||||
|
||||
self.cfg
|
||||
|
||||
)
|
||||
|
||||
|
||||
importer.import_database()
|
||||
|
||||
|
||||
logger.info(
|
||||
"IEEE database created"
|
||||
)
|
||||
|
||||
# =====================================================
|
||||
# Проверка IEEE базы
|
||||
# =====================================================
|
||||
|
||||
def check(
|
||||
self
|
||||
):
|
||||
|
||||
logger.info(
|
||||
"Checking IEEE vendor database..."
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
# База уже существует
|
||||
#
|
||||
|
||||
if self.database_exists():
|
||||
|
||||
if self.database.stat().st_size < 10000:
|
||||
|
||||
logger.warning(
|
||||
"IEEE database corrupted"
|
||||
)
|
||||
|
||||
self.database.unlink()
|
||||
|
||||
self.check()
|
||||
|
||||
return
|
||||
|
||||
logger.info(
|
||||
"IEEE database found"
|
||||
)
|
||||
|
||||
|
||||
if self.metadata_exists():
|
||||
|
||||
logger.info(
|
||||
"IEEE metadata found"
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
|
||||
logger.warning(
|
||||
"IEEE metadata missing"
|
||||
)
|
||||
|
||||
|
||||
resolver = VendorResolver(
|
||||
self.database
|
||||
)
|
||||
|
||||
if resolver.count() == 0:
|
||||
|
||||
resolver.close()
|
||||
|
||||
logger.warning(
|
||||
"IEEE database is empty"
|
||||
)
|
||||
|
||||
self.database.unlink()
|
||||
|
||||
self.check()
|
||||
|
||||
return
|
||||
|
||||
resolver.set_metadata(
|
||||
"last_import",
|
||||
"unknown"
|
||||
)
|
||||
|
||||
|
||||
resolver.commit()
|
||||
|
||||
resolver.close()
|
||||
|
||||
|
||||
logger.info(
|
||||
"IEEE metadata restored"
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
|
||||
#
|
||||
# Базы нет
|
||||
#
|
||||
|
||||
logger.warning(
|
||||
"IEEE database not found"
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
# Проверяем CSV
|
||||
#
|
||||
|
||||
if not self.csv_exists():
|
||||
|
||||
logger.warning(
|
||||
"IEEE CSV files not found"
|
||||
)
|
||||
|
||||
self.download_csv()
|
||||
|
||||
|
||||
logger.info(
|
||||
"IEEE CSV files found"
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
# Создаем базу
|
||||
#
|
||||
|
||||
self.create_database()
|
||||
|
||||
# =====================================================
|
||||
# Загрузка IEEE CSV
|
||||
# =====================================================
|
||||
|
||||
def download_csv(
|
||||
self
|
||||
):
|
||||
|
||||
|
||||
logger.info(
|
||||
"Downloading IEEE CSV files..."
|
||||
)
|
||||
|
||||
self.database.parent.mkdir(
|
||||
|
||||
parents=True,
|
||||
|
||||
exist_ok=True
|
||||
|
||||
)
|
||||
|
||||
downloads = [
|
||||
|
||||
(
|
||||
self.cfg.vendor_sources[key],
|
||||
|
||||
self.project_root
|
||||
/
|
||||
"database"
|
||||
/
|
||||
filename
|
||||
)
|
||||
|
||||
for filename, key
|
||||
|
||||
in CSV_FILES.items()
|
||||
|
||||
]
|
||||
|
||||
|
||||
for url, filename in downloads:
|
||||
|
||||
|
||||
logger.info(
|
||||
f"Downloading {filename.name}"
|
||||
)
|
||||
|
||||
|
||||
try:
|
||||
|
||||
urllib.request.urlretrieve(
|
||||
|
||||
url,
|
||||
|
||||
filename
|
||||
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
|
||||
logger.error(
|
||||
|
||||
f"Download failed: {filename.name}"
|
||||
|
||||
)
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
str(error)
|
||||
|
||||
)
|
||||
|
||||
|
||||
if not filename.exists():
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
f"{filename.name} download failed"
|
||||
|
||||
)
|
||||
|
||||
|
||||
if filename.stat().st_size < 1000:
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
f"{filename.name} is too small"
|
||||
|
||||
)
|
||||
|
||||
|
||||
size = (
|
||||
|
||||
filename.stat().st_size
|
||||
|
||||
/ 1024
|
||||
|
||||
/ 1024
|
||||
|
||||
)
|
||||
|
||||
|
||||
logger.info(
|
||||
|
||||
f"{filename.name} downloaded "
|
||||
|
||||
f"({size:.2f} MB)"
|
||||
|
||||
)
|
||||
|
||||
|
||||
logger.info(
|
||||
"IEEE CSV download finished"
|
||||
)
|
||||
|
||||
@@ -2729,4 +2729,3 @@ def import_wifitrip(
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
Reference in New Issue
Block a user