"""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 snapshot_process_ids(name): """Read executable names from the local process table without starting WMI.""" import ctypes from ctypes import wintypes class ProcessEntry(ctypes.Structure): _fields_ = [('size', wintypes.DWORD), ('usage', wintypes.DWORD), ('pid', wintypes.DWORD), ('heap_id', ctypes.c_size_t), ('module_id', wintypes.DWORD), ('threads', wintypes.DWORD), ('parent', wintypes.DWORD), ('priority', wintypes.LONG), ('flags', wintypes.DWORD), ('name', wintypes.WCHAR * 260)] kernel = ctypes.WinDLL('kernel32', use_last_error=True) kernel.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD] kernel.CreateToolhelp32Snapshot.restype = wintypes.HANDLE kernel.CloseHandle.argtypes = [wintypes.HANDLE] for step in (kernel.Process32FirstW, kernel.Process32NextW): step.argtypes = [wintypes.HANDLE, ctypes.POINTER(ProcessEntry)] step.restype = wintypes.BOOL handle = kernel.CreateToolhelp32Snapshot(2, 0) # TH32CS_SNAPPROCESS if handle == ctypes.c_void_p(-1).value: raise ctypes.WinError(ctypes.get_last_error()) try: entry = ProcessEntry(size=ctypes.sizeof(ProcessEntry)) found = [] processing = kernel.Process32FirstW(handle, ctypes.byref(entry)) while processing: if entry.name.casefold() == name.casefold(): found.append(entry.pid) processing = kernel.Process32NextW(handle, ctypes.byref(entry)) if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES raise ctypes.WinError(ctypes.get_last_error()) return found finally: kernel.CloseHandle(handle) 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) try: request = json.loads(job.read_text('utf-8')) except (OSError, ValueError): return 1 if not isinstance(request, dict): return 1 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 except OSError: # The supervisor may remove its temporary request while this helper exits. return 1 finally: pythoncom.CoUninitialize()