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

+7 -2
View File
@@ -13,6 +13,8 @@ jobs:
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
- name: Install X11 headers for the compatibility library
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libx11-dev pkg-config
- name: Rust checks
run: |
cargo fmt --check
@@ -22,6 +24,8 @@ jobs:
/tmp/frame-protocol
cc -std=c11 -O2 -Wall -Wextra -Werror tests/cursor-overlay.c -o /tmp/cursor-overlay
/tmp/cursor-overlay
- name: Build the lock-modifier compatibility library
run: ./compat/build.sh
- name: Build
run: cargo build --locked --release
@@ -50,13 +54,14 @@ jobs:
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
appstream binutils-mingw-w64-x86-64 desktop-file-utils \
gcc gcc-mingw-w64-x86-64 libpipewire-0.3-dev libwayland-dev pkg-config \
wine xvfb
gcc gcc-mingw-w64-x86-64 libpipewire-0.3-dev libwayland-dev \
libx11-dev libxtst-dev pkg-config wine xvfb
- name: Build and stage
run: |
cargo build --release --locked
./hook/build.sh
./capture/build.sh
./compat/build.sh
stage="$(mktemp -d)"
./packaging/stage.sh "$stage"
test -x "$stage/usr/bin/uur"
+3 -2
View File
@@ -39,7 +39,7 @@ jobs:
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
binutils-mingw-w64-x86-64 gcc libpipewire-0.3-dev libwayland-dev \
gcc-mingw-w64-x86-64 pkg-config zstd
gcc-mingw-w64-x86-64 libx11-dev pkg-config zstd
- name: Install nFPM
env:
NFPM_VERSION: 2.47.0
@@ -73,7 +73,7 @@ jobs:
- name: Install Arch build dependencies
run: |
pacman -Syu --noconfirm \
cargo rust gcc pkgconf pipewire wayland \
cargo rust gcc pkgconf pipewire wayland libx11 \
mingw-w64-gcc mingw-w64-binutils
- name: Build native pacman package with makepkg
run: |
@@ -84,6 +84,7 @@ jobs:
CARGO_BUILD_JOBS=2 cargo build --release --locked
./hook/build.sh
./capture/build.sh
./compat/build.sh
./packaging/build-arch-package.sh "$1/dist"
' _ "$GITHUB_WORKSPACE"
- uses: actions/upload-artifact@v4
+1
View File
@@ -126,6 +126,7 @@ An `APKBUILD` is included under `packaging/alpine/`.
cargo build --release --locked
./hook/build.sh
./capture/build.sh
./compat/build.sh
./scripts/install-user.sh
```
+1
View File
@@ -122,6 +122,7 @@ docker build -f packaging/alpine/Dockerfile .
cargo build --release --locked
./hook/build.sh
./capture/build.sh
./compat/build.sh
./scripts/install-user.sh
```
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env bash
# Build the Wine lock-modifier shim (LD_PRELOAD, links libX11).
set -euo pipefail
root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)
readonly root
out="$root/build/compat"
cc="${CC:-gcc}"
flags=(-std=c11 -O2 -Wall -Wextra -Werror -fPIC -pthread)
command -v "$cc" >/dev/null 2>&1 || { printf 'missing tool: %s\n' "$cc" >&2; exit 1; }
command -v pkg-config >/dev/null 2>&1 || { printf 'missing tool: pkg-config\n' >&2; exit 1; }
mkdir -p "$out"
"$cc" "${flags[@]}" -shared -o "$out/libuur-lock-mods.so" \
"$root/compat/uur-lock-mods.c" \
$(pkg-config --cflags --libs x11) -ldl
printf 'built: %s\n' "$out/libuur-lock-mods.so"
+193
View File
@@ -0,0 +1,193 @@
/* Process-local workaround for Wine/UU lock-key reconciliation. */
#define _GNU_SOURCE
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/XKBlib.h>
#include <X11/keysym.h>
#include <dlfcn.h>
#include <errno.h>
#include <limits.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef Bool (*predicate_fn)(Display *, XEvent *, XPointer);
static pthread_once_t init_once = PTHREAD_ONCE_INIT;
static unsigned int requested_mask;
static int enabled;
static _Atomic unsigned long generation = 1;
static _Thread_local Display *cached_display;
static _Thread_local unsigned long cached_generation;
static _Thread_local unsigned int cached_mask;
#define EVENT_FUNCTIONS(X) \
X(int, XNextEvent, (Display *d, XEvent *e), (d, e), rc == 0) \
X(int, XPeekEvent, (Display *d, XEvent *e), (d, e), rc == 0) \
X(int, XWindowEvent, (Display *d, Window w, long m, XEvent *e), (d, w, m, e), rc == 0) \
X(Bool, XCheckWindowEvent, (Display *d, Window w, long m, XEvent *e), (d, w, m, e), rc != 0) \
X(int, XMaskEvent, (Display *d, long m, XEvent *e), (d, m, e), rc == 0) \
X(Bool, XCheckMaskEvent, (Display *d, long m, XEvent *e), (d, m, e), rc != 0) \
X(Bool, XCheckTypedEvent, (Display *d, int t, XEvent *e), (d, t, e), rc != 0) \
X(Bool, XCheckTypedWindowEvent, (Display *d, Window w, int t, XEvent *e), (d, w, t, e), rc != 0) \
X(int, XIfEvent, (Display *d, XEvent *e, predicate_fn p, XPointer a), (d, e, p, a), rc == 0) \
X(int, XPeekIfEvent, (Display *d, XEvent *e, predicate_fn p, XPointer a), (d, e, p, a), rc == 0) \
X(Bool, XCheckIfEvent, (Display *d, XEvent *e, predicate_fn p, XPointer a), (d, e, p, a), rc != 0)
#define DECLARE(result, name, args, call, success) static result (*real_##name) args;
EVENT_FUNCTIONS(DECLARE)
#undef DECLARE
static int (*real_XRefreshKeyboardMapping)(XMappingEvent *);
static Status (*real_XkbRefreshKeyboardMapping)(XkbMapNotifyEvent *);
static int (*real_XCloseDisplay)(Display *);
static void *symbol(const char *name)
{
void *address = dlsym(RTLD_NEXT, name);
if (address == NULL) {
fprintf(stderr, "uur keyboard compatibility: cannot resolve %s\n", name);
abort();
}
return address;
}
static int wine_process(void)
{
char executable[PATH_MAX];
ssize_t size = readlink("/proc/self/exe", executable, sizeof(executable) - 1);
if (size <= 0 || (size_t)size >= sizeof(executable) - 1)
return 0;
executable[size] = '\0';
char *deleted = strstr(executable, " (deleted)");
if (deleted != NULL)
*deleted = '\0';
char *name = strrchr(executable, '/');
name = name == NULL ? executable : name + 1;
if (*name == '.')
name++;
char *wrapped = strstr(name, "-wrapped");
if (wrapped != NULL && wrapped[8] == '\0')
*wrapped = '\0';
return !strcmp(name, "wine") || !strcmp(name, "wine64") ||
!strcmp(name, "wine-preloader") || !strcmp(name, "wine64-preloader") ||
!strcmp(name, "wineserver");
}
static void initialize(void)
{
#define RESOLVE(result, name, args, call, success) real_##name = symbol(#name);
EVENT_FUNCTIONS(RESOLVE)
#undef RESOLVE
real_XRefreshKeyboardMapping = symbol("XRefreshKeyboardMapping");
real_XkbRefreshKeyboardMapping = symbol("XkbRefreshKeyboardMapping");
real_XCloseDisplay = symbol("XCloseDisplay");
if (getenv("WINEPREFIX") == NULL || !wine_process())
return;
const char *mask = getenv("UUR_STRIP_LOCK_MODS");
requested_mask = 0xff;
if (mask != NULL && strcmp(mask, "auto")) {
char *end;
errno = 0;
unsigned long value = strtoul(mask, &end,
mask[0] == '0' && (mask[1] == 'x' || mask[1] == 'X') ? 16 : 10);
if (errno || end == mask || *end != '\0' || value > 0xff) {
fprintf(stderr, "uur keyboard compatibility: invalid modifier mask\n");
return;
}
requested_mask = (unsigned int)value;
}
enabled = requested_mask != 0;
}
/* A modifier shared with a shortcut/layout key is left alone. CapsLock and
* ShiftLock are never removed: their state affects character translation. */
static unsigned int locking_mask(Display *display)
{
unsigned long current = atomic_load_explicit(&generation, memory_order_relaxed);
if (cached_display == display && cached_generation == current)
return cached_mask;
unsigned int mask = 0;
XModifierKeymap *mapping = XGetModifierMapping(display);
if (mapping != NULL) {
for (int modifier = 3; modifier < 8; ++modifier) {
int locking = 0, other = 0;
for (int key = 0; key < mapping->max_keypermod; ++key) {
KeyCode code = mapping->modifiermap[modifier * mapping->max_keypermod + key];
if (code == 0)
continue;
int lock_key = 0;
for (int level = 0; level < 4; ++level) {
KeySym sym = XkbKeycodeToKeysym(display, code, 0, level);
if (sym == XK_Num_Lock || sym == XK_Scroll_Lock)
lock_key = 1;
else if (sym != NoSymbol)
other = 1;
}
if (lock_key)
locking = 1;
else
other = 1;
}
if (locking && !other)
mask |= 1u << modifier;
}
XFreeModifiermap(mapping);
}
cached_display = display;
cached_generation = current;
cached_mask = mask & requested_mask;
return cached_mask;
}
static void scrub(Display *display, XEvent *event)
{
if (!enabled || event == NULL)
return;
if (event->type == MappingNotify) {
atomic_fetch_add_explicit(&generation, 1, memory_order_relaxed);
return;
}
if (event->type != KeyPress && event->type != KeyRelease)
return;
/* NumLock changes keypad virtual keys in EVENT_event_to_vkey(). Leave
* those events intact rather than turning numeric input into navigation. */
KeySym key = XkbKeycodeToKeysym(display, event->xkey.keycode, 0, 0);
if (IsKeypadKey(key))
return;
event->xkey.state &= ~locking_mask(display);
}
#define IMPLEMENT(result, name, args, call, success) \
result name args { \
pthread_once(&init_once, initialize); \
result rc = real_##name call; \
if (success) scrub(d, e); \
return rc; \
}
EVENT_FUNCTIONS(IMPLEMENT)
#undef IMPLEMENT
int XRefreshKeyboardMapping(XMappingEvent *event)
{
pthread_once(&init_once, initialize);
int result = real_XRefreshKeyboardMapping(event);
atomic_fetch_add_explicit(&generation, 1, memory_order_relaxed);
return result;
}
Status XkbRefreshKeyboardMapping(XkbMapNotifyEvent *event)
{
pthread_once(&init_once, initialize);
Status result = real_XkbRefreshKeyboardMapping(event);
atomic_fetch_add_explicit(&generation, 1, memory_order_relaxed);
return result;
}
int XCloseDisplay(Display *display)
{
pthread_once(&init_once, initialize);
atomic_fetch_add_explicit(&generation, 1, memory_order_relaxed);
return real_XCloseDisplay(display);
}
+1 -1
View File
@@ -6,7 +6,7 @@ adapts stable Windows APIs at runtime; the Rust host owns policy, desktop
integration, and process lifetime.
```text
UU Remote / Wine
UU Remote / Wine (LD_PRELOAD: compat/libuur-lock-mods.so)
└─ PE ABI adapter (SendInput, GDI/DXGI capture entry points)
└─ authenticated loopback protocol + private frame transport
└─ Rust session supervisor
+2 -1
View File
@@ -79,7 +79,7 @@ sudo apk add ~/packages/*/x86_64/uur-*.apk
Gentoo, Funtoo, Void Linux, Slackware, Solus, Clear Linux, ALT Linux, Exherbo,
Mageia, OpenMandriva, PCLinuxOS, Venom Linux, and other FHS/glibc systems can
install the portable release archive or build from source. Their native recipe
can call `packaging/stage.sh` after the three standard builds; the staged tree
can call `packaging/stage.sh` after the standard builds (`hook`, `capture`, `compat`); the staged tree
is shared with pacman, deb, rpm, APK, and the portable archive.
GNU Guix can wrap the same source build and staged tree. Flatpak and Snap need
@@ -91,6 +91,7 @@ manifests granting Wine execution, session D-Bus, PipeWire, and input access.
cargo build --release --locked
./hook/build.sh
./capture/build.sh
./compat/build.sh
./scripts/install-user.sh
```
+1 -1
View File
@@ -6,7 +6,7 @@
| Receive remote video | available | Official UU UI under Wine |
| Share X11 desktop | available | Wine X11 capture |
| Share Wayland desktop | available | ScreenCast/PipeWire or explicitly enabled native screencopy → GDI adapter |
| Mouse and keyboard | implemented | RemoteDesktop portal → uinput → XTest capability order |
| Mouse and keyboard | implemented | RemoteDesktop portal → uinput → XTest capability order; process-local NumLock/ScrollLock workaround for ordinary controller keys; keypad/case behavior remains native |
| X11 multi-monitor | Wine integration | Native Wine/XRandR display topology |
| Wayland monitor/window selection | available | Persistent portal source selection |
| Wayland virtual source | available when advertised | `uur display source virtual` → ScreenCast Virtual source |
+26
View File
@@ -100,6 +100,7 @@ Alternatively, build and install for one user:
cargo build --release --locked
./hook/build.sh
./capture/build.sh
./compat/build.sh
./scripts/install-user.sh
```
@@ -132,6 +133,31 @@ Openbox, Fluxbox, IceWM, dwm, qtile, herbstluftwm, spectrwm, and FVWM.
Wine captures the X11 desktop directly and uur injects input with XTest. A
ScreenCast portal is not required for this path.
#### Lock modifier bits in the client's key events
Wine can inject a NumLock correction pair on each ordinary key when the
official client's low-level hook blocks lock-key synchronization. This affects
controller-side typing before uur's remote-input bridge receives any records.
The process-local `libuur-lock-mods.so` workaround discovers exclusive NumLock
and ScrollLock modifiers from each X11 display's actual keymap. With
`strip_lock_mods = "auto"` (the default), it filters those bits on ordinary key
events. Numeric masks further restrict the discovered set; `"0"` disables it.
It preserves Super, Ctrl, Alt, AltGr, Shift and CapsLock rather than assuming
that Mod2 and Mod4 are both locks, and refreshes its mapping after layout
changes. No X server, compositor or user lock setting is changed.
Keypad events keep their original state so NumLock-on digits do not become
navigation keys. CapsLock also keeps its case semantics. These events retain
Wine's native reconciliation behavior and can still trigger lock-key
corrections. Use `WINEDEBUG=+key,+keyboard uur run` and the
private session log to distinguish real key conversions from correction
pairs. `uur doctor` reports the local lock state and configured workaround.
After acquiring the session lock, a shim-enabled run restarts only the managed
Wine prefix so its service manager and service-spawned clients receive the
same compatibility environment. Other Wine prefixes remain running.
### Wayland session with ScreenCast and RemoteDesktop portals
Requirements: a working session D-Bus, PipeWire, the xdg-desktop-portal
+4 -2
View File
@@ -9,6 +9,7 @@
pipewire,
wayland,
wayland-scanner,
xorg,
pulseaudio,
curl,
glib,
@@ -38,14 +39,14 @@ rustPlatform.buildRustPackage {
bash
wayland-scanner
];
buildInputs = [ pipewire wayland ];
buildInputs = [ pipewire wayland xorg.libX11 xorg.libXext ];
CC = "${stdenv.cc}/bin/cc";
UUR_BUILD_SHELL = runtimeShell;
doCheck = false;
postPatch = ''
patchShebangs hook/build.sh capture/build.sh packaging/stage.sh
patchShebangs hook/build.sh capture/build.sh compat/build.sh packaging/stage.sh
'';
postBuild = ''
@@ -54,6 +55,7 @@ rustPlatform.buildRustPackage {
UU_MINGW_DLLTOOL=${windowsBinutils}/bin/${targetPrefix}dlltool \
./hook/build.sh
./capture/build.sh
./compat/build.sh
'';
installPhase = ''
+3 -2
View File
@@ -7,8 +7,8 @@ pkgdesc="Native Linux companion for NetEase UU Remote"
url="https://github.com/panxuc/uur"
arch="x86_64"
license="MIT"
depends="bash wine curl glib wayland-libs-client pulseaudio-utils xdg-desktop-portal"
makedepends="cargo rust gcc musl-dev pipewire-dev wayland-dev pkgconf mingw-w64-gcc mingw-w64-binutils"
depends="bash wine curl glib wayland-libs-client libx11 pulseaudio-utils xdg-desktop-portal"
makedepends="cargo rust gcc musl-dev pipewire-dev wayland-dev libx11-dev pkgconf mingw-w64-gcc mingw-w64-binutils"
options="!check"
source="$pkgname-$pkgver.tar.gz::$url/archive/refs/tags/v$pkgver.tar.gz"
builddir="$srcdir/$pkgname-$pkgver"
@@ -17,6 +17,7 @@ build() {
cargo build --release --locked
./hook/build.sh
./capture/build.sh
./compat/build.sh
}
check() {
+3 -2
View File
@@ -1,7 +1,7 @@
FROM alpine:edge AS build
RUN apk add --no-cache \
bash cargo rust gcc musl-dev pipewire-dev wayland-dev pkgconf \
bash cargo rust gcc musl-dev pipewire-dev wayland-dev libx11-dev pkgconf \
mingw-w64-gcc mingw-w64-binutils
WORKDIR /src
@@ -12,10 +12,11 @@ RUN --mount=type=cache,target=/root/.cargo/registry \
&& cargo build --release --locked \
&& ./hook/build.sh \
&& ./capture/build.sh \
&& ./compat/build.sh \
&& ./packaging/stage.sh /out
FROM alpine:edge
RUN apk add --no-cache \
bash ca-certificates curl glib pipewire-libs wayland-libs-client pulseaudio-utils wine xdg-desktop-portal
bash ca-certificates curl glib pipewire-libs wayland-libs-client libx11 pulseaudio-utils wine xdg-desktop-portal
COPY --from=build /out/ /
ENTRYPOINT ["/usr/bin/uur"]
+1 -1
View File
@@ -5,7 +5,7 @@ pkgdesc="Native Linux companion for NetEase UU Remote"
arch=('x86_64')
url="https://github.com/panxuc/uur"
license=('MIT')
depends=('glibc' 'gcc-libs' 'glib2' 'wine' 'curl' 'pipewire' 'wayland' 'xdg-desktop-portal')
depends=('glibc' 'gcc-libs' 'glib2' 'wine' 'curl' 'pipewire' 'wayland' 'libx11' 'libxext' 'xdg-desktop-portal')
optdepends=(
'xdg-desktop-portal-gnome: GNOME-compatible Wayland capture and input'
'xdg-desktop-portal-kde: Plasma Wayland capture and input'
+4 -1
View File
@@ -22,9 +22,11 @@ depends=(
'curl'
'pipewire'
'wayland'
'libx11'
'libxext'
'xdg-desktop-portal'
)
makedepends=('cargo' 'gcc' 'pkgconf' 'wayland' 'mingw-w64-gcc' 'mingw-w64-binutils')
makedepends=('cargo' 'gcc' 'pkgconf' 'wayland' 'libx11' 'mingw-w64-gcc' 'mingw-w64-binutils')
optdepends=(
'osslsigncode: Authenticode verification of official updater downloads'
'xdg-desktop-portal-gnome: GNOME, niri, and compatible Wayland capture/input'
@@ -50,6 +52,7 @@ build() {
cargo build --release --locked
./hook/build.sh
./capture/build.sh
./compat/build.sh
}
check() {
+1
View File
@@ -15,6 +15,7 @@ find "$output" -maxdepth 1 -type f \
cargo build --manifest-path "$project_root/Cargo.toml" --release --locked
"$project_root/hook/build.sh"
"$project_root/capture/build.sh"
"$project_root/compat/build.sh"
"$project_root/packaging/stage.sh" "$stage"
tar --zstd -C "$stage" -cf "$output/uur-${version}-linux-x86_64.tar.zst" .
+4
View File
@@ -25,6 +25,8 @@ overrides:
- curl
- libpipewire-0.3-0
- libwayland-client0
- libx11-6
- libxext6
- xdg-desktop-portal
recommends:
- xdg-desktop-portal-gnome | xdg-desktop-portal-kde | xdg-desktop-portal-wlr
@@ -43,6 +45,8 @@ overrides:
- curl
- "libpipewire-0.3.so.0()(64bit)"
- "libwayland-client.so.0()(64bit)"
- "libX11.so.6()(64bit)"
- "libXext.so.6()(64bit)"
- xdg-desktop-portal
recommends:
- ethtool
+2
View File
@@ -12,6 +12,8 @@ install -Dm0755 "$project_root/capture/uur-pw-capture" \
"$destination$prefix/lib/uur/uur-pw-capture"
install -Dm0755 "$project_root/capture/uur-wl-capture" \
"$destination$prefix/lib/uur/uur-wl-capture"
install -Dm0755 "$project_root/build/compat/libuur-lock-mods.so" \
"$destination$prefix/lib/uur/libuur-lock-mods.so"
install -Dm0755 "$project_root/packaging/post-install-message" \
"$destination$prefix/lib/uur/post-install-message"
for component in wevtapi.dll uur-hook.dll wtsapi32.dll winlogon.exe uur-terminal-proxy.exe uur-mux-proxy.exe uur-launch-proxy.exe; do
+1
View File
@@ -17,3 +17,4 @@ cc -std=c11 -O2 -Wall -Wextra -Werror \
"$temporary/cursor-overlay"
"$project_root/hook/build.sh"
"$project_root/capture/build.sh"
"$project_root/compat/build.sh"
+6
View File
@@ -29,11 +29,17 @@ done
printf 'missing capture helper — run: ./capture/build.sh\n' >&2
exit 1
}
[[ -f "$root/build/compat/libuur-lock-mods.so" ]] || {
printf 'missing lock-modifier shim — run: ./compat/build.sh\n' >&2
exit 1
}
install -Dm0755 "$root/target/release/uur" "$prefix/bin/uur"
for helper in uur-pw-capture uur-wl-capture; do
install -Dm0755 "$root/capture/$helper" "$prefix/lib/uur/$helper"
done
install -Dm0755 "$root/build/compat/libuur-lock-mods.so" \
"$prefix/lib/uur/libuur-lock-mods.so"
for dll in "${components[@]}"; do
install -Dm0644 "$root/build/hook/$dll" "$prefix/lib/uur/hook/$dll"
done
+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())