fix(input): preserve keyboard modifiers while preventing forged lock keys (#34)

This commit is contained in:
喵喵机 authored and GitHub committed 2026-11-09 23:25:07 +08:00
1 parent 62cf979dd6
commit 6d0e733cd7
31 files changed
+569 -40

No files matched your search

+1 -1
View File
@@ -52,7 +52,7 @@ pub fn sync_wine(prefix: &Path) -> Result<Backend> {
Backend::None => None,
};
if let Some(driver) = driver {
let status = Command::new("wine")
let status = crate::wine::command(prefix)
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all")
.args([
+9
View File
@@ -28,6 +28,14 @@ pub struct Config {
pub capture_backend: String,
/// Named Wayland output for direct capture; a single-output session needs no name.
pub capture_output: Option<String>,
/// Strip these X11 modifier bits from key events handed to the managed
/// client. Wine reconciles its asynchronous keyboard state against the
/// modifier bits on every key event and, when the client's low-level hook
/// swallows lock keys, forges a lock-key down/up pair per keystroke. The
/// "auto" discovers NumLock/ScrollLock from the actual X11 keymap.
/// Shortcut, layout, case and keypad modifiers are preserved. Numeric
/// masks restrict this discovered set; 0 disables the workaround.
pub strip_lock_mods: Option<String>,
}
impl Default for Config {
@@ -43,6 +51,7 @@ impl Default for Config {
capture_source: "monitor".into(),
capture_backend: "portal".into(),
capture_output: None,
strip_lock_mods: Some("auto".into()),
}
}
}
+23
View File
@@ -347,6 +347,29 @@ pub fn report() -> Result<()> {
let session_type = std::env::var("XDG_SESSION_TYPE").unwrap_or_default();
let on_wayland = session_type == "wayland" || std::env::var_os("WAYLAND_DISPLAY").is_some();
let configured = crate::config::Config::load()?;
if std::env::var_os("DISPLAY").is_some() {
match crate::input::xtest::lock_state() {
Ok(state) => line("info", "X11 lock state", &state),
Err(error) => line("WARN", "X11 lock state", &error.to_string()),
}
let policy = configured.strip_lock_mods.as_deref().unwrap_or("disabled");
let shim = crate::session::lock_mods_shim();
let disabled = matches!(policy, "disabled" | "0" | "0x0" | "0x00");
line(
if !disabled && shim.is_none() {
"WARN"
} else {
"info"
},
"Wine keyboard workaround",
&format!(
"{policy}; shim={}; case/keypad remain native",
shim.as_deref()
.map(|path| path.display().to_string())
.unwrap_or_else(|| "not installed".into())
),
);
}
line(
"info",
"capture backend",
+43
View File
@@ -15,6 +15,49 @@ const FAKE_MOTION: u8 = 6;
/// XTEST detail for motion: 0 = absolute, 1 = relative.
const MOTION_RELATIVE: u8 = 1;
/// Observe this display's effective lock state without changing any XKB state.
pub(crate) fn lock_state() -> Result<String> {
let (connection, screen) = x11rb::connect(None)?;
let setup = connection.setup();
let state = u16::from(
connection
.query_pointer(setup.roots[screen].root)?
.reply()?
.mask,
);
let modifiers = connection.get_modifier_mapping()?.reply()?;
let keys = connection
.get_keyboard_mapping(setup.min_keycode, setup.max_keycode - setup.min_keycode + 1)?
.reply()?;
let width = modifiers.keycodes.len() / 8;
let mut num = 0u16;
let mut scroll = 0u16;
for (index, code) in modifiers.keycodes.iter().copied().enumerate() {
if code < setup.min_keycode || width == 0 {
continue;
}
let offset = usize::from(code - setup.min_keycode) * usize::from(keys.keysyms_per_keycode);
let symbols = keys
.keysyms
.get(offset..offset + usize::from(keys.keysyms_per_keycode));
if let Some(symbols) = symbols {
if symbols.contains(&0xff7f) {
num |= 1 << (index / width);
}
if symbols.contains(&0xff14) {
scroll |= 1 << (index / width);
}
}
}
let flag = |mask| if state & mask != 0 { "on" } else { "off" };
Ok(format!(
"CapsLock={} NumLock={} ScrollLock={} (Num mask={num:#x}, Scroll mask={scroll:#x})",
flag(2),
flag(num),
flag(scroll)
))
}
/// X11 XTest injection. Works on every X11 session; on XWayland it reaches
/// XWayland-native windows only, which is why the portal backend is
/// preferred on Wayland-only sessions.
+1 -1
View File
@@ -66,7 +66,7 @@ pub fn prepare(prefix: &Path, proxy: &Path) -> Result<usize> {
std::fs::write(root.with_extension("keys"), keys.join("\n") + "\n")?;
let registry_path = prefix.join("drive_c/uur-linux-apps.reg");
write_utf16_registry(&registry_path, &registry)?;
let status = Command::new("wine")
let status = crate::wine::command(prefix)
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all")
.args(["reg", "import"])
+2 -2
View File
@@ -2,7 +2,7 @@
use anyhow::{Context, Result};
use std::path::Path;
use std::process::{Command, Stdio};
use std::process::Stdio;
pub fn sync(prefix: &Path) -> Result<Option<String>> {
let http = environment_proxy("HTTP_PROXY", "http_proxy");
@@ -60,7 +60,7 @@ fn proxy_endpoint(value: &str) -> Option<String> {
}
fn reg_add(prefix: &Path, value: &str, kind: &str, data: &str) -> Result<()> {
let status = Command::new("wine")
let status = crate::wine::command(prefix)
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all")
.args([
+182 -14
View File
@@ -71,6 +71,93 @@ fn hook_source_dir() -> Result<PathBuf> {
hook_dir()
}
/// Path of the lock-modifier shim that is LD_PRELOADed into the managed Wine
/// processes. Layout mirrors the other native helpers (installed under
/// `<prefix>/lib/uur`, found next to the build tree during development).
pub(crate) fn lock_mods_shim() -> Option<PathBuf> {
let mut candidates = Vec::new();
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
candidates.push(dir.join("../lib/uur/libuur-lock-mods.so"));
candidates.push(dir.join("../../build/compat/libuur-lock-mods.so"));
candidates.push(dir.join("libuur-lock-mods.so"));
}
}
candidates.push(PathBuf::from("/usr/lib/uur/libuur-lock-mods.so"));
candidates.push(PathBuf::from("/usr/local/lib/uur/libuur-lock-mods.so"));
if let Ok(home) = std::env::var("HOME") {
candidates.push(PathBuf::from(&home).join(".local/lib/uur/libuur-lock-mods.so"));
}
if let Ok(directory) = std::env::current_dir() {
candidates.push(directory.join("build/compat/libuur-lock-mods.so"));
}
candidates.into_iter().find(|path| path.is_file())
}
/// Environment for the managed client: keep Wine from forging lock-key
/// events when X11 reports a locked modifier that the client's keyboard hook
/// swallows. See `compat/uur-lock-mods.c` for the full rationale.
///
/// This only affects the child process environment; the X server, the
/// compositor and the user's NumLock setting are never touched.
fn lock_mods_mask(config: &Config) -> Result<Option<String>> {
let Some(mask) = config.strip_lock_mods.as_deref().map(str::trim) else {
return Ok(None);
};
if mask == "auto" {
return Ok(Some(mask.to_string()));
}
let value = match mask.strip_prefix("0x").or_else(|| mask.strip_prefix("0X")) {
Some(hex) => u8::from_str_radix(hex, 16),
None => mask.parse::<u8>(),
}
.context("strip_lock_mods must be auto, 0, or an 8-bit decimal/hex mask")?;
Ok((value != 0).then(|| format!("0x{value:x}")))
}
pub(crate) fn apply_lock_mods_env(command: &mut Command, config: &Config) -> Result<()> {
apply_lock_mods_with_shim(
command,
config,
lock_mods_shim().as_deref(),
std::env::var_os("LD_PRELOAD").as_deref(),
)
}
fn apply_lock_mods_with_shim(
command: &mut Command,
config: &Config,
shim: Option<&Path>,
existing: Option<&std::ffi::OsStr>,
) -> Result<()> {
let Some(mask) = lock_mods_mask(config)? else {
return Ok(());
};
let Some(shim) = shim else {
eprintln!("lock-modifier shim not found; leaving Wine keyboard handling untouched");
return Ok(());
};
// The dynamic loader splits LD_PRELOAD on ':' and whitespace and offers no
// escaping, so a path containing either cannot be expressed there.
let Some(shim_text) = shim.to_str() else {
eprintln!("lock-modifier shim path must be valid UTF-8; skipping it");
return Ok(());
};
if shim_text.contains(':') || shim_text.chars().any(|ch| ch.is_ascii_whitespace()) {
eprintln!("lock-modifier shim path cannot be expressed in LD_PRELOAD; skipping it");
return Ok(());
}
let mut preload = shim.as_os_str().to_os_string();
if let Some(existing) = existing.filter(|value| !value.is_empty()) {
preload.push(":");
preload.push(existing);
}
command
.env("UUR_STRIP_LOCK_MODS", mask)
.env("LD_PRELOAD", preload);
Ok(())
}
static DEPLOY_TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
/// Replace a managed prefix file without inheriting the source's permissions.
@@ -214,7 +301,7 @@ fn deploy_terminal_proxy(install_dir: &Path) -> Result<PathBuf> {
const WEBVIEW2_DLL_OVERRIDES: &str = "wtsapi32=b,wevtapi=b";
fn webview2_install_command(prefix: &Path, bootstrapper: &Path) -> Command {
let mut command = Command::new("wine");
let mut command = crate::wine::command(prefix);
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
@@ -404,6 +491,7 @@ pub fn start() -> Result<()> {
let _session_lock = acquire_session_lock()?;
rotate_session_log();
let config = Config::load()?;
let _ = lock_mods_mask(&config)?;
let on_wayland = std::env::var_os("WAYLAND_DISPLAY").is_some()
|| std::env::var("XDG_SESSION_TYPE").is_ok_and(|session| session == "wayland");
let prefix = data_dir()?.join("wine");
@@ -413,6 +501,12 @@ pub fn start() -> Result<()> {
anyhow::bail!("{}", t!("setup.service_incomplete"));
}
let mut resources = SessionResources::new(prefix.clone());
if lock_mods_mask(&config)?.is_some() && lock_mods_shim().is_some() {
// A server left by setup or an older client has the old environment.
// The session lock excludes a running uur session; restart only this
// managed prefix so its SCM-spawned clients inherit the same shim.
stop_wineserver(&prefix);
}
if let Some(dpi) = xft_dpi() {
match crate::wine::set_log_pixels(&prefix, dpi) {
Ok(()) => println!("{}", t!("session.wine_dpi", dpi = dpi)),
@@ -532,7 +626,7 @@ pub fn start() -> Result<()> {
// Windows process table without repeatedly initializing Wine utilities.
use std::os::unix::process::CommandExt;
let marker = hook_dir()?.join("winlogon.exe");
let mut monitor = Command::new("wine")
let mut monitor = crate::wine::command(&prefix)
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
@@ -561,7 +655,7 @@ pub fn start() -> Result<()> {
// waits forever.
if !service_running(&prefix) {
let _ = run_with_timeout(
Command::new("wine")
crate::wine::command(&prefix)
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
@@ -585,7 +679,8 @@ pub fn start() -> Result<()> {
println!("{}", t!("session.launching_client"));
let ui = install_dir.join("GameViewer.exe");
let launch = || -> Result<Child> {
Command::new("wine")
let mut command = crate::wine::command(&prefix);
command
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.current_dir(&install_dir)
@@ -595,9 +690,8 @@ pub fn start() -> Result<()> {
.env("UUR_BRIDGE_TOKEN", config.bridge_token.clone())
.stdout(Stdio::from(log.try_clone()?))
.stderr(Stdio::from(log.try_clone()?))
.arg(ui.to_string_lossy().as_ref())
.spawn()
.context("launching the managed client")
.arg(ui.to_string_lossy().as_ref());
command.spawn().context("launching the managed client")
};
// Start the client detached: it IS the session's lifetime anchor.
@@ -759,7 +853,7 @@ fn run_with_timeout(command: &mut Command, timeout: std::time::Duration) -> Opti
/// True when the Windows service reports STATE 4 (RUNNING) via `sc query`.
fn service_running(prefix: &Path) -> bool {
let output = run_with_timeout(
Command::new("wine")
crate::wine::command(prefix)
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=b;wtsapi32=b")
@@ -817,7 +911,8 @@ pub(crate) fn show_client() -> Result<()> {
if process_start_time(pid).ok() != Some(start) {
anyhow::bail!("managed session is not running");
}
let mut child = Command::new("wine")
let mut command = crate::wine::command(&prefix);
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n")
@@ -825,9 +920,8 @@ pub(crate) fn show_client() -> Result<()> {
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.arg(install.join("GameViewer.exe"))
.spawn()
.context("showing the managed client")?;
.arg(install.join("GameViewer.exe"));
let mut child = command.spawn().context("showing the managed client")?;
thread::spawn(move || {
let _ = child.wait();
});
@@ -1037,9 +1131,16 @@ fn wine_process_matches(directory: &Path, prefix: &Path) -> bool {
let Ok(executable) = std::fs::read_link(directory.join("exe")) else {
return false;
};
let name = executable
.file_name()
.and_then(|name| name.to_str())
.unwrap_or_default();
let name = name.strip_suffix(" (deleted)").unwrap_or(name);
let name = name.strip_prefix('.').unwrap_or(name);
let name = name.strip_suffix("-wrapped").unwrap_or(name);
if !matches!(
executable.file_name().and_then(|name| name.to_str()),
Some("wine" | "wine64" | "wine-preloader" | "wine64-preloader" | "wineserver")
name,
"wine" | "wine64" | "wine-preloader" | "wine64-preloader" | "wineserver"
) {
return false;
}
@@ -1109,6 +1210,73 @@ mod tests {
}
}
fn command_env(command: &Command, key: &str) -> Option<String> {
command
.get_envs()
.find(|(name, _)| *name == OsStr::new(key))
.and_then(|(_, value)| value)
.map(|value| value.to_string_lossy().into_owned())
}
#[test]
fn lock_modifier_env_is_skipped_when_disabled() {
for mask in [None, Some("0".to_string()), Some("0x00".to_string())] {
let config = Config {
strip_lock_mods: mask,
..Config::default()
};
let mut command = Command::new("wine");
apply_lock_mods_with_shim(&mut command, &config, Some(Path::new("/shim.so")), None)
.unwrap();
assert!(command_env(&command, "LD_PRELOAD").is_none());
assert!(command_env(&command, "UUR_STRIP_LOCK_MODS").is_none());
}
}
#[test]
fn lock_modifier_env_sets_mask_and_preloads_shim() {
let config = Config {
strip_lock_mods: Some("0x50".into()),
..Config::default()
};
let mut command = Command::new("wine");
apply_lock_mods_with_shim(
&mut command,
&config,
Some(Path::new("/build/compat/libuur-lock-mods.so")),
Some(OsStr::new("/nonexistent/first.so")),
)
.unwrap();
assert_eq!(
command_env(&command, "UUR_STRIP_LOCK_MODS").as_deref(),
Some("0x50")
);
let preload = command_env(&command, "LD_PRELOAD").expect("preload set");
assert!(preload.ends_with("/build/compat/libuur-lock-mods.so:/nonexistent/first.so"));
}
#[test]
fn lock_modifier_env_reports_missing_shim_without_failing() {
let config = Config::default();
let mut command = Command::new("wine");
apply_lock_mods_with_shim(&mut command, &config, None, None).unwrap();
let mask = command_env(&command, "UUR_STRIP_LOCK_MODS");
let preload = command_env(&command, "LD_PRELOAD");
assert_eq!(mask.is_some(), preload.is_some());
assert!(mask.is_none());
for path in [
"/bad path/shim.so",
"/bad\npath/shim.so",
"/bad:path/shim.so",
] {
let mut command = Command::new("wine");
apply_lock_mods_with_shim(&mut command, &config, Some(Path::new(path)), None).unwrap();
assert!(command_env(&command, "LD_PRELOAD").is_none());
assert!(command_env(&command, "UUR_STRIP_LOCK_MODS").is_none());
}
}
#[test]
fn deploy_file_repairs_readonly_targets_and_is_repeatable() {
let directory = TestDirectory::create();
+1
View File
@@ -254,6 +254,7 @@ impl Plan {
"lib/uur/user-install",
"lib/uur/uur-pw-capture",
"lib/uur/uur-wl-capture",
"lib/uur/libuur-lock-mods.so",
"lib/uur/hook/wevtapi.dll",
"lib/uur/hook/uur-hook.dll",
"lib/uur/hook/wtsapi32.dll",
+1 -1
View File
@@ -71,7 +71,7 @@ fn extract_version(filename: &str) -> Option<String> {
fn installed_version() -> Option<String> {
let prefix = crate::config::data_dir().ok()?.join("wine");
crate::wine::find_client_dir(&prefix)?;
let output = Command::new("wine")
let output = crate::wine::command(&prefix)
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", "-all")
.args([
+1 -1
View File
@@ -90,7 +90,7 @@ pub fn sync(prefix: &Path) -> Result<Option<Wallpaper>> {
};
let compatible = windows_compatible_path(&wallpaper.path)?;
let windows_path = format!("Z:{}", compatible.display()).replace('/', "\\");
let status = Command::new("wine")
let status = crate::wine::command(prefix)
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", "-all")
.args([
+21 -5
View File
@@ -9,6 +9,22 @@ const OFFICIAL_DOWNLOAD_URL: &str = "https://api.nrd.nie.163.com/api/v1/release/
const EULA_URL: &str = "https://uuyc.163.com/contact/20240402/40294_1146065.html";
const SETUP_DLL_OVERRIDES: &str = "wevtapi=b,wtsapi32=b";
/// Apply process-local compatibility to every managed-prefix Wine launch,
/// including the first utility that starts wineserver and its service manager.
pub(crate) fn command(prefix: &Path) -> Command {
let mut command = Command::new("wine");
command.env("WINEPREFIX", prefix);
let managed = crate::config::data_dir().is_ok_and(|data| data.join("wine") == prefix);
if managed {
if let Ok(config) = Config::load() {
if let Err(error) = crate::session::apply_lock_mods_env(&mut command, &config) {
eprintln!("Wine keyboard compatibility unavailable: {error}");
}
}
}
command
}
struct SetupPrefix(PathBuf);
impl Drop for SetupPrefix {
@@ -90,7 +106,7 @@ pub fn setup(accept_eula: bool, repair: bool) -> Result<()> {
}
println!("{}", t!("setup.installing_client"));
let status = Command::new("wine")
let status = command(&prefix)
.env("WINEPREFIX", &prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
@@ -174,7 +190,7 @@ pub fn client_service_registered(prefix: &Path) -> bool {
}
fn query_client_service(prefix: &Path) -> Result<bool> {
let output = Command::new("wine")
let output = command(prefix)
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.env("WINEDLLOVERRIDES", SETUP_DLL_OVERRIDES)
@@ -260,7 +276,7 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
format!("HKCU\\{key}")
};
for (value, reg_type, data) in &values {
let status = Command::new("wine")
let status = command(prefix)
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.args([
@@ -280,7 +296,7 @@ pub fn apply_registry_compat(prefix: &Path) -> Result<()> {
}
pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> {
let status = Command::new("wine")
let status = command(prefix)
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())
.args([
@@ -317,7 +333,7 @@ pub fn set_log_pixels(prefix: &Path, dpi: u32) -> Result<()> {
}
fn log_pixels_command(prefix: &Path, dpi: u32) -> Command {
let mut command = Command::new("wine");
let mut command = command(prefix);
command
.env("WINEPREFIX", prefix)
.env("WINEDEBUG", wine_debug())