Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): attribute X11 windows without _NET_WM_PID via X-Resource (#4214)

Francesco Bonaccia02df78c40b3
diff --git a/libs/cua-driver/rust/Cargo.lock b/libs/cua-driver/rust/Cargo.lock
index 1141e17db3..edf0a34318 100644
--- a/libs/cua-driver/rust/Cargo.lock
+++ b/libs/cua-driver/rust/Cargo.lock
@@ -1321,6 +1321,7 @@ dependencies = [
"tokio",
"tokio-tungstenite",
"windows 0.61.3",
+ "x11rb",
]
[[package]]
diff --git a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
index c4fa2f56a9..4def10ac17 100644
--- a/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
+++ b/libs/cua-driver/rust/Skills/cua-driver/LINUX.md
@@ -95,6 +95,19 @@ stays in screen coordinates, as on every platform); `frame_scale` < 1 and
pixels back to the window.
An explicit per-call `max_image_dimension` (0 = native) replaces this cap.
+**Windows without `_NET_WM_PID`.** Tk, many Java/AWT builds, Wine, and legacy
+Xlib/Xt clients do not publish `_NET_WM_PID`. On X11, `list_windows` then asks
+the X server's X-Resource extension (XRes 1.2 `LocalClientPID`) which local
+process created the window, so these windows still carry a `pid` and accept
+`get_window_state` / `click` by `pid` + `window_id`. The driver never guesses:
+`pid` stays `null` when XRes is missing or older than 1.2, when the client
+is remote (TCP, or SSH-forwarded with a `WM_CLIENT_MACHINE` naming another
+host), or when the X server cannot report the driver's own PID correctly
+(remote `DISPLAY`, container PID namespace). A `pid: null` window can only be
+reached through desktop scope. An SSH-forwarded client that publishes
+neither `_NET_WM_PID` nor `WM_CLIENT_MACHINE` is attributed to the local
+`ssh` process, because that is the socket peer the server sees.
+
**Keys while the app's own popup is open.** A Qt combo list / completer or a
GTK/VCL menu holds a keyboard grab that makes the X server drop keys from the
virtual keyboard. `press_key` / `hotkey` / `type_text` / `set_value` then go
diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml
index c3beb702f3..832cf0108b 100644
--- a/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml
+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml
@@ -49,6 +49,9 @@ libc = "0.2"
[target.'cfg(target_os = "linux")'.dependencies]
platform-linux = { path = "../platform-linux" }
+[target.'cfg(target_os = "linux")'.dev-dependencies]
+x11rb = "0.13"
+
[target.'cfg(target_os = "macos")'.dev-dependencies]
core-foundation = "0.10"
diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/x11_unpublished_pid_linux_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/x11_unpublished_pid_linux_test.rs
new file mode 100644
index 0000000000..1fb52c7799
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/x11_unpublished_pid_linux_test.rs
@@ -0,0 +1,242 @@
+//! Linux/X11 toplevels that never publish `_NET_WM_PID` (Tk, many Java/AWT
+//! builds, Wine, legacy Xlib/Xt clients) must still be addressable by
+//! `pid` + `window_id` (#3894).
+//!
+//! The test process is itself the bare Xlib-style client: it maps a titled
+//! toplevel through x11rb without `_NET_WM_PID` or `WM_CLIENT_MACHINE`, so
+//! the only way the driver can attribute it is the X-Resource
+//! `LocalClientPID` of the connection that created it. The oracles are
+//! protocol (`list_windows` reports this process's pid, a pid-filtered list
+//! finds the window, and `get_window_state` accepts the pair) and fixture
+//! state (the window's own connection receives the ButtonPress of a
+//! window-scoped background click).
+//!
+//! #[ignore] (needs an X11 display with a window manager). Run:
+//! cargo test -p cua-driver-e2e --test x11_unpublished_pid_linux_test -- --ignored --nocapture --test-threads=1
+
+#![cfg(target_os = "linux")]
+
+use std::time::{Duration, Instant};
+
+use cua_driver_testkit::e2e::{
+ execute_case, recording_evidence, CaseSpec, Delivery, DriverRoute, Observation, OracleKind,
+ Scope, Targeting,
+};
+use cua_driver_testkit::{Driver, McpDriver};
+use x11rb::connection::Connection;
+use x11rb::protocol::xproto::{
+ AtomEnum, ConnectionExt as _, CreateWindowAux, EventMask, PropMode, WindowClass,
+};
+use x11rb::protocol::Event;
+use x11rb::rust_connection::RustConnection;
+use x11rb::wrapper::ConnectionExt as _;
+
+struct BareClient {
+ conn: RustConnection,
+ window: u32,
+ title: String,
+}
+
+impl BareClient {
+ fn map() -> Self {
+ let (conn, screen_num) =
+ RustConnection::connect(None).expect("connect to the X11 display under test");
+ let screen = &conn.setup().roots[screen_num];
+ let window = conn.generate_id().expect("allocate X11 window id");
+ let title = format!("CuaUnpublishedPid-{}", std::process::id());
+ conn.create_window(
+ x11rb::COPY_DEPTH_FROM_PARENT,
+ window,
+ screen.root,
+ 80,
+ 80,
+ 480,
+ 320,
+ 0,
+ WindowClass::INPUT_OUTPUT,
+ x11rb::COPY_FROM_PARENT,
+ &CreateWindowAux::new()
+ .background_pixel(screen.white_pixel)
+ .event_mask(EventMask::BUTTON_PRESS | EventMask::EXPOSURE),
+ )
+ .expect("create bare X11 toplevel");
+ conn.change_property8(
+ PropMode::REPLACE,
+ window,
+ AtomEnum::WM_NAME,
+ AtomEnum::STRING,
+ title.as_bytes(),
+ )
+ .expect("set WM_NAME");
+ conn.change_property8(
+ PropMode::REPLACE,
+ window,
+ AtomEnum::WM_CLASS,
+ AtomEnum::STRING,
+ b"cua-unpublished-pid\0CuaUnpublishedPid\0",
+ )
+ .expect("set WM_CLASS");
+ conn.map_window(window).expect("map bare X11 toplevel");
+ conn.flush().expect("flush X11 requests");
+ Self {
+ conn,
+ window,
+ title,
+ }
+ }
+
+ /// Precondition: the client really publishes no `_NET_WM_PID`.
+ fn publishes_net_wm_pid(&self) -> bool {
+ let atom = self
+ .conn
+ .intern_atom(false, b"_NET_WM_PID")
+ .expect("intern _NET_WM_PID")
+ .reply()
+ .expect("intern _NET_WM_PID reply")
+ .atom;
+ let reply = self
+ .conn
+ .get_property(false, self.window, atom, AtomEnum::ANY, 0, 1)
+ .expect("read _NET_WM_PID")
+ .reply()
+ .expect("read _NET_WM_PID reply");
+ reply.type_ != x11rb::NONE
+ }
+
+ fn drain_button_presses(&self) -> usize {
+ let mut presses = 0;
+ while let Ok(Some(event)) = self.conn.poll_for_event() {
+ if matches!(event, Event::ButtonPress(press) if press.event == self.window) {
+ presses += 1;
+ }
+ }
+ presses
+ }
+}
+
+fn listed_record(
+ driver: &mut McpDriver,
+ args: serde_json::Value,
+ window: u64,
+) -> Option<serde_json::Value> {
+ driver.call("list_windows", args).structured()["windows"]
+ .as_array()?
+ .iter()
+ .find(|w| w["window_id"].as_u64() == Some(window))
+ .cloned()
+}
+
+#[test]
+#[ignore]
+fn x11_toplevel_without_net_wm_pid_is_attributed_and_addressable() {
+ if std::env::var_os("DISPLAY").is_none() || std::env::var_os("WAYLAND_DISPLAY").is_some() {
+ if std::env::var_os("CUA_TEST_REQUIRE_FIXTURES").is_some() {
+ panic!("the unpublished-pid X11 case requires a native X11 session");
+ }
+ eprintln!("[x11-unpublished-pid] not a native X11 session; skipping");
+ return;
+ }
+ let cell_id = "linux-xlib-unpublished-pid-left-click-px-background";
+ let case = CaseSpec::delivered(
+ cell_id,
+ "x11-bare-client",
+ "xlib",
+ "left_click",
+ Targeting::Px,
+ Delivery::Background,
+ Scope::Window,
+ DriverRoute::LinuxXSendEvent,
+ vec![OracleKind::FixtureState, OracleKind::Protocol],
+ );
+ execute_case(case, |evidence| {
+ let mut driver = McpDriver::spawn_named(cell_id).expect("start source-built Linux driver");
+ *evidence = recording_evidence(driver.recording_dir());
+ let client = BareClient::map();
+ let own_pid = std::process::id();
+ let window = u64::from(client.window);
+ assert!(
+ !client.publishes_net_wm_pid(),
+ "fixture precondition: the bare client must not publish _NET_WM_PID"
+ );
+
+ // Unfiltered enumeration must attribute the window to this process.
+ let deadline = Instant::now() + Duration::from_secs(10);
+ let record = loop {
+ if let Some(record) = listed_record(&mut driver, serde_json::json!({}), window) {
+ if record["is_on_screen"].as_bool() == Some(true) {
+ break record;
+ }
+ }
+ assert!(
+ Instant::now() < deadline,
+ "window {window:#x} ({}) never appeared on screen in list_windows",
+ client.title
+ );
+ std::thread::sleep(Duration::from_millis(200));
+ };
+ assert_eq!(
+ record["pid"].as_u64(),
+ Some(u64::from(own_pid)),
+ "window without _NET_WM_PID was not attributed to its X-Resource owner: {record}"
+ );
+
+ // A pid-filtered listing finds it.
+ assert!(
+ listed_record(&mut driver, serde_json::json!({"pid": own_pid}), window).is_some(),
+ "list_windows {{pid: {own_pid}}} omitted window {window:#x}"
+ );
+
+ driver.start_behavior_recording();
+ // get_window_state accepts the pid + window_id pair.
+ let state = driver.call(
+ "get_window_state",
+ serde_json::json!({"pid": own_pid, "window_id": window}),
+ );
+ assert!(
+ !state.is_error(),
+ "get_window_state refused the attributed window: {}",
+ state.text()
+ );
+ let width = state.structured()["screenshot_width"]
+ .as_f64()
+ .unwrap_or(0.0);
+ let height = state.structured()["screenshot_height"]
+ .as_f64()
+ .unwrap_or(0.0);
+ assert!(
+ width > 0.0 && height > 0.0,
+ "get_window_state returned no screenshot geometry: {}",
+ state.text()
+ );
+
+ // A window-scoped background click reaches the window's own connection.
+ client.drain_button_presses();
+ let clicked = driver.call(
+ "click",
+ serde_json::json!({
+ "pid": own_pid,
+ "window_id": window,
+ "x": width / 2.0,
+ "y": height / 2.0,
+ "delivery_mode": "background"
+ }),
+ );
+ assert!(
+ !clicked.is_error(),
+ "window-scoped click on the attributed window failed: {}",
+ clicked.text()
+ );
+ let deadline = Instant::now() + Duration::from_secs(3);
+ let mut presses = 0;
+ while presses == 0 && Instant::now() < deadline {
+ presses += client.drain_button_presses();
+ std::thread::sleep(Duration::from_millis(50));
+ }
+ assert!(
+ presses > 0,
+ "the bare client received no ButtonPress from the window-scoped click: {}",
+ clicked.text()
+ );
+ Observation::delivered_with_fixture_state(vec![OracleKind::Protocol])
+ });
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
index ba3c7a15bb..b9d9805759 100644
--- a/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
+++ b/libs/cua-driver/rust/crates/platform-linux/Cargo.toml
@@ -26,7 +26,7 @@ tiny-skia = { version = "0.11", default-features = false, features = ["std"] }
clipboard-rs = { version = "0.3.5", features = ["wayland"] }
keyring = { version = "4.1.6", default-features = false, features = ["v1"] }
# X11 background input + window enumeration + MIT-SHM capture
-x11rb = { version = "0.13", features = ["xinput", "randr", "xfixes", "composite", "shape", "xtest", "shm"] }
+x11rb = { version = "0.13", features = ["xinput", "randr", "xfixes", "composite", "shape", "xtest", "shm", "res"] }
x11 = { version = "2.21", features = ["xlib", "xinput", "xtest"] }
base64 = { workspace = true }
image = { workspace = true }
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
index de74ead569..b29e82d2e8 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
@@ -20,6 +20,9 @@ pub mod tools;
#[cfg(target_os = "linux")]
pub mod x11;
+#[cfg(any(target_os = "linux", test))]
+mod x11_client_pid;
+
#[cfg(target_os = "linux")]
pub mod input;
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs b/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs
index 7c8acc578f..edbfaf4728 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/x11/mod.rs
@@ -2,9 +2,13 @@
//!
//! Uses _NET_CLIENT_LIST_STACKING to get the list of top-level windows,
//! then reads WM_NAME/_NET_WM_NAME, _NET_WM_PID, and geometry per window.
+//! A toplevel without `_NET_WM_PID` is attributed through the X-Resource
+//! extension when the server can prove it is a local client (see
+//! [`crate::x11_client_pid`]); otherwise its `pid` stays `None`.
use anyhow::Result;
use x11rb::connection::Connection;
+use x11rb::protocol::res::{ClientIdMask, ClientIdSpec, ConnectionExt as _};
use x11rb::protocol::xproto::*;
use x11rb::rust_connection::RustConnection;
@@ -80,7 +84,7 @@ pub fn window_belongs_to_pid(xid: u64, pid: u32) -> bool {
let Ok((conn, _)) = RustConnection::connect(None) else {
return false;
};
- window_owner_matches(get_window_pid(&conn, xid).ok().flatten(), pid)
+ window_owner_matches(OwnerResolver::new(&conn).owner_pid(xid), pid)
}
fn window_owner_matches(owner: Option<u32>, requested_pid: u32) -> bool {
@@ -95,9 +99,10 @@ fn list_windows_inner(filter_pid: Option<u32>) -> Result<Vec<WindowInfo>> {
// Get _NET_CLIENT_LIST_STACKING (or fallback to _NET_CLIENT_LIST).
let windows = get_window_list(&conn, root)?;
+ let owners = OwnerResolver::new(&conn);
let mut result = Vec::new();
for (z_index, xid) in windows.into_iter().enumerate() {
- let pid = get_window_pid(&conn, xid).ok().flatten();
+ let pid = owners.owner_pid(xid);
if let Some(fp) = filter_pid {
if pid != Some(fp) {
continue;
@@ -210,11 +215,10 @@ pub fn set_window_frame(
let xid = u32::try_from(xid).map_err(|_| anyhow::anyhow!("window_id is out of X11 range"))?;
let (conn, screen_num) = RustConnection::connect(None)?;
let root = conn.setup().roots[screen_num].root;
- let owner = get_window_pid(&conn, xid)?;
- match owner {
+ match OwnerResolver::new(&conn).owner_pid(xid) {
Some(owner) if owner == pid => {}
Some(owner) => anyhow::bail!("window_id {xid} belongs to pid {owner}, not pid {pid}"),
- None => anyhow::bail!("window_id {xid} has no verifiable _NET_WM_PID owner"),
+ None => anyhow::bail!("window_id {xid} has no verifiable owner pid ({UNATTRIBUTED_OWNER})"),
}
let atom = get_atom(&conn, "_NET_MOVERESIZE_WINDOW")?;
@@ -459,10 +463,10 @@ pub fn close_window(xid: u64, pid: u32) -> Result<()> {
u32::try_from(xid).map_err(|_| anyhow::anyhow!("window_id is out of X11 range"))?;
let (conn, screen_num) = RustConnection::connect(None)?;
let root = conn.setup().roots[screen_num].root;
- match get_window_pid(&conn, window)? {
+ match OwnerResolver::new(&conn).owner_pid(window) {
Some(owner) if owner == pid => {}
Some(owner) => anyhow::bail!("window_id {xid} belongs to pid {owner}, not pid {pid}"),
- None => anyhow::bail!("window_id {xid} has no verifiable _NET_WM_PID owner"),
+ None => anyhow::bail!("window_id {xid} has no verifiable owner pid ({UNATTRIBUTED_OWNER})"),
}
let atom = get_atom(&conn, "_NET_CLOSE_WINDOW")?;
let event = ClientMessageEvent::new(
@@ -508,7 +512,11 @@ pub fn window_is_viewable(xid: u64) -> bool {
window_info(xid).is_some_and(|w| w.is_on_screen)
}
-/// `_NET_WM_PID` of a toplevel, when the window advertises one.
+/// `_NET_WM_PID` of a window, when it advertises one.
+///
+/// Deliberately property-only: input paths walk this up through child and
+/// window-manager frame windows, where an X-Resource answer would name the
+/// window manager. Client-list toplevels use [`OwnerResolver`] instead.
pub fn window_pid(xid: u64) -> Option<u32> {
let xid = u32::try_from(xid).ok()?;
let (conn, _) = RustConnection::connect(None).ok()?;
@@ -523,6 +531,118 @@ fn get_window_pid(conn: &RustConnection, window: Window) -> Result<Option<u32>>
Ok(reply.value32().and_then(|mut i| i.next()))
}
+/// Why an X11 toplevel can be listed with no owner pid.
+const UNATTRIBUTED_OWNER: &str = "the client publishes no _NET_WM_PID and the X server's \
+X-Resource extension could not attribute it to a local process: XRes 1.2 is unavailable, \
+the client is remote or forwarded, or the server is outside this PID namespace";
+
+/// Owner pid of client-list toplevels: `_NET_WM_PID` when published, else
+/// the X-Resource `LocalClientPID` of the connection that created the window,
+/// subject to the fail-closed rules in [`crate::x11_client_pid`]. The XRes
+/// probe runs at most once per connection and only for windows that lack
+/// `_NET_WM_PID`.
+struct OwnerResolver<'c> {
+ conn: &'c RustConnection,
+ xres: std::cell::OnceCell<bool>,
+ hostname: std::cell::OnceCell<Option<String>>,
+}
+
+impl<'c> OwnerResolver<'c> {
+ fn new(conn: &'c RustConnection) -> Self {
+ Self {
+ conn,
+ xres: std::cell::OnceCell::new(),
+ hostname: std::cell::OnceCell::new(),
+ }
+ }
+
+ fn owner_pid(&self, window: Window) -> Option<u32> {
+ match get_window_pid(self.conn, window) {
+ Ok(Some(pid)) => Some(pid),
+ Ok(None) => self.xres_pid(window),
+ Err(_) => None,
+ }
+ }
+
+ fn xres_pid(&self, window: Window) -> Option<u32> {
+ use crate::x11_client_pid::{
+ client_base, client_machine_is_local, select_owner_pid, xres_supports_client_ids,
+ XresClientValue,
+ };
+ let available = *self.xres.get_or_init(|| {
+ self.conn
+ .res_query_version(1, 2)
+ .ok()
+ .and_then(|cookie| cookie.reply().ok())
+ .is_some_and(|v| xres_supports_client_ids(v.server_major, v.server_minor))
+ });
+ if !available {
+ return None;
+ }
+ let machine = get_client_machine(self.conn, window).ok()?;
+ let hostname = self.hostname.get_or_init(|| {
+ std::fs::read_to_string("/proc/sys/kernel/hostname")
+ .ok()
+ .map(|h| h.trim().to_owned())
+ });
+ if !client_machine_is_local(machine.as_deref(), hostname.as_deref()) {
+ return None;
+ }
+ let setup = self.conn.setup();
+ let own_base = setup.resource_id_base;
+ let specs = [
+ ClientIdSpec {
+ client: own_base,
+ mask: ClientIdMask::LOCAL_CLIENT_PID,
+ },
+ ClientIdSpec {
+ client: window,
+ mask: ClientIdMask::LOCAL_CLIENT_PID,
+ },
+ ];
+ let reply = self.conn.res_query_client_ids(&specs).ok()?.reply().ok()?;
+ let values: Vec<XresClientValue<'_>> = reply
+ .ids
+ .iter()
+ .map(|id| XresClientValue {
+ client: id.spec.client,
+ mask: u32::from(id.spec.mask),
+ value: &id.value,
+ })
+ .collect();
+ let pid = select_owner_pid(
+ &values,
+ own_base,
+ std::process::id(),
+ client_base(window, setup.resource_id_mask),
+ )?;
+ // The server keys the query by the client slot in the XID. A window
+ // that still exists after the reply proves its creator held that slot
+ // when the server answered, so a recycled slot cannot be attributed.
+ self.conn.get_window_attributes(window).ok()?.reply().ok()?;
+ Some(pid)
+ }
+}
+
+/// `WM_CLIENT_MACHINE`, `None` when unset. Errors when the window is gone.
+fn get_client_machine(conn: &RustConnection, window: Window) -> Result<Option<String>> {
+ let reply = conn
+ .get_property(
+ false,
+ window,
+ AtomEnum::WM_CLIENT_MACHINE,
+ AtomEnum::ANY,
+ 0,
+ 256,
+ )?
+ .reply()?;
+ if reply.type_ == x11rb::NONE {
+ return Ok(None);
+ }
+ let value = String::from_utf8_lossy(&reply.value);
+ Ok(Some(value.trim_end_matches('\0').to_owned()))
+}
+
fn get_window_title(conn: &RustConnection, window: Window) -> Result<String> {
// Try _NET_WM_NAME (UTF-8) first.
if let Ok(atom) = get_atom(conn, "_NET_WM_NAME") {
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/x11_client_pid.rs b/libs/cua-driver/rust/crates/platform-linux/src/x11_client_pid.rs
new file mode 100644
index 0000000000..ee5d57e2bb
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/x11_client_pid.rs
@@ -0,0 +1,291 @@
+//! Pure selection rules for attributing an X11 toplevel to a local process
+//! when the client does not publish `_NET_WM_PID`.
+//!
+//! Tk, many Java/AWT builds, Wine, and legacy Xlib/Xt clients never set
+//! `_NET_WM_PID`. The X-Resource extension (`XResQueryClientIds` with
+//! `XRES_CLIENT_ID_PID_MASK`, XRes >= 1.2) lets the X server report the PID
+//! of the connection that created a resource, which it learns from the Unix
+//! socket peer credentials. That answer is only trustworthy when all of the
+//! following hold, and these rules fail closed otherwise:
+//!
+//! - the server reports our own connection's PID as our real PID, which proves
+//! the driver is a local client in the same PID namespace as the server (a
+//! remote `DISPLAY`, a TCP connection, or a container boundary fails this);
+//! - the server reports exactly one PID for the client that created the
+//! window, never the server itself (client 0 owns the root window);
+//! - the window does not name a different host in `WM_CLIENT_MACHINE`, which
+//! is how an SSH-forwarded client (whose socket peer is the local `ssh`
+//! process, not the application) identifies itself.
+//!
+//! The X11 I/O lives in `crate::x11`; everything here is platform-independent
+//! so it is unit-tested on every host.
+
+/// `XRES_CLIENT_ID_PID_MASK` (X-Resource 1.2, `LocalClientPID`).
+pub(crate) const LOCAL_CLIENT_PID_MASK: u32 = 1 << 1;
+
+/// One `ClientIdValue` of an `XResQueryClientIds` reply.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(crate) struct XresClientValue<'a> {
+ /// The client's resource-id base (`clientAsMask`), as echoed by the server.
+ pub client: u32,
+ pub mask: u32,
+ pub value: &'a [u32],
+}
+
+/// The XRes version that introduced `QueryClientIds`.
+pub(crate) fn xres_supports_client_ids(major: u16, minor: u16) -> bool {
+ (major, minor) >= (1, 2)
+}
+
+/// Resource-id base of the client that created `xid`: the server allocates
+/// every client a disjoint id range, so clearing the client-local bits of
+/// `resource_id_mask` (from the connection setup) names the creator.
+pub(crate) fn client_base(xid: u32, resource_id_mask: u32) -> u32 {
+ xid & !resource_id_mask
+}
+
+/// The PID the server reported for `client`, if it reported exactly one.
+fn reported_pid(values: &[XresClientValue<'_>], client: u32) -> Option<u32> {
+ let mut pids = values
+ .iter()
+ .filter(|v| v.client == client && v.mask == LOCAL_CLIENT_PID_MASK)
+ .map(|v| match v.value {
+ [pid] if *pid != 0 && i32::try_from(*pid).is_ok() => Some(*pid),
+ _ => None,
+ });
+ let first = pids.next()??;
+ pids.next().is_none().then_some(first)
+}
+
+/// Select the owner PID of the window created by the client at `target_base`
+/// from a reply that also covered our own client at `own_base`.
+///
+/// Returns `None` unless the server reported `own_pid` for our own
+/// connection (so its PIDs are local and in our namespace) and exactly one
+/// valid PID for the target client. The server's own resources (client base
+/// 0, e.g. the root window) are never attributed.
+pub(crate) fn select_owner_pid(
+ values: &[XresClientValue<'_>],
+ own_base: u32,
+ own_pid: u32,
+ target_base: u32,
+) -> Option<u32> {
+ if target_base == 0 || reported_pid(values, own_base) != Some(own_pid) {
+ return None;
+ }
+ reported_pid(values, target_base)
+}
+
+/// Whether `WM_CLIENT_MACHINE` allows a local-socket PID to stand for the
+/// application. An absent or empty property is accepted (most clients that
+/// omit `_NET_WM_PID` omit it too); a present one must name this host, and an
+/// unknown local hostname fails closed.
+pub(crate) fn client_machine_is_local(machine: Option<&str>, local_hostname: Option<&str>) -> bool {
+ let Some(machine) = machine.map(str::trim).filter(|m| !m.is_empty()) else {
+ return true;
+ };
+ let Some(local) = local_hostname.map(str::trim).filter(|h| !h.is_empty()) else {
+ return false;
+ };
+ let short = |name: &str| name.split('.').next().unwrap_or(name).to_ascii_lowercase();
+ machine.eq_ignore_ascii_case(local) || short(machine) == short(local)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const OWN_BASE: u32 = 0x0060_0000;
+ const OWN_PID: u32 = 4242;
+ const TK_BASE: u32 = 0x0120_0000;
+ const MASK: u32 = 0x001f_ffff;
+
+ #[test]
+ fn a_local_client_without_net_wm_pid_is_attributed_to_its_creator() {
+ let own = [OWN_PID];
+ let tk = [777];
+ let values = [
+ XresClientValue {
+ client: OWN_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &own,
+ },
+ XresClientValue {
+ client: TK_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &tk,
+ },
+ ];
+ let window = TK_BASE | 0x0000_0017;
+ assert_eq!(client_base(window, MASK), TK_BASE);
+ assert_eq!(
+ select_owner_pid(&values, OWN_BASE, OWN_PID, client_base(window, MASK)),
+ Some(777)
+ );
+ }
+
+ #[test]
+ fn a_remote_or_forwarded_target_without_a_pid_value_stays_unattributed() {
+ // The server returns no LocalClientPID value for TCP clients.
+ let own = [OWN_PID];
+ let values = [XresClientValue {
+ client: OWN_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &own,
+ }];
+ assert_eq!(select_owner_pid(&values, OWN_BASE, OWN_PID, TK_BASE), None);
+ }
+
+ #[test]
+ fn a_server_in_another_pid_namespace_or_host_is_never_trusted() {
+ // Our own connection reports a different PID (container boundary) or
+ // none at all (the driver itself reached the server over TCP).
+ let own = [1];
+ let tk = [777];
+ let foreign = [
+ XresClientValue {
+ client: OWN_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &own,
+ },
+ XresClientValue {
+ client: TK_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &tk,
+ },
+ ];
+ assert_eq!(select_owner_pid(&foreign, OWN_BASE, OWN_PID, TK_BASE), None);
+ let remote = [XresClientValue {
+ client: TK_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &tk,
+ }];
+ assert_eq!(select_owner_pid(&remote, OWN_BASE, OWN_PID, TK_BASE), None);
+ }
+
+ #[test]
+ fn ambiguous_malformed_or_invalid_pid_values_fail_closed() {
+ let own = [OWN_PID];
+ let a = [777];
+ let b = [778];
+ let two = [777, 778];
+ let zero = [0];
+ let negative = [u32::MAX];
+ let base = XresClientValue {
+ client: OWN_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &own,
+ };
+ for target in [&two[..], &zero[..], &negative[..], &[][..]] {
+ let values = [
+ base,
+ XresClientValue {
+ client: TK_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: target,
+ },
+ ];
+ assert_eq!(
+ select_owner_pid(&values, OWN_BASE, OWN_PID, TK_BASE),
+ None,
+ "{target:?}"
+ );
+ }
+ let duplicated = [
+ base,
+ XresClientValue {
+ client: TK_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &a,
+ },
+ XresClientValue {
+ client: TK_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &b,
+ },
+ ];
+ assert_eq!(
+ select_owner_pid(&duplicated, OWN_BASE, OWN_PID, TK_BASE),
+ None
+ );
+ // A CLIENT_XID value is not a PID.
+ let wrong_mask = [
+ base,
+ XresClientValue {
+ client: TK_BASE,
+ mask: 1,
+ value: &a,
+ },
+ ];
+ assert_eq!(
+ select_owner_pid(&wrong_mask, OWN_BASE, OWN_PID, TK_BASE),
+ None
+ );
+ }
+
+ #[test]
+ fn server_owned_resources_are_never_attributed() {
+ let own = [OWN_PID];
+ let server = [1];
+ let values = [
+ XresClientValue {
+ client: OWN_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &own,
+ },
+ XresClientValue {
+ client: 0,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &server,
+ },
+ ];
+ assert_eq!(select_owner_pid(&values, OWN_BASE, OWN_PID, 0), None);
+ }
+
+ #[test]
+ fn our_own_window_resolves_to_our_pid() {
+ let own = [OWN_PID];
+ let values = [XresClientValue {
+ client: OWN_BASE,
+ mask: LOCAL_CLIENT_PID_MASK,
+ value: &own,
+ }];
+ assert_eq!(
+ select_owner_pid(&values, OWN_BASE, OWN_PID, OWN_BASE),
+ Some(OWN_PID)
+ );
+ }
+
+ #[test]
+ fn query_client_ids_requires_xres_1_2() {
+ assert!(!xres_supports_client_ids(1, 0));
+ assert!(!xres_supports_client_ids(1, 1));
+ assert!(xres_supports_client_ids(1, 2));
+ assert!(xres_supports_client_ids(2, 0));
+ }
+
+ #[test]
+ fn wm_client_machine_must_be_absent_or_this_host() {
+ assert!(client_machine_is_local(None, Some("ci-runner")));
+ assert!(client_machine_is_local(Some(""), None));
+ assert!(client_machine_is_local(
+ Some("ci-runner"),
+ Some("ci-runner")
+ ));
+ assert!(client_machine_is_local(
+ Some("CI-Runner.example.com"),
+ Some("ci-runner")
+ ));
+ assert!(client_machine_is_local(
+ Some("ci-runner"),
+ Some("ci-runner.local\n")
+ ));
+ // An SSH-forwarded client names its remote host.
+ assert!(!client_machine_is_local(
+ Some("build-box"),
+ Some("ci-runner")
+ ));
+ // Unknown local hostname: cannot prove a named machine is local.
+ assert!(!client_machine_is_local(Some("ci-runner"), None));
+ }
+}
diff --git a/scripts/ci/linux/run-rust-e2e.sh b/scripts/ci/linux/run-rust-e2e.sh
index e7be5f1641..cfe0749080 100755
--- a/scripts/ci/linux/run-rust-e2e.sh
+++ b/scripts/ci/linux/run-rust-e2e.sh
@@ -363,6 +363,26 @@ if [[ "${SUITE}" == capture || "${SUITE}" == all ]]; then
cargo test -p cua-driver-e2e "${CARGO_DRIVER_FEATURE_ARGS[@]}" \
--test desktop_scope_linux_test -- \
--ignored --nocapture --test-threads=1
+ if [[ -z "${WAYLAND_DISPLAY:-}" ]]; then
+ run_test x11-unpublished-pid \
+ cargo test -p cua-driver-e2e "${CARGO_DRIVER_FEATURE_ARGS[@]}" \
+ --test x11_unpublished_pid_linux_test -- \
+ --ignored --nocapture --test-threads=1
+ else
+ limitation="The unpublished-_NET_WM_PID case maps a bare X11 client and runs in the canonical X11 lane."
+ jq -n \
+ --arg reason "${limitation}" \
+ '{
+ schema: "cua-e2e-limitation-v1",
+ platform: "linux",
+ display_server: "wayland",
+ harness: "x11-bare-client",
+ test: "x11-unpublished-pid",
+ status: "not_applicable",
+ reason: $reason
+ }' > "${ARTIFACT_DIR}/x11-unpublished-pid-limitation.json"
+ echo "[LIMITATION] x11-unpublished-pid: ${limitation}"
+ fi
if [[ -z "${WAYLAND_DISPLAY:-}" ]]; then
run_test perception-capture-loop \
cargo test -p cua-driver-e2e "${CARGO_DRIVER_FEATURE_ARGS[@]}" \