fix: validate library and data paths at the application boundary
This commit is contained in:
1 parent
47c2cfecc6
commit
6d2b6de027
10 files changed
+336
-36
No files matched your search
@@ -3,6 +3,7 @@ import argparse, os, sys
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
from typing import Sequence
|
||||
from .network_path import NetworkPathError
|
||||
from .runtime_logging import configure
|
||||
|
||||
|
||||
@@ -62,6 +63,29 @@ def resolve_data_root(cli_value: Path | None) -> Path:
|
||||
local = os.environ.get("LOCALAPPDATA")
|
||||
return (Path(local) / "CbbRefreshVerify" if local else Path.home() / "AppData" / "Local" / "CbbRefreshVerify").resolve()
|
||||
|
||||
def _report_entry_error(message: str, *, command_line: bool) -> int:
|
||||
if not command_line:
|
||||
import win32api
|
||||
import win32con
|
||||
win32api.MessageBox(None, message, 'CBB 刷新校验启动失败', win32con.MB_ICONERROR)
|
||||
elif sys.stderr is not None:
|
||||
print(message, file=sys.stderr, flush=True)
|
||||
elif os.name == 'nt':
|
||||
# PyInstaller's windowed executable leaves sys.stderr unset even
|
||||
# when the caller supplied a redirected Windows stderr handle.
|
||||
import pywintypes
|
||||
import win32api
|
||||
import win32console
|
||||
import win32file
|
||||
try:
|
||||
handle = win32api.GetStdHandle(win32console.STD_ERROR_HANDLE)
|
||||
if handle:
|
||||
win32file.WriteFile(handle, (message + '\n').encode('utf-8'))
|
||||
except pywintypes.error:
|
||||
pass
|
||||
return 1
|
||||
|
||||
|
||||
def _positive_int(value):
|
||||
try:
|
||||
number = int(value)
|
||||
@@ -171,14 +195,24 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
return dialog_agent_main(args.dialog_agent)
|
||||
if args.verify_worker:
|
||||
return _native_worker_entry('verify', args.verify_worker)
|
||||
context = configure(resolve_data_root(args.data_root)); logger = context.logger; logger.info("application_start")
|
||||
command_line = bool(args.batch_lmc or args.smoke_test)
|
||||
data_root = args.data_root
|
||||
try:
|
||||
data_root = resolve_data_root(data_root)
|
||||
context = configure(data_root)
|
||||
except (OSError, ValueError, RuntimeError):
|
||||
location = data_root if data_root is not None else '默认数据目录'
|
||||
return _report_entry_error(f'DATA_ROOT_UNWRITABLE: 无法写入数据目录 {location}。'
|
||||
'请指定可写的 --data-root。', command_line=command_line)
|
||||
logger = context.logger
|
||||
logger.info("application_start")
|
||||
try:
|
||||
if args.batch_lmc:
|
||||
from .verify_runner import (VerifyRequest, native_lm_verify_enabled,
|
||||
run_batch, write_batch_report, failure_report_path)
|
||||
from .library_reader import read_library_fast
|
||||
from .batch_status import authoritative_status_map
|
||||
from .network_path import LibraryPathLease, select_library_file
|
||||
from .network_path import LibraryPathLease, select_library_file, validate_library_file
|
||||
with LibraryPathLease.acquire(args.batch_lmc) as lease:
|
||||
mentor_path = select_library_file(lease.mentor_path)
|
||||
logger.info(
|
||||
@@ -186,15 +220,18 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
lease.display_path, mentor_path, lease.drive or '-',
|
||||
lease.remote_root or '-', lease.created)
|
||||
names = list(args.block)
|
||||
if not names:
|
||||
if names:
|
||||
validate_library_file(mentor_path)
|
||||
else:
|
||||
library = read_library_fast(
|
||||
mentor_path,
|
||||
status_reader=lambda path, names: authoritative_status_map(
|
||||
names, path, context.root/'status-scan.jsonl'),
|
||||
)
|
||||
if library.error: raise RuntimeError(library.error)
|
||||
if library.error: raise NetworkPathError(library.error)
|
||||
names = [record.name for record in library.records if record.status != 'READY']
|
||||
if not names: raise RuntimeError('中心库未读取到需要校验的 CBB')
|
||||
if not names:
|
||||
raise NetworkPathError('INPUT_NO_BLOCKS: 中心库未读取到需要校验的 CBB。')
|
||||
total = len(names)
|
||||
if args.limit is not None:
|
||||
names = names[:args.limit]
|
||||
@@ -248,6 +285,12 @@ def main(argv: Sequence[str] | None = None) -> int:
|
||||
logger.info('gui_smoke_window_created title=%s', window.windowTitle())
|
||||
QTimer.singleShot(250, app.quit)
|
||||
code = int(app.exec()); logger.info("application_clean_shutdown exit_code=%s", code); return code
|
||||
except Exception: logger.exception("application_startup_failure"); return 1
|
||||
except NetworkPathError as error:
|
||||
logger.warning('application_input_failure %s', error)
|
||||
return _report_entry_error(str(error), command_line=command_line)
|
||||
except Exception:
|
||||
logger.exception('application_startup_failure')
|
||||
return _report_entry_error(f'APPLICATION_STARTUP_FAILED: 无法完成启动或批次,请查看日志目录 {context.root}。',
|
||||
command_line=command_line)
|
||||
finally:
|
||||
for handler in logger.handlers: handler.flush()
|
||||
@@ -4,7 +4,7 @@ import logging
|
||||
import json
|
||||
from collections import Counter, defaultdict
|
||||
from .models import CbbRecord, LibraryReadResult
|
||||
from .network_path import absolute_preserving_drive
|
||||
from .network_path import absolute_preserving_drive, validate_library_file
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
CACHE_SCHEMA_VERSION = 2
|
||||
@@ -206,15 +206,7 @@ def read_library_fast(path: Path, *, status_reader=None):
|
||||
"""Discover directories; this does not validate native format/registration."""
|
||||
try:
|
||||
path = Path(path)
|
||||
if path.suffix.casefold() != '.lmc':
|
||||
return LibraryReadResult((), 'INPUT_SUFFIX: 请选择 .lmc 中心库文件。')
|
||||
if not path.is_file():
|
||||
return LibraryReadResult((), f'INPUT_MISSING: 中心库不存在或不是文件: {path}')
|
||||
with path.open('rb') as stream:
|
||||
if not stream.read(1):
|
||||
return LibraryReadResult((), 'INPUT_EMPTY: 中心库文件为空。')
|
||||
if any(lock.is_dir() for lock in (path.with_suffix('.lock'), path.with_name('.'+path.stem+'.cbb-upload.lock'))):
|
||||
return LibraryReadResult((), 'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录。')
|
||||
validate_library_file(path)
|
||||
folder = path.parent/'ReusableBlocksLP'
|
||||
if folder.exists() and not folder.is_dir():
|
||||
return LibraryReadResult((), f'INPUT_DIRECTORY: ReusableBlocksLP 不是目录: {folder}')
|
||||
|
||||
@@ -183,22 +183,41 @@ def _normalize_input_path(path) -> str:
|
||||
def select_library_file(path) -> Path:
|
||||
"""Return a concrete LMC, accepting a directory with exactly one LMC."""
|
||||
candidate = Path(path)
|
||||
if candidate.is_file():
|
||||
if candidate.suffix.casefold() != ".lmc":
|
||||
raise NetworkPathError(f"中心库文件必须是 .lmc: {candidate}")
|
||||
return candidate
|
||||
if candidate.is_dir():
|
||||
files = sorted(
|
||||
(item for item in candidate.iterdir()
|
||||
if item.is_file() and item.suffix.casefold() == ".lmc"),
|
||||
key=lambda item: item.name.casefold(),
|
||||
)
|
||||
if len(files) != 1:
|
||||
raise NetworkPathError(
|
||||
f"中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}"
|
||||
)
|
||||
return files[0]
|
||||
raise NetworkPathError(f"中心库路径不存在或不可访问: {candidate}")
|
||||
try:
|
||||
if candidate.is_file():
|
||||
if candidate.suffix.casefold() != ".lmc":
|
||||
raise NetworkPathError(f"INPUT_SUFFIX: 中心库文件必须是 .lmc: {candidate}")
|
||||
return candidate
|
||||
if candidate.is_dir():
|
||||
files = [item for item in candidate.iterdir()
|
||||
if item.suffix.casefold() == ".lmc" and item.is_file()]
|
||||
if len(files) != 1:
|
||||
raise NetworkPathError(
|
||||
f"INPUT_DIRECTORY: 中心库目录必须包含唯一的 .lmc 文件,当前找到 {len(files)} 个: {candidate}"
|
||||
)
|
||||
return files[0]
|
||||
except PermissionError as error:
|
||||
raise NetworkPathError(f"INPUT_PERMISSION: 无权读取中心库: {candidate}") from error
|
||||
raise NetworkPathError(f"INPUT_MISSING: 中心库路径不存在或不可访问: {candidate}")
|
||||
|
||||
|
||||
def validate_library_file(path: Path) -> None:
|
||||
"""Reject invalid LMC inputs before a directory scan or native dispatch."""
|
||||
if path.suffix.casefold() != '.lmc':
|
||||
raise NetworkPathError(f'INPUT_SUFFIX: 请选择 .lmc 中心库文件: {path}')
|
||||
try:
|
||||
if not path.is_file():
|
||||
raise NetworkPathError(f'INPUT_MISSING: 中心库不存在或不是文件: {path}')
|
||||
with path.open('rb') as stream:
|
||||
if not stream.read(1):
|
||||
raise NetworkPathError(f'INPUT_EMPTY: 中心库文件为空: {path}')
|
||||
if any(lock.is_dir() for lock in
|
||||
(path.with_suffix('.lock'), path.with_name('.' + path.stem + '.cbb-upload.lock'))):
|
||||
raise NetworkPathError(f'INPUT_LOCK_DIRECTORY: 中心库锁路径是目录: {path}')
|
||||
except FileNotFoundError as error:
|
||||
raise NetworkPathError(f'INPUT_MISSING: 中心库不存在: {path}') from error
|
||||
except PermissionError as error:
|
||||
raise NetworkPathError(f'INPUT_PERMISSION: 无权读取中心库: {path}') from error
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
Reference in new issue
Block a user