"""Preview and cooperatively close the exact native sessions a user confirms.""" from contextlib import contextmanager import json import hashlib import os from pathlib import Path import re import time from uuid import uuid4 from .owner_probe import query_process_snapshot from .native_engineering_identity import _OWNER_NAMES _NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'icdbprojectbackup.exe', 'viewdraw.exe', 'icdbnetserver.exe', 'icdbserver.exe', 'reuseblockimporter.exe', 'cleanwglib.exe', 'cscript.exe', 'wscript.exe'} | _OWNER_NAMES _WORKER_NAMES = {'python.exe', 'pythonw.exe', 'cbbrefreshverify.exe'} _WORKER_FLAGS = ('--verify-worker', '--repair-worker', '--management-worker', '--native-backup-worker') _FORCE_CLIENT_NAMES = {'expeditionpcb.exe', 'librarymanager.exe', 'viewdraw.exe', 'icdbprojectbackup.exe'} def force_block_reason(row): """A library path proves scope, never exclusive ownership of a server.""" if row.get('runtime_phase') in ('NATIVE_CALL', 'CLOSING', 'UNCONFIRMED'): return '本工具的保存或原生调用尚未确认返回,请等待或查看原生提示' if row.get('scope_confirmed') is not True: return '进程归属未确认,不允许强制结束' name = str(row.get('name', '')).casefold() if name not in _FORCE_CLIENT_NAMES: return '服务器或其他受保护进程仅供观察,不允许强制结束' if (not row.get('created_handle') or not row.get('image') or Path(row['image']).name.casefold() != name): return '客户端身份未确认,不允许强制结束' if (row.get('force_user_confirmed') is not True or not row.get('owner_sid') or not isinstance(row.get('session_id'), int)): return '未确认属于当前用户和 Windows 会话,不允许强制结束' activity = row.get('native_activity', {}) if activity.get('status') in ('ACTIVE', 'UNCONFIRMED'): return activity.get('detail', '原生操作状态未确认')+';请查看进展或请求原生取消后重新检查' if name == 'icdbprojectbackup.exe' and activity.get('status') != 'IDLE': return '备份/恢复/修复状态未确认,请重新检查' return '' def native_activity(name, windows, *, incomplete=None): if incomplete or any(w['class'] == 'UNCONFIRMED' for w in windows): return {'status': 'UNCONFIRMED', 'detail': '原生窗口读取不完整'} if any((name.casefold() == 'icdbprojectbackup.exe' and not w['enabled']) or any(c['class'].casefold() == 'msctls_progress32' for c in w['children']) for w in windows): return {'status': 'ACTIVE', 'detail': '原生窗口显示操作进行中'} if name.casefold() == 'icdbprojectbackup.exe': main = [w for w in windows if w['class'].startswith('Afx:') and w['title'].startswith('iCDB Project Backup')] output = main[0].get('output') if len(main) == 1 else None if not isinstance(output, str) or not output.strip(): return {'status': 'UNCONFIRMED', 'detail': '无法确认备份/恢复/修复输出'} active = list(re.finditer(r'(?i)repairing|restoring|backing up|creating (?:a )?backup', output)) if active and max(output.rfind('Backup information loaded correctly.'), output.rfind('Repair project error [')) < active[-1].start(): return {'status': 'ACTIVE', 'detail': '原生备份/恢复/修复尚未确认结束', 'output': output} return {'status': 'IDLE', 'detail': '未观察到进行中的原生操作'} @contextmanager def _process_handle(pid, *, terminate=False): import win32api, win32con handle = win32api.OpenProcess(win32con.SYNCHRONIZE | 0x1000 | (1 if terminate else 0), False, int(pid)) try: yield handle finally: handle.Close() def _handle_identity(handle): import ctypes from ctypes import wintypes import win32process kernel = ctypes.WinDLL('kernel32', use_last_error=True) kernel.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD)] kernel.QueryFullProcessImageNameW.restype = wintypes.BOOL buffer = ctypes.create_unicode_buffer(32768) length = wintypes.DWORD(len(buffer)) if not kernel.QueryFullProcessImageNameW(int(handle), 0, buffer, ctypes.byref(length)): raise ctypes.WinError(ctypes.get_last_error()) return {'created_handle': win32process.GetProcessTimes(handle)['CreationTime'].isoformat(), 'image': buffer.value} def _process_identity(row): with _process_handle(row['pid']) as handle: identity = _handle_identity(handle) try: identity.update(_force_ownership(handle, row['pid'])) except Exception as error: identity.update(force_user_confirmed=False, owner_error=str(error)) return identity def _force_ownership(handle, pid): import win32api, win32con, win32process, win32security, win32ts if win32process.GetProcessId(handle) != pid: raise ValueError('进程身份已变化') def owner(process): token = win32security.OpenProcessToken(process, win32con.TOKEN_QUERY) try: return win32security.ConvertSidToStringSid( win32security.GetTokenInformation(token, win32security.TokenUser)[0]) finally: token.Close() sid = owner(handle) session = win32ts.ProcessIdToSessionId(pid) return {'owner_sid': sid, 'session_id': session, 'force_user_confirmed': sid == owner(win32api.GetCurrentProcess()) and session == win32ts.ProcessIdToSessionId(os.getpid())} class _WindowSnapshot(dict): def __init__(self, pids): super().__init__((pid, []) for pid in pids) self.incomplete = {} def _process_threads(pids): import ctypes from ctypes import wintypes class ThreadEntry(ctypes.Structure): _fields_ = [('size', wintypes.DWORD), ('usage', wintypes.DWORD), ('tid', wintypes.DWORD), ('pid', wintypes.DWORD), ('base', wintypes.LONG), ('delta', wintypes.LONG), ('flags', wintypes.DWORD)] 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 name in ('Thread32First', 'Thread32Next'): function = getattr(kernel, name) function.argtypes = [wintypes.HANDLE, ctypes.POINTER(ThreadEntry)] function.restype = wintypes.BOOL snapshot = kernel.CreateToolhelp32Snapshot(4, 0) # TH32CS_SNAPTHREAD if snapshot == ctypes.c_void_p(-1).value: raise ctypes.WinError(ctypes.get_last_error()) result = {pid: [] for pid in pids} try: entry = ThreadEntry(); entry.size = ctypes.sizeof(entry) more = kernel.Thread32First(snapshot, ctypes.byref(entry)) while more: if entry.pid in result: result[entry.pid].append(int(entry.tid)) entry.size = ctypes.sizeof(entry) more = kernel.Thread32Next(snapshot, ctypes.byref(entry)) if ctypes.get_last_error() != 18: # ERROR_NO_MORE_FILES raise ctypes.WinError(ctypes.get_last_error()) finally: kernel.CloseHandle(snapshot) return result def _thread_desktop_name(tid): import ctypes from ctypes import wintypes user = ctypes.WinDLL('user32', use_last_error=True) user.GetThreadDesktop.argtypes = [wintypes.DWORD] user.GetThreadDesktop.restype = wintypes.HANDLE user.GetUserObjectInformationW.argtypes = [wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)] user.GetUserObjectInformationW.restype = wintypes.BOOL ctypes.set_last_error(0) desktop = user.GetThreadDesktop(tid) if not desktop: if error := ctypes.get_last_error(): raise ctypes.WinError(error) return None # A non-GUI thread need not have an assigned desktop. # GetThreadDesktop returns a borrowed handle; never CloseDesktop it. name, needed = ctypes.create_unicode_buffer(512), wintypes.DWORD() if not user.GetUserObjectInformationW(desktop, 2, name, ctypes.sizeof(name), ctypes.byref(needed)): raise ctypes.WinError(ctypes.get_last_error()) return name.value def _window_error(snapshot, pid): return getattr(snapshot, 'incomplete', {}).get(pid) def _process_windows(pids): result = _WindowSnapshot(pids) if not pids: return result import win32api, win32con, win32gui, win32process, win32service from .native_repair_ui import _native_output observed = set() def capture(hwnd, _, *, pid, desktop_name): if win32process.GetWindowThreadProcessId(hwnd)[1] != pid: raise ValueError('窗口所属进程已变化') if hwnd in observed or not win32gui.IsWindowVisible(hwnd): return if desktop_name is None: raise ValueError('窗口所属桌面无法读取') observed.add(hwnd) children, documents = [], [] def child(handle, _): kind = win32gui.GetClassName(handle) if kind == 'MDIClient' and win32gui.GetWindow(handle, win32con.GW_CHILD): documents.append(handle) if win32gui.IsWindowVisible(handle): children.append({'hwnd': int(handle), 'class': kind, 'id': win32gui.GetDlgCtrlID(handle) & 0xffff, 'text': win32gui.GetWindowText(handle), 'enabled': bool(win32gui.IsWindowEnabled(handle))}) win32api.SetLastError(0) win32gui.EnumChildWindows(hwnd, child, None) window = {'hwnd': int(hwnd), 'title': win32gui.GetWindowText(hwnd), 'desktop': desktop_name, 'class': win32gui.GetClassName(hwnd), 'enabled': bool(win32gui.IsWindowEnabled(hwnd)), 'children': children, 'documents': documents, 'rect': list(win32gui.GetWindowRect(hwnd))} if any(c['class'].casefold().startswith('richedit') for c in children): window['output'] = _native_output([window]) result[pid].append(window) try: threads = _process_threads(pids) except Exception as error: result.incomplete = {pid: str(error)[:500] for pid in pids} return result desktops = {} for pid in pids: if not threads.get(pid): result.incomplete[pid] = '进程线程已退出或暂时无法读取' for tid in threads.get(pid, ()): try: desktop = _thread_desktop_name(tid) if desktop: desktops.setdefault(desktop, set()).add(pid) except Exception as error: result.incomplete.setdefault(pid, str(error)[:500]) if not any(pid in members for members in desktops.values()): result.incomplete.setdefault(pid, '窗口所属桌面暂时无法确认') # EnumThreadWindows silently omits windows on other desktops. Enumerate # only desktops actually assigned to the target processes' threads. for name, members in desktops.items(): desktop = None try: desktop = win32service.OpenDesktop(name, 0, False, win32con.DESKTOP_READOBJECTS) win32api.SetLastError(0) for hwnd in desktop.EnumDesktopWindows(): pid = None try: pid = win32process.GetWindowThreadProcessId(hwnd)[1] if pid in members: capture(hwnd, None, pid=pid, desktop_name=name) except Exception as error: for affected in (members if pid is None else {pid} & members): result.incomplete.setdefault(affected, str(error)[:500]) except Exception as error: for pid in members: result.incomplete.setdefault(pid, str(error)[:500]) finally: if desktop is not None: desktop.CloseDesktop() return result def _project_name(row, library): from .failed_session import _command_args for arg in _command_args(row['command'])[1:]: try: relative = Path(arg.split('=', 1)[-1]).relative_to(library.parent/'ReusableBlocksLP') if len(relative.parts) >= 2 and relative.parts[1].casefold() == 'work': return relative.parts[0] except ValueError: continue return '当前库关联会话' def close_target(name, windows, *, incomplete=None): """No save/restore approval and no close against an unknown modal/window.""" if incomplete: return None, '该会话窗口读取不完整,请重新检查:'+str(incomplete) main = [w for w in windows if w['class'].startswith('Afx:') and ( name.casefold() == 'icdbprojectbackup.exe' and w['title'].startswith('iCDB Project Backup') or name.casefold() == 'librarymanager.exe' and w['title'].startswith('Library Manager') or name.casefold() == 'expeditionpcb.exe' and 'Expedition PCB' in w['title'])] if len(main) != 1: return None, '未确认空闲主窗口;有工程时请先在原生窗口保存并关闭' window = main[0] for other in windows: if other is window: continue benign = (not other['title'] and other['class'] in ('UAC_InputIndicatorOverlayWnd', 'UAC Input Indicator')) benign = benign or (other['class'] == 'Internet Explorer_Hidden' and not other['title'] and not other.get('children') and other.get('rect', [1, 1, 2, 2])[0:2] == other.get('rect', [1, 1, 2, 2])[2:4]) if not benign: return None, '存在原生弹窗,请先处理该窗口后重新检查' if not window['enabled']: return None, '原生程序正在工作,请稍后重新检查' if any(c['class'].casefold() == 'msctls_progress32' for c in window['children']): return None, '原生操作尚未结束' if name.casefold() == 'icdbprojectbackup.exe': output = window.get('output') if not isinstance(output, str): return None, '原生输出尚无法确认,请重新检查' active = list(re.finditer(r'(?i)repairing|restoring|backing up|creating (?:a )?backup', output)) last_load = output.rfind('Backup information loaded correctly.') failure = output.rfind('Repair project error [') if active and max(last_load, failure) < active[-1].start(): return None, '备份、恢复或修复需要在原生窗口确认结束后再释放' return window, ('将正常关闭工程;未保存时等待确认' if window.get('documents') else '可正常关闭') def _save_question(windows, *, incomplete=None): if incomplete: return None for window in windows: text = '\n'.join(c['text'] for c in window['children'] if c['class'] == 'Static') buttons = {c['id']: c for c in window['children'] if c['class'] == 'Button' and c['enabled']} if (window['class'] == '#32770' and 'Expedition' in window['title'] and re.search(r'\bsave\b', text, re.I) and re.search(r'changes|modified', text, re.I) and set(buttons) == {6, 7, 2}): return {'hwnd': window['hwnd'], 'text': text, 'buttons': buttons, 'desktop': window.get('desktop', '')} return None def _cancel_question(name, windows, *, incomplete=None): if (name.casefold() != 'icdbprojectbackup.exe' or native_activity(name, windows, incomplete=incomplete)['status'] != 'ACTIVE'): return None candidates = [] for window in windows: if not (window['class'].startswith('Afx:') or window['class'] == '#32770'): continue if not window['title'].startswith('iCDB Project Backup') or not window['enabled']: continue for button in window['children']: if (button['class'] == 'Button' and button.get('id') == 2 and button.get('enabled') and button.get('text', '').replace('&', '').strip() in ('Cancel', '取消')): candidates.append({'hwnd': window['hwnd'], 'button': button, 'title': window['title'], 'desktop': window.get('desktop', '')}) return candidates[0] if len(candidates) == 1 else None def inspect_residual_sessions(library, *, block_names=()): from .library_lock import _owner_matches_scope, blocker_path, checkpoint_record, has_retained_library library = Path(library).resolve() if library.suffix.casefold() != '.lmc': raise ValueError('请选择中心库 .lmc 文件') if not library.is_file(): raise ValueError('中心库路径当前不可见,请检查文件是否存在及网络盘映射后重新检查') blocks = tuple(dict.fromkeys(str(name) for name in block_names)) if any(not name or name in ('.', '..') or any(c in name for c in '\\/:*?"<>|') for name in blocks): raise ValueError('残留检查的工程名称无效') roots = tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks) + (library.parent/'SymbolLibs',) if not blocks: roots = (library.parent,) candidates = [] for row in query_process_snapshot(): if row['pid'] == os.getpid(): continue native = row['name'].casefold() in _NAMES worker = (row['name'].casefold() in _WORKER_NAMES and any(flag in row['command'].casefold() for flag in _WORKER_FLAGS)) if not (native or worker): continue scope = _owner_matches_scope(row, library, roots) if scope is not False: candidates.append({**row, 'scope_confirmed': scope is True}) windows = _process_windows({r['pid'] for r in candidates}) from .session_record import active_write_records runtime_writes = active_write_records(library) sessions = [] for row in candidates: item = dict(row) item['library'] = str(library) if runtime_writes and row['scope_confirmed']: item['runtime_phase'] = runtime_writes[0]['phase'] item['block_names'] = list(blocks) error = _window_error(windows, row['pid']) item.update(windows_incomplete=bool(error), window_read_error=error) try: item.update(_process_identity(row)) target, detail = close_target(row['name'], windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else ( None, '归属未确认,请在原生窗口确认工程并关闭后重新检查') item.update(can_close=target is not None, detail=detail) except Exception as identity_error: item.update(can_close=False, detail=f'进程已变化或暂时无法确认:{identity_error}') item['project'] = _project_name(row, library) if row['scope_confirmed'] else '归属未确认' item['prompt'] = _save_question(windows.get(row['pid'], []), incomplete=error) if row['scope_confirmed'] else None observed = windows.get(row['pid'], []) item['windows'] = observed item['desktops'] = sorted({w.get('desktop', '') for w in observed if w.get('desktop')}) item['native_activity'] = native_activity(row['name'], observed, incomplete=error) item['cancel_prompt'] = (_cancel_question(row['name'], observed, incomplete=error) if row['scope_confirmed'] and item.get('force_user_confirmed') is True else None) if any(name.startswith('Cbb') for name in item['desktops']) and not item['can_close']: item['detail'] += ';窗口在后台,可查看原生提示并使用已提供的保存/取消操作' item['force_block_reason'] = force_block_reason(item) item['force_allowed'] = not item['force_block_reason'] if item['force_block_reason']: item['detail'] += ';'+item['force_block_reason'] sessions.append(item) previous = [] marker = blocker_path(library) for path in (marker, marker.with_suffix('.pending')): if path.exists(): record = checkpoint_record(path) previous.append({'path': str(path), 'recognized': record is not None, 'status': record.get('status', 'UNRECOGNIZED') if record else 'UNRECOGNIZED', 'time': record.get('time', '') if record else '', 'pid': record.get('pid') if record else None}) if has_retained_library(library): previous.append({'path': str(library), 'status': 'RETAINED_IN_MEMORY', 'time': '', 'pid': os.getpid(), 'kind': 'in_memory'}) return {'library': str(library), 'block_names': list(blocks), 'sessions': sessions, 'previous_records': previous} def _request_close(row, *, stop=None): import win32con, win32event, win32gui, win32process with _process_handle(row['pid']) as handle: if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0: return {'release_status': 'RELEASED', 'detail': '已退出'} identity = _handle_identity(handle) if identity != {key: row.get(key) for key in ('created_handle', 'image')}: return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未关闭'} snapshot = _process_windows({row['pid']}) windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid']) if error: return {'release_status': 'WAITING', 'detail': '该会话窗口读取不完整,请重新检查:'+error} if row['name'].casefold() == 'expeditionpcb.exe': from .failed_session import _startup_snapshot, _cancel_target for window in windows: if window['class'] != '#32770': continue target = _cancel_target(_startup_snapshot(window['hwnd'], row['pid'])) if target: win32gui.PostMessage(target[1].handle, win32con.BM_CLICK, 0, 0) deadline = time.monotonic()+3 while time.monotonic() < deadline: if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0: return {'release_status': 'RELEASED', 'detail': '已取消启动并退出'} if stop is not None and stop.is_set(): return {'release_status': 'CANCELLED', 'detail': '已停止释放'} snapshot = _process_windows({row['pid']}) windows, error = snapshot.get(row['pid'], []), _window_error(snapshot, row['pid']) if error: break if close_target(row['name'], windows)[0] is not None: break break target, detail = close_target(row['name'], windows, incomplete=error) if target is None: return {'release_status': 'WAITING', 'detail': detail} if stop is not None and stop.is_set(): return {'release_status': 'CANCELLED', 'detail': '已停止释放'} if win32process.GetWindowThreadProcessId(target['hwnd'])[1] != row['pid']: return {'release_status': 'IDENTITY_CHANGED', 'detail': '窗口归属已变化,未关闭'} win32gui.PostMessage(target['hwnd'], win32con.WM_CLOSE, 0, 0) deadline = time.monotonic()+3 while time.monotonic() < deadline: if win32event.WaitForSingleObject(handle, 100) == win32con.WAIT_OBJECT_0: return {'release_status': 'RELEASED', 'detail': '已正常退出'} if stop is not None and stop.is_set(): break return {'release_status': 'WAITING', 'detail': '已请求正常关闭;请处理原生窗口,完成后重新检查'} def _force_close(row, *, stop=None): """Separate UI consent permits ending only this exact, scoped process handle.""" import win32api, win32con, win32event if stop is not None and stop.is_set(): return {'release_status': 'CANCELLED', 'detail': '已停止释放'} if row.get('library'): from .session_record import active_write_records if active_write_records(row['library']): return {'release_status': 'WAITING', 'detail': '保存或原生调用尚未确认返回,未强制结束'} if reason := force_block_reason(row): return {'release_status': 'WAITING', 'detail': reason} with _process_handle(row['pid'], terminate=True) as handle: if win32event.WaitForSingleObject(handle, 0) == win32con.WAIT_OBJECT_0: return {'release_status': 'RELEASED', 'detail': '已退出'} if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}: return {'release_status': 'IDENTITY_CHANGED', 'detail': '进程身份已变化,未结束'} ownership = _force_ownership(handle, row['pid']) if (not ownership['force_user_confirmed'] or any(ownership[k] != row.get(k) for k in ('owner_sid', 'session_id'))): return {'release_status': 'IDENTITY_CHANGED', 'detail': '用户或 Windows 会话已变化,未结束'} snapshot = _process_windows({row['pid']}) activity = native_activity(row['name'], snapshot.get(row['pid'], []), incomplete=_window_error(snapshot, row['pid'])) if reason := force_block_reason({**row, 'native_activity': activity}): return {'release_status': 'WAITING', 'detail': reason, 'native_activity': activity} if stop is not None and stop.is_set(): return {'release_status': 'CANCELLED', 'detail': '已停止释放,未强制结束'} win32api.TerminateProcess(handle, 1) exited = win32event.WaitForSingleObject(handle, 3000) == win32con.WAIT_OBJECT_0 return {'release_status': 'RELEASED' if exited else 'WAITING', 'detail': '已强制结束客户端,工程待检查,未执行修复' if exited else '已请求结束客户端,等待退出'} def _finish_library_release(library, evidence): from .library_lock import release_retained_library return release_retained_library(library, evidence) def _request_native_cancel(row, *, stop=None): """Only click the exact currently visible Cancel control the user confirmed.""" import win32con, win32gui, win32process if row.get('scope_confirmed') is not True: raise ValueError('取消目标归属未确认,请重新检查') fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None) if fresh is None or any(fresh.get(k) != row.get(k) for k in ('created', 'command', 'executable', 'name')): raise ValueError('取消目标身份已变化,请重新检查') with _process_handle(row['pid']) as handle: if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}: raise ValueError('取消目标身份已变化,请重新检查') owner = _force_ownership(handle, row['pid']) if not owner['force_user_confirmed'] or any(owner[k] != row.get(k) for k in ('owner_sid', 'session_id')): raise ValueError('取消目标用户/会话已变化') snapshot = _process_windows({row['pid']}) prompt = _cancel_question(row['name'], snapshot.get(row['pid'], []), incomplete=_window_error(snapshot, row['pid'])) if not prompt or prompt != row.get('cancel_prompt'): raise ValueError('原生取消按钮已变化,请重新检查') button = prompt['button'] if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']: raise ValueError('原生取消按钮归属已变化') if stop is not None and stop.is_set(): return {'release_status': 'CANCELLED', 'detail': '已停止,未请求原生取消'} win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0) return {'release_status': 'WAITING', 'detail': '已请求原生取消,需重新检查实际结果;未强制结束'} def request_native_cancel(row, library, evidence_dir, *, stop=None): # Reuse serialized admission, consent and incremental evidence for cancellation. plan = {'library': str(library), 'sessions': [row], 'block_names': row.get('block_names', [])} return release_residual_sessions(plan, evidence_dir, stop=stop, cancel_native=True) def _session_evidence(row): """Keep the full preview in memory, but bound repeatedly written Output.""" value = dict(row) if 'native_activity' in value: value['native_activity'] = {k: v for k, v in value['native_activity'].items() if k != 'output'} if 'windows' in value: value['windows'] = [] for window in row['windows']: saved = {k: window[k] for k in ('hwnd', 'title', 'class', 'desktop', 'enabled') if k in window} output = window.get('output') if isinstance(output, str): data = output.encode('utf-8') saved.update(output_excerpt=data[:4096].decode('utf-8', errors='ignore'), output_bytes=len(data), output_sha256=hashlib.sha256(data).hexdigest(), output_truncated=len(data) > 4096) value['windows'].append(saved) return value def _release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False): library = Path(plan['library']).resolve() root = Path(evidence_dir).resolve()/('sessions-'+uuid4().hex[:12]) if root.is_relative_to(library.parent) or library.parent.is_relative_to(root): raise ValueError('释放记录需位于中心库之外') root.mkdir(parents=True) result = {'status': 'PARTIAL', 'library': str(library), 'sessions': [ {**row, 'release_status': 'NOT_STARTED', 'detail': '尚未执行', 'consent_allowed': not force_block_reason(row) if force else row.get('scope_confirmed') is True} for row in plan['sessions']], 'force': force, 'cancel_native': cancel_native, 'evidence_path': str(root/'result.json'), 'previous_records': plan.get('previous_records', [])} def save(): from .management import _write_json try: result['report_saved'] = True _write_json(root/'result.json', {**result, 'sessions': [_session_evidence(row) for row in result['sessions']]}) return True except OSError as error: result.update(status='PARTIAL', report_saved=False, evidence_error=str(error)) return False if not save(): return result # No native actions without the initial checkpoint. if force or cancel_native: consent_path = root/'consent.json' consent = {'version': 1, 'mode': 'cancel_native' if cancel_native else 'force_document_clients', 'library': str(library), 'time_ns': time.time_ns(), 'sessions': [ {**_session_evidence(row), 'force_allowed': not force_block_reason(row), 'cancel_allowed': bool(row.get('cancel_prompt')) and row.get('scope_confirmed') is True, 'force_block_reason': force_block_reason(row)} for row in plan['sessions']]} try: with consent_path.open('x', encoding='utf-8') as stream: json.dump(consent, stream, ensure_ascii=False, indent=2) stream.flush(); os.fsync(stream.fileno()) except OSError as error: result['detail'] = f'确认记录保存失败,未执行:{error}' save() raise result['consent_path'] = str(consent_path) try: fresh = {r['pid']: r for r in query_process_snapshot()} blocks = plan.get('block_names', ()) roots = (tuple(library.parent/'ReusableBlocksLP'/b/'Work' for b in blocks) + (library.parent/'SymbolLibs',)) if blocks else (library.parent,) # Close native children first; keep output rows in the original preview order. ordered = sorted(result['sessions'], key=lambda r: r['name'].casefold() in _WORKER_NAMES) for row in ordered: current = fresh.get(row['pid']) outcome = {'release_status': 'RELEASED', 'detail': '已退出'} if stop is not None and stop.is_set(): outcome = {'release_status': 'CANCELLED', 'detail': '已停止释放'} elif current is not None: from .library_lock import _owner_matches_scope scoped = _owner_matches_scope(current, library, roots) is True if row.get('scope_confirmed') is not True or not scoped or row['pid'] == os.getpid(): outcome = {'release_status': 'WAITING', 'detail': '未在确认名单中证明属于当前库,未关闭;请重新检查'} elif not row.get('created') or any(current.get(key) != row.get(key) for key in ('created', 'executable', 'command', 'name')): outcome = {'release_status': 'IDENTITY_CHANGED', 'detail': '确认后进程身份已变化,未关闭'} elif force and (reason := force_block_reason(row)): outcome = {'release_status': 'WAITING', 'detail': reason, 'force_allowed': False} else: row.update(release_status='REQUESTING', detail='正在请求原生操作,结果待确认') if not save(): return result try: outcome = (_request_native_cancel(row, stop=stop) if cancel_native else (_force_close if force else _request_close)(row, stop=stop)) except Exception as error: outcome = {'release_status': 'WAITING', 'detail': str(error)} row.update(outcome) if not save(): return result # Preserve completed facts; stop further actions on storage failure. after = {r['pid']: r for r in query_process_snapshot()} remaining_windows = _process_windows({r['pid'] for r in result['sessions'] if r['release_status'] == 'WAITING' and r['pid'] in after}) for row in result['sessions']: if row['release_status'] == 'WAITING' and row['pid'] not in after: row.update(release_status='RELEASED', detail='已退出') elif row['release_status'] == 'WAITING': windows = remaining_windows.get(row['pid'], []) error = _window_error(remaining_windows, row['pid']) row.update(prompt=_save_question(windows, incomplete=error), windows=windows, windows_incomplete=bool(error), window_read_error=error, cancel_prompt=(_cancel_question(row['name'], windows, incomplete=error) if row.get('force_user_confirmed') is True else None), native_activity=native_activity(row['name'], windows, incomplete=error)) if all(row['release_status'] == 'RELEASED' for row in result['sessions']) and not (stop and stop.is_set()): result['proof'] = _finish_library_release(library, root/'library-proof') proof = result['proof'] if (proof.get('status') != 'RELEASE_CONFIRMED' or Path(proof.get('library', '')).resolve() != library): raise ValueError('释放证明与当前库不一致') result['status'] = 'RELEASE_CONFIRMED' from .session_record import record_session_release errors = record_session_release(proof, plan.get('runtime_sessions', [])) if errors: result['evidence_error'] = ';'.join(errors) except BaseException as error: result.update(status='PARTIAL', detail=f'{type(error).__name__}: {error}') if not isinstance(error, Exception): raise finally: save() return result def release_residual_sessions(plan, evidence_dir, *, stop=None, force=False, cancel_native=False): import win32con, win32event mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') acquired = False try: deadline = time.monotonic()+15 while time.monotonic() < deadline and not (stop and stop.is_set()): acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) if acquired: break time.sleep(.2) if not acquired: return {'status': 'PARTIAL', 'library': plan['library'], 'sessions': [ {**r, 'release_status': 'WAITING', 'detail': '其它批次尚在执行;请停止该批次后重试'} for r in plan['sessions']], 'detail': '未取得执行通道,未关闭任何进程。'} return _release_residual_sessions(plan, evidence_dir, stop=stop, force=force, cancel_native=cancel_native) finally: if acquired: win32event.ReleaseMutex(mutex) mutex.Close() def answer_save_question(row, choice): """Only the exact displayed save question receives an explicit user answer.""" import win32con, win32event, win32gui if choice not in (6, 7, 2): raise ValueError('无效的保存选择') mutex = win32event.CreateMutex(None, False, r'Local\CbbRefreshVerify795') acquired = win32event.WaitForSingleObject(mutex, 0) in (win32con.WAIT_OBJECT_0, win32con.WAIT_ABANDONED) if not acquired: mutex.Close() raise ValueError('其它批次正在执行,请稍后处理保存提示') try: _answer_save_question(row, choice) finally: win32event.ReleaseMutex(mutex) mutex.Close() def _answer_save_question(row, choice): import win32con, win32gui fresh = next((r for r in query_process_snapshot() if r['pid'] == row['pid']), None) if fresh is None or any(fresh.get(k) != row.get(k) for k in ('created', 'command', 'executable')): raise ValueError('进程已变化,请重新检查') with _process_handle(row['pid']) as handle: if _handle_identity(handle) != {k: row.get(k) for k in ('created_handle', 'image')}: raise ValueError('进程已变化,请重新检查') snapshot = _process_windows({row['pid']}) prompt = _save_question(snapshot.get(row['pid'], []), incomplete=_window_error(snapshot, row['pid'])) if not prompt or prompt != row.get('prompt'): raise ValueError('原生提示已变化,请重新检查') button = prompt['buttons'][choice] import win32process if win32process.GetWindowThreadProcessId(button['hwnd'])[1] != row['pid']: raise ValueError('保存按钮归属已变化') win32gui.PostMessage(button['hwnd'], win32con.BM_CLICK, 0, 0)