feat: inspect windows browser process identity

This commit is contained in:
QiuSW
2026-07-22 14:59:57 +08:00
parent 23be05210b
commit d6f6bb0f2c
8 changed files with 370 additions and 3 deletions
+1 -1
View File
@@ -15,7 +15,7 @@
| ID | 任务 | 依赖 | 状态 |
| --- | --- | --- | --- |
| T-101 | 实现启动、registry、Wait 和 profile 占用检测 | T-003 | DONE |
| T-102 | 实现 Windows 进程身份查询和外部实例保守识别 | T-101 | TODO |
| T-102 | 实现 Windows 进程身份查询和外部实例保守识别 | T-101 | DONE |
| T-103 | 实现优雅关闭、强制关闭和 Job Object 进程树 | T-102 | TODO |
| T-104 | Chrome/Edge 双实例、异常退出和权限失败 smoke | T-103 | TODO |
+2 -2
View File
@@ -4,10 +4,10 @@
- 日期:2026-07-22
- 阶段:文档与交互原型准备
- 代码:已建立 Go module `chub`、`cmd/chub` 入口、logging 测试基座、浏览器 domain/application 合约、Chrome/Edge 参数/发现模块和启动 registry,T-001 至 T-003、T-101 已完成
- 代码:已建立 Go module `chub`、`cmd/chub` 入口、logging 测试基座、浏览器 domain/application 合约、Chrome/Edge 参数/发现模块、启动 registry 和 Windows 身份/占用检查,T-001 至 T-003、T-101、T-102 已完成
- UI:尚未实现;P0 页面需要先制作 HTML 原型
- 浏览器核心:设计参考来自 `D:\OPC\shop_helm\internal\platform\chrome`,尚未复制或接入本项目
- blocker:无;下一个任务为 T-102
- blocker:无;下一个任务为 T-103
## 当前目录
+36
View File
@@ -0,0 +1,36 @@
---
id: T-102
title: 实现 Windows 进程身份查询和外部实例保守识别
phase: 1
deps: [T-101]
status: DONE
created: 2026-07-22
owner: codex
---
## 需求与背景
Chub 重启后不能只依赖本进程 registry 判断 profile 状态;需要读取 Windows 进程和 Chromium profile 的系统证据,同时避免误认或误关闭外部进程。
## 方案与边界
- Windows 使用 `QueryFullProcessImageNameW` 查询 executable,使用进程句柄和 `WaitForSingleObject` 判断存活。
- 使用 `Chrome_MessageWindow` + user data dir 识别 Chrome/Edge profile singleton。
- 使用 lockfile sharing violation 作为占用证据;stale lock 和 stale PID 只记录来源,不转化为可关闭实例。
- executable 名称必须与浏览器类型匹配;无法确认时返回 unknown source。
- 非 Windows 编译为明确 unsupported 降级。
## 验收要点
- 当前测试进程可读取 executable 和 alive 状态。
- Chrome/Edge executable 类型匹配校验通过。
- 外部 profile 检查不会只凭历史 PID 直接授权关闭。
- `go test ./...`、`go vet ./...` 通过。
## 执行记录
- 状态:DONE
- 变更:新增跨平台 identity port、Windows Win32 实现、message window/lockfile profile inspector 和非 Windows 降级。
- 验证:`gofmt`、`go test ./...`、`go vet ./...` 均通过;包含真实 Windows 当前进程查询。
- 阻塞:无。
- 残余风险:真实 Chrome/Edge profile lock 占用仍需 T-104 用临时 profile smoke 验证。
+82
View File
@@ -0,0 +1,82 @@
package browser
import (
"context"
"errors"
"fmt"
"strings"
"chub/internal/domain"
)
const (
ProfileSourceMessageWindow = "browser_message_window"
ProfileSourceLock = "browser_lock"
ProfileSourceStaleLock = "stale_lock"
ProfileSourceStalePID = "stale_pid"
ProfileSourceUnknown = "unknown"
)
var ErrIdentityUnavailable = errors.New("browser process identity is unavailable")
type ProcessIdentity struct {
PID int
Executable string
CommandLine string
UserDataDir string
}
type ProcessInspector interface {
Inspect(context.Context, int) (ProcessIdentity, error)
Alive(context.Context, int) (bool, error)
}
type ExternalProfileInspector interface {
InspectProfile(context.Context, domain.BrowserKind, string, int) (ProfileUse, error)
}
type RuntimeInspector struct {
process ProcessInspector
profiles ExternalProfileInspector
}
func NewRuntimeInspector(process ProcessInspector, profiles ExternalProfileInspector) *RuntimeInspector {
return &RuntimeInspector{process: process, profiles: profiles}
}
func (i *RuntimeInspector) InspectProcess(ctx context.Context, pid int) (ProcessIdentity, error) {
if i == nil || i.process == nil {
return ProcessIdentity{}, ErrIdentityUnavailable
}
return i.process.Inspect(ctx, pid)
}
func (i *RuntimeInspector) InspectProfile(ctx context.Context, kind domain.BrowserKind, userDataDir string, historicalPID int) (ProfileUse, error) {
if i == nil || i.profiles == nil {
return ProfileUse{}, ErrIdentityUnavailable
}
return i.profiles.InspectProfile(ctx, kind, userDataDir, historicalPID)
}
func expectedExecutableName(kind domain.BrowserKind) string {
if kind == domain.BrowserEdge {
return "msedge.exe"
}
return "chrome.exe"
}
func executableMatchesKind(path string, kind domain.BrowserKind) bool {
return strings.EqualFold(pathBase(path), expectedExecutableName(kind))
}
func pathBase(path string) string {
path = strings.TrimRight(path, `\\/`)
if index := strings.LastIndexAny(path, `\\/`); index >= 0 {
return path[index+1:]
}
return path
}
func unsupportedError() error {
return fmt.Errorf("%w: Windows process inspection is unavailable", ErrIdentityUnavailable)
}
@@ -0,0 +1,27 @@
//go:build !windows
package browser
import (
"context"
"chub/internal/domain"
)
type unsupportedProcessInspector struct{}
func NewWindowsProcessInspector() ProcessInspector { return unsupportedProcessInspector{} }
func NewWindowsProfileInspector() ExternalProfileInspector { return unsupportedProfileInspector{} }
func (unsupportedProcessInspector) Inspect(context.Context, int) (ProcessIdentity, error) {
return ProcessIdentity{}, unsupportedError()
}
func (unsupportedProcessInspector) Alive(context.Context, int) (bool, error) {
return false, unsupportedError()
}
type unsupportedProfileInspector struct{}
func (unsupportedProfileInspector) InspectProfile(context.Context, domain.BrowserKind, string, int) (ProfileUse, error) {
return ProfileUse{}, unsupportedError()
}
@@ -0,0 +1,19 @@
package browser
import (
"testing"
"chub/internal/domain"
)
func TestExecutableMatchesKind(t *testing.T) {
if !executableMatchesKind(`C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe`, domain.BrowserChrome) {
t.Fatal("Chrome executable was not recognized")
}
if !executableMatchesKind(`C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe`, domain.BrowserEdge) {
t.Fatal("Edge executable was not recognized")
}
if executableMatchesKind("other.exe", domain.BrowserChrome) {
t.Fatal("unrelated executable was recognized")
}
}
@@ -0,0 +1,179 @@
//go:build windows
package browser
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"syscall"
"unsafe"
"chub/internal/domain"
)
const chromeMessageWindowClass = "Chrome_MessageWindow"
const processQueryLimitedInformation = 0x1000
var (
user32 = syscall.NewLazyDLL("user32.dll")
kernel32 = syscall.NewLazyDLL("kernel32.dll")
findWindowExW = user32.NewProc("FindWindowExW")
getWindowThreadProcessID = user32.NewProc("GetWindowThreadProcessId")
queryFullProcessImageName = kernel32.NewProc("QueryFullProcessImageNameW")
waitForSingleObject = kernel32.NewProc("WaitForSingleObject")
)
type windowsProcessInspector struct{}
func NewWindowsProcessInspector() ProcessInspector { return windowsProcessInspector{} }
func (windowsProcessInspector) Inspect(ctx context.Context, pid int) (ProcessIdentity, error) {
if err := ctx.Err(); err != nil {
return ProcessIdentity{}, err
}
if pid <= 0 {
return ProcessIdentity{}, fmt.Errorf("%w: invalid PID", ErrIdentityUnavailable)
}
handle, err := syscall.OpenProcess(syscall.SYNCHRONIZE|processQueryLimitedInformation, false, uint32(pid))
if err != nil {
return ProcessIdentity{}, fmt.Errorf("%w: open process: %v", ErrIdentityUnavailable, err)
}
defer syscall.CloseHandle(handle)
path, err := queryImagePath(handle)
if err != nil {
return ProcessIdentity{}, fmt.Errorf("%w: query executable: %v", ErrIdentityUnavailable, err)
}
return ProcessIdentity{PID: pid, Executable: path}, nil
}
func (windowsProcessInspector) Alive(ctx context.Context, pid int) (bool, error) {
if err := ctx.Err(); err != nil {
return false, err
}
if pid <= 0 {
return false, nil
}
handle, err := syscall.OpenProcess(syscall.SYNCHRONIZE, false, uint32(pid))
if err != nil {
return false, nil
}
defer syscall.CloseHandle(handle)
const waitTimeout = 258
result, _, callErr := waitForSingleObject.Call(uintptr(handle), 0)
if callErr != syscall.Errno(0) {
return false, callErr
}
return result == waitTimeout, nil
}
func queryImagePath(handle syscall.Handle) (string, error) {
buffer := make([]uint16, syscall.MAX_PATH)
for {
size := uint32(len(buffer))
result, _, callErr := queryFullProcessImageName.Call(uintptr(handle), 0, uintptr(unsafe.Pointer(&buffer[0])), uintptr(unsafe.Pointer(&size)))
if result != 0 {
return syscall.UTF16ToString(buffer[:size]), nil
}
if callErr != syscall.ERROR_INSUFFICIENT_BUFFER || len(buffer) >= 32768 {
return "", callErr
}
buffer = make([]uint16, len(buffer)*2)
}
}
type windowsProfileInspector struct{ process ProcessInspector }
func NewWindowsProfileInspector() ExternalProfileInspector {
return windowsProfileInspector{process: NewWindowsProcessInspector()}
}
func (i windowsProfileInspector) InspectProfile(ctx context.Context, kind domain.BrowserKind, userDataDir string, historicalPID int) (ProfileUse, error) {
if err := ctx.Err(); err != nil {
return ProfileUse{}, err
}
profile, err := filepath.Abs(filepath.Clean(userDataDir))
if err != nil {
return ProfileUse{}, err
}
if pid, found, err := findProfileWindow(profile); err != nil {
return ProfileUse{}, err
} else if found {
identity, identityErr := i.process.Inspect(ctx, pid)
if identityErr == nil && executableMatchesKind(identity.Executable, kind) {
return ProfileUse{Occupied: true, PID: pid, Source: ProfileSourceMessageWindow}, nil
}
return ProfileUse{Occupied: true, PID: pid, Source: ProfileSourceUnknown}, nil
}
lockPath := filepath.Join(profile, "lockfile")
file, err := os.OpenFile(lockPath, os.O_WRONLY, 0)
if err == nil {
_ = file.Close()
if historicalPID > 0 {
alive, aliveErr := i.process.Alive(ctx, historicalPID)
if aliveErr == nil && alive {
return ProfileUse{Source: ProfileSourceStalePID}, nil
}
}
return ProfileUse{Source: ProfileSourceStaleLock}, nil
}
if errors.Is(err, os.ErrNotExist) {
return ProfileUse{}, nil
}
if isSharingViolation(err) {
pid := 0
if historicalPID > 0 {
alive, aliveErr := i.process.Alive(ctx, historicalPID)
if aliveErr == nil && alive {
pid = historicalPID
}
}
return ProfileUse{Occupied: true, PID: pid, Source: ProfileSourceLock}, nil
}
return ProfileUse{}, fmt.Errorf("inspect browser lock: %w", err)
}
func findProfileWindow(profile string) (int, bool, error) {
className, err := syscall.UTF16PtrFromString(chromeMessageWindowClass)
if err != nil {
return 0, false, err
}
windowName, err := syscall.UTF16PtrFromString(profile)
if err != nil {
return 0, false, err
}
const hwndMessage = ^uintptr(2)
hwnd, _, callErr := findWindowExW.Call(hwndMessage, 0, uintptr(unsafe.Pointer(className)), uintptr(unsafe.Pointer(windowName)))
if hwnd == 0 {
if callErr != syscall.Errno(0) {
return 0, false, callErr
}
return 0, false, nil
}
var pid uint32
threadID, _, callErr := getWindowThreadProcessID.Call(hwnd, uintptr(unsafe.Pointer(&pid)))
if threadID == 0 || pid == 0 {
if callErr == syscall.Errno(0) {
callErr = errors.New("profile window has no process")
}
return 0, false, callErr
}
return int(pid), true, nil
}
func isSharingViolation(err error) bool {
const (
sharingViolation syscall.Errno = 32
lockViolation syscall.Errno = 33
)
var pathErr *os.PathError
if !errors.As(err, &pathErr) {
return false
}
errno, ok := pathErr.Err.(syscall.Errno)
return ok && (errno == sharingViolation || errno == lockViolation)
}
@@ -0,0 +1,24 @@
//go:build windows
package browser
import (
"context"
"os"
"testing"
)
func TestWindowsProcessInspectorReadsCurrentProcess(t *testing.T) {
inspector := NewWindowsProcessInspector()
identity, err := inspector.Inspect(context.Background(), os.Getpid())
if err != nil {
t.Fatalf("Inspect(current process) error = %v", err)
}
if identity.PID != os.Getpid() || identity.Executable == "" {
t.Fatalf("identity = %+v", identity)
}
alive, err := inspector.Alive(context.Background(), os.Getpid())
if err != nil || !alive {
t.Fatalf("Alive(current process) = %v, %v", alive, err)
}
}