180 lines
5.3 KiB
Go
180 lines
5.3 KiB
Go
//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)
|
|
}
|