Files
cbb-refresh-verify-795/src/cbb_refresh_verify/owner_probe.py
T

89 lines
4.5 KiB
Python

"""Bound WMI enumeration in a read-only helper, never in the Qt thread."""
from pathlib import Path
import json
import re
import subprocess
import sys
import tempfile
def query_owners(names, *, timeout_seconds=10):
names = tuple(names)
if not names or any(not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names):
raise ValueError('OWNER_QUERY_INVALID')
return _query_processes(names, timeout_seconds=timeout_seconds)
def query_process_snapshot(*, timeout_seconds=10):
"""Bound a complete process tree; retain unknown executable descendants."""
return _query_processes(None, timeout_seconds=timeout_seconds)
def _query_processes(names, *, timeout_seconds):
full_snapshot = names is None
request = {'snapshot_version': 1} if full_snapshot else {'names': names}
with tempfile.TemporaryDirectory(prefix='cbb-owner-probe-') as directory:
job = Path(directory)/'request.json'
job.write_text(json.dumps(request), encoding='utf-8')
command = ([sys.executable] if getattr(sys, 'frozen', False) else
[sys.executable, '-m', 'cbb_refresh_verify']) + ['--owner-probe', str(job)]
try:
result = subprocess.run(command, timeout=max(.1, min(10, timeout_seconds)),
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
except subprocess.TimeoutExpired as error:
# This helper only enumerates processes; it never launches Mentor
# or acquires a native database session.
raise RuntimeError('OWNER_QUERY_TIMEOUT: 进程查询超时,占用状态无法确认') from error
try:
record = json.loads(job.with_name('result.json').read_text('utf-8'))
rows = record['owners']
identity_matches = (type(record.get('snapshot_version')) is int and record['snapshot_version'] == 1
if full_snapshot else record.get('names') == list(names))
if result.returncode != 0 or not identity_matches or not isinstance(rows, list):
raise ValueError('invalid result')
seen = set()
for row in rows:
if (type(row['pid']) is not int or row['pid'] < (0 if full_snapshot else 1)
or row['pid'] in seen or not isinstance(row['name'], str) or not row['name']
or not full_snapshot and row['name'].casefold() not in {n.casefold() for n in names}
or full_snapshot and not isinstance(row['created'], str)
or not isinstance(row['command'], str) or not isinstance(row['executable'], str)
or type(row['parent']) is not int or row['parent'] < 0):
raise ValueError('invalid owner')
seen.add(row['pid'])
return rows
except (OSError, ValueError, KeyError, TypeError, AttributeError) as error:
raise RuntimeError('OWNER_QUERY_UNCONFIRMED: 进程查询未返回有效证据') from error
def owner_probe_main(job):
import pythoncom
import win32com.client
job = Path(job)
request = json.loads(job.read_text('utf-8'))
full_snapshot = request == {'snapshot_version': 1} and type(request.get('snapshot_version')) is int
names = request.get('names')
if not full_snapshot:
if (not isinstance(names, list) or not names
or any(not isinstance(name, str) or not re.fullmatch(r'[\w.-]+\.exe', name, re.I) for name in names)):
return 1
pythoncom.CoInitialize()
try:
service = win32com.client.GetObject('winmgmts:')
query = ('SELECT ProcessId,Name,CommandLine,ExecutablePath,ParentProcessId' +
(',CreationDate' if full_snapshot else '') + ' FROM Win32_Process')
if not full_snapshot:
query += ' WHERE ' + ' OR '.join(f"Name='{name}'" for name in names)
rows = [{'pid': int(item.ProcessId), 'name': str(item.Name),
'command': str(item.CommandLine or ''), 'executable': str(item.ExecutablePath or ''),
'parent': int(item.ParentProcessId or 0),
**({'created': str(item.CreationDate or '')} if full_snapshot else {})}
for item in service.ExecQuery(query)]
service = None
response = {'snapshot_version': 1} if full_snapshot else {'names': names}
job.with_name('result.json').write_text(json.dumps({**response, 'owners': rows}), encoding='utf-8')
return 0
finally:
pythoncom.CoUninitialize()