From 4e51ae60af4b668ac6f9b8c51c0152a12ef1aa69 Mon Sep 17 00:00:00 2001 From: Storm Dragon Date: Wed, 2 Dec 2026 22:16:12 -0500 Subject: [PATCH] Accept Wine browser publishers as foreground window owners Wine Access publishes a Windows browser's accessibility tree from a separate process, so its D-Bus PID never matches the X11 owner of the browser window and foreground correlation rejected it. Map a publisher to the X11 client only when both are owned by the reader's user, the publisher was started with WINE_ACCESS_BROWSER_PUBLISHER=1, the client is a Wine loader, both resolve to the same Wine prefix, and the frame's wine-access-x11-window attribute names the foreground X11 window. Existing active, showing and bounds checks still apply. Prefix and loader identity move to internal/wine/identity so Wine discovery and foreground correlation share one definition. Matches are cached per publisher PID and X11 window and cleared with the foreground client; the window attribute is checked on every call. Foreground recovery skips applications that match neither the client nor an eligible publisher before fetching their frames. Checked: go build ./..., gofmt, go vet, and go test ./internal/atspi ./internal/wine/... (fake /proc fixtures for accepted publishers, markers, prefixes, window IDs, owners, users and cache isolation). Live acceptance with a Wine browser, window switching, recovery and OCR remains; see docs/testing/wine-browser-foreground.md. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + docs/testing/wine-browser-foreground.md | 66 ++++++++ internal/atspi/adapter.go | 11 +- internal/atspi/adapter_event_filter_native.go | 2 +- internal/atspi/adapter_foreground_native.go | 12 +- internal/atspi/adapter_ocr_native.go | 2 +- internal/atspi/wine_process.go | 48 ++++++ internal/atspi/wine_process_native.go | 29 ++++ internal/atspi/wine_process_test.go | 159 ++++++++++++++++++ internal/version/version.go | 2 +- internal/wine/identity/process.go | 92 ++++++++++ internal/wine/manager.go | 22 +-- 12 files changed, 418 insertions(+), 28 deletions(-) create mode 100644 docs/testing/wine-browser-foreground.md create mode 100644 internal/atspi/wine_process.go create mode 100644 internal/atspi/wine_process_native.go create mode 100644 internal/atspi/wine_process_test.go create mode 100644 internal/wine/identity/process.go diff --git a/README.md b/README.md index 53bb376..3a523a5 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,7 @@ Cthulhu is a Linux screen reader written in Go. - [Graphical terminals](docs/testing/graphical-terminals.md): repaint coalescing, editing feedback, title animation, and verification. - [Messaging support](docs/testing/messaging.md): Pidgin and Mumble message review/copy shortcuts, application boundaries, and verification. - [Flatpak foreground accessibility](docs/testing/flatpak-foreground.md): process identity and proxy matching, tests, and live acceptance. +- [Wine browser foreground ownership](docs/testing/wine-browser-foreground.md): publisher identity, per-window matching, tests, and live acceptance. - [Background event filtering](docs/testing/background-events.md): early foreground checks, notification exceptions, and performance verification. - [Browser Find](docs/testing/browser-find.md): native Ctrl+F focus, typing, window ownership and verification. - [Browse-key focus routing](docs/testing/browser-focus-routing.md): native window transitions, stale foreground metadata, and key-delivery verification. diff --git a/docs/testing/wine-browser-foreground.md b/docs/testing/wine-browser-foreground.md new file mode 100644 index 0000000..78094f8 --- /dev/null +++ b/docs/testing/wine-browser-foreground.md @@ -0,0 +1,66 @@ +# Wine browser publisher foreground ownership + +Wine browser accessibility comes from a separate publisher, whose D-Bus PID +differs from the Wine process owning the X11 browser window. Foreground +correlation applies the existing Flatpak mapping first, then accepts a Wine +publisher only when: + +- Both PIDs are positive, distinct and owned by the reader's user. +- The publisher's environment contains `WINE_ACCESS_BROWSER_PUBLISHER=1`. +- The X11 client's executable is `wine`, `wine64`, `wine-preloader` or + `wine64-preloader` (the same executable check used by Wine discovery). +- Both processes resolve to the same Wine prefix: `WINEPREFIX`, otherwise + `STEAM_COMPAT_DATA_PATH/pfx`, otherwise the process's own `HOME/.wine`. + Paths are cleaned and symlinks resolved where available; missing or + relative paths cannot establish ownership. +- The accessible frame's `wine-access-x11-window` attribute is the decimal + X11 foreground window ID. + +This only maps process identity. Existing active, showing, non-iconified, +bounds and correlated-window checks still apply. Event handling, recovery +and OCR use the window-aware mapping. Recovery first skips applications whose +process matches neither the foreground client nor an eligible Wine publisher, +so unrelated frames are never fetched; it then checks each remaining frame, +including its `wine-access-x11-window` attribute. + +The GLib thread caches positive and negative process matches by publisher PID +and X11 window ID, with at most 128 entries. Like Flatpak comparisons, these +entries last until the foreground window, client PID or known state changes. +Cached process rejections avoid AT-SPI attribute queries for unrelated +providers. An eligible frame's attribute is checked on every call, so a sibling +frame cannot borrow a cached match. No process scan or init system is required +by the mapping. + +## Automated checks + +```sh +go test ./internal/atspi ./internal/wine/... -run 'TestWinePublisher|TestFlatpak|TestForeground|TestDiscover' -count=1 +``` + +The fake `/proc` fixtures cover accepted publishers, executable variants, +missing/wrong markers, different/missing prefixes, Steam and default prefixes, +symlink aliases, different/invalid/missing window IDs, non-Wine owners, +missing processes, user/PID boundaries and cache isolation between windows +and publishers. Existing Wine discovery tests exercise the shared prefix +and executable helpers. Existing foreground tests retain geometry checks. + +## Live acceptance + +After human diff review, use a freshly built reader and a publisher providing +the marker, prefix and frame attribute. Replacing the active reader requires +the maintainer's authorization. + +1. Focus the Wine browser and navigate controls and document content. Confirm + speech and, if connected, Braille follow focus. +2. Switch to another application and back, including a window that retains its + focused child without emitting another focus event. Confirm recovery works + and background browser events do not interrupt the other application. +3. Open a second browser window in the same prefix. Each frame must carry its + own X11 ID; the inactive frame must not acquire the active window's ownership. +4. Exercise OCR on the foreground browser and confirm it rejects a stale or + background target after switching windows. +5. Check an ordinary native application and an available Flatpak application + for foreground navigation and recovery regressions. + +Fake-process tests do not establish live Wine integration, audible speech, +physical input or Braille acceptance. diff --git a/internal/atspi/adapter.go b/internal/atspi/adapter.go index 32dfd98..6488492 100644 --- a/internal/atspi/adapter.go +++ b/internal/atspi/adapter.go @@ -115,11 +115,12 @@ var eventTypes = []string{ type Adapter struct { captureLogger atomic.Pointer[slog.Logger] - libreOfficeHeaders libreOfficeHeaderStore // copied choices shared with the event loop - applicationProcesses map[string]string // GLib owner; bounded provider identity cache - deferredLiveRegions deferredLiveRegionStore // GLib owner; copied identities only - foregroundReader *xorg.ForegroundReader // GLib thread only - foregroundProcesses map[int]bool // GLib thread; provider PID matches for current client + libreOfficeHeaders libreOfficeHeaderStore // copied choices shared with the event loop + applicationProcesses map[string]string // GLib owner; bounded provider identity cache + deferredLiveRegions deferredLiveRegionStore // GLib owner; copied identities only + foregroundReader *xorg.ForegroundReader // GLib thread only + foregroundProcesses map[int]bool // GLib thread; provider PID matches for current client + foregroundPublishers map[foregroundPublisher]bool // GLib thread; Wine publisher/window matches for current client foreground atomic.Pointer[ForegroundState] preferencesPID atomic.Int64 // Owned preferences helper; zero when closed. echoFocus atomic.Pointer[echoFocus] diff --git a/internal/atspi/adapter_event_filter_native.go b/internal/atspi/adapter_event_filter_native.go index f5218a6..811a22c 100644 --- a/internal/atspi/adapter_event_filter_native.go +++ b/internal/atspi/adapter_event_filter_native.go @@ -101,7 +101,7 @@ func (adapter *Adapter) matchSteamOverlayFocus(window *C.AtspiAccessible) bool { if webscripts.MatchProcess(process) != webscripts.Steam { return false } - pid := adapter.foregroundProcessID(int(C.atspi_accessible_get_process_id(window, nil))) + pid := adapter.foregroundWindowProcessID(window, int(C.atspi_accessible_get_process_id(window, nil))) C.atspi_accessible_clear_cache_single(window) states := C.atspi_accessible_get_state_set(window) if states == nil { diff --git a/internal/atspi/adapter_foreground_native.go b/internal/atspi/adapter_foreground_native.go index 357ed38..204c6c1 100644 --- a/internal/atspi/adapter_foreground_native.go +++ b/internal/atspi/adapter_foreground_native.go @@ -31,6 +31,7 @@ func (adapter *Adapter) refreshForeground() { state := ForegroundState{Client: value, Epoch: previous.Epoch} if value.Window != previous.Client.Window || value.PID != previous.Client.PID || value.Known != previous.Client.Known { clear(adapter.foregroundProcesses) + clear(adapter.foregroundPublishers) } if value.Known != previous.Client.Known || value.Window != previous.Client.Window { state.Epoch++ @@ -82,7 +83,7 @@ func (adapter *Adapter) matchForeground(source, window *C.AtspiAccessible, id Ob if check != nil { check.AccessiblePID = pid } - pid = adapter.foregroundProcessID(pid) + pid = adapter.foregroundWindowProcessID(window, pid) // Desktop panel menus can grab the keyboard while X11 still names the // previous application. Orca accepts their active, showing menu window. // Keep the correlated X11 owner so dismissal can return to that client. @@ -337,7 +338,10 @@ func (adapter *Adapter) recoverForeground() { continue } pid := int(C.atspi_accessible_get_process_id(application, nil)) - if adapter.foregroundProcessID(pid) != state.Client.PID { + // Skip unrelated applications before fetching their frames over D-Bus. + // A Wine publisher passes here on process identity alone; each frame + // below must still carry the foreground X11 window ID. + if adapter.foregroundProcessID(pid) != state.Client.PID && !adapter.matchesWinePublisher("/proc", pid) { C.g_object_unref(C.gpointer(application)) continue } @@ -347,6 +351,10 @@ func (adapter *Adapter) recoverForeground() { if window == nil { continue } + if adapter.foregroundWindowProcessID(window, pid) != state.Client.PID { + C.g_object_unref(C.gpointer(window)) + continue + } if state.Epoch == adapter.Foreground().Epoch && adapter.matchesForeground(window, window, nativeObjectID(window)) { target := adapter.libreOfficeFrameTarget(window) officeFrame := target != nil diff --git a/internal/atspi/adapter_ocr_native.go b/internal/atspi/adapter_ocr_native.go index a6d00d7..4d91bd0 100644 --- a/internal/atspi/adapter_ocr_native.go +++ b/internal/atspi/adapter_ocr_native.go @@ -97,7 +97,7 @@ func (adapter *Adapter) nativeOCRGeometry(ctx context.Context, object ObjectID, return OCRGeometry{}, ErrOCRGeometry } defer C.g_object_unref(C.gpointer(window)) - if adapter.foregroundProcessID(int(C.atspi_accessible_get_process_id(window, nil))) != before.Client.PID || (adapter.foregroundWindow.Valid() && adapter.foregroundWindow != nativeObjectID(window)) { + if adapter.foregroundWindowProcessID(window, int(C.atspi_accessible_get_process_id(window, nil))) != before.Client.PID || (adapter.foregroundWindow.Valid() && adapter.foregroundWindow != nativeObjectID(window)) { return OCRGeometry{}, ErrOCRGeometry } states := C.atspi_accessible_get_state_set(window) diff --git a/internal/atspi/wine_process.go b/internal/atspi/wine_process.go new file mode 100644 index 0000000..7335cb6 --- /dev/null +++ b/internal/atspi/wine_process.go @@ -0,0 +1,48 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package atspi + +import ( + "os" + "strconv" + + "git.stormux.org/storm/cthulhu/internal/wine/identity" +) + +type foregroundPublisher struct { + pid int + window uint64 +} + +// Owned by the GLib thread and cleared with the foreground client, like the +// Flatpak cache. This resolves processes only; each frame must independently +// supply the foreground X11 window ID before it can use a cached match. +func (adapter *Adapter) matchesWinePublisher(procRoot string, pid int) bool { + client := adapter.Foreground().Client + if client.Window == 0 || client.PID <= 0 || pid <= 0 || pid == client.PID { + return false + } + key := foregroundPublisher{pid: pid, window: client.Window} + matched, known := adapter.foregroundPublishers[key] + if !known { + matched = identity.BrowserPublisherMatches(procRoot, pid, client.PID, uint32(os.Getuid())) + if adapter.foregroundPublishers == nil || len(adapter.foregroundPublishers) >= 128 { + adapter.foregroundPublishers = make(map[foregroundPublisher]bool) + } + adapter.foregroundPublishers[key] = matched + } + return matched +} + +func (adapter *Adapter) wineForegroundProcessID(procRoot string, pid int, windowID string) int { + if adapter.matchesWinePublisher(procRoot, pid) { + client := adapter.Foreground().Client + window, err := strconv.ParseUint(windowID, 10, 32) + if err == nil && window == client.Window { + return client.PID + } + } + return pid +} diff --git a/internal/atspi/wine_process_native.go b/internal/atspi/wine_process_native.go new file mode 100644 index 0000000..3bb0155 --- /dev/null +++ b/internal/atspi/wine_process_native.go @@ -0,0 +1,29 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package atspi + +/* +#include "adapter_native.h" +*/ +import "C" + +import "unsafe" + +func (adapter *Adapter) foregroundWindowProcessID(window *C.AtspiAccessible, pid int) int { + pid = adapter.foregroundProcessID(pid) + // Reject unrelated providers using the process cache before making an + // AT-SPI attribute query. A positive match still needs this frame's ID. + if window == nil || !adapter.matchesWinePublisher("/proc", pid) { + return pid + } + key := C.CString("wine-access-x11-window") + defer C.free(unsafe.Pointer(key)) + value := C.cthulhu_live_attribute(window, key) + if value == nil { + return pid + } + defer C.g_free(C.gpointer(value)) + return adapter.wineForegroundProcessID("/proc", pid, C.GoString(value)) +} diff --git a/internal/atspi/wine_process_test.go b/internal/atspi/wine_process_test.go new file mode 100644 index 0000000..0d90b34 --- /dev/null +++ b/internal/atspi/wine_process_test.go @@ -0,0 +1,159 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package atspi + +import ( + "fmt" + "os" + "path/filepath" + "testing" + + "git.stormux.org/storm/cthulhu/internal/platform/xorg" + "git.stormux.org/storm/cthulhu/internal/wine/identity" +) + +func writeWineProcess(t *testing.T, root string, pid int, executable, environment string) { + t.Helper() + path := filepath.Join(root, fmt.Sprint(pid)) + if err := os.MkdirAll(path, 0700); err != nil { + t.Fatal(err) + } + if executable != "" { + if err := os.Symlink(executable, filepath.Join(path, "exe")); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(path, "environ"), []byte(environment), 0600); err != nil { + t.Fatal(err) + } +} + +func TestWinePublisherProcessBoundaries(t *testing.T) { + const marker = "WINE_ACCESS_BROWSER_PUBLISHER=1\x00" + for _, test := range []struct { + name, publisherEnvironment, clientEnvironment, executable, windowID string + missingPublisher, missingClient, accepted bool + }{ + {name: "matching publisher", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "123", accepted: true}, + {name: "wine64", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine64", windowID: "123", accepted: true}, + {name: "preloader", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine-preloader", windowID: "123", accepted: true}, + {name: "64-bit preloader", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine64-preloader", windowID: "123", accepted: true}, + {name: "missing marker", publisherEnvironment: "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "123"}, + {name: "wrong marker value", publisherEnvironment: "WINE_ACCESS_BROWSER_PUBLISHER=0\x00WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "123"}, + {name: "marker on client only", publisherEnvironment: "WINEPREFIX=/prefix\x00", clientEnvironment: marker + "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "123"}, + {name: "different prefix", publisherEnvironment: marker + "WINEPREFIX=/other\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "123"}, + {name: "relative prefix", publisherEnvironment: marker + "WINEPREFIX=relative\x00", clientEnvironment: "WINEPREFIX=relative\x00", executable: "/usr/bin/wine", windowID: "123"}, + {name: "missing prefix", publisherEnvironment: marker, executable: "/usr/bin/wine", windowID: "123"}, + {name: "different window", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "124"}, + {name: "missing window", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine"}, + {name: "hex window", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "0x7b"}, + {name: "invalid window", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "invalid"}, + {name: "overflow window", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "4294967419"}, + {name: "non-Wine client", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/electron", windowID: "123"}, + {name: "wineserver client", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wineserver", windowID: "123"}, + {name: "missing executable", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", windowID: "123"}, + {name: "publisher exited", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "123", missingPublisher: true}, + {name: "client exited", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00", windowID: "123", missingClient: true}, + {name: "Steam prefix", publisherEnvironment: marker + "WINEPREFIX=/steam/pfx\x00", clientEnvironment: "STEAM_COMPAT_DATA_PATH=/steam\x00", executable: "/usr/bin/wine", windowID: "123", accepted: true}, + {name: "default prefix", publisherEnvironment: marker + "HOME=/home/Username\x00", clientEnvironment: "HOME=/home/Username\x00", executable: "/usr/bin/wine", windowID: "123", accepted: true}, + {name: "different homes", publisherEnvironment: marker + "HOME=/home/Username\x00", clientEnvironment: "HOME=/home/Other\x00", executable: "/usr/bin/wine", windowID: "123"}, + {name: "explicit prefix precedence", publisherEnvironment: marker + "WINEPREFIX=/prefix\x00STEAM_COMPAT_DATA_PATH=/other\x00", clientEnvironment: "WINEPREFIX=/prefix\x00", executable: "/usr/bin/wine", windowID: "123", accepted: true}, + } { + t.Run(test.name, func(t *testing.T) { + root := t.TempDir() + if !test.missingPublisher { + writeWineProcess(t, root, 100, "/usr/bin/python3", test.publisherEnvironment) + } + if !test.missingClient { + writeWineProcess(t, root, 200, test.executable, test.clientEnvironment) + } + adapter := &Adapter{} + adapter.foreground.Store(&ForegroundState{Client: xorg.Foreground{Known: true, Window: 123, PID: 200}}) + want := 100 + if test.accepted { + want = 200 + } + if got := adapter.wineForegroundProcessID(root, 100, test.windowID); got != want { + t.Fatalf("mapped PID = %d; want %d", got, want) + } + }) + } +} + +func TestWinePublisherPrefixSymlinks(t *testing.T) { + root := t.TempDir() + prefix := filepath.Join(root, "prefix") + alias := filepath.Join(root, "alias") + if err := os.Mkdir(prefix, 0700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(prefix, alias); err != nil { + t.Fatal(err) + } + writeWineProcess(t, root, 100, "/usr/bin/python3", "WINE_ACCESS_BROWSER_PUBLISHER=1\x00WINEPREFIX="+alias+"/../alias\x00") + writeWineProcess(t, root, 200, "/usr/bin/wine", "WINEPREFIX="+prefix+"\x00") + adapter := &Adapter{} + adapter.foreground.Store(&ForegroundState{Client: xorg.Foreground{Known: true, Window: 123, PID: 200}}) + if got := adapter.wineForegroundProcessID(root, 100, "123"); got != 200 { + t.Fatalf("symlinked prefix PID = %d; want 200", got) + } +} + +func TestWinePublisherProcessIdentity(t *testing.T) { + root := t.TempDir() + writeWineProcess(t, root, 100, "/usr/bin/python3", "WINE_ACCESS_BROWSER_PUBLISHER=1\x00WINEPREFIX=/prefix\x00") + writeWineProcess(t, root, 200, "/usr/bin/wine", "WINEPREFIX=/prefix\x00") + uid := uint32(os.Getuid()) + for _, test := range []struct { + name string + publisherPID int + clientPID int + uid uint32 + }{ + {"other user", 100, 200, uid + 1}, + {"same process", 100, 100, uid}, + {"unknown publisher", 0, 200, uid}, + {"negative publisher", -1, 200, uid}, + {"unknown client", 100, 0, uid}, + {"negative client", 100, -1, uid}, + } { + t.Run(test.name, func(t *testing.T) { + if identity.BrowserPublisherMatches(root, test.publisherPID, test.clientPID, test.uid) { + t.Fatal("invalid process identity matched") + } + }) + } +} + +func TestWinePublisherCacheWindowBoundaries(t *testing.T) { + root := t.TempDir() + writeWineProcess(t, root, 100, "/usr/bin/python3", "WINE_ACCESS_BROWSER_PUBLISHER=1\x00WINEPREFIX=/prefix\x00") + writeWineProcess(t, root, 200, "/usr/bin/wine", "WINEPREFIX=/prefix\x00") + adapter := &Adapter{} + adapter.foreground.Store(&ForegroundState{Client: xorg.Foreground{Known: true, Window: 123, PID: 200}}) + if got := adapter.wineForegroundProcessID(root, 100, "123"); got != 200 { + t.Fatalf("initial mapped PID = %d; want 200", got) + } + if got := adapter.wineForegroundProcessID(root, 100, "124"); got != 100 { + t.Fatalf("another frame borrowed cached match: PID = %d", got) + } + // Remove the marker after caching. Reusing this exact pair is cached, but + // another X11 window must perform its own process comparison. + if err := os.WriteFile(filepath.Join(root, "100", "environ"), []byte("WINEPREFIX=/prefix\x00"), 0600); err != nil { + t.Fatal(err) + } + if got := adapter.wineForegroundProcessID(root, 100, "123"); got != 200 { + t.Fatalf("cached mapped PID = %d; want 200", got) + } + adapter.foreground.Store(&ForegroundState{Client: xorg.Foreground{Known: true, Window: 124, PID: 200}}) + if got := adapter.wineForegroundProcessID(root, 100, "124"); got != 100 { + t.Fatalf("another X11 window reused cached match: PID = %d", got) + } + // A rejection for the first publisher must not reject a new publisher. + writeWineProcess(t, root, 300, "/usr/bin/python3", "WINE_ACCESS_BROWSER_PUBLISHER=1\x00WINEPREFIX=/prefix\x00") + if got := adapter.wineForegroundProcessID(root, 300, "124"); got != 200 { + t.Fatalf("new publisher mapped PID = %d; want 200", got) + } +} diff --git a/internal/version/version.go b/internal/version/version.go index 0f189d7..a6dcdd7 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -21,7 +21,7 @@ import "strings" const Name = "Cthulhu" -const Version = "2026.12.01" +const Version = "2026.12.02" const Channel = "testing" var Build = Version diff --git a/internal/wine/identity/process.go b/internal/wine/identity/process.go new file mode 100644 index 0000000..75d81f5 --- /dev/null +++ b/internal/wine/identity/process.go @@ -0,0 +1,92 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +// Package identity shares Wine process and prefix identity between discovery +// and AT-SPI foreground correlation without depending on either subsystem. +package identity + +import ( + "os" + "path/filepath" + "strconv" + "strings" + "syscall" +) + +// IsLoader reports whether an executable is a Wine application loader. +func IsLoader(executable string) bool { + switch strings.ToLower(filepath.Base(executable)) { + case "wine", "wine64", "wine-preloader", "wine64-preloader": + return true + } + return false +} + +// Prefix resolves Wine's prefix from the launching process's environment. +// Missing or relative paths cannot establish a session identity. +func Prefix(environment map[string]string) string { + path := environment["WINEPREFIX"] + if path == "" && environment["STEAM_COMPAT_DATA_PATH"] != "" { + path = filepath.Join(environment["STEAM_COMPAT_DATA_PATH"], "pfx") + } + if path == "" && filepath.IsAbs(environment["HOME"]) { + path = filepath.Join(environment["HOME"], ".wine") + } + if path == "" { + return "" + } + path = filepath.Clean(path) + if resolved, err := filepath.EvalSymlinks(path); err == nil { + path = resolved + } + if !filepath.IsAbs(path) { + return "" + } + return path +} + +// BrowserPublisherMatches ties an explicitly marked publisher to a Wine +// client in the same prefix and user account. The caller must also verify the +// accessible frame's X11 window attribute before granting window ownership. +func BrowserPublisherMatches(procRoot string, publisherPID, clientPID int, uid uint32) bool { + if publisherPID <= 0 || clientPID <= 0 || publisherPID == clientPID { + return false + } + publisher := filepath.Join(procRoot, strconv.Itoa(publisherPID)) + client := filepath.Join(procRoot, strconv.Itoa(clientPID)) + for _, path := range []string{publisher, client} { + info, err := os.Stat(path) + if err != nil { + return false + } + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok || stat.Uid != uid { + return false + } + } + executable, err := os.Readlink(filepath.Join(client, "exe")) + if err != nil || !IsLoader(executable) { + return false + } + publisherEnvironment := readEnvironment(publisher) + if publisherEnvironment["WINE_ACCESS_BROWSER_PUBLISHER"] != "1" { + return false + } + prefix := Prefix(publisherEnvironment) + return prefix != "" && prefix == Prefix(readEnvironment(client)) +} + +func readEnvironment(processPath string) map[string]string { + raw, err := os.ReadFile(filepath.Join(processPath, "environ")) + if err != nil { + return nil + } + environment := make(map[string]string) + for _, item := range strings.Split(string(raw), "\x00") { + if key, value, found := strings.Cut(item, "="); found { + environment[key] = value + } + } + return environment +} diff --git a/internal/wine/manager.go b/internal/wine/manager.go index b3eed47..b7cc14a 100644 --- a/internal/wine/manager.go +++ b/internal/wine/manager.go @@ -16,6 +16,8 @@ import ( "sync/atomic" "syscall" "time" + + "git.stormux.org/storm/cthulhu/internal/wine/identity" ) const managedKey = "CTHULHU_WINE_ACCESS_MANAGED" @@ -433,8 +435,7 @@ func discover(root string, uid uint32) map[string]prefix { if err != nil { continue } - name := strings.ToLower(filepath.Base(exe)) - if name != "wine" && name != "wine64" && name != "wine-preloader" && name != "wine64-preloader" { + if !identity.IsLoader(exe) { continue } commandLine, err := os.ReadFile(filepath.Join(base, "cmdline")) @@ -455,25 +456,10 @@ func discover(root string, uid uint32) map[string]prefix { if environment[managedKey] == "1" { continue } - path := environment["WINEPREFIX"] - if path == "" && environment["STEAM_COMPAT_DATA_PATH"] != "" { - path = filepath.Join(environment["STEAM_COMPAT_DATA_PATH"], "pfx") - } - // Wine defaults to .wine in the launching process's home directory. - // Use that process's HOME, which may differ from the reader's HOME. - if path == "" && filepath.IsAbs(environment["HOME"]) { - path = filepath.Join(environment["HOME"], ".wine") - } + path := identity.Prefix(environment) if path == "" { continue } - path = filepath.Clean(path) - if resolved, err := filepath.EvalSymlinks(path); err == nil { - path = resolved - } - if !filepath.IsAbs(path) { - continue - } loader := wineLoader(exe, environment["WINELOADER"]) programs := map[string]bool{programName(string(commandLine)): true} if previous, ok := result[path]; ok {