commit 611383544b28d504fe6806ff0190317e653a9bb6 Author: Xuc Pan Date: Fri Sep 4 01:56:14 2026 +0800 Initial commit diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..ad00f93 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +.git +target +build +dist +capture/uur-pw-capture diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..e13ad1b --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,83 @@ +name: ci + +on: + push: + branches: [master] + pull_request: + +jobs: + rust: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + with: + components: clippy, rustfmt + - name: Rust checks + run: | + cargo fmt --check + cargo clippy --locked --all-targets -- -D warnings + cargo test --locked --all-targets + cc -std=c11 -O2 -Wall -Wextra -Werror tests/frame-protocol.c -o /tmp/frame-protocol + /tmp/frame-protocol + - name: Build + run: cargo build --locked --release + + hook: + runs-on: ubuntu-latest + container: archlinux:base-devel + steps: + - uses: actions/checkout@v4 + - name: Install mingw toolchain + run: | + pacman -Syu --noconfirm mingw-w64-gcc mingw-w64-binutils + - name: Build PE components + run: ./hook/build.sh + - uses: actions/upload-artifact@v4 + with: + name: uur-hook-pe + path: build/hook/*.dll + + package-layout: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - name: Install native and PE build dependencies + run: | + 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 pkg-config \ + wine xvfb + - name: Build and stage + run: | + cargo build --release --locked + ./hook/build.sh + ./capture/build.sh + stage="$(mktemp -d)" + ./packaging/stage.sh "$stage" + test -x "$stage/usr/bin/uur" + test -x "$stage/usr/lib/uur/uur-pw-capture" + test -f "$stage/usr/lib/uur/hook/winlogon.exe" + desktop-file-validate "$stage/usr/share/applications/uur.desktop" + appstreamcli validate --no-net "$stage/usr/share/metainfo/io.github.panxuc.uur.metainfo.xml" + ./tests/hook-smoke.sh + ./tests/terminal-smoke.sh + + alpine-musl: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Build and test the musl package layout + run: docker build --target build -f packaging/alpine/Dockerfile . + + nix: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: cachix/install-nix-action@v31 + - name: Evaluate and build the flake + run: | + nix flake check --no-build + nix build .#uur diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..7c676a1 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,67 @@ +name: release + +on: + push: + tags: ['v*'] + workflow_dispatch: + +permissions: + contents: write + +jobs: + packages: + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - name: Install build dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + binutils-mingw-w64-x86-64 gcc libpipewire-0.3-dev \ + gcc-mingw-w64-x86-64 pkg-config zstd + - name: Install nFPM + uses: goreleaser/nfpm-action@v2 + with: + version: latest + - name: Build distribution packages + run: ./packaging/build-packages.sh + - name: Publish GitHub release assets + env: + GH_TOKEN: ${{ github.token }} + run: | + gh release upload "${GITHUB_REF_NAME}" \ + dist/*.tar.zst dist/*.deb dist/*.rpm dist/SHA256SUMS \ + --clobber + + aur: + needs: packages + runs-on: ubuntu-latest + container: archlinux:base-devel + if: ${{ github.event_name == 'push' }} + steps: + - uses: actions/checkout@v4 + - name: Install publication tools + run: pacman -Syu --noconfirm curl git openssh + - name: Publish AUR metadata + env: + AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }} + run: | + install -Dm0600 /dev/null ~/.ssh/aur + printf '%s\n' "$AUR_SSH_PRIVATE_KEY" > ~/.ssh/aur + ssh-keyscan aur.archlinux.org >> ~/.ssh/known_hosts + git clone ssh://aur@aur.archlinux.org/uur.git aur + cp packaging/aur/PKGBUILD packaging/aur/uur.install aur/ + version="${GITHUB_REF_NAME#v}" + sed -i "s/^pkgver=.*/pkgver=$version/" aur/PKGBUILD + source_url="https://github.com/${GITHUB_REPOSITORY}/archive/refs/tags/${GITHUB_REF_NAME}.tar.gz" + digest="$(curl -fsSL "$source_url" | sha256sum | cut -d' ' -f1)" + sed -i "s/^sha256sums=.*/sha256sums=('$digest')/" aur/PKGBUILD + useradd --create-home builder + chown -R builder:builder aur + runuser -u builder -- bash -lc 'cd "$1" && makepkg --printsrcinfo > .SRCINFO' _ "$PWD/aur" + git -C aur config user.name uur-release-bot + git -C aur config user.email actions@users.noreply.github.com + git -C aur add PKGBUILD uur.install .SRCINFO + git -C aur commit -m "uur $version" + GIT_SSH_COMMAND='ssh -i ~/.ssh/aur -o IdentitiesOnly=yes' git -C aur push diff --git a/.github/workflows/upstream-watch.yml b/.github/workflows/upstream-watch.yml new file mode 100644 index 0000000..3be600b --- /dev/null +++ b/.github/workflows/upstream-watch.yml @@ -0,0 +1,68 @@ +name: upstream-watch + +# Periodically check NetEase's official release feed. When a new UU Remote +# version appears this workflow runs the version-independent adapter probe and +# records the result. See docs/upstream-adaptation.md for the release split. + +on: + schedule: + - cron: "0 3 * * *" # daily, 03:00 UTC + workflow_dispatch: + +permissions: + issues: write + +jobs: + check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Query the official release feed + id: feed + run: | + url="$(./scripts/latest-installer-url.sh)" + filename="$(basename "${url%%\?*}")" + version="$(./scripts/extract-version.sh "$filename")" + echo "url=$url" >> "$GITHUB_OUTPUT" + echo "filename=$filename" >> "$GITHUB_OUTPUT" + echo "version=$version" >> "$GITHUB_OUTPUT" + - name: Download and probe stable API contracts + id: probe + continue-on-error: true + env: + URL: ${{ steps.feed.outputs.url }} + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends \ + binutils osslsigncode p7zip-full wine xvfb + curl -fL --retry 3 -o upstream.exe "$URL" + ./scripts/probe-upstream.sh upstream.exe + - name: Open or update a tracking issue when upstream moved + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VERSION: ${{ steps.feed.outputs.version }} + FILENAME: ${{ steps.feed.outputs.filename }} + PROBE: ${{ steps.probe.outcome }} + run: | + gh label create upstream-release --description "Official UU Remote changed" \ + --color 1d76db --force + existing="$(gh issue list --label upstream-release \ + --state open --json number --jq '.[0].number' || true)" + body="$(cat < + UU Remote icon +

+ +

uur

+ +

+ A native Linux compatibility layer for the official NetEase UU Remote client. +

+ +

+ Linux x86_64 + X11 and Wayland + Rust + MIT license +

+ +

+ English · 简体中文 +

+ +> [!IMPORTANT] +> `uur` does not redistribute UU Remote. It downloads the official Windows +> installer from NetEase after the user explicitly accepts the upstream EULA. + +## ✨ Highlights + +| Capability | Linux integration | +| --- | --- | +| Control other computers | Official UU interface and media stack under Wine | +| Allow this Linux computer to be controlled | ScreenCast portal/PipeWire capture and native Linux input | +| X11 and Wayland | Capability detection instead of distribution or desktop allowlists | +| Clean lifecycle | Bridges start with UU and stop with its managed Wine prefix | +| Native tools | Linux PTY terminal, wallpaper, Quick Launch, proxy, and sleep inhibition | +| Upstream resilience | API-level runtime adapters; no version/RVA patch matrix | +| Distribution | Arch/pacman, deb, rpm, portable tar.zst, and an AUR recipe | + +## 🚀 First run + +After installing any package, run these commands **in this order**: + +```bash +# 1. Inspect the current Wine, portal, PipeWire, and input capabilities. +uur doctor + +# 2. Accept NetEase's EULA, download the official client, and create the prefix. +uur setup --accept-eula + +# 3. Start capture, input, the managed Wine services, and the UU interface. +uur run +``` + +`uur setup` without `--accept-eula` intentionally stops after printing the +official EULA URL. It does not install the proprietary client. + +Many capabilities remain untested; runtime testing so far covers Arch Linux, KDE Plasma, and Wayland. + +After setup, UU Remote is also available from the application menu. The menu +entry launches the complete `uur run` session. + +## 📦 Installation + +Download the newest package for the system from the +[GitHub Releases page](https://github.com/panxuc/uur/releases/latest). Native +recipes and release artifacts share one version and filesystem layout. + +### Arch Linux + +Install a downloaded release package with pacman: + +```bash +sudo pacman -U ./dist/uur-0.1.0-1-x86_64.pkg.tar.zst +``` + +### AUR + +After the package is available from AUR: + +```bash +paru -S uur +``` + +### Debian and Ubuntu package family + +```bash +sudo apt install ./uur_0.1.0_amd64.deb +``` + +### Fedora and compatible RPM systems + +```bash +sudo dnf install ./uur-0.1.0-1.x86_64.rpm +``` + +On systems with different RPM dependency names, install the dependencies +manually or use the portable archive. + +### Portable archive + +```bash +sudo tar --zstd -C / -xf ./uur-0.1.0-linux-x86_64.tar.zst +``` + +### Nix and NixOS + +```bash +nix build +nix run . -- doctor +``` + +The flake also exports `nixosModules.default`; see [Nix and NixOS](docs/nix.md). + +### Alpine Linux + +Alpine edge can build the native musl package layout with: + +```bash +docker build -f packaging/alpine/Dockerfile . +``` + +An `APKBUILD` is included under `packaging/alpine/`. + +### User installation from source + +```bash +cargo build --release --locked +./hook/build.sh +./capture/build.sh +./scripts/install-user.sh +``` + +The source build requires Rust, a C compiler, PipeWire development files, +`pkg-config`, and the MinGW-w64 x86_64 toolchain. + +Gentoo, Void Linux, Slackware, Solus, ALT Linux, Exherbo, Clear Linux, Mageia, +OpenMandriva, PCLinuxOS, Venom Linux, Guix System, and other package ecosystems +can use the portable archive or the shared `packaging/stage.sh` source layout. + +See [Platform support and usage](docs/platform-support.md) for distribution +families, portal choices, X11/Wayland sessions, standalone window managers, +immutable systems, and libc boundaries. + +## 🧭 Daily use + +```bash +uur run # Start or show the managed UU session +uur doctor # Read-only environment diagnostics +uur upstream check # Check the official NetEase release feed +uur autostart enable # Optional: start after graphical login +uur autostart disable # Remove the managed login entry +uur wol status # Inspect the physical wired adapter's WOL state +uur display status # Monitor, window, or portal virtual source +uur display source virtual +uur stop # Stop only uur's helpers and Wine prefix +``` + +Diagnostic input overrides: + +```bash +UUR_INPUT_BACKEND=portal uur run +UUR_INPUT_BACKEND=uinput uur run +UUR_INPUT_BACKEND=xtest uur run +``` + +Use the default `auto` mode after troubleshooting. + +## 🖥️ Desktop integration + +- A Wayland session with both RemoteDesktop and ScreenCast portals uses one + combined, unprivileged session for input and video. +- A Wayland session with only ScreenCast uses PipeWire for video and uinput + for full-desktop input. +- An X11 session uses Wine's native X11 capture and XTest input. +- XTest under XWayland is only a partial fallback and is not advertised as + full Wayland desktop control. + +Run `uur doctor` instead of inferring support from a desktop or distribution +name. + +## 🧩 Native Linux features + +Screen capture, keyboard, pointer, lifecycle management, wallpaper metadata, +native terminal, Quick Launch, proxy synchronization, suspend inhibition, and +host WOL configuration are implemented. Quick Launch exposes the XDG +application catalog through UU and resolves each request back to `gio launch`; +it never accepts an arbitrary command from Wine. Other UU features require +native Linux service adapters rather than being left inside the Wine prefix: + +| Feature | Direction | +| --- | --- | +| Terminal | Authenticated UU transport → native PTY and the user's login shell | +| Quick Launch | UU application inventory → authenticated XDG desktop activation | +| Wake-on-LAN setup | `uur wol` → real wired interface and NetworkManager profile | +| Received files | Validated staging → the user's XDG Downloads directory | +| Sending files | File portal or explicit CLI selection → bounded native staging | +| Port mapping | Policy-controlled native TCP/UDP broker; loopback by default | +| Clipboard and phone text | RemoteDesktop Clipboard portal with X11 fallback | + +The protocol, security boundaries, lifecycle, and implementation phases are in +[Native service adapters](docs/native-services.md). + +## 🔬 How it works + +```text +Official UU Remote client (managed Wine prefix) + │ + ├─ Windows API adapter ── authenticated input/control protocol + │ + └─ GDI/DXGI capture boundary ◄── private triple-buffer frame transport + ▲ +Linux supervisor ── ScreenCast portal ── PipeWire + │ + └─ RemoteDesktop portal / uinput / XTest +``` + +The Windows ABI adapter is small C code. Session policy, desktop integration, +capability selection, and lifecycle management are implemented in Rust. + +## 🛠️ Troubleshooting + +Start with: + +```bash +uur doctor +``` + +Session logs are stored at: + +```text +${XDG_STATE_HOME:-$HOME/.local/state}/uur/session.log +``` + +For Wine diagnostics only: + +```bash +WINEDEBUG=+loaddll uur run +``` + +Normal runs suppress Wine's non-actionable `fixme` output. + +## 📚 Documentation + +- [Architecture](docs/architecture.md) +- [Platform support and usage](docs/platform-support.md) +- [Capture protocol](docs/capture-protocol.md) +- [Native service adapters](docs/native-services.md) +- [Feature parity](docs/feature-parity.md) +- [Upstream adaptation](docs/upstream-adaptation.md) +- [Package installation](docs/distribution.md) +- [Nix and NixOS](docs/nix.md) +- [Windows feature map](docs/windows-feature-map.md) +- [Video and display backends](docs/video-backends.md) + +## 🙏 Credits + +The project learned from +[GuoWQ222/uu-remote-for-linux](https://github.com/GuoWQ222/uu-remote-for-linux), +[lachlanchen/uu-remote-ubuntu-bridge](https://github.com/lachlanchen/uu-remote-ubuntu-bridge). + +NetEase UU Remote is proprietary software of NetEase. `uur` is an unofficial +compatibility project and is not affiliated with NetEase. diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000..de8f3e0 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,250 @@ +

+ UU 远程图标 +

+ +

uur

+ +

+ 适用于网易 UU 远程官方客户端的原生 Linux 兼容层。 +

+ +

+ Linux x86_64 + X11 与 Wayland + Rust + MIT 许可证 +

+ +

+ English · 简体中文 +

+ +> [!IMPORTANT] +> `uur` 不分发 UU 远程客户端。只有用户明确接受网易官方协议后,它才会从网易官方 +> 地址下载 Windows 安装程序。 + +## ✨ 功能亮点 + +| 能力 | Linux 集成方式 | +| --- | --- | +| 控制其他电脑 | 在 Wine 中使用 UU 官方界面和媒体栈 | +| 让本 Linux 设备被控 | ScreenCast Portal/PipeWire 画面与 Linux 原生输入 | +| X11 与 Wayland | 按实际能力探测,不维护发行版或桌面白名单 | +| 生命周期 | UU 启动时加载桥接,受管 Wine 前缀退出时一并清理 | +| 原生工具 | Linux PTY 终端、壁纸、快速启动、代理同步与防休眠 | +| 上游兼容 | 基于稳定 API 的运行时适配,不维护版本/RVA 补丁矩阵 | +| 软件分发 | Arch/pacman、deb、rpm、通用 tar.zst 与 AUR 配方 | + +## 🚀 首次运行 + +安装任意格式的软件包后,必须**按顺序**执行: + +```bash +# 1. 检查当前 Wine、Portal、PipeWire 和输入能力。 +uur doctor + +# 2. 接受网易协议、下载官方客户端并创建 Wine 前缀。 +uur setup --accept-eula + +# 3. 启动画面、输入桥、受管 Wine 服务和 UU 主界面。 +uur run +``` + +不带 `--accept-eula` 的 `uur setup` 只会显示官方协议地址并停止,不会安装专有客户端。 + +很多功能尚未经测试;目前实际运行测试仅覆盖 Arch Linux、KDE Plasma 和 Wayland。 + +设置完成后,也可以从应用菜单打开 UU Remote。菜单入口会启动完整的 `uur run` 会话。 + +## 📦 安装 + +请从 [GitHub Releases](https://github.com/panxuc/uur/releases/latest) 下载适合当前系统的 +最新软件包。所有原生配方与发布产物使用同一版本和文件布局。 + +### Arch Linux + +使用 pacman 安装下载的正式发布包: + +```bash +sudo pacman -U ./dist/uur-0.1.0-1-x86_64.pkg.tar.zst +``` + +### AUR + +软件包正式发布到 AUR 后可执行: + +```bash +paru -S uur +``` + +### Debian、Ubuntu 及兼容发行版 + +```bash +sudo apt install ./uur_0.1.0_amd64.deb +``` + +### Fedora 及兼容 RPM 发行版 + +```bash +sudo dnf install ./uur-0.1.0-1.x86_64.rpm +``` + +如果发行版的 RPM 依赖名称不同,请手动安装依赖或使用通用压缩包。 + +### 通用压缩包 + +```bash +sudo tar --zstd -C / -xf ./uur-0.1.0-linux-x86_64.tar.zst +``` + +### Nix 与 NixOS + +```bash +nix build +nix run . -- doctor +``` + +flake 同时导出 `nixosModules.default`,详见 [Nix 与 NixOS](docs/nix.md)。 + +### Alpine Linux + +Alpine edge 可直接构建原生 musl 软件包布局: + +```bash +docker build -f packaging/alpine/Dockerfile . +``` + +`packaging/alpine/` 中也提供了 `APKBUILD`。 + +### 从源码安装到当前用户 + +```bash +cargo build --release --locked +./hook/build.sh +./capture/build.sh +./scripts/install-user.sh +``` + +源码构建需要 Rust、C 编译器、PipeWire 开发文件、`pkg-config` 和 MinGW-w64 x86_64 +工具链。 + +Gentoo、Void Linux、Slackware、Solus、ALT Linux、Exherbo、Clear Linux、Mageia、 +OpenMandriva、PCLinuxOS、Venom Linux、Guix System 等软件包生态可以使用通用压缩包, +或复用 `packaging/stage.sh` 的源码构建布局。 + +发行版家族、Portal 选择、X11/Wayland、独立窗口管理器、不可变系统和 libc 边界见 +[平台支持与使用说明](docs/platform-support.md)。 + +## 🧭 日常使用 + +```bash +uur run # 启动或显示受管 UU 会话 +uur doctor # 只读环境诊断 +uur upstream check # 检查网易官方版本 +uur autostart enable # 可选:图形会话登录后自动启动 +uur autostart disable # 删除受管登录自启动项 +uur wol status # 检查物理有线网卡的 WOL 状态 +uur display status # 查看显示器、窗口或 Portal 虚拟源设置 +uur display source virtual +uur stop # 只停止 uur 助手与专用 Wine 前缀 +``` + +输入后端排错: + +```bash +UUR_INPUT_BACKEND=portal uur run +UUR_INPUT_BACKEND=uinput uur run +UUR_INPUT_BACKEND=xtest uur run +``` + +排错结束后应恢复默认的 `auto` 模式。 + +## 🖥️ 桌面集成 + +- 同时提供 RemoteDesktop 和 ScreenCast Portal 的 Wayland 会话,使用一个无特权组合 + 会话传输输入与画面。 +- 只提供 ScreenCast 的 Wayland 会话,使用 PipeWire 捕获和 uinput 全桌面输入。 +- X11 会话使用 Wine 原生 X11 捕获与 XTest 输入。 +- XWayland 下的 XTest 只是局部回退,不会被描述成完整 Wayland 桌面控制。 + +请以 `uur doctor` 的实际接口检查为准,不要仅根据桌面或发行版名称推断支持情况。 + +## 🧩 Linux 原生功能 + +画面、键盘、鼠标、生命周期管理、壁纸信息、原生终端、快速启动、代理同步、防休眠和 +主机 WOL 配置已经实现。快速启动会把 XDG 应用目录提供给 UU,并将每次请求重新解析为 +`gio launch`;Wine 侧不能传入任意命令。其他 UU 功能应由 Linux 原生服务承接,而不是 +留在 Wine 虚拟环境中: + +| 功能 | 实现方向 | +| --- | --- | +| 终端 | UU 鉴权通道 → 原生 PTY 与当前用户登录 Shell | +| 快速启动 | UU 应用清单 → 带鉴权的 XDG 桌面应用激活 | +| 网络唤醒配置 | `uur wol` → 真实有线网卡与 NetworkManager 配置 | +| 接收文件 | 安全暂存与校验 → 用户 XDG 下载目录 | +| 发送文件 | File Portal 或显式 CLI 选择 → 有界原生暂存区 | +| 端口映射 | 带策略的原生 TCP/UDP broker,默认只绑定回环地址 | +| 剪贴板与手机文字 | RemoteDesktop Clipboard Portal 与 X11 回退 | + +协议、安全边界、生命周期和实施阶段见 +[Linux 原生服务适配器](docs/native-services.md)。 + +## 🔬 工作原理 + +```text +官方 UU 远程客户端(受管 Wine 前缀) + │ + ├─ Windows API 适配器 ── 带鉴权的输入/控制协议 + │ + └─ GDI/DXGI 捕获边界 ◄── 私有三缓冲画面传输 + ▲ +Linux 监督器 ── ScreenCast Portal ── PipeWire + │ + └─ RemoteDesktop Portal / uinput / XTest +``` + +Windows ABI 边界保留少量 C 代码;会话策略、桌面集成、能力选择和生命周期由 Rust +实现。 + +## 🛠️ 排错 + +首先执行: + +```bash +uur doctor +``` + +会话日志位于: + +```text +${XDG_STATE_HOME:-$HOME/.local/state}/uur/session.log +``` + +只在需要 Wine 诊断时执行: + +```bash +WINEDEBUG=+loaddll uur run +``` + +正常启动会隐藏无操作价值的 Wine `fixme` 输出。 + +## 📚 文档 + +- [架构](docs/architecture.md) +- [平台支持与使用](docs/platform-support.md) +- [画面传输协议](docs/capture-protocol.md) +- [Linux 原生服务适配器](docs/native-services.md) +- [功能对齐](docs/feature-parity.md) +- [上游自动适配](docs/upstream-adaptation.md) +- [软件包安装](docs/distribution.md) +- [Nix 与 NixOS](docs/nix.md) +- [Windows 功能映射](docs/windows-feature-map.md) +- [视频与显示后端](docs/video-backends.md) + +## 🙏 致谢 + +本项目参考了 +[GuoWQ222/uu-remote-for-linux](https://github.com/GuoWQ222/uu-remote-for-linux)、 +[lachlanchen/uu-remote-ubuntu-bridge](https://github.com/lachlanchen/uu-remote-ubuntu-bridge)。 + +网易 UU 远程是网易的专有软件。`uur` 是非官方兼容项目,与网易无隶属或合作关系。 diff --git a/assets/uur-icon-master.png b/assets/uur-icon-master.png new file mode 100644 index 0000000..984340a Binary files /dev/null and b/assets/uur-icon-master.png differ diff --git a/capture/build.sh b/capture/build.sh new file mode 100755 index 0000000..47beede --- /dev/null +++ b/capture/build.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Build the PipeWire capture helper (host C, links libpipewire). +set -euo pipefail + +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +readonly root +out="$root/capture" +cc="${CC:-gcc}" +flags=(-std=c11 -O2 -Wall -Wextra -Werror) + +command -v "$cc" >/dev/null 2>&1 || { printf 'missing tool: %s\n' "$cc" >&2; exit 1; } + +"$cc" "${flags[@]}" -o "$out/uur-pw-capture" \ + "$root/capture/uur-pw-capture.c" \ + $(pkg-config --cflags --libs libpipewire-0.3) + +printf 'built: %s\n' "$out/uur-pw-capture" diff --git a/capture/uur-pw-capture.c b/capture/uur-pw-capture.c new file mode 100644 index 0000000..3fa3ad4 --- /dev/null +++ b/capture/uur-pw-capture.c @@ -0,0 +1,382 @@ +#define _GNU_SOURCE +/* + * uur-pw-capture — PipeWire ScreenCast consumer. + * + * Receives an inherited portal PipeWire fd (UUR_PW_FD) and the authorized + * video node id (UUR_PW_NODE), streams the monitor as BGRx and publishes + * frames into the private UUR_FRAME_PATH following the seqlock protocol in + * docs/capture-protocol.md. + * + * The shared file is created only after the stream format is negotiated, + * because its size depends on the negotiated stride. The uur PE hook maps + * it read-only through Wine's Z: drive whenever the client captures. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "../hook/frame-protocol.h" + +#define FRAME_FORMAT_BGRX 1 + +struct frame_header { + uint32_t magic; + uint32_t version; + uint32_t width; + uint32_t height; + uint32_t stride; + uint32_t format; + _Atomic uint64_t total_frames; + uint8_t reserved[32]; +}; + +_Static_assert(sizeof(struct frame_header) == UURF_HEADER_BYTES, + "frame protocol header size changed"); + +struct frame_slot { + _Atomic uint64_t seq; + /* frame bytes follow */ +}; + +struct capture { + struct pw_main_loop *loop; + struct pw_stream *stream; + struct spa_hook listener; + uint32_t width; + uint32_t height; + uint32_t stride; + enum spa_video_format format; + uint64_t counter; + int shm_fd; + uint8_t *shm; + size_t shm_size; + char frame_path[PATH_MAX]; +}; + +static struct capture *active_capture; + +static void stop_capture(int signal_number) +{ + (void)signal_number; + if (active_capture != NULL && active_capture->loop != NULL) + pw_main_loop_quit(active_capture->loop); +} + +static struct frame_slot *slot_at(struct capture *c, uint64_t n) +{ + size_t slot_bytes = sizeof(struct frame_slot) + + (size_t)c->stride * c->height; + uint8_t *base = c->shm + uurf_slot_offset(n, slot_bytes); + return (struct frame_slot *)base; +} + +static uint8_t *slot_frame(struct frame_slot *slot) +{ + return (uint8_t *)slot + sizeof(struct frame_slot); +} + +/* Create (or resize) the shared file for the negotiated geometry and write + * the header. Called once, from param_changed, before any frame exists. */ +static int shm_setup(struct capture *c) +{ + size_t slot_bytes = sizeof(struct frame_slot) + + (size_t)c->stride * c->height; + size_t total = UURF_HEADER_BYTES + UURF_SLOT_COUNT * slot_bytes; + + if (c->stride == 0 || c->height == 0 || + (size_t)c->stride > + (SIZE_MAX - UURF_HEADER_BYTES) / c->height / UURF_SLOT_COUNT) { + fprintf(stderr, "invalid capture geometry\n"); + return -1; + } + + c->shm_fd = open(c->frame_path, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, + 0600); + if (c->shm_fd < 0) { + perror("open frame transport"); + return -1; + } + if (ftruncate(c->shm_fd, (off_t)total) < 0) { + perror("ftruncate"); + return -1; + } + c->shm = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_SHARED, + c->shm_fd, 0); + if (c->shm == MAP_FAILED) { + perror("mmap"); + c->shm = NULL; + return -1; + } + c->shm_size = total; + + struct frame_header *header = (struct frame_header *)c->shm; + header->magic = 0x46525555u; /* "UURF" */ + header->version = UURF_VERSION; + header->width = c->width; + header->height = c->height; + header->stride = c->stride; + header->format = FRAME_FORMAT_BGRX; + atomic_init(&header->total_frames, 0); + for (uint32_t i = 0; i < UURF_SLOT_COUNT; ++i) { + atomic_init(&slot_at(c, (uint64_t)i)->seq, 0); + } + return 0; +} + +static void publish_frame(struct capture *c, const uint8_t *pixels, + uint32_t src_stride, uint32_t src_height) +{ + if (c->shm == NULL) + return; + + c->counter += 1; + struct frame_slot *slot = slot_at(c, c->counter); + atomic_store_explicit(&slot->seq, 2 * c->counter - 1, + memory_order_release); /* writing */ + + uint8_t *dst = slot_frame(slot); + uint32_t rows = src_height < c->height ? src_height : c->height; + for (uint32_t row = 0; row < rows; ++row) { + uint8_t *target = dst + (size_t)row * c->stride; + const uint8_t *source = pixels + (size_t)row * src_stride; + if (c->format == SPA_VIDEO_FORMAT_BGRx || + c->format == SPA_VIDEO_FORMAT_BGRA) { + memcpy(target, source, c->stride); + } else if (c->format == SPA_VIDEO_FORMAT_RGBx || + c->format == SPA_VIDEO_FORMAT_RGBA) { + for (uint32_t column = 0; column < c->width; ++column) { + target[column * 4 + 0] = source[column * 4 + 2]; + target[column * 4 + 1] = source[column * 4 + 1]; + target[column * 4 + 2] = source[column * 4 + 0]; + target[column * 4 + 3] = 0; + } + } else { + int rgb = c->format == SPA_VIDEO_FORMAT_RGB; + for (uint32_t column = 0; column < c->width; ++column) { + target[column * 4 + 0] = source[column * 3 + (rgb ? 2 : 0)]; + target[column * 4 + 1] = source[column * 3 + 1]; + target[column * 4 + 2] = source[column * 3 + (rgb ? 0 : 2)]; + target[column * 4 + 3] = 0; + } + } + } + + atomic_store_explicit(&slot->seq, 2 * c->counter, memory_order_release); + struct frame_header *header = (struct frame_header *)c->shm; + atomic_store_explicit(&header->total_frames, c->counter, + memory_order_release); +} + +static void on_process(void *userdata) +{ + struct capture *c = userdata; + struct pw_buffer *buffer = pw_stream_dequeue_buffer(c->stream); + if (buffer == NULL) + return; + struct spa_buffer *buf = buffer->buffer; + + if (buf->n_datas >= 1 && c->shm != NULL) { + struct spa_data *plane = &buf->datas[0]; + uint8_t *pixels = NULL; + void *mapping = MAP_FAILED; + size_t mapping_size = 0; + + if (plane->chunk == NULL) { + pw_stream_queue_buffer(c->stream, buffer); + return; + } + if (plane->data != NULL) { + pixels = plane->data + plane->chunk->offset; + } else if (plane->type == SPA_DATA_MemFd && plane->fd >= 0) { + long page_size = sysconf(_SC_PAGESIZE); + uint64_t offset = (uint64_t)plane->mapoffset + plane->chunk->offset; + uint64_t page_mask = (uint64_t)(page_size > 0 ? page_size : 4096) - 1; + off_t aligned = (off_t)(offset & ~page_mask); + size_t delta = (size_t)(offset - (uint64_t)aligned); + mapping_size = delta + plane->chunk->size; + mapping = mmap(NULL, mapping_size, PROT_READ, MAP_PRIVATE, + plane->fd, aligned); + if (mapping != MAP_FAILED) + pixels = (uint8_t *)mapping + delta; + } + if (pixels != NULL) { + int32_t signed_stride = plane->chunk->stride; + uint32_t stride = signed_stride > 0 + ? (uint32_t)signed_stride + : (c->format == SPA_VIDEO_FORMAT_BGR || + c->format == SPA_VIDEO_FORMAT_RGB + ? c->width * 3 + : c->width * 4); + uint32_t rows = stride > 0 ? plane->chunk->size / stride : 0; + publish_frame(c, pixels, stride, rows); + if (mapping != MAP_FAILED) + munmap(mapping, mapping_size); + } + } + + pw_stream_queue_buffer(c->stream, buffer); +} + +static void on_param_changed(void *userdata, uint32_t id, + const struct spa_pod *param) +{ + struct capture *c = userdata; + if (param == NULL || id != SPA_PARAM_Format) + return; + + struct spa_video_info_raw info; + if (spa_format_video_raw_parse(param, &info) < 0) + return; + if (info.format != SPA_VIDEO_FORMAT_BGRx && + info.format != SPA_VIDEO_FORMAT_BGRA && + info.format != SPA_VIDEO_FORMAT_RGBx && + info.format != SPA_VIDEO_FORMAT_RGBA && + info.format != SPA_VIDEO_FORMAT_BGR && + info.format != SPA_VIDEO_FORMAT_RGB) { + fprintf(stderr, "negotiated unexpected format %d\n", info.format); + return; + } + + c->width = (uint32_t)info.size.width; + c->height = (uint32_t)info.size.height; + c->format = info.format; + c->stride = SPA_ROUND_UP_N(c->width * 4, 4); + fprintf(stderr, "negotiated: %ux%u stride %u\n", c->width, c->height, + c->stride); + + if (c->shm == NULL && shm_setup(c) < 0) { + pw_main_loop_quit(c->loop); + } +} + +static void on_state_changed(void *userdata, enum pw_stream_state old, + enum pw_stream_state state, const char *error) +{ + (void)userdata; + (void)old; + fprintf(stderr, "stream state: %s%s%s\n", + pw_stream_state_as_string(state), + error != NULL && error[0] != '\0' ? " - " : "", + error != NULL ? error : ""); +} + +static const struct pw_stream_events stream_events = { + .version = PW_VERSION_STREAM_EVENTS, + .process = on_process, + .param_changed = on_param_changed, + .state_changed = on_state_changed, +}; + +int main(void) +{ + const char *fd_text = getenv("UUR_PW_FD"); + const char *node_text = getenv("UUR_PW_NODE"); + if (fd_text == NULL || node_text == NULL) { + fprintf(stderr, + "UUR_PW_FD and UUR_PW_NODE must be set by 'uur capture'\n"); + return 2; + } + const char *frame_path = getenv("UUR_FRAME_PATH"); + if (frame_path == NULL || frame_path[0] != '/' || + strlen(frame_path) >= PATH_MAX) { + fprintf(stderr, "UUR_FRAME_PATH must be a short absolute path\n"); + return 2; + } + int pw_fd = atoi(fd_text); + uint32_t node_id = (uint32_t)strtoul(node_text, NULL, 10); + + pw_init(NULL, NULL); + + struct capture c; + memset(&c, 0, sizeof(c)); + c.shm_fd = -1; + memcpy(c.frame_path, frame_path, strlen(frame_path) + 1); + active_capture = &c; + signal(SIGINT, stop_capture); + signal(SIGTERM, stop_capture); + signal(SIGHUP, stop_capture); + + struct pw_main_loop *loop = pw_main_loop_new(NULL); + if (loop == NULL) { + fprintf(stderr, "pw_main_loop_new failed\n"); + return 1; + } + c.loop = loop; + + struct pw_context *context = pw_context_new(pw_main_loop_get_loop(loop), + NULL, 0); + if (context == NULL) { + fprintf(stderr, "pw_context_new failed\n"); + return 1; + } + + /* Connect through the portal's private PipeWire instance: only the + * consented node is reachable on this descriptor. */ + struct pw_core *core = pw_context_connect_fd(context, pw_fd, NULL, 0); + if (core == NULL) { + fprintf(stderr, "pw_context_connect_fd failed\n"); + return 1; + } + + struct pw_properties *props = pw_properties_new( + PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture", + PW_KEY_MEDIA_ROLE, "Screen", NULL); + c.stream = pw_stream_new(core, "uur-capture", props); + if (c.stream == NULL) { + fprintf(stderr, "pw_stream_new failed\n"); + return 1; + } + pw_stream_add_listener(c.stream, &c.listener, &stream_events, &c); + + uint8_t pod_buffer[1024]; + struct spa_pod_builder pod_builder = + SPA_POD_BUILDER_INIT(pod_buffer, sizeof(pod_buffer)); + const struct spa_pod *params[1]; + params[0] = spa_pod_builder_add_object( + &pod_builder, SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat, + SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video), + SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw), + SPA_FORMAT_VIDEO_format, + SPA_POD_CHOICE_ENUM_Id(6, SPA_VIDEO_FORMAT_BGRx, + SPA_VIDEO_FORMAT_BGRA, + SPA_VIDEO_FORMAT_RGBx, + SPA_VIDEO_FORMAT_RGBA, + SPA_VIDEO_FORMAT_BGR, + SPA_VIDEO_FORMAT_RGB)); + + if (pw_stream_connect(c.stream, PW_DIRECTION_INPUT, node_id, + PW_STREAM_FLAG_MAP_BUFFERS | + PW_STREAM_FLAG_AUTOCONNECT | + PW_STREAM_FLAG_RT_PROCESS, + params, 1) < 0) { + fprintf(stderr, "pw_stream_connect failed\n"); + return 1; + } + + pw_main_loop_run(loop); + + active_capture = NULL; + pw_stream_destroy(c.stream); + pw_context_destroy(context); + pw_main_loop_destroy(loop); + if (c.shm != NULL) + munmap(c.shm, c.shm_size); + if (c.shm_fd >= 0) + close(c.shm_fd); + unlink(c.frame_path); + pw_deinit(); + return 0; +} diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..167ddca --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,76 @@ +# Architecture + +`uur` is a compatibility layer, not a repackaged Windows application. The +official client remains in an isolated per-user Wine prefix. A small PE hook +adapts stable Windows APIs at runtime; the Rust host owns policy, desktop +integration, and process lifetime. + +```text +UU Remote / Wine + └─ PE ABI adapter (SendInput, GDI/DXGI capture entry points) + └─ authenticated loopback protocol + private frame transport + └─ Rust session supervisor + ├─ capture source: xdg ScreenCast → PipeWire + ├─ input sink (capability-selected) + ├─ xdg RemoteDesktop + ├─ Linux uinput + └─ X11 XTest + └─ native services + ├─ authenticated terminal proxy → Linux PTY + ├─ authenticated Quick Launch proxy → XDG applications + ├─ wallpaper metadata synchronizer + └─ desktop suspend/idle inhibitor +``` + +## Capability negotiation + +No runtime branch checks a desktop or distribution name. The order is based on +available interfaces: + +1. On Wayland, try a combined RemoteDesktop + ScreenCast portal session. This + is the preferred unprivileged path and uses one consent session for video + and input. +2. If the compositor exposes ScreenCast but not RemoteDesktop, keep portal + capture and inject through `/dev/uinput`. This covers compositors whose + portal currently implements capture only. +3. On X11, use XTest. Wine already sees the real X11 desktop, so an additional + portal capture is unnecessary. +4. XTest remains a final partial fallback for XWayland windows. + +Portal implementations are selected by `xdg-desktop-portal`, not by uur. This +keeps compositor-specific policy in the component designed to own it. + +## Adapter boundary + +The PE DLL is intentionally small C code because it must obey the Windows ABI. +It intercepts API imports and dynamic `GetProcAddress` resolution; it does not +search for product-version-specific instruction bytes or patch official +binaries. Everything above that ABI boundary is Rust. + +Capture follows the same pattern as `wemeet-wayland-screenshare`: intercept a +stable capture boundary, obtain real compositor frames through PipeWire, and +substitute those frames before the proprietary application consumes them. +The implementation supports GDI today and keeps DXGI behind the same adapter +surface. + +## Lifetime and isolation + +`uur run` is the only supervisor. It creates each native helper in a dedicated +process group and records the supervisor PID plus Linux process start time. +When the UU UI exits, or when `uur stop` sends SIGTERM to that exact supervisor, +RAII cleanup terminates only those helper groups and the one managed Wine +prefix. There are no permanent daemons, global `pkill` calls, or required +systemd units. + +Frame data lives in `$XDG_RUNTIME_DIR/uur/frames.v1` with mode 0600. The path is +passed through the adapter configuration, so users and concurrent sessions do +not share a global `/dev/shm` object. + +## Extension seams + +- `InputBackend`: portal, uinput, XTest, and future libei transports. +- capture helper protocol: producer-independent triple-buffer transport. +- PE adapter: API-level UU integration isolated from Linux backends. +- session supervisor: process lifetime independent of init system. +- packaging stage: one filesystem layout consumed by AUR, deb, rpm, Arch, and + portable tarball builders. diff --git a/docs/capture-protocol.md b/docs/capture-protocol.md new file mode 100644 index 0000000..11e9589 --- /dev/null +++ b/docs/capture-protocol.md @@ -0,0 +1,49 @@ +# Capture frame protocol + +How frames travel from the compositor (via PipeWire) into the client's +capture calls. Two producers/consumers, one shared file, no locks. + +```text +xdg-desktop-portal ScreenCast + │ (portal-consented session; per-monitor) + ▼ +uur-pw-capture (C) ── PipeWire stream, BGRx, SHM buffers + │ writes slots, seqlock per slot + ▼ +$XDG_RUNTIME_DIR/uur/frames.v1 (mode 0600, 64-byte header + 3 slots) + │ mapped read-only by the PE hook through its configured Wine Z: path + ▼ +uur-hook.dll ── intercepts static/dynamic gdi32!BitBlt/StretchBlt calls; + scales the newest stable snapshot into the destination DIB +``` + +## Shared file layout + +All integers little-endian. Total size = 64 + 3 × (8 + stride × height). + +| offset | type | field | +| --- | --- | --- | +| 0 | u32 | magic `0x46525555` ("UURF") | +| 4 | u32 | protocol version = 1 | +| 8 | u32 | frame width (px) | +| 12 | u32 | frame height (px) | +| 16 | u32 | stride (bytes per row) | +| 20 | u32 | format: 1 = BGRx (32 bits per pixel) | +| 24 | u64 | total frames written (monotonic counter) | +| 32..64 | — | reserved, zero | + +Slot *i* (i = 0, 1, 2) at offset `64 + i × (8 + stride × height)`: + +| offset | type | field | +| --- | --- | --- | +| 0 | u64 | sequence: `2×n − 1` while slot n is being written, `2×n` when slot n is stable | +| 8 | bytes | frame, `stride × height`, rows top-to-bottom, pixels BGRx | + +Writer picks slots round-robin (`n mod 3`), bumps the counter, publishes +the odd sequence (release), copies the frame, then publishes the even +sequence (release). The reader is a classic seqlock read: load the +sequence, copy, re-load; retry while the value changed or is odd. No +mutexes; a torn read is detected, never observed. + +The transport path is created per user and passed to the Wine adapter through +the managed prefix configuration. It is never a global shared-memory name. diff --git a/docs/distribution.md b/docs/distribution.md new file mode 100644 index 0000000..eb95b71 --- /dev/null +++ b/docs/distribution.md @@ -0,0 +1,113 @@ +# Package installation + +Choose the package format native to the system. Every format installs the same +Rust supervisor, Wine adapters, PipeWire helper, desktop entry, icon, and +uinput integration files. `sudo`, `doas`, or another privilege frontend may be +needed for system-wide package installation. + +## Arch Linux + +```bash +# AUR +paru -S uur + +# Downloaded release package +sudo pacman -U ./uur-0.1.0-1-x86_64.pkg.tar.zst +``` + +## Debian, Ubuntu, and derivatives + +```bash +sudo apt install ./uur_0.1.0_amd64.deb +``` + +The same release artifact covers Debian, Ubuntu, Linux Mint, Pop!_OS, KDE neon, +Zorin OS, elementary OS, Kali Linux, MX Linux, TUXEDO OS, and compatible +derivatives. + +## Fedora, RHEL, and openSUSE families + +```bash +sudo dnf install ./uur-0.1.0-1.x86_64.rpm + +# openSUSE +sudo zypper install ./uur-0.1.0-1.x86_64.rpm +``` + +This format also covers Fedora derivatives and RPM systems whose repositories +provide the declared Wine, GLib, PipeWire, and portal dependencies. + +## Portable archive + +The portable archive targets conventional glibc/FHS systems: + +```bash +sudo tar --zstd -C / -xf ./uur-0.1.0-linux-x86_64.tar.zst +``` + +## Nix and NixOS + +```bash +nix build +nix run . -- doctor +``` + +The flake includes a package, application, development shell, lock file, and +NixOS module. See [Nix and NixOS](nix.md). + +## Alpine Linux and musl + +`packaging/alpine/APKBUILD` builds an x86_64 musl package from a tagged source +archive. The container recipe runs the same Rust, MinGW, and PipeWire builds: + +```bash +docker build -f packaging/alpine/Dockerfile . +``` + +Alpine edge provides native x86_64 Wine, PulseAudio/ALSA Wine drivers, +PipeWire, desktop portals, Rust, and the MinGW-w64 toolchain. + +```bash +cd packaging/alpine +abuild checksum +abuild -r +sudo apk add ~/packages/*/x86_64/uur-*.apk +``` + +## Other package ecosystems + +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 +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 +manifests granting Wine execution, session D-Bus, PipeWire, and input access. + +## Source installation for one user + +```bash +cargo build --release --locked +./hook/build.sh +./capture/build.sh +./scripts/install-user.sh +``` + +This installs under `~/.local` by default. It requires Rust, a native C +compiler, PipeWire development files, `pkg-config`, and the MinGW-w64 x86_64 +toolchain. + +## Required first run + +Package installation does not implicitly accept NetEase's EULA or download the +official client. Complete the setup explicitly: + +```bash +uur doctor +uur setup --accept-eula +uur run +``` + +See [Platform support and usage](platform-support.md) for desktop-session and +portal requirements. diff --git a/docs/feature-parity.md b/docs/feature-parity.md new file mode 100644 index 0000000..3a75ac4 --- /dev/null +++ b/docs/feature-parity.md @@ -0,0 +1,35 @@ +# Feature parity + +| Capability | Status | Linux route | +| --- | --- | --- | +| Control other devices | available | Official UU UI and decoder under Wine | +| Receive remote video | available | Official UU UI under Wine | +| Share X11 desktop | available | Wine X11 capture | +| Share Wayland desktop | available | ScreenCast portal → PipeWire → GDI adapter | +| Mouse and keyboard | implemented | RemoteDesktop portal → uinput → XTest capability order | +| 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 | +| Independent Wayland multi-screen switching | in progress | Multiple PipeWire streams → UU display topology adapter | +| Clipboard and phone IME text | planned | RemoteDesktop Clipboard portal, then X11 fallback | +| Speaker and microphone audio | available through Wine | PulseAudio, pipewire-pulse, or ALSA selected from live capabilities | +| System-audio loopback and remote mute | Wine integration | WASAPI → winepulse/winealsa | +| Native tray | Wine baseline | Official tray, with StatusNotifierItem as the native route | +| Terminal | available | ConPTY/mux ABI adapters → authenticated native Rust PTY/login shell | +| Quick Launch | implemented | Windows app inventory adapter → XDG desktop catalog → `gio launch` | +| Desktop wallpaper | available | Capability providers → Wine desktop metadata | +| Prevent suspend/idle | available | Inhibit portal, scoped to `uur run` | +| System proxy | available | Standard proxy environment → Wine WinINet settings | +| Login autostart | available | User-controlled XDG autostart entry | +| Wake-on-LAN host setup | available | Physical-interface discovery → ethtool/NetworkManager configuration | +| Wake button in UU cloud UI | planned | Stable server capability API integration | +| VA-API capability | detected | DRM render nodes + `vainfo` | +| Vulkan Video capability | detected | Vulkan device and `VK_KHR_video_queue` | +| NVENC/NVDEC capability | detected | NVIDIA encode/decode driver libraries | +| Native hardware encode/decode data path | in progress | A common frame/codec interface feeds VA-API, Vulkan Video, and NVENC/NVDEC | +| Gamepad | Wine baseline | Wine HID/XInput for the controller UI; native host injection is planned | +| Resolution, orientation, HiDPI, zoom | partial | Portal stream geometry and Wine display settings | +| Privacy screen | planned | Compositor output policy and virtual display routing | +| Lock, reboot, shutdown, task manager | planned | logind/Polkit and desktop-native actions | +| Unattended login screen | compositor-dependent | Display-manager or compositor remote-desktop session | +| Upstream update detection | available | Official feed + API-contract CI probe | diff --git a/docs/native-services.md b/docs/native-services.md new file mode 100644 index 0000000..53d362d --- /dev/null +++ b/docs/native-services.md @@ -0,0 +1,159 @@ +# Native service adapters + +UU Remote exposes features beyond screen control. On Linux, those features +must operate on the host user account and network namespace, not on Wine's +emulated Windows environment. + +## Design boundary + +```text +UU feature protocol under Wine + │ + ▼ +small Win64 ABI proxy + │ authenticated loopback, bounded frames + ▼ +Rust native service owned by `uur run` + │ + ├─ PTY and login shell + ├─ XDG user directories and file portals + └─ host TCP/UDP sockets +``` + +Proxies translate only the Windows process or stdio boundary expected by UU. +They do not implement Linux policy. Native services are children of the uur +supervisor and cannot outlive the managed session. + +## Terminal + +Status: implemented. + +UU's server uses `conpty_bridge.exe`, `uuyc-mux.exe`, and WTS session queries. +At session startup, uur installs narrow Win64 adapters at those documented +process and API boundaries. The ConPTY adapter forwards stdio and resize +frames; the mux adapter preserves UU's named-session lifecycle; the WTS shim +supplies an active unlocked Wine session. UU's private visible-attach IPC is +delegated to the retained original helper while shell I/O remains native. + +The Rust service: + +- binds an ephemeral IPv4 loopback port; +- generates a new 256-bit token for every `uur run`; +- accepts at most four concurrent terminal sessions; +- validates a fixed-size handshake and caps frames at 64 KiB; +- opens a real PTY and starts `$SHELL -l` in `$HOME`; +- forwards terminal resize events with `TIOCSWINSZ`; +- sends a hangup and reaps the shell when the UU terminal closes; +- never logs commands, input, output, or environment contents. + +The mode-0600 runtime configuration is removed during session shutdown. The +listener, proxy configuration, PTYs, and shells share the main uur lifecycle. + +Implementation files: + +- `src/terminal.rs` +- `hook/terminal-proxy.c` +- `hook/terminal-protocol.h` +- `tests/terminal-smoke.sh` + +The smoke test starts the Rust service, runs the Win64 proxy under Wine, sends a +command through it, and requires a marker emitted by the native Linux shell. + +## Quick Launch + +Status: implemented. + +UU discovers launchable Windows applications through the standard Uninstall +registry. Before starting the server, uur exports the current XDG desktop +application catalog into a private registry namespace. Each item targets a +small Win64 launcher stored in the managed prefix. + +The launcher cannot execute an arbitrary command. It reads its immutable +desktop ID, authenticates to a per-run loopback endpoint, and asks the Rust +service to launch that ID only if it is still present in the freshly scanned +catalog. The host uses `gio launch` with `gtk-launch` as a fallback, so normal +desktop activation also covers applications installed through integration +layers that publish `.desktop` entries. + +The runtime token is mode 0600 and removed with the main session. A bounded +catalog prevents an untrusted application directory from causing unbounded +registry or prefix growth. + +## Desktop integration services + +The same lifecycle owns wallpaper synchronization and suspend/idle inhibition. +Proxy settings are imported before Wine starts. Login autostart is explicitly +controlled with `uur autostart`; no permanent root daemon is used. + +## File transfer + +Status: UU's existing Wine-visible filesystem remains available; native path +integration is not implemented yet. + +This means transfers can use paths under the managed prefix or Wine's `Z:` +mapping. A future native adapter should preserve UU's existing transfer +protocol while changing only filesystem access: + +### Receiving + +1. Receive into a mode-0700 staging directory under the user's XDG data or + runtime directory. +2. Reject absolute paths, parent traversal, device names, symlinks, sparse-file + amplification, and declared-size mismatches. +3. Keep partial files hidden and enforce per-file and per-session quotas. +4. After the final size and digest are known, atomically publish into the XDG + Downloads directory with collision-safe names. +5. Optionally notify the desktop through the standard notification portal. + +### Sending + +1. Obtain files from an explicit CLI argument, drag-and-drop request, or the + FileChooser portal. +2. Open and retain file descriptors before acknowledging the request, avoiding + path replacement races. +3. Expose only selected files through a private staging view; never expose the + entire home directory by default. +4. Stream from descriptors with bounded memory and cancellation support. + +The native adapter should not attempt to translate every Windows path into a +POSIX path. Explicitly selected files and well-defined staging directories are +safer and work in sandboxed environments. + +## Port mapping + +Status: design complete; protocol attachment to UU is not implemented yet. + +The data plane should use host sockets directly so mapped services refer to the +Linux network namespace. The native broker will: + +- support TCP first, then UDP after session and timeout semantics are proven; +- bind loopback by default; +- require explicit configuration before binding a LAN or wildcard address; +- reject privileged ports unless a separately configured capability permits + them; +- enforce destination allowlists, connection limits, idle timeouts, and byte + quotas; +- resolve names through the host resolver without exposing arbitrary proxy + environment variables to Wine; +- close every listener and connection when `uur run` ends. + +The remaining reverse-engineering task is the stable control-plane boundary +between UU's `PortMappingModule` and its tunnel implementation. The adapter +attaches at an API or helper-process boundary. + +## Clipboard and phone text + +Clipboard access belongs to the active desktop session. The preferred Wayland +route is the Clipboard interface attached to the existing RemoteDesktop portal +session. X11 uses normal selection ownership. Text payloads require strict size +limits and must not be written to logs. + +## Security invariants + +- Every service authenticates its Wine-side proxy with a per-run random token. +- Runtime endpoints bind only to loopback or use private Unix descriptors. +- Payload lengths and concurrent sessions are bounded before allocation. +- Native services run as the logged-in user; no root daemon handles content. +- User content is absent from diagnostics. +- Session shutdown revokes tokens, removes runtime files, closes listeners, and + reaps child processes. diff --git a/docs/nix.md b/docs/nix.md new file mode 100644 index 0000000..8ebd4a0 --- /dev/null +++ b/docs/nix.md @@ -0,0 +1,49 @@ +# Nix and NixOS + +The repository exports an x86_64 Linux package, an app, a development shell, +and a NixOS module. The lock file pins NixOS/nixpkgs 26.05. + +## Build or run from a checkout + +```bash +nix build +nix run . -- doctor +nix run . -- setup --accept-eula +nix run . -- run +``` + +The derivation builds the Rust supervisor, the musl/glibc-independent source +components, the PipeWire helper, and all MinGW Win64 adapters. Runtime tools +are wrapped into `PATH`; the UU client and Wine prefix remain in the user's XDG +data directory. + +## NixOS module + +Add this repository as a flake input and import its module: + +```nix +{ + inputs.uur.url = "github:panxuc/uur"; + + outputs = { self, nixpkgs, uur, ... }: { + nixosConfigurations.my-host = nixpkgs.lib.nixosSystem { + system = "x86_64-linux"; + modules = [ + uur.nixosModules.default + ({ ... }: { + programs.uur.enable = true; + }) + ]; + }; + }; +} +``` + +The module installs the package, loads `uinput`, and registers uur's udev rule. +The selected desktop still supplies its matching xdg-desktop-portal backend. + +Override the package when following a fork or local build: + +```nix +programs.uur.package = inputs.uur.packages.x86_64-linux.uur; +``` diff --git a/docs/platform-support.md b/docs/platform-support.md new file mode 100644 index 0000000..2639c92 --- /dev/null +++ b/docs/platform-support.md @@ -0,0 +1,278 @@ +# Platform support and usage + +`uur` selects Linux integrations by observable capability. Distribution and +desktop names below help users install the right dependencies. `uur doctor` +reports the active login session. + +The current release target is Linux x86_64. Wine must be able to run the +official 64-bit UU Remote client. + +## Runtime dependency axes + +| Capability | Preferred route | Alternatives | +| --- | --- | --- | +| Wayland video | ScreenCast portal + PipeWire | Portal virtual/window sources | +| X11 video | Wine X11 capture | ScreenCast portal when explicitly selected | +| Wayland input | RemoteDesktop portal | uinput; XTest for XWayland windows | +| X11 input | XTest | uinput | +| Audio | PulseAudio protocol | pipewire-pulse; ALSA | +| Wine windows | X11/XWayland | Wine Wayland driver | +| Application launch | `gio launch` | `gtk-launch` | +| Suspend inhibition | Inhibit portal | Session continues without an inhibitor | +| WOL persistence | NetworkManager + ethtool | ethtool runtime state | +| Hardware inventory | DRM + VA-API/Vulkan Video | NVENC/NVDEC; software codec | + +Common portal packages include `xdg-desktop-portal-gnome`, +`xdg-desktop-portal-kde`, `xdg-desktop-portal-hyprland`, +`xdg-desktop-portal-wlr`, `xdg-desktop-portal-lxqt`, +`xdg-desktop-portal-xapp`, `xdg-desktop-portal-gtk`, and compositor-specific +implementations. The active interfaces determine the selected path. + +## Install by distribution family + +### Arch package family + +This includes Arch Linux and distributions that consume Arch packages or the +AUR, such as EndeavourOS, CachyOS, Manjaro, Garuda Linux, Artix Linux, and +Arch-based development systems. Init-system choice does not affect uur; it +does not require a persistent systemd service. + +From AUR: + +```bash +paru -S uur +``` + +From a downloaded Arch package: + +```bash +sudo pacman -U ./uur-0.1.0-1-x86_64.pkg.tar.zst +``` + +Install the portal backend supplied or recommended by the selected desktop. +On a capture-only Wayland portal, ensure the active user can open +`/dev/uinput`; the package installs a udev rule and a module-load entry. + +### Debian package family + +The deb artifact is intended for current Debian, Ubuntu, Linux Mint, Pop!_OS, +Zorin OS, elementary OS, KDE neon, TUXEDO OS, Kali Linux, MX Linux, and other +compatible derivatives: + +```bash +sudo apt install ./uur_0.1.0_amd64.deb +``` + +The package manager resolves Wine, PipeWire, and the portal frontend. Install +the session's portal backend separately when the distribution does not pull it +in with the desktop environment. + +### RPM package family + +The rpm artifact targets current Fedora and distributions with compatible RPM +dependency names. Install it with the native frontend: + +```bash +# Fedora and compatible systems +sudo dnf install ./uur-0.1.0-1.x86_64.rpm + +# openSUSE family +sudo zypper install ./uur-0.1.0-1.x86_64.rpm +``` + +RHEL, CentOS Stream, Rocky Linux, AlmaLinux, Oracle Linux, Nobara, Ultramarine, +openSUSE Tumbleweed, and openSUSE Leap can use the RPM when its dependency names +resolve, with the portable or source build covering other package layouts. + +### Other conventional distributions + +Gentoo, Funtoo, Void Linux, Slackware, Solus, Clear Linux, Mageia, OpenMandriva, +PCLinuxOS, and similar mutable/FHS systems can use the portable archive when +they provide compatible glibc, Wine, PipeWire, and portal libraries: + +```bash +sudo tar --zstd -C / -xf ./uur-0.1.0-linux-x86_64.tar.zst +``` + +Alternatively, build and install for one user: + +```bash +cargo build --release --locked +./hook/build.sh +./capture/build.sh +./scripts/install-user.sh +``` + +The source build needs Rust, a native C compiler, PipeWire development files, +`pkg-config`, and the MinGW-w64 x86_64 compiler and binutils. Package names are +distribution-specific; uur does not invoke a package manager itself. + +### Immutable, declarative, and musl systems + +NixOS uses the repository flake and NixOS module described in [Nix and +NixOS](nix.md). The module installs the package, udev integration, and `uinput` +kernel module declaratively. + +Alpine edge uses `packaging/alpine/APKBUILD` or the included musl container +build. GNU Guix can package the same staged layout. Flatpak and Snap require +host input, Wine, and portal permissions that are best expressed as dedicated +manifests. + +## Select the desktop integration path + +### X11 session + +Requirements: `DISPLAY`, Wine's X11 driver, and the XTest extension. + +This path applies to full desktops and standalone window managers alike. Common +examples include Xorg sessions of GNOME, Plasma, Cinnamon, MATE, Xfce, LXQt, +LXDE, Budgie, Deepin, Pantheon, Trinity, and UKUI, plus i3, bspwm, awesome, +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. + +### Wayland session with ScreenCast and RemoteDesktop portals + +Requirements: a working session D-Bus, PipeWire, the xdg-desktop-portal +frontend, and a backend exposing both `ScreenCast` and `RemoteDesktop`. + +Where those interfaces are available, uur creates one combined session for +capture and input. This is the preferred unprivileged route. Examples can +include current GNOME Shell, KDE Plasma, niri with its recommended portal +configuration, COSMIC, and other sessions whose selected portal backend +advertises both interfaces. Interface availability—not the desktop name—makes +the final decision. + +### Wayland session with a capture-only portal + +Requirements: ScreenCast/PipeWire plus writable `/dev/uinput` for full desktop +input. XTest remains only a partial fallback for XWayland surfaces. + +This route commonly applies to compositors using Hyprland or wlroots-oriented +portal backends, including Hyprland, Sway, Wayfire, river, labwc, dwl, Waybox, +and other wlroots-based sessions. It may also apply to a desktop whose portal +installation is incomplete or whose selected backend omits RemoteDesktop. + +Install the compositor's ScreenCast portal and enable uinput access. A +`portals.conf` selects the backend when several are installed. + +### Wine window backend + +The UU user interface still needs a Wine display driver: + +- Existing X11 and most Wayland desktop sessions normally use Wine through + X11 or XWayland. +- Compositors without built-in XWayland can use an external XWayland manager; + niri, for example, integrates xwayland-satellite in current releases. +- Wine builds with a usable native Wayland driver may run without XWayland, + but that combination must still pass UU WebView2 and window-management tests. + +This choice is independent from desktop capture. A client window can use +XWayland while the controlled desktop is captured through the Wayland portal. + +### Audio servers + +Wine's PulseAudio driver is selected for both a native PulseAudio daemon and +the `pipewire-pulse` compatibility server. A native PipeWire session without +PulseAudio compatibility uses Wine's ALSA driver. `uur doctor` prints the live +choice; this is independent from PipeWire's Wayland video role. + +### Displays and virtual sources + +```bash +uur display status +uur display source monitor +uur display source window +uur display source virtual +``` + +The command clears the old restore token so the next Portal session can create +or select the requested source. X11 exposes its XRandR topology to Wine. +Wayland currently carries one selected stream; independent multi-stream +switching is the next display-topology adapter. + +## First run and normal use + +After installing any package format: + +```bash +uur doctor +uur setup --accept-eula +uur run +``` + +Optional host integration is managed explicitly: + +```bash +uur autostart enable +uur autostart status +uur wol status +sudo uur wol enable --interface enp3s0 +``` + +The WOL command configures the real Linux adapter; it requires `ethtool`, and +persists the setting through an active NetworkManager wired profile when one +exists. The adapter name above is only an example—omit it for automatic +physical-interface selection. + +The package installs `uur.desktop` as the canonical application-menu entry. +During setup, an existing Wine-generated Linux desktop entry for the official +client is converted into a hidden compatibility alias whose command is also +`uur run`. This keeps already pinned Dock, panel, or launcher favorites working +without showing a duplicate application in new searches. + +The `.lnk` file inside the Wine prefix remains available for diagnosis. Normal +desktop integration launches `uur.desktop` or `uur run` so all helpers share +the same lifetime. + +The first Wayland run may show a portal chooser. Select the monitor to expose +to remote controllers. A successful persistent portal grant is reused where +the backend supports restore tokens. + +UU Quick Launch is populated from visible XDG desktop entries every time +`uur run` starts. This includes conventional packages and any containerized or +portable application that publishes a valid `.desktop` entry. Application +activation uses the desktop entry itself, so uur does not maintain a command +translation table. + +Stop only the managed session and its Wine prefix with: + +```bash +uur stop +``` + +Useful input-backend overrides for diagnosis are: + +```bash +UUR_INPUT_BACKEND=portal uur run +UUR_INPUT_BACKEND=uinput uur run +UUR_INPUT_BACKEND=xtest uur run +``` + +An override is a diagnostic tool, not a desktop-specific configuration. The +default `auto` mode should be used after troubleshooting. + +## Reading `uur doctor` + +- `portal ScreenCast`: required to capture a Wayland desktop. +- `portal RemoteDesktop`: preferred unprivileged Wayland input route. +- `uinput (/dev/uinput)`: full-desktop fallback when RemoteDesktop is absent. +- `DISPLAY`: required for Wine/X11 or Wine/XWayland and for XTest fallback. +- `WAYLAND_DISPLAY`: identifies the active Wayland session. +- `PipeWire`: required for the Wayland frame transport. + +If both Wayland input routes are unavailable, XTest controls XWayland windows. + +## Session model + +Portal sessions operate in the logged-in desktop seat. Display-manager access +uses a display-manager remote session, while headless operation uses a portal +virtual source or a provisioned virtual display. `uur doctor` reports the +active backend capabilities. + +Relevant upstream documentation: + +- [xdg-desktop-portal backend selection](https://flatpak.github.io/xdg-desktop-portal/docs/portals.conf.html) +- [RemoteDesktop portal](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.RemoteDesktop.html) +- [ScreenCast portal](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.ScreenCast.html) diff --git a/docs/upstream-adaptation.md b/docs/upstream-adaptation.md new file mode 100644 index 0000000..811621b --- /dev/null +++ b/docs/upstream-adaptation.md @@ -0,0 +1,43 @@ +# Upstream adaptation + +UU Remote and uur have independent release lifecycles. The AUR package +contains only uur, so a new proprietary client does not automatically require +a package rebuild. + +## Compatibility contract + +The adapter depends on named operating-system APIs, not a table of UU versions, +hashes, RVAs, or instruction patches: + +- `wevtapi!EvtOpenPublisherMetadata` loads the compatibility shim; +- `USER32!SendInput` is routed to the native input bridge; +- GDI or DXGI desktop-capture entry points are routed to the frame adapter; +- dynamic `GetProcAddress` resolution is intercepted as well as static imports. + +`scripts/probe-upstream.sh` verifies those contracts across every PE file in +an installed client tree. If an installer cannot be extracted directly, the +probe installs it in a disposable Wine prefix and examines the result. + +## Automation + +The daily `upstream-watch` workflow: + +1. resolves NetEase's official HTTPS release URL; +2. verifies the Authenticode signature; +3. extracts or installs the client in an ephemeral environment; +4. runs the static API-contract probe; +5. opens or updates a tracking issue with the result. + +Static success means the generic adapter still has a viable attachment point; +it is not presented as full runtime proof. A release candidate must also pass +the Wine input round-trip and changing-frame canary before it is promoted. + +Project releases build all package formats from the same source and publish +immutable artifacts and checksums. A new proprietary client version alone does +not cause a meaningless uur package rebuild. + +## When a contract changes + +Compatibility changes add a stable API adapter or transport behind the existing +Rust traits. Capability probes select the route whose prerequisite API is +available. diff --git a/docs/video-backends.md b/docs/video-backends.md new file mode 100644 index 0000000..9079354 --- /dev/null +++ b/docs/video-backends.md @@ -0,0 +1,31 @@ +# Video and display backends + +## Frame sources + +- X11 sessions expose the XRandR monitor topology directly to Wine. +- Wayland monitor and window sources use ScreenCast/PipeWire. +- `uur display source virtual` requests the portal's Virtual source type and + stores its restore token. +- A multi-stream compositor will combine or expose several PipeWire nodes to + UU's display topology for independent Wayland screen switching. + +## Codec capabilities + +`uur doctor` inventories the native acceleration APIs independently: + +- DRM render nodes are the common device boundary; +- VA-API covers Intel, AMD, and supported third-party drivers; +- Vulkan Video is recognized through `VK_KHR_video_queue`; +- NVENC and NVDEC are recognized through NVIDIA's encode/decode libraries; +- software H.264 remains available through UU's current Windows path. + +The native codec data path will consume the same BGRx frame transport used by +the current capture adapter. A backend receives frame descriptors, negotiated +color metadata, dimensions, and target latency; it returns encoded access units +through one common interface. Codec selection can then prefer a verified +hardware route and fall back to software without changing capture, display, or +UU protocol code. + +HDR requires a 10-bit frame format, color primaries, transfer function, and +mastering metadata across the portal, PipeWire, encoder, and UU transport. The +current BGRx transport is SDR. diff --git a/docs/windows-feature-map.md b/docs/windows-feature-map.md new file mode 100644 index 0000000..dbe68a4 --- /dev/null +++ b/docs/windows-feature-map.md @@ -0,0 +1,30 @@ +# UU Windows feature map + +The current UU server advertises these capability families. The Linux route is +organized by host subsystem so each backend can evolve independently. + +| UU capability family | Linux integration | +| --- | --- | +| Desktop, window, and emulator capture | X11/Wine or portal/PipeWire frame source | +| Monitor, second screen, virtual display | XRandR topology or portal monitor/window/virtual sources | +| Resolution, orientation, HiDPI, zoom | Display topology and stream geometry adapters | +| 90/144 fps, true color, chroma, HDR | Frame format and encoder capability negotiation | +| Keyboard, mouse, smart/virtual mouse | RemoteDesktop portal, uinput, XTest | +| Touch, pen, gamepad | uinput tablet and future multitouch/gamepad devices | +| Speaker, microphone, remote mute | Wine WASAPI over PulseAudio, pipewire-pulse, or ALSA | +| Clipboard and phone text input | Portal clipboard and X11 selections | +| File transfer v1-v4 | Wine-visible paths now; native XDG staging next | +| Terminal and multiple sessions | Native PTY with ConPTY and mux ABI adapters | +| Port mapping | Native host socket broker | +| Quick Launch and remote application list | XDG desktop catalog and authenticated launcher | +| Wallpaper and privacy wallpaper | Desktop wallpaper providers and capture routing | +| Privacy screen | Compositor output policy or a dedicated virtual output | +| Wake-on-LAN | Physical NIC configuration and UU capability reporting | +| Lock, reboot, shutdown, task manager | logind/Polkit and desktop-native actions | +| Auto unlock and login-screen access | Display-manager remote session integration | +| Controlled update | Official release feed and compatibility probes | + +The [App Store release history](https://apps.apple.com/hk/app/uu%E8%BF%9C%E7%A8%8B-%E8%BF%9C%E7%A8%8B%E5%8A%9E%E5%85%AC-%E6%B8%B8%E6%88%8F%E4%B8%B2%E6%B5%81/id1642306791?platform=mac) +also confirms multi-session terminal support, view-only mode, automatic unlock, +and remote terminal access on current Apple clients. The server capability +table is broader and is the implementation map used by uur. diff --git a/flake.lock b/flake.lock new file mode 100644 index 0000000..039ba2b --- /dev/null +++ b/flake.lock @@ -0,0 +1,24 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1788405554, + "narHash": "sha256-z3ACU3NTAstjK+JNjW0zmIH2Q0GYo2pgGfJddesv7Xo=", + "rev": "a5cc6f2c37bf518436dc8d1c288ccd0c43c2f4c4", + "type": "tarball", + "url": "https://releases.nixos.org/nixos/26.05/nixos-26.05.8954.a5cc6f2c37bf/nixexprs.tar.xz" + }, + "original": { + "type": "tarball", + "url": "https://channels.nixos.org/nixos-26.05/nixexprs.tar.xz" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/flake.nix b/flake.nix new file mode 100644 index 0000000..46290d1 --- /dev/null +++ b/flake.nix @@ -0,0 +1,38 @@ +{ + description = "UU Remote compatibility layer for Linux"; + + inputs.nixpkgs.url = "https://channels.nixos.org/nixos-26.05/nixexprs.tar.xz"; + + outputs = + { self, nixpkgs }: + let + system = "x86_64-linux"; + pkgs = nixpkgs.legacyPackages.${system}; + uur = pkgs.callPackage ./nix/package.nix { }; + in + { + packages.${system} = { + inherit uur; + default = uur; + }; + + apps.${system}.default = { + type = "app"; + program = "${uur}/bin/uur"; + meta.description = "Run the uur command-line interface"; + }; + + nixosModules.default = import ./nix/module.nix { inherit self; }; + + devShells.${system}.default = pkgs.mkShell { + inputsFrom = [ uur ]; + packages = [ + pkgs.cargo + pkgs.rustc + pkgs.pkgsCross.mingwW64.stdenv.cc + ]; + }; + + formatter.${system} = pkgs.nixfmt; + }; +} diff --git a/hook/build.sh b/hook/build.sh new file mode 100755 index 0000000..1ba8939 --- /dev/null +++ b/hook/build.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# Cross-build the Windows PE hook components (needs the mingw-w64 +# toolchain; see packaging/aur/PKGBUILD makedepends). +set -euo pipefail + +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +readonly root +out="$root/build/hook" +if [[ -n ${UU_MINGW_CC:-} ]]; then + cc=$UU_MINGW_CC +elif command -v x86_64-w64-mingw32-gcc >/dev/null 2>&1; then + cc=x86_64-w64-mingw32-gcc +else + cc=x86_64-w64-mingw32-cc +fi +strip="${UU_MINGW_STRIP:-x86_64-w64-mingw32-strip}" +dlltool="${UU_MINGW_DLLTOOL:-x86_64-w64-mingw32-dlltool}" +flags=(-std=c11 -O2 -Wall -Wextra -Werror -Wl,--no-insert-timestamp) + +mkdir -p "$out" + +for tool in "$cc" "$dlltool" "$strip"; do + command -v "$tool" >/dev/null 2>&1 || { printf 'missing tool: %s\n' "$tool" >&2; exit 1; } +done + +"$dlltool" --def "$root/hook/uur-hook.def" \ + --output-lib "$out/libuur-hook.dll.a" + +"$cc" "${flags[@]}" -shared -o "$out/uur-hook.dll" \ + "$root/hook/uur-hook.c" "$root/hook/uur-hook.def" \ + -lws2_32 -lgdi32 -luser32 -lkernel32 + +"$cc" "${flags[@]}" -shared -o "$out/wevtapi.dll" \ + "$root/hook/wevtapi.c" "$root/hook/wevtapi.def" \ + "$out/libuur-hook.dll.a" + +"$cc" "${flags[@]}" -shared -o "$out/wtsapi32.dll" \ + "$root/hook/wtsapi32.c" -ladvapi32 -lkernel32 + +"$dlltool" --def "$root/hook/wevtapi.def" \ + --output-lib "$out/libwevtapi.dll.a" + +"$cc" "${flags[@]}" -mwindows -o "$out/winlogon.exe" \ + "$root/hook/winlogon.c" -lkernel32 + +"$cc" "${flags[@]}" -mwindows -o "$out/uur-terminal-proxy.exe" \ + "$root/hook/terminal-proxy.c" -lws2_32 -lkernel32 + +"$cc" "${flags[@]}" -mwindows -o "$out/uur-mux-proxy.exe" \ + "$root/hook/mux-proxy.c" -lkernel32 + +"$cc" "${flags[@]}" -mwindows -o "$out/uur-launch-proxy.exe" \ + "$root/hook/launch-proxy.c" -lws2_32 -lkernel32 + +"$cc" "${flags[@]}" -o "$out/selftest.exe" \ + "$root/hook/selftest.c" -L"$out" -lwevtapi -luser32 -lgdi32 + +"$strip" --strip-unneeded "$out/uur-hook.dll" "$out/wevtapi.dll" \ + "$out/wtsapi32.dll" "$out/winlogon.exe" \ + "$out/uur-terminal-proxy.exe" "$out/uur-mux-proxy.exe" \ + "$out/uur-launch-proxy.exe" +printf 'built: %s\n' "$out" diff --git a/hook/frame-protocol.h b/hook/frame-protocol.h new file mode 100644 index 0000000..60e7cc6 --- /dev/null +++ b/hook/frame-protocol.h @@ -0,0 +1,18 @@ +#ifndef UUR_FRAME_PROTOCOL_H +#define UUR_FRAME_PROTOCOL_H + +#include +#include + +#define UURF_MAGIC 0x46525555u +#define UURF_VERSION 1u +#define UURF_SLOT_COUNT 3u +#define UURF_HEADER_BYTES 64u + +static inline size_t uurf_slot_offset(uint64_t sequence, size_t slot_bytes) +{ + return UURF_HEADER_BYTES + + (size_t)(sequence % UURF_SLOT_COUNT) * slot_bytes; +} + +#endif diff --git a/hook/launch-proxy.c b/hook/launch-proxy.c new file mode 100644 index 0000000..f782869 --- /dev/null +++ b/hook/launch-proxy.c @@ -0,0 +1,122 @@ +#define WIN32_LEAN_AND_MEAN +#include +#include + +#include +#include +#include + +#define TOKEN_BYTES 64 +#define MAGIC 0x55554c41u + +static int sibling(char *path, size_t capacity, const char *name) +{ + DWORD length = GetModuleFileNameA(NULL, path, (DWORD)capacity); + char *separator; + if (length == 0 || length >= capacity) + return 0; + separator = strrchr(path, '\\'); + if (separator == NULL) + return 0; + if ((size_t)(separator - path) + strlen(name) + 2 > capacity) + return 0; + strcpy(separator + 1, name); + return 1; +} + +static int read_small_file(const char *path, char *buffer, size_t capacity) +{ + HANDLE file; + DWORD count; + file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, + NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (file == INVALID_HANDLE_VALUE) + return 0; + if (!ReadFile(file, buffer, (DWORD)capacity - 1, &count, NULL)) { + CloseHandle(file); + return 0; + } + CloseHandle(file); + buffer[count] = '\0'; + while (count > 0 && (buffer[count - 1] == '\r' || buffer[count - 1] == '\n')) + buffer[--count] = '\0'; + return count > 0; +} + +static int send_all(SOCKET socket, const void *data, size_t length) +{ + const char *cursor = data; + while (length > 0) { + int sent = send(socket, cursor, (int)length, 0); + if (sent <= 0) + return 0; + cursor += sent; + length -= (size_t)sent; + } + return 1; +} + +static void put_u16_be(unsigned char *output, uint16_t value) +{ + output[0] = (unsigned char)(value >> 8); + output[1] = (unsigned char)value; +} + +static void put_u32_be(unsigned char *output, uint32_t value) +{ + output[0] = (unsigned char)(value >> 24); + output[1] = (unsigned char)(value >> 16); + output[2] = (unsigned char)(value >> 8); + output[3] = (unsigned char)value; +} + +int main(void) +{ + char id_path[32768]; + char app_id[512]; + char config[512]; + char token[TOKEN_BYTES + 1]; + unsigned port; + WSADATA winsock; + SOCKET socket = INVALID_SOCKET; + struct sockaddr_in address; + unsigned char header[12]; + unsigned char accepted = 0; + size_t id_length; + int result = 1; + + if (!sibling(id_path, sizeof(id_path), "app-id.txt") || + !read_small_file(id_path, app_id, sizeof(app_id)) || + !read_small_file("C:\\uur-launcher.runtime", config, sizeof(config)) || + sscanf(config, "version=1\nport=%u\ntoken=%64[0-9a-f]\n", &port, token) != 2 || + port == 0 || port > 65535 || strlen(token) != TOKEN_BYTES) + return 2; + id_length = strlen(app_id); + if (id_length == 0 || id_length > 500 || WSAStartup(MAKEWORD(2, 2), &winsock) != 0) + return 3; + socket = WSASocketA(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, 0); + if (socket == INVALID_SOCKET) + goto done; + ZeroMemory(&address, sizeof(address)); + address.sin_family = AF_INET; + address.sin_port = htons((uint16_t)port); + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (connect(socket, (struct sockaddr *)&address, sizeof(address)) != 0) + goto done; + put_u32_be(header + 0, MAGIC); + put_u16_be(header + 4, 1); + put_u16_be(header + 6, TOKEN_BYTES); + put_u16_be(header + 8, (uint16_t)id_length); + put_u16_be(header + 10, 0); + if (!send_all(socket, header, sizeof(header)) || + !send_all(socket, token, TOKEN_BYTES) || + !send_all(socket, app_id, id_length) || recv(socket, (char *)&accepted, 1, 0) != 1) + goto done; + result = accepted == 1 ? 0 : 4; +done: + if (socket != INVALID_SOCKET) + closesocket(socket); + SecureZeroMemory(token, sizeof(token)); + WSACleanup(); + return result; +} diff --git a/hook/mux-proxy.c b/hook/mux-proxy.c new file mode 100644 index 0000000..31795d2 --- /dev/null +++ b/hook/mux-proxy.c @@ -0,0 +1,254 @@ +/* UU's uuyc-mux session bookkeeping mapped onto native PTY adapters. */ +#define WIN32_LEAN_AND_MEAN +#include + +#include +#include +#include + +static int sibling_path(char *path, size_t capacity, const char *name); + +static void log_result(const char *command, const char *session, int result) +{ + char path[32768]; + char line[384]; + HANDLE file; + DWORD length; + DWORD written; + if (!sibling_path(path, sizeof(path), "uur-mux-adapter.status")) + return; + file = CreateFileA(path, FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (file == INVALID_HANDLE_VALUE) + return; + length = (DWORD)snprintf(line, sizeof(line), + "command=%s session=%s result=%d\r\n", + command != NULL ? command : "", + session != NULL ? session : "", result); + if (length < sizeof(line)) + WriteFile(file, line, length, &written, NULL); + CloseHandle(file); +} + +static int sibling_path(char *path, size_t capacity, const char *name) +{ + DWORD length = GetModuleFileNameA(NULL, path, (DWORD)capacity); + char *separator; + size_t prefix; + size_t name_length = strlen(name); + if (length == 0 || length >= capacity) + return 0; + separator = strrchr(path, '\\'); + if (separator == NULL) + return 0; + prefix = (size_t)(separator - path) + 1; + if (prefix + name_length + 1 > capacity) + return 0; + memcpy(path + prefix, name, name_length + 1); + return 1; +} + +static int valid_session(const char *session) +{ + size_t index; + if (session == NULL || session[0] == '\0') + return 0; + for (index = 0; session[index] != '\0'; ++index) { + char c = session[index]; + if (index >= 126 || !((c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '-' || c == '_')) + return 0; + } + return 1; +} + +static int marker_path(const char *session, char *path, size_t capacity) +{ + char name[192]; + if (!valid_session(session) || + snprintf(name, sizeof(name), "uur-terminal-session-%s.active", + session) >= (int)sizeof(name)) + return 0; + return sibling_path(path, capacity, name); +} + +static DWORD marker_pid(const char *session, char *path, size_t capacity) +{ + HANDLE file; + char content[64]; + DWORD count; + char *end; + unsigned long pid; + if (!marker_path(session, path, capacity)) + return 0; + file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | + FILE_SHARE_DELETE, NULL, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, NULL); + if (file == INVALID_HANDLE_VALUE) + return 0; + if (!ReadFile(file, content, sizeof(content) - 1, &count, NULL)) { + CloseHandle(file); + return 0; + } + CloseHandle(file); + content[count] = '\0'; + pid = strtoul(content, &end, 10); + if (end == content || pid == 0 || pid > 0xffffffffUL) + return 0; + return (DWORD)pid; +} + +static int session_alive(const char *session, char *path, size_t capacity) +{ + return marker_pid(session, path, capacity) != 0; +} + +static int wait_for_session(const char *session, char *path, size_t capacity) +{ + unsigned attempt; + for (attempt = 0; attempt < 75; ++attempt) { + if (session_alive(session, path, capacity)) + return 1; + Sleep(10); + } + return 0; +} + +static int attach_session(const char *session, char *path, size_t capacity) +{ + if (!wait_for_session(session, path, capacity)) + return 1; + log_result("attach-start", session, 0); + while (marker_pid(session, path, capacity) != 0) + Sleep(100); + return 0; +} + +static const char *option_value(int argc, char **argv, const char *name) +{ + int index; + for (index = 1; index + 1 < argc; ++index) { + if (strcmp(argv[index], name) == 0) + return argv[index + 1]; + } + return NULL; +} + +static const char *command_name(int argc, char **argv) +{ + int index; + for (index = 1; index < argc; ++index) { + if ((strcmp(argv[index], "-L") == 0 || + strcmp(argv[index], "-f") == 0 || + strcmp(argv[index], "-S") == 0) && index + 1 < argc) { + ++index; + continue; + } + return argv[index]; + } + return NULL; +} + +static int delegate_version(void) +{ + char executable[32768]; + char command[33000]; + STARTUPINFOA startup; + PROCESS_INFORMATION process; + DWORD code = 1; + if (!sibling_path(executable, sizeof(executable), + "uuyc-mux.exe.uur-original")) + return 1; + snprintf(command, sizeof(command), "\"%s\" --version", executable); + ZeroMemory(&startup, sizeof(startup)); + ZeroMemory(&process, sizeof(process)); + startup.cb = sizeof(startup); + if (!CreateProcessA(executable, command, NULL, NULL, TRUE, 0, NULL, + NULL, &startup, &process)) + return 1; + WaitForSingleObject(process.hProcess, 10000); + GetExitCodeProcess(process.hProcess, &code); + CloseHandle(process.hThread); + CloseHandle(process.hProcess); + return (int)code; +} + +static int list_sessions(void) +{ + char pattern[32768]; + WIN32_FIND_DATAA entry; + HANDLE search; + char *separator; + if (!sibling_path(pattern, sizeof(pattern), "uur-terminal-session-*.active")) + return 1; + separator = strrchr(pattern, '\\'); + search = FindFirstFileA(pattern, &entry); + if (search == INVALID_HANDLE_VALUE) + return 0; + do { + const char *prefix = "uur-terminal-session-"; + const char *suffix = ".active"; + size_t length = strlen(entry.cFileName); + size_t prefix_length = strlen(prefix); + size_t suffix_length = strlen(suffix); + if (length > prefix_length + suffix_length && + strncmp(entry.cFileName, prefix, prefix_length) == 0 && + strcmp(entry.cFileName + length - suffix_length, suffix) == 0) { + char session[128]; + char marker[32768]; + size_t session_length = length - prefix_length - suffix_length; + memcpy(session, entry.cFileName + prefix_length, session_length); + session[session_length] = '\0'; + if (session_alive(session, marker, sizeof(marker))) + printf("%s\n", session); + } + } while (FindNextFileA(search, &entry)); + FindClose(search); + (void)separator; + return 0; +} + +int main(int argc, char **argv) +{ + const char *command = command_name(argc, argv); + const char *session = option_value(argc, argv, "-t"); + char marker[32768]; + int result; + if (command == NULL || strcmp(command, "--version") == 0 || + strcmp(command, "version") == 0) { + result = delegate_version(); + log_result(command, session, result); + return result; + } + if (strcmp(command, "has-session") == 0 || strcmp(command, "has") == 0) { + result = wait_for_session(session, marker, sizeof(marker)) ? 0 : 1; + log_result(command, session, result); + return result; + } + if (strcmp(command, "list-sessions") == 0 || strcmp(command, "ls") == 0) { + result = list_sessions(); + log_result(command, session, result); + return result; + } + if (strcmp(command, "attach") == 0 || + strcmp(command, "attach-session") == 0 || + strcmp(command, "a") == 0 || strcmp(command, "at") == 0) { + result = attach_session(session, marker, sizeof(marker)); + log_result(command, session, result); + return result; + } + if (strcmp(command, "kill-session") == 0 || + strcmp(command, "kill-ses") == 0) { + DWORD pid = marker_pid(session, marker, sizeof(marker)); + if (marker[0] != '\0') + DeleteFileA(marker); + result = pid ? 0 : 1; + log_result(command, session, result); + return result; + } + /* Configuration and display commands are no-ops for a native PTY. */ + log_result(command, session, 0); + return 0; +} diff --git a/hook/selftest.c b/hook/selftest.c new file mode 100644 index 0000000..cef8f95 --- /dev/null +++ b/hook/selftest.c @@ -0,0 +1,163 @@ +/* + * selftest — end-to-end probe without NetEase software. + * + * Statically imports wevtapi!EvtOpenPublisherMetadata so the Windows + * loader resolves the preload chain (wevtapi.dll -> uur-hook.dll) at + * process start, and USER32!SendInput so the hook has something to + * rewrite. Then it issues a few absolute pointer motions and one key + * press/release pair. The uur host bridge should log the connection and + * inject the motions onto the real desktop; `uur pointer` before/after + * observes the effect. + */ + +#include +#include +#include +#include + +#include "frame-protocol.h" + +/* Static import: forces wevtapi.dll (the shim) to load at startup. */ +void *__stdcall EvtOpenPublisherMetadata(void *session, void *publisher_id, + void *log_file_path, + unsigned long locale, + unsigned long flags); + +static void move_absolute(int x, int y) +{ + INPUT input; + ZeroMemory(&input, sizeof(input)); + input.type = INPUT_MOUSE; + input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE; + input.mi.dx = (DWORD)((int64_t)x * 65535 / 1920); + input.mi.dy = (DWORD)((int64_t)y * 65535 / 1080); + SendInput(1, &input, sizeof(input)); +} + +static void put_u32(unsigned char *target, uint32_t value) +{ + target[0] = (unsigned char)value; + target[1] = (unsigned char)(value >> 8); + target[2] = (unsigned char)(value >> 16); + target[3] = (unsigned char)(value >> 24); +} + +static void put_u64(unsigned char *target, uint64_t value) +{ + put_u32(target, (uint32_t)value); + put_u32(target + 4, (uint32_t)(value >> 32)); +} + +static int capture_round_trip(void) +{ + static const char frame_path[] = "C:\\uur-selftest-frames.bin"; + const uint32_t width = 2; + const uint32_t height = 2; + const uint32_t stride = width * 4; + const size_t slot_bytes = 8 + stride * height; + const size_t total_bytes = UURF_HEADER_BYTES + UURF_SLOT_COUNT * slot_bytes; + unsigned char *transport = calloc(1, total_bytes); + DWORD written = 0; + HANDLE file; + HDC screen = NULL; + HDC destination = NULL; + HBITMAP bitmap = NULL; + HGDIOBJ previous = NULL; + unsigned char *pixels = NULL; + int passed = 0; + + if (transport == NULL) + return 0; + put_u32(transport, UURF_MAGIC); + put_u32(transport + 4, UURF_VERSION); + put_u32(transport + 8, width); + put_u32(transport + 12, height); + put_u32(transport + 16, stride); + put_u32(transport + 20, 1); + put_u64(transport + 24, 1); + unsigned char *slot = transport + uurf_slot_offset(1, slot_bytes); + put_u64(slot, 2); + for (size_t offset = 8; offset < slot_bytes; offset += 4) { + slot[offset + 0] = 0x00; + slot[offset + 1] = 0x00; + slot[offset + 2] = 0xff; + slot[offset + 3] = 0x00; + } + + file = CreateFileA(frame_path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, + NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (file == INVALID_HANDLE_VALUE) + goto cleanup; + if (!WriteFile(file, transport, (DWORD)total_bytes, &written, NULL) || + written != total_bytes) { + CloseHandle(file); + goto cleanup; + } + CloseHandle(file); + if (!WritePrivateProfileStringA("bridge", "frame_path", frame_path, + "C:\\uur-bridge.ini")) + goto cleanup; + + BITMAPINFO info; + ZeroMemory(&info, sizeof(info)); + info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); + info.bmiHeader.biWidth = (LONG)width; + info.bmiHeader.biHeight = -(LONG)height; + info.bmiHeader.biPlanes = 1; + info.bmiHeader.biBitCount = 32; + info.bmiHeader.biCompression = BI_RGB; + + screen = GetDC(NULL); + destination = CreateCompatibleDC(screen); + bitmap = CreateDIBSection(destination, &info, DIB_RGB_COLORS, + (void **)&pixels, NULL, 0); + if (screen == NULL || destination == NULL || bitmap == NULL || pixels == NULL) + goto cleanup; + previous = SelectObject(destination, bitmap); + if (!BitBlt(destination, 0, 0, width, height, screen, 0, 0, SRCCOPY)) + goto cleanup; + passed = pixels[0] == 0x00 && pixels[1] == 0x00 && pixels[2] == 0xff; + +cleanup: + if (previous != NULL) + SelectObject(destination, previous); + if (bitmap != NULL) + DeleteObject(bitmap); + if (destination != NULL) + DeleteDC(destination); + if (screen != NULL) + ReleaseDC(NULL, screen); + DeleteFileA(frame_path); + free(transport); + return passed; +} + +int main(void) +{ + (void)EvtOpenPublisherMetadata(NULL, NULL, NULL, 0, 0); + + if (!capture_round_trip()) { + fprintf(stderr, "capture adapter round-trip failed\n"); + return 10; + } + + move_absolute(200, 200); + Sleep(400); + move_absolute(700, 500); + Sleep(400); + move_absolute(960, 540); + Sleep(400); + + INPUT key; + ZeroMemory(&key, sizeof(key)); + key.type = INPUT_KEYBOARD; + key.ki.wVk = 0x41; /* 'A' */ + SendInput(1, &key, sizeof(key)); + key.ki.dwFlags = KEYEVENTF_KEYUP; + SendInput(1, &key, sizeof(key)); + + + Sleep(200); + printf("hook capture and input smoke test passed\n"); + return 0; +} diff --git a/hook/terminal-protocol.h b/hook/terminal-protocol.h new file mode 100644 index 0000000..5e430fe --- /dev/null +++ b/hook/terminal-protocol.h @@ -0,0 +1,35 @@ +#ifndef UUR_TERMINAL_PROTOCOL_H +#define UUR_TERMINAL_PROTOCOL_H + +#include + +#define UUR_TERMINAL_MAGIC 0x55555242u +#define UUR_TERMINAL_VERSION 1u +#define UUR_TERMINAL_TOKEN_BYTES 64u +#define UUR_TERMINAL_MAX_FRAME 65536u +#define UUR_TERMINAL_ACCEPTED 0x06u +#define UUR_TERMINAL_CONFIG "uu-terminal-bridge.runtime" + +enum uur_terminal_frame_type { + UUR_TERMINAL_DATA = 1, + UUR_TERMINAL_RESIZE = 2, + UUR_TERMINAL_EOF = 3, +}; + +#pragma pack(push, 1) +struct uur_terminal_hello { + uint32_t magic; + uint16_t version; + uint16_t token_length; + uint16_t columns; + uint16_t rows; +}; + +struct uur_terminal_frame { + uint8_t type; + uint8_t reserved[3]; + uint32_t length; +}; +#pragma pack(pop) + +#endif diff --git a/hook/terminal-proxy.c b/hook/terminal-proxy.c new file mode 100644 index 0000000..5b65496 --- /dev/null +++ b/hook/terminal-proxy.c @@ -0,0 +1,559 @@ +#define WIN32_LEAN_AND_MEAN +#include +#include + +#include +#include +#include +#include + +#include "terminal-protocol.h" + +static SOCKET bridge = INVALID_SOCKET; +static CRITICAL_SECTION write_lock; +static HANDLE stopping; +static HANDLE terminal_input; +static HANDLE terminal_output; +static HANDLE terminal_control; +static volatile LONG saw_input; +static volatile LONG saw_output; + +static int executable_sibling(char *path, size_t capacity, const char *name); + +static int delegate_visible_attach(void) +{ + char executable[32768]; + char *command; + STARTUPINFOA startup; + PROCESS_INFORMATION process; + DWORD exit_code = 1; + DWORD wait; + if (!executable_sibling(executable, sizeof(executable), + "conpty_bridge.exe.uur-original")) + return 1; + command = _strdup(GetCommandLineA()); + if (command == NULL) + return 1; + ZeroMemory(&startup, sizeof(startup)); + ZeroMemory(&process, sizeof(process)); + startup.cb = sizeof(startup); + if (!CreateProcessA(executable, command, NULL, NULL, FALSE, + CREATE_NO_WINDOW, NULL, NULL, &startup, &process)) { + free(command); + return 1; + } + free(command); + CloseHandle(process.hThread); + wait = WaitForSingleObject(process.hProcess, 15000); + if (wait == WAIT_OBJECT_0) + GetExitCodeProcess(process.hProcess, &exit_code); + else + TerminateProcess(process.hProcess, 1); + CloseHandle(process.hProcess); + return (int)exit_code; +} + +struct launch_options { + HANDLE input; + HANDLE output; + HANDLE control; + uint16_t columns; + uint16_t rows; + int explicit_handles; + int attach_existing; + int visible_attach; + char session[128]; +}; + +static void write_status(const char *stage, DWORD detail) +{ + char path[32768]; + char line[192]; + DWORD length; + DWORD written; + HANDLE file; + + if (!executable_sibling(path, sizeof(path), "uur-terminal-adapter.status")) + return; + file = CreateFileA(path, FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + if (file == INVALID_HANDLE_VALUE) + return; + length = (DWORD)snprintf(line, sizeof(line), + "pid=%lu stage=%s detail=%lu\r\n", + (unsigned long)GetCurrentProcessId(), stage, + (unsigned long)detail); + if (length < sizeof(line)) + WriteFile(file, line, length, &written, NULL); + CloseHandle(file); + SecureZeroMemory(path, sizeof(path)); +} + +static int send_all(const void *data, size_t length) +{ + const char *cursor = data; + while (length > 0) { + int request = length > INT_MAX ? INT_MAX : (int)length; + int written = send(bridge, cursor, request, 0); + if (written <= 0) + return 0; + cursor += written; + length -= (size_t)written; + } + return 1; +} + +static int receive_all(void *data, size_t length) +{ + char *cursor = data; + while (length > 0) { + int request = length > INT_MAX ? INT_MAX : (int)length; + int received = recv(bridge, cursor, request, 0); + if (received <= 0) + return 0; + cursor += received; + length -= (size_t)received; + } + return 1; +} + +static int send_frame(uint8_t type, const void *payload, uint32_t length) +{ + struct uur_terminal_frame frame; + int result; + + ZeroMemory(&frame, sizeof(frame)); + frame.type = type; + frame.length = htonl(length); + EnterCriticalSection(&write_lock); + result = send_all(&frame, sizeof(frame)); + if (result && length != 0) + result = send_all(payload, length); + LeaveCriticalSection(&write_lock); + return result; +} + +static int executable_sibling(char *path, size_t capacity, const char *name) +{ + DWORD length = GetModuleFileNameA(NULL, path, (DWORD)capacity); + char *separator; + size_t prefix; + size_t name_length = strlen(name); + + if (length == 0 || length >= capacity) + return 0; + separator = strrchr(path, '\\'); + if (separator == NULL) + separator = strrchr(path, '/'); + if (separator == NULL) + return 0; + prefix = (size_t)(separator - path) + 1; + if (prefix + name_length + 1 > capacity) + return 0; + memcpy(path + prefix, name, name_length + 1); + return 1; +} + +static int valid_token(const char *token) +{ + size_t index; + if (strlen(token) != UUR_TERMINAL_TOKEN_BYTES) + return 0; + for (index = 0; index < UUR_TERMINAL_TOKEN_BYTES; ++index) { + if (!((token[index] >= '0' && token[index] <= '9') || + (token[index] >= 'a' && token[index] <= 'f'))) + return 0; + } + return 1; +} + +static int load_config(uint16_t *port, char *token) +{ + char path[32768]; + char content[256]; + DWORD count; + LARGE_INTEGER size; + HANDLE file = INVALID_HANDLE_VALUE; + unsigned parsed_port; + char parsed_token[UUR_TERMINAL_TOKEN_BYTES + 1]; + int result = 0; + + if (!executable_sibling(path, sizeof(path), UUR_TERMINAL_CONFIG)) + goto done; + file = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_DELETE, + NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + if (file == INVALID_HANDLE_VALUE || !GetFileSizeEx(file, &size) || + size.QuadPart <= 0 || size.QuadPart >= (LONGLONG)sizeof(content) || + !ReadFile(file, content, (DWORD)size.QuadPart, &count, NULL) || + count != (DWORD)size.QuadPart) + goto done; + content[count] = '\0'; + if (sscanf(content, "version=1\nport=%u\ntoken=%64[0-9a-f]\n", + &parsed_port, parsed_token) != 2 || parsed_port == 0 || + parsed_port > 65535 || !valid_token(parsed_token)) + goto done; + *port = (uint16_t)parsed_port; + memcpy(token, parsed_token, UUR_TERMINAL_TOKEN_BYTES + 1); + result = 1; + +done: + if (file != INVALID_HANDLE_VALUE) + CloseHandle(file); + SecureZeroMemory(content, sizeof(content)); + SecureZeroMemory(parsed_token, sizeof(parsed_token)); + SecureZeroMemory(path, sizeof(path)); + return result; +} + +static const char *option_value(int argc, char **argv, const char *name) +{ + int index; + for (index = 1; index + 1 < argc; ++index) { + if (strcmp(argv[index], name) == 0) + return argv[index + 1]; + } + return NULL; +} + +static int has_option(int argc, char **argv, const char *name) +{ + int index; + for (index = 1; index < argc; ++index) { + if (strcmp(argv[index], name) == 0) + return 1; + } + return 0; +} + +static HANDLE parse_handle(const char *value) +{ + unsigned long long raw; + char *end; + + if (value == NULL) + return INVALID_HANDLE_VALUE; + raw = _strtoui64(value, &end, 0); + if (*value == '\0' || *end != '\0' || raw == 0) + return INVALID_HANDLE_VALUE; + return (HANDLE)(uintptr_t)raw; +} + +static uint16_t parse_dimension(const char *value, uint16_t fallback, + uint16_t minimum, uint16_t maximum) +{ + unsigned long parsed; + char *end; + + if (value == NULL) + return fallback; + parsed = strtoul(value, &end, 10); + if (*value == '\0' || *end != '\0' || parsed < minimum || parsed > maximum) + return fallback; + return (uint16_t)parsed; +} + +static int parse_launch_options(int argc, char **argv, + struct launch_options *options) +{ + const char *input = option_value(argc, argv, "--stdin-handle"); + const char *output = option_value(argc, argv, "--stdout-handle"); + + ZeroMemory(options, sizeof(*options)); + options->columns = parse_dimension(option_value(argc, argv, "--cols"), + 80, 20, 1000); + options->rows = parse_dimension(option_value(argc, argv, "--rows"), + 24, 5, 500); + options->control = parse_handle(option_value(argc, argv, "--ctl-handle")); + options->attach_existing = + has_option(argc, argv, "--uuyc-mux-attach-existing"); + options->visible_attach = has_option(argc, argv, "--visible-attach"); + { + const char *session = option_value(argc, argv, "--uuyc-mux-session"); + size_t index; + if (session != NULL) { + for (index = 0; session[index] != '\0'; ++index) { + char c = session[index]; + if (index + 1 >= sizeof(options->session) || + !((c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '-' || c == '_')) + return 0; + options->session[index] = c; + } + } + } + if (input == NULL && output == NULL) { + options->input = GetStdHandle(STD_INPUT_HANDLE); + options->output = GetStdHandle(STD_OUTPUT_HANDLE); + return options->input != INVALID_HANDLE_VALUE && + options->output != INVALID_HANDLE_VALUE; + } + options->input = parse_handle(input); + options->output = parse_handle(output); + options->explicit_handles = 1; + return options->input != INVALID_HANDLE_VALUE && + options->output != INVALID_HANDLE_VALUE; +} + +static int session_marker_path(const char *session, char *path, size_t capacity) +{ + char name[192]; + if (session == NULL || session[0] == '\0') + return 0; + if (snprintf(name, sizeof(name), "uur-terminal-session-%s.active", + session) >= (int)sizeof(name)) + return 0; + return executable_sibling(path, capacity, name); +} + +static int publish_session(const char *session, char *path, size_t capacity) +{ + HANDLE file; + char content[64]; + DWORD length; + DWORD written; + if (!session_marker_path(session, path, capacity)) + return session == NULL || session[0] == '\0'; + file = CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, + NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN, NULL); + if (file == INVALID_HANDLE_VALUE) + return 0; + length = (DWORD)snprintf(content, sizeof(content), "%lu\r\n", + (unsigned long)GetCurrentProcessId()); + if (!WriteFile(file, content, length, &written, NULL) || written != length) { + CloseHandle(file); + DeleteFileA(path); + return 0; + } + CloseHandle(file); + return 1; +} + +static void console_size(uint16_t *columns, uint16_t *rows) +{ + CONSOLE_SCREEN_BUFFER_INFO info; + *columns = 80; + *rows = 24; + if (GetConsoleScreenBufferInfo(terminal_output, &info)) { + SHORT width = info.srWindow.Right - info.srWindow.Left + 1; + SHORT height = info.srWindow.Bottom - info.srWindow.Top + 1; + if (width > 0) + *columns = (uint16_t)width; + if (height > 0) + *rows = (uint16_t)height; + } +} + +static DWORD WINAPI stdin_worker(LPVOID unused) +{ + unsigned char data[16384]; + DWORD count; + (void)unused; + + while (WaitForSingleObject(stopping, 0) == WAIT_TIMEOUT) { + if (!ReadFile(terminal_input, data, sizeof(data), &count, NULL) || count == 0) { + send_frame(UUR_TERMINAL_EOF, NULL, 0); + break; + } + if (InterlockedCompareExchange(&saw_input, 1, 0) == 0) + write_status("first-input", count); + if (!send_frame(UUR_TERMINAL_DATA, data, count)) + break; + } + return 0; +} + +static DWORD WINAPI resize_worker(LPVOID unused) +{ + uint16_t previous_columns = 0; + uint16_t previous_rows = 0; + (void)unused; + + while (WaitForSingleObject(stopping, 250) == WAIT_TIMEOUT) { + uint16_t columns; + uint16_t rows; + uint16_t dimensions[2]; + console_size(&columns, &rows); + if (columns == previous_columns && rows == previous_rows) + continue; + previous_columns = columns; + previous_rows = rows; + dimensions[0] = htons(columns); + dimensions[1] = htons(rows); + if (!send_frame(UUR_TERMINAL_RESIZE, dimensions, sizeof(dimensions))) + break; + } + return 0; +} + +static DWORD WINAPI control_worker(LPVOID unused) +{ + unsigned char type; + DWORD count; + (void)unused; + while (WaitForSingleObject(stopping, 0) == WAIT_TIMEOUT) { + if (!ReadFile(terminal_control, &type, 1, &count, NULL) || count != 1) + break; + if (type == 1) { + uint16_t dimensions[2]; + uint16_t payload[2]; + if (!ReadFile(terminal_control, dimensions, sizeof(dimensions), + &count, NULL) || count != sizeof(dimensions)) + break; + payload[0] = htons(dimensions[0]); + payload[1] = htons(dimensions[1]); + if (!send_frame(UUR_TERMINAL_RESIZE, payload, sizeof(payload))) + break; + write_status("resize", ((DWORD)dimensions[0] << 16) | dimensions[1]); + } else if (type == 2) { + write_status("control-close", 0); + SetEvent(stopping); + shutdown(bridge, SD_BOTH); + break; + } + } + return 0; +} + +int main(int argc, char **argv) +{ + WSADATA winsock; + struct sockaddr_in address; + struct uur_terminal_hello hello; + char token[UUR_TERMINAL_TOKEN_BYTES + 1]; + uint16_t port; + uint16_t columns; + uint16_t rows; + unsigned char accepted; + unsigned char output_buffer[16384]; + HANDLE input_thread = NULL; + HANDLE size_thread = NULL; + HANDLE control_thread = NULL; + DWORD written; + int received; + int exit_code = 1; + struct launch_options options; + char session_marker[32768] = ""; + + write_status("started", 0); + if (!parse_launch_options(argc, argv, &options)) { + write_status("invalid-arguments", GetLastError()); + return 1; + } + terminal_input = options.input; + terminal_output = options.output; + terminal_control = options.control; + if (options.visible_attach) { + write_status("mode-visible", 0); + return delegate_visible_attach(); + } + write_status(options.attach_existing ? "mode-attach" : "mode-new", 0); + if (!load_config(&port, token)) { + write_status("config-unavailable", GetLastError()); + return 2; + } + if (WSAStartup(MAKEWORD(2, 2), &winsock) != 0) { + write_status("winsock-unavailable", WSAGetLastError()); + return 3; + } + if (!options.attach_existing && + !publish_session(options.session, session_marker, + sizeof(session_marker))) { + write_status("session-publish-failed", GetLastError()); + WSACleanup(); + return 4; + } + bridge = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (bridge == INVALID_SOCKET) + goto done; + ZeroMemory(&address, sizeof(address)); + address.sin_family = AF_INET; + address.sin_port = htons(port); + address.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + if (connect(bridge, (struct sockaddr *)&address, sizeof(address)) != 0) { + write_status("connect-failed", WSAGetLastError()); + goto done; + } + + if (options.explicit_handles) { + columns = options.columns; + rows = options.rows; + } else { + console_size(&columns, &rows); + } + ZeroMemory(&hello, sizeof(hello)); + hello.magic = htonl(UUR_TERMINAL_MAGIC); + hello.version = htons(UUR_TERMINAL_VERSION); + hello.token_length = htons(UUR_TERMINAL_TOKEN_BYTES); + hello.columns = htons(columns); + hello.rows = htons(rows); + if (!send_all(&hello, sizeof(hello)) || + !send_all(token, UUR_TERMINAL_TOKEN_BYTES) || + !receive_all(&accepted, 1) || accepted != UUR_TERMINAL_ACCEPTED) + { + write_status("handshake-failed", WSAGetLastError()); + goto done; + } + + write_status("running", 0); + + InitializeCriticalSection(&write_lock); + stopping = CreateEventW(NULL, TRUE, FALSE, NULL); + if (stopping == NULL) { + DeleteCriticalSection(&write_lock); + goto done; + } + input_thread = CreateThread(NULL, 0, stdin_worker, NULL, 0, NULL); + if (options.explicit_handles && terminal_control != INVALID_HANDLE_VALUE) + control_thread = CreateThread(NULL, 0, control_worker, NULL, 0, NULL); + else if (!options.explicit_handles) + size_thread = CreateThread(NULL, 0, resize_worker, NULL, 0, NULL); + if (input_thread == NULL || + (options.explicit_handles && terminal_control != INVALID_HANDLE_VALUE && + control_thread == NULL) || + (!options.explicit_handles && size_thread == NULL)) + goto workers_done; + + while ((received = recv(bridge, (char *)output_buffer, + sizeof(output_buffer), 0)) > 0) { + if (InterlockedCompareExchange(&saw_output, 1, 0) == 0) + write_status("first-output", (DWORD)received); + if (!WriteFile(terminal_output, output_buffer, + (DWORD)received, &written, NULL)) { + write_status("output-write-failed", GetLastError()); + break; + } + } + exit_code = 0; + +workers_done: + SetEvent(stopping); + shutdown(bridge, SD_BOTH); + if (input_thread != NULL) { + CancelSynchronousIo(input_thread); + WaitForSingleObject(input_thread, 1000); + CloseHandle(input_thread); + } + if (size_thread != NULL) { + WaitForSingleObject(size_thread, 1000); + CloseHandle(size_thread); + } + if (control_thread != NULL) { + CancelSynchronousIo(control_thread); + WaitForSingleObject(control_thread, 1000); + CloseHandle(control_thread); + } + CloseHandle(stopping); + DeleteCriticalSection(&write_lock); + +done: + if (session_marker[0] != '\0') + DeleteFileA(session_marker); + if (bridge != INVALID_SOCKET) + closesocket(bridge); + SecureZeroMemory(token, sizeof(token)); + WSACleanup(); + write_status("exited", (DWORD)exit_code); + return exit_code; +} diff --git a/hook/uur-hook.c b/hook/uur-hook.c new file mode 100644 index 0000000..019505b --- /dev/null +++ b/hook/uur-hook.c @@ -0,0 +1,933 @@ +/* + * uur-hook — input reroute for NetEase UU Remote under Wine. + * + * Loaded into GameViewerServer.exe through the wevtapi.dll preload chain + * (see wevtapi.c). At PROCESS_ATTACH it rewrites the SendInput entries of + * every loaded module's import table to point at hook_SendInput, which + * forwards each input record over an authenticated loopback socket to the + * uur host daemon. The daemon injects the record onto the real desktop + * (XTest on X11, RemoteDesktop portal on Wayland). + * + * Failure policy: if the socket is unavailable, hook_SendInput falls back + * to the original SendInput so the client keeps working with input + * contained inside the managed Wine prefix. + * + * Wire format mirrors src/protocol.rs: 16-byte record + * u32 kind (1 keyboard, 2 mouse) u16 code u16 state i32 a i32 b + */ + +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include + +#include +#include +#include +#include "frame-protocol.h" + +#define UUR_MAGIC 0x50495555u +#define UUR_VERSION 1u +#define UUR_RECORD_HELLO 1u +#define UUR_RECORD_MOUSE 2u +#define UUR_RECORD_KEYBOARD 3u + +static UINT(WINAPI *original_send_input)(UINT, LPINPUT, int); +static HRESULT(WINAPI *original_create_dxgi_factory1)(REFIID, void **); +static FARPROC(WINAPI *original_get_proc_address)(HMODULE, LPCSTR); +UINT WINAPI hook_send_input(UINT count, LPINPUT inputs, int size); + +static volatile LONG dxgi_factories_patched = 0; +static volatile LONG dxgi_adapters_patched = 0; +static volatile LONG dxgi_outputs_patched = 0; +static volatile LONG dxgi_duplicate_calls = 0; +static volatile LONG dxgi_dup_acquires = 0; +static volatile LONG dxgi_dup_frames = 0; + +static HRESULT __attribute__((unused))(STDMETHODCALLTYPE *original_dxgi_acquire_next_frame)( + void *duplication, UINT timeout, void *frame_info, void **resource) = NULL; +/* referenced by patch_dxgi_duplication below */ + +/* ---- DXGI duplication disable ----------------------------------------- */ + +/* The client's primary capture is IDXGIOutput1::DuplicateOutput. Wine's + * implementation succeeds but only delivers the empty XWayland desktop + * (black video). Forcing DuplicateOutput to fail makes the client fall + * back to its GDI capture path, which the frame feed below supplies. */ + +static const GUID uur_iid_idxgioutput1 = { + 0x00cddea8, 0x939b, 0x4b83, + {0xa3, 0x40, 0xa6, 0x85, 0x22, 0x66, 0x66, 0xcc} +}; + +/* Minimal IDXGIOutput1 shape: mingw's C-mode dxgi.h lacks it. The + * vtable is IUnknown(3) + IDXGIOutput(12) methods, then DuplicateOutput. */ +typedef struct uur_idxgioutput1_vtbl { + void *methods[15]; + HRESULT(STDMETHODCALLTYPE *DuplicateOutput)(void *, IUnknown *); +} uur_idxgioutput1_vtbl; +typedef struct uur_idxgioutput1 { + uur_idxgioutput1_vtbl *lpVtbl; +} uur_idxgioutput1; + +#ifndef DXGI_ERROR_UNSUPPORTED +#define DXGI_ERROR_UNSUPPORTED ((HRESULT)0x887A0004) +#endif + +static HRESULT(STDMETHODCALLTYPE *original_dxgi_enum_adapters1)( + IDXGIFactory1 *factory, UINT index, IDXGIAdapter1 **adapter) = NULL; +static HRESULT(STDMETHODCALLTYPE *original_dxgi_enum_outputs)( + IDXGIAdapter *adapter, UINT index, IDXGIOutput **output) = NULL; +static HRESULT STDMETHODCALLTYPE hook_dxgi_enum_adapters1( + IDXGIFactory1 *factory, UINT index, IDXGIAdapter1 **adapter); +static HRESULT STDMETHODCALLTYPE hook_dxgi_enum_outputs( + IDXGIAdapter *adapter, UINT index, IDXGIOutput **output); +static HRESULT WINAPI hook_dxgi_duplicate_output(uur_idxgioutput1 *output, + IUnknown *device); + +static int patch_vtable_slot(void **slot, void *hook, void **original) +{ + DWORD old_protect = 0; + if (*slot == hook) + return 1; + if (original != NULL) + *original = *slot; + if (!VirtualProtect(slot, sizeof(void *), PAGE_READWRITE, &old_protect)) + return 0; + *slot = hook; + VirtualProtect(slot, sizeof(void *), old_protect, &old_protect); + return 1; +} + +static HRESULT(STDMETHODCALLTYPE *original_dxgi_enum_adapters)( + IDXGIFactory *factory, UINT index, IDXGIAdapter **adapter) = NULL; +static void patch_dxgi_adapter(IDXGIAdapter *adapter); + +static void patch_dxgi_output(IDXGIOutput *output) +{ + uur_idxgioutput1 *output1 = NULL; + + if (output == NULL || output->lpVtbl == NULL) + return; + if (output->lpVtbl->QueryInterface( + output, &uur_iid_idxgioutput1, (void **)&output1) != S_OK) + return; + if (output1 != NULL && output1->lpVtbl != NULL) { + if (patch_vtable_slot((void **)&output1->lpVtbl->DuplicateOutput, + (void *)hook_dxgi_duplicate_output, NULL)) { + InterlockedIncrement(&dxgi_outputs_patched); + } + /* release through the known-good base interface */ + output->lpVtbl->Release(output); + } +} + +static HRESULT STDMETHODCALLTYPE hook_dxgi_enum_adapters( + IDXGIFactory *factory, UINT index, IDXGIAdapter **adapter) +{ + HRESULT result = original_dxgi_enum_adapters + ? original_dxgi_enum_adapters(factory, index, adapter) + : DXGI_ERROR_INVALID_CALL; + + if (result == S_OK && adapter != NULL && *adapter != NULL) + patch_dxgi_adapter(*adapter); + return result; +} + +static void patch_dxgi_adapter(IDXGIAdapter *adapter) +{ + if (adapter == NULL || adapter->lpVtbl == NULL) + return; + if (patch_vtable_slot((void **)&adapter->lpVtbl->EnumOutputs, + (void *)hook_dxgi_enum_outputs, + (void **)&original_dxgi_enum_outputs)) { + InterlockedIncrement(&dxgi_adapters_patched); + } +} + +static HRESULT STDMETHODCALLTYPE hook_dxgi_enum_adapters1( + IDXGIFactory1 *factory, UINT index, IDXGIAdapter1 **adapter) +{ + HRESULT result = original_dxgi_enum_adapters1 + ? original_dxgi_enum_adapters1(factory, index, adapter) + : DXGI_ERROR_INVALID_CALL; + + if (result == S_OK && adapter != NULL && *adapter != NULL) + patch_dxgi_adapter((IDXGIAdapter *)*adapter); + return result; +} + +static HRESULT STDMETHODCALLTYPE hook_dxgi_enum_outputs( + IDXGIAdapter *adapter, UINT index, IDXGIOutput **output) +{ + HRESULT result = original_dxgi_enum_outputs + ? original_dxgi_enum_outputs(adapter, index, output) + : DXGI_ERROR_INVALID_CALL; + + if (result == S_OK && output != NULL && *output != NULL) + patch_dxgi_output(*output); + return result; +} + +static HRESULT WINAPI hook_dxgi_duplicate_output(uur_idxgioutput1 *output, + IUnknown *device) +{ + (void)output; + (void)device; + InterlockedIncrement(&dxgi_duplicate_calls); + /* Wine's duplication succeeds but delivers the empty XWayland desktop. + * Failing it sends the client to its GDI capture path. */ + return DXGI_ERROR_UNSUPPORTED; +} + +static void patch_dxgi_factory(IDXGIFactory1 *factory) +{ + if (factory == NULL || factory->lpVtbl == NULL) + return; + patch_vtable_slot((void **)&factory->lpVtbl->EnumAdapters1, + (void *)hook_dxgi_enum_adapters1, + (void **)&original_dxgi_enum_adapters1); + patch_vtable_slot((void **)&factory->lpVtbl->EnumAdapters, + (void *)hook_dxgi_enum_adapters, + (void **)&original_dxgi_enum_adapters); +} + +static HRESULT WINAPI hook_create_dxgi_factory1(REFIID interface_id, + void **factory) +{ + HRESULT result = original_create_dxgi_factory1 != NULL + ? original_create_dxgi_factory1(interface_id, factory) + : DXGI_ERROR_INVALID_CALL; + + if (result == S_OK && factory != NULL && *factory != NULL) { + IDXGIFactory1 *f = (IDXGIFactory1 *)*factory; + if (f->lpVtbl != NULL) { + patch_dxgi_factory(f); + InterlockedIncrement(&dxgi_factories_patched); + } + } + return result; +} +static BOOL(WINAPI *original_bit_blt)(HDC, int, int, int, int, HDC, int, int, + DWORD); +static BOOL(WINAPI *original_stretch_blt)(HDC, int, int, int, int, HDC, int, + int, int, int, DWORD); +static volatile LONG capture_calls = 0; +static volatile LONG capture_rendered = 0; +static volatile LONG capture_fallbacks = 0; +static volatile LONG iat_hooks_installed = 0; + +static SOCKET hook_socket = INVALID_SOCKET; +static volatile LONG hook_busy = 0; + +/* ---- capture frame feed (docs/capture-protocol.md) -------------------- */ + +static void *frame_map = NULL; +static HANDLE frame_map_handle = NULL; +static uint32_t frame_width; +static uint32_t frame_height; +static uint32_t frame_stride; +static uint64_t frame_slot_bytes; +static unsigned char *frame_snapshot; +static size_t frame_snapshot_capacity; +static size_t frame_map_size; + +static char *read_ini_value(const char *path, const char *key); + +static int resolve_frame_path(WCHAR *path, int capacity) +{ + DWORD count = GetEnvironmentVariableW(L"UUR_FRAME_PATH_WIN", path, + (DWORD)capacity); + if (count > 0 && count < (DWORD)capacity) + return 1; + + char *utf8 = read_ini_value("C:\\uur-bridge.ini", "frame_path"); + if (utf8 == NULL) + return 0; + int converted = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, + -1, path, capacity); + free(utf8); + return converted > 0; +} + +static uint32_t load_u32(const unsigned char *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | + ((uint32_t)p[3] << 24); +} + +static uint64_t load_u64(const unsigned char *p) +{ + return load_u32(p) | ((uint64_t)load_u32(p + 4) << 32); +} + +/* Open (or re-open after a resolution change) the capture file that the + * native uur-pw-capture helper publishes. */ +static int ensure_frame_map(void) +{ + HANDLE file; + void *view; + const unsigned char *header; + LARGE_INTEGER size; + WCHAR path[32768]; + + if (frame_map != NULL) + return 1; + + if (!resolve_frame_path(path, (int)(sizeof(path) / sizeof(path[0])))) + return 0; + file = CreateFileW(path, GENERIC_READ, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, + 0, NULL); + if (file == INVALID_HANDLE_VALUE) + return 0; + if (!GetFileSizeEx(file, &size) || size.QuadPart < UURF_HEADER_BYTES || + (uint64_t)size.QuadPart > SIZE_MAX) { + CloseHandle(file); + return 0; + } + frame_map_handle = CreateFileMappingW(file, NULL, PAGE_READONLY, 0, 0, + NULL); + CloseHandle(file); + if (frame_map_handle == NULL) + return 0; + view = MapViewOfFile(frame_map_handle, FILE_MAP_READ, 0, 0, 0); + if (view == NULL) + return 0; + + header = (const unsigned char *)view; + if (load_u32(header) != UURF_MAGIC || + load_u32(header + 4) != UURF_VERSION || load_u32(header + 20) != 1u) { + UnmapViewOfFile(view); + CloseHandle(frame_map_handle); + frame_map_handle = NULL; + return 0; + } + frame_width = load_u32(header + 8); + frame_height = load_u32(header + 12); + frame_stride = load_u32(header + 16); + frame_slot_bytes = 8ull + (uint64_t)frame_stride * frame_height; + uint64_t expected = UURF_HEADER_BYTES + UURF_SLOT_COUNT * frame_slot_bytes; + if (frame_width == 0 || frame_height == 0 || frame_stride < frame_width * 4 || + expected > (uint64_t)size.QuadPart) { + UnmapViewOfFile(view); + CloseHandle(frame_map_handle); + frame_map_handle = NULL; + return 0; + } + frame_map_size = (size_t)size.QuadPart; + frame_map = view; + return 1; +} + +static BOOL source_is_screen_dc(HDC source) +{ + return GetObjectType(source) == OBJ_DC && + GetDeviceCaps(source, TECHNOLOGY) == DT_RASDISPLAY; +} + +/* Feed the newest desktop frame into the capture destination by drawing + * our shared-memory frame with StretchDIBits. Works regardless of the + * destination bitmap type (DDB or DIB section). */ +static BOOL feed_capture_frame(HDC hdc_dest, int x, int y, int width, + int height, int source_x, int source_y, + int source_width, int source_height) +{ + const unsigned char *header; + uint32_t fw, fh, fstride; + uint64_t total; + int tries; + int ok = 0; + + if (!ensure_frame_map()) + return FALSE; + header = (const unsigned char *)frame_map; + fw = load_u32(header + 8); + fh = load_u32(header + 12); + fstride = load_u32(header + 16); + size_t frame_bytes = (size_t)fstride * fh; + total = load_u64(header + 24); + if (fw == 0 || fh == 0 || fstride < fw * 4 || total == 0 || + frame_bytes / fstride != fh || + UURF_HEADER_BYTES + UURF_SLOT_COUNT * frame_slot_bytes > frame_map_size) + return FALSE; + if (frame_snapshot_capacity < frame_bytes) { + unsigned char *fresh = HeapReAlloc(GetProcessHeap(), 0, frame_snapshot, + frame_bytes); + if (fresh == NULL && frame_snapshot == NULL) + fresh = HeapAlloc(GetProcessHeap(), 0, frame_bytes); + if (fresh == NULL) + return FALSE; + frame_snapshot = fresh; + frame_snapshot_capacity = frame_bytes; + } + + for (tries = 0; tries < 16 && !ok; ++tries) { + const unsigned char *shm_slot = + frame_map + uurf_slot_offset(total, (size_t)frame_slot_bytes); + uint64_t before = load_u64(shm_slot); + if ((before & 1) == 0 && before / 2 == total) { + MemoryBarrier(); + memcpy(frame_snapshot, shm_slot + 8, frame_bytes); + MemoryBarrier(); + uint64_t after = load_u64(shm_slot); + if (before != after) + continue; + BITMAPINFOHEADER bmp_header; + ZeroMemory(&bmp_header, sizeof(bmp_header)); + bmp_header.biSize = sizeof(BITMAPINFOHEADER); + bmp_header.biWidth = (LONG)fw; + bmp_header.biHeight = -(LONG)fh; /* top-down */ + bmp_header.biPlanes = 1; + bmp_header.biBitCount = 32; + bmp_header.biCompression = BI_RGB; + bmp_header.biSizeImage = fstride * fh; + + int screen_width = GetSystemMetrics(SM_CXVIRTUALSCREEN); + int screen_height = GetSystemMetrics(SM_CYVIRTUALSCREEN); + if (screen_width < 1) + screen_width = (int)fw; + if (screen_height < 1) + screen_height = (int)fh; + int sx = (int)((int64_t)source_x * fw / screen_width); + int sy = (int)((int64_t)source_y * fh / screen_height); + int sw = (int)((int64_t)source_width * fw / screen_width); + int sh = (int)((int64_t)source_height * fh / screen_height); + if (sw < 1) + sw = (int)fw; + if (sh < 1) + sh = (int)fh; + int result = StretchDIBits( + hdc_dest, x, y, width, height, sx, sy, sw, sh, + (const void *)frame_snapshot, (const BITMAPINFO *)&bmp_header, + DIB_RGB_COLORS, SRCCOPY); + ok = result != 0 && (DWORD)result != GDI_ERROR; + } else { + uint64_t now = load_u64(header + 24); + total = (now < total) ? now : total - 1; + if (total == 0) + return FALSE; + } + } + return ok; +} + +static BOOL try_capture_feed(HDC hdc_dest, int x, int y, DWORD rop, + HDC hdc_src, int width, int height, int source_x, + int source_y, int source_width, int source_height) +{ + InterlockedIncrement(&capture_calls); + /* The client's desktop capture is an SRCCOPY blit whose source is the + * screen DC; anything else falls through untouched. */ + if ((rop & 0x00ffffffu) == SRCCOPY && hdc_src != NULL && + source_is_screen_dc(hdc_src)) { + if (feed_capture_frame(hdc_dest, x, y, width, height, source_x, + source_y, source_width, source_height)) { + InterlockedIncrement(&capture_rendered); + return TRUE; + } + } + InterlockedIncrement(&capture_fallbacks); + return FALSE; +} + +BOOL WINAPI hook_bit_blt(HDC hdc_dest, int x, int y, int width, int height, + HDC hdc_src, int x_src, int y_src, DWORD rop) +{ + if (try_capture_feed(hdc_dest, x, y, rop, hdc_src, width, height, x_src, + y_src, width, height)) + return TRUE; + return original_bit_blt(hdc_dest, x, y, width, height, hdc_src, x_src, + y_src, rop); +} + +BOOL WINAPI hook_stretch_blt(HDC hdc_dest, int x, int y, int w, int h, + HDC hdc_src, int xs, int ys, int sw, int sh, + DWORD rop) +{ + if (try_capture_feed(hdc_dest, x, y, rop, hdc_src, w, h, xs, ys, sw, sh)) + return TRUE; + return original_stretch_blt(hdc_dest, x, y, w, h, hdc_src, xs, ys, sw, + sh, rop); +} + +/* ---- diagnostics ------------------------------------------------------ */ + +static void hook_log(const char *text) +{ + char path[MAX_PATH]; + if (GetEnvironmentVariableA("UUR_HOOK_LOG", path, sizeof(path)) == 0 || + path[0] == '\0') + lstrcpynA(path, "C:\\uur-bridge.log", sizeof(path)); + FILE *f = fopen(path, "a"); + if (f == NULL) + return; + fprintf(f, "%s\n", text); + fclose(f); +} + +/* ---- wire helpers ---------------------------------------------------- */ + +static void put_u32(unsigned char *p, uint32_t v) +{ + p[0] = (unsigned char)(v); + p[1] = (unsigned char)(v >> 8); + p[2] = (unsigned char)(v >> 16); + p[3] = (unsigned char)(v >> 24); +} + +static void put_u16(unsigned char *p, uint16_t v) +{ + p[0] = (unsigned char)(v); + p[1] = (unsigned char)(v >> 8); +} + +static void put_i32(unsigned char *p, int32_t v) +{ + put_u32(p, (uint32_t)v); +} + +static void send_record(uint32_t kind, uint16_t code, uint16_t state, + int32_t a, int32_t b) +{ + unsigned char frame[16 + 16]; + put_u32(frame + 0, UUR_MAGIC); + put_u32(frame + 4, UUR_VERSION); + put_u32(frame + 8, kind); + put_u32(frame + 12, 16); + put_u32(frame + 16, kind); + put_u16(frame + 20, code); + put_u16(frame + 22, state); + put_i32(frame + 24, a); + put_i32(frame + 28, b); + + int total = 0; + while (total < (int)sizeof(frame)) { + int sent = send(hook_socket, (const char *)frame + total, + (int)sizeof(frame) - total, 0); + if (sent <= 0) { + closesocket(hook_socket); + hook_socket = INVALID_SOCKET; + return; + } + total += sent; + } +} + +static FARPROC WINAPI hook_get_proc_address(HMODULE module, LPCSTR name) +{ + union { + FARPROC generic; + UINT(WINAPI *send_input)(UINT, LPINPUT, int); + BOOL(WINAPI *bit_blt)(HDC, int, int, int, int, HDC, int, int, DWORD); + BOOL(WINAPI *stretch_blt)(HDC, int, int, int, int, HDC, int, int, + int, int, DWORD); + HRESULT(WINAPI *create_dxgi_factory1)(REFIID, void **); + } replacement; + FARPROC resolved = original_get_proc_address(module, name); + if (name == NULL || ((uintptr_t)name >> 16) == 0) + return resolved; + if (lstrcmpiA(name, "SendInput") == 0) { + replacement.send_input = hook_send_input; + return replacement.generic; + } + if (lstrcmpiA(name, "BitBlt") == 0) { + replacement.bit_blt = hook_bit_blt; + return replacement.generic; + } + if (lstrcmpiA(name, "StretchBlt") == 0) { + replacement.stretch_blt = hook_stretch_blt; + return replacement.generic; + } + if (lstrcmpiA(name, "CreateDXGIFactory1") == 0) { + replacement.create_dxgi_factory1 = hook_create_dxgi_factory1; + return replacement.generic; + } + return resolved; +} + +/* Minimal ini reader: returns a malloc'd value for `key` or NULL. */ +static char *read_ini_value(const char *path, const char *key) +{ + FILE *f = fopen(path, "r"); + char line[512]; + size_t key_len; + + if (f == NULL) + return NULL; + key_len = strlen(key); + while (fgets(line, sizeof(line), f) != NULL) { + if (strncmp(line, key, key_len) == 0 && line[key_len] == '=') { + char *end = line + strlen(line); + char *value = line + key_len + 1; + char *out; + size_t len; + while (end > value && + (end[-1] == '\n' || end[-1] == '\r' || end[-1] == ' ')) + *--end = '\0'; + fclose(f); + len = (size_t)(end - value); + out = malloc(len + 1); + if (out != NULL) { + memcpy(out, value, len); + out[len] = '\0'; + } + return out; + } + } + fclose(f); + return NULL; +} + +static int connect_bridge(void) +{ + char port_text[16] = "47010"; + char token_hex[80] = ""; + char *value; + + /* Config: environment first (fast path for uur-spawned processes), + * then C:\uur-bridge.ini — the file form survives any spawn path, + * including the Wine service manager restarting the service without + * uur's environment. */ + if ((value = getenv("UUR_BRIDGE_PORT")) != NULL && *value) + lstrcpynA(port_text, value, sizeof(port_text)); + else { + char *v = read_ini_value("C:\\uur-bridge.ini", "port"); + if (v != NULL) { + lstrcpynA(port_text, v, sizeof(port_text)); + free(v); + } + } + if ((value = getenv("UUR_BRIDGE_TOKEN")) != NULL && *value) + lstrcpynA(token_hex, value, sizeof(token_hex)); + else { + char *v = read_ini_value("C:\\uur-bridge.ini", "token"); + if (v != NULL) { + lstrcpynA(token_hex, v, sizeof(token_hex)); + free(v); + } + } + + WSADATA wsa; + if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) { + hook_log("connect: WSAStartup failed"); + return 0; + } + + struct addrinfo hints; + struct addrinfo *result = NULL; + ZeroMemory(&hints, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + if (getaddrinfo("127.0.0.1", port_text, &hints, &result) != 0 || + result == NULL) { + char buf[96]; + sprintf(buf, "connect: getaddrinfo failed (port=%s)", port_text); + hook_log(buf); + WSACleanup(); + return 0; + } + + SOCKET sock = socket(result->ai_family, result->ai_socktype, + result->ai_protocol); + if (sock == INVALID_SOCKET) { + freeaddrinfo(result); + WSACleanup(); + return 0; + } + if (connect(sock, result->ai_addr, (int)result->ai_addrlen) != 0) { + char buf[96]; + sprintf(buf, "connect: failed wsae=%lu port=%s", + (unsigned long)WSAGetLastError(), port_text); + hook_log(buf); + closesocket(sock); + freeaddrinfo(result); + WSACleanup(); + return 0; + } + freeaddrinfo(result); + + /* HELLO: header only; the daemon then reads 32 raw token bytes. */ + unsigned char hello[16]; + put_u32(hello + 0, UUR_MAGIC); + put_u32(hello + 4, UUR_VERSION); + put_u32(hello + 8, UUR_RECORD_HELLO); + put_u32(hello + 12, 32); + if (send(sock, (const char *)hello, sizeof(hello), 0) != sizeof(hello)) { + closesocket(sock); + WSACleanup(); + return 0; + } + + unsigned char token[32]; + ZeroMemory(token, sizeof(token)); + for (int i = 0; i < 32; ++i) { + unsigned byte = 0; + char hex[3] = {token_hex[2 * i], token_hex[2 * i + 1], 0}; + if (hex[0] && hex[1]) { + byte = (unsigned)strtoul(hex, NULL, 16); + } + token[i] = (unsigned char)byte; + } + if (send(sock, (const char *)token, sizeof(token), 0) != sizeof(token)) { + closesocket(sock); + WSACleanup(); + return 0; + } + + /* Nothing to read until the daemon closes; the connection is + * fire-and-forget from here on. */ + hook_socket = sock; + return 1; +} + +/* ---- SendInput interception ------------------------------------------ */ + +UINT WINAPI hook_send_input(UINT count, LPINPUT inputs, int size) +{ + if (inputs == NULL || size < (int)sizeof(INPUT)) + return original_send_input(count, inputs, size); + + LONG busy = InterlockedCompareExchange(&hook_busy, 1, 0); + if (busy == 0) { + for (UINT i = 0; i < count; ++i) { + LPINPUT input = &inputs[i]; + if (input->type == INPUT_KEYBOARD) { + uint16_t code = input->ki.wVk; + if (input->ki.dwFlags & KEYEVENTF_EXTENDEDKEY) + code |= 0x100; + send_record(UUR_RECORD_KEYBOARD, code, + (input->ki.dwFlags & KEYEVENTF_KEYUP) ? 0 : 1, + 0, 0); + } else if (input->type == INPUT_MOUSE) { + DWORD flags = input->mi.dwFlags; + if (flags & MOUSEEVENTF_WHEEL) { + /* wheel delta rides in the low word of mouseData */ + send_record(UUR_RECORD_MOUSE, 0xfffe /*wheel*/, + 0, 0, + (int16_t)(input->mi.mouseData & 0xffff)); + } else if (flags & (MOUSEEVENTF_XDOWN | MOUSEEVENTF_XUP)) { + /* XBUTTON1/2 map to X11 buttons 8/9 */ + uint16_t button = (input->mi.mouseData & 0xffff) == + XBUTTON1 + ? 8 + : 9; + send_record(UUR_RECORD_MOUSE, button, + (flags & MOUSEEVENTF_XDOWN) ? 1 : 0, 0, 0); + } else if (flags & (MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP | + MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP | + MOUSEEVENTF_MIDDLEDOWN | MOUSEEVENTF_MIDDLEUP)) { + uint16_t button = 0; + if (flags & (MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_LEFTUP)) + button = 1; + else if (flags & (MOUSEEVENTF_RIGHTDOWN | MOUSEEVENTF_RIGHTUP)) + button = 2; + else + button = 3; + int down = (flags & (MOUSEEVENTF_LEFTDOWN | + MOUSEEVENTF_RIGHTDOWN | + MOUSEEVENTF_MIDDLEDOWN)) ? 1 : 0; + send_record(UUR_RECORD_MOUSE, button, (uint16_t)down, 0, 0); + } + if (flags & MOUSEEVENTF_MOVE) { + if (flags & MOUSEEVENTF_ABSOLUTE) { + /* Preserve Windows' normalized coordinate space. The + * selected Linux backend performs the final mapping. */ + send_record(UUR_RECORD_MOUSE, 0xffff /*motion*/, 1, + input->mi.dx, input->mi.dy); + } else { + send_record(UUR_RECORD_MOUSE, 0xffff /*motion*/, 0, + input->mi.dx, input->mi.dy); + } + } + } + } + InterlockedExchange(&hook_busy, 0); + } + + /* Keep the in-client behaviour identical: UU verifies its calls. */ + return original_send_input(count, inputs, size); +} + +/* ---- IAT rewrite ------------------------------------------------------ */ + +static int patch_module_iat(HMODULE base) +{ + if (base == NULL) + return 0; + + IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)base; + if (dos->e_magic != IMAGE_DOS_SIGNATURE) + return 0; + IMAGE_NT_HEADERS *nt = (IMAGE_NT_HEADERS *)((char *)base + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE) + return 0; + + IMAGE_DATA_DIRECTORY *dir = + &nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + if (dir->VirtualAddress == 0) + return 0; + + int patched = 0; + IMAGE_IMPORT_DESCRIPTOR *descriptor = (IMAGE_IMPORT_DESCRIPTOR *) + ((char *)base + dir->VirtualAddress); + for (; descriptor->Name != 0; ++descriptor) { + const char *module_name = (const char *)base + descriptor->Name; + if (_stricmp(module_name, "USER32.dll") != 0 && + _stricmp(module_name, "GDI32.dll") != 0 && + _stricmp(module_name, "dxgi.dll") != 0 && + _stricmp(module_name, "KERNEL32.dll") != 0 && + _stricmp(module_name, "KERNELBASE.dll") != 0) + continue; + + IMAGE_THUNK_DATA *thunk = (IMAGE_THUNK_DATA *) + ((char *)base + descriptor->FirstThunk); + IMAGE_THUNK_DATA *original = thunk; + if (descriptor->OriginalFirstThunk != 0) + original = (IMAGE_THUNK_DATA *) + ((char *)base + descriptor->OriginalFirstThunk); + + for (; original->u1.AddressOfData != 0; ++thunk, ++original) { + if (original->u1.Ordinal & IMAGE_ORDINAL_FLAG) + continue; + IMAGE_IMPORT_BY_NAME *name = (IMAGE_IMPORT_BY_NAME *) + ((char *)base + original->u1.AddressOfData); + void *hook_fn = NULL; + void **original_slot = NULL; + + if (lstrcmpiA(name->Name, "SendInput") == 0) { + hook_fn = (void *)hook_send_input; + original_slot = (void **)&original_send_input; + } else if (lstrcmpiA(name->Name, "BitBlt") == 0) { + hook_fn = (void *)hook_bit_blt; + original_slot = (void **)&original_bit_blt; + } else if (lstrcmpiA(name->Name, "StretchBlt") == 0) { + hook_fn = (void *)hook_stretch_blt; + original_slot = (void **)&original_stretch_blt; + } else if (lstrcmpiA(name->Name, "CreateDXGIFactory1") == 0) { + hook_fn = (void *)hook_create_dxgi_factory1; + original_slot = (void **)&original_create_dxgi_factory1; + } else if (lstrcmpiA(name->Name, "GetProcAddress") == 0) { + hook_fn = (void *)hook_get_proc_address; + original_slot = (void **)&original_get_proc_address; + } + if (hook_fn == NULL) + continue; + if (thunk->u1.Function == (uintptr_t)hook_fn) + continue; + *original_slot = (void *)thunk->u1.Function; + DWORD old_protect = 0; + if (!VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), + PAGE_READWRITE, &old_protect)) + continue; + thunk->u1.Function = (uintptr_t)hook_fn; + VirtualProtect(&thunk->u1.Function, sizeof(thunk->u1.Function), + old_protect, &old_protect); + ++patched; + InterlockedIncrement(&iat_hooks_installed); + } + } + return patched; +} + +static int patch_loaded_modules(void) +{ + int patched = 0; + HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, + GetCurrentProcessId()); + if (snapshot == INVALID_HANDLE_VALUE) + return 0; + MODULEENTRY32W entry; + entry.dwSize = sizeof(entry); + if (Module32FirstW(snapshot, &entry)) { + do { + patched += patch_module_iat(entry.hModule); + } while (Module32NextW(snapshot, &entry)); + } + CloseHandle(snapshot); + return patched; +} + +/* ---- late-module watchdog --------------------------------------------- */ + +static DWORD WINAPI patch_watchdog(LPVOID parameter) +{ + (void)parameter; + for (;;) { + Sleep(2000); + patch_loaded_modules(); + char status_path[MAX_PATH]; + sprintf(status_path, "C:\\uur-capture-status-%lu.txt", + (unsigned long)GetCurrentProcessId()); + FILE *f = fopen(status_path, "w"); + if (f != NULL) { + fprintf(f, + "pid=%lu iat=%ld dxgi_f=%ld dxgi_a=%ld dxgi_o=%ld dup=%ld\n\ + calls=%ld rendered=%ld fallbacks=%ld\n", + GetCurrentProcessId(), iat_hooks_installed, + dxgi_factories_patched, dxgi_adapters_patched, + dxgi_outputs_patched, dxgi_duplicate_calls, + capture_calls, capture_rendered, capture_fallbacks); + fclose(f); + } + } + return 0; +} + +static DWORD WINAPI bridge_retry_thread(LPVOID parameter) +{ + (void)parameter; + for (int attempt = 0; attempt < 120; ++attempt) { + Sleep(2000); + if (hook_socket != INVALID_SOCKET) + return 0; + if (connect_bridge()) { + hook_log("retry: bridge connected"); + return 0; + } + char buf[96]; + sprintf(buf, "retry %d failed wsae=%lu", attempt, + (unsigned long)WSAGetLastError()); + hook_log(buf); + } + return 0; +} + +/* ---- entry ------------------------------------------------------------ */ + +/* Marker export: the wevtapi shim references this symbol purely so the + * linker emits the uur-hook.dll dependency that carries the preload chain. */ +void uur_hook_version(void) {} + +BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) +{ + (void)instance; + (void)reserved; + if (reason != DLL_PROCESS_ATTACH) + return TRUE; + + DisableThreadLibraryCalls(instance); + if (connect_bridge()) { + hook_log("attach: bridge connected"); + } else { + /* The daemon may simply not be bound yet: the service spawns the + * server seconds before uur binds the bridge. Retry in the + * background instead of staying idle forever. */ + hook_log("attach: bridge unavailable, retrying"); + CreateThread(NULL, 0, bridge_retry_thread, NULL, 0, NULL); + } + if (patch_loaded_modules() > 0) { + hook_log("attach: SendInput/BitBlt imports rewritten"); + } else { + hook_log("attach: no SendInput import found"); + } + + /* streamer.dll and friends can load after us; keep scanning so late + * modules get their capture imports rewritten too. */ + HANDLE watchdog = CreateThread(NULL, 0, patch_watchdog, NULL, 0, NULL); + if (watchdog != NULL) + CloseHandle(watchdog); + return TRUE; +} diff --git a/hook/uur-hook.def b/hook/uur-hook.def new file mode 100644 index 0000000..079b0c4 --- /dev/null +++ b/hook/uur-hook.def @@ -0,0 +1,7 @@ +LIBRARY uur-hook +EXPORTS + ; No functional exports: this import library exists so the wevtapi + ; shim can link against uur-hook.dll and force the Windows loader to + ; preload it into the client process. + hook_send_input + uur_hook_version diff --git a/hook/wevtapi.c b/hook/wevtapi.c new file mode 100644 index 0000000..30b0ba7 --- /dev/null +++ b/hook/wevtapi.c @@ -0,0 +1,146 @@ +/* + * wevtapi.dll replacement for the managed UU Remote prefix. + * + * Wine's builtin wevtapi aborts callers of EvtOpenPublisherMetadata, which + * UU Remote issues periodically. This replacement returns the ordinary + * Windows failure shape for the whole Evt* surface and — critically — links + * against uur-hook.dll so the Windows loader pulls the input hook into + * GameViewerServer.exe at process start, before any code runs. No disk + * patching, no injector race. + * + * Drop this file next to GameViewerServer.exe inside the managed prefix; + * Wine resolves DLLs from the application directory first. + * + * mingw ships no , so the EVT types are defined locally. + */ + +#include + +typedef PVOID EHANDLE; +typedef EHANDLE EVT_HANDLE; +typedef BOOL(CALLBACK *EVT_SUBSCRIBE_CALLBACK)(PVOID, DWORD, PVOID); + +/* Force the uur-hook.dll dependency. Referencing its marker symbol makes + * the linker emit the import, which is how the hook enters the client + * before any client code runs. */ +void uur_hook_version(void); +__attribute__((used)) static void (*const uur_hook_anchor)(void) = + uur_hook_version; + +#ifndef ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND +#define ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND 15028 +#endif +#ifndef ERROR_EVT_CHANNEL_NOT_FOUND +#define ERROR_EVT_CHANNEL_NOT_FOUND 15007 +#endif +#ifndef ERROR_EVT_QUERY_RESULT_STALE +#define ERROR_EVT_QUERY_RESULT_STALE 15031 +#endif + +static void *fail_metadata(void) +{ + SetLastError(ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND); + return NULL; +} + +static void *fail_channel(void) +{ + SetLastError(ERROR_EVT_CHANNEL_NOT_FOUND); + return NULL; +} + +static void *fail_query(void) +{ + SetLastError(ERROR_EVT_QUERY_RESULT_STALE); + return NULL; +} + +BOOL WINAPI EvtClose(EHANDLE object) +{ + (void)object; + SetLastError(ERROR_SUCCESS); + return TRUE; +} + +BOOL WINAPI EvtCancel(EHANDLE object) +{ + (void)object; + SetLastError(ERROR_SUCCESS); + return TRUE; +} + +EHANDLE WINAPI EvtOpenPublisherMetadata(EVT_HANDLE session, LPCWSTR publisher_id, + LPCWSTR log_file_path, LCID locale, + DWORD flags) +{ + (void)session; (void)publisher_id; (void)log_file_path; + (void)locale; (void)flags; + return fail_metadata(); +} + +EHANDLE WINAPI EvtOpenPublisherEnum(EVT_HANDLE session, DWORD flags) +{ + (void)session; (void)flags; + return fail_metadata(); +} + +EHANDLE WINAPI EvtOpenChannelEnum(EVT_HANDLE session, DWORD flags) +{ + (void)session; (void)flags; + return fail_channel(); +} + +EHANDLE WINAPI EvtOpenLog(EVT_HANDLE session, LPCWSTR path, DWORD flags) +{ + (void)session; (void)path; (void)flags; + return fail_channel(); +} + +EHANDLE WINAPI EvtQuery(EVT_HANDLE session, LPCWSTR path, LPCWSTR query, + DWORD flags) +{ + (void)session; (void)path; (void)query; (void)flags; + return fail_channel(); +} + +EHANDLE WINAPI EvtSubscribe(EVT_HANDLE session, HANDLE signal_event, + LPCWSTR channel_path, LPCWSTR query, + EVT_HANDLE bookmark, PVOID context, + EVT_SUBSCRIBE_CALLBACK callback, DWORD flags) +{ + (void)session; (void)signal_event; (void)channel_path; (void)query; + (void)bookmark; (void)context; (void)callback; (void)flags; + return fail_channel(); +} + +BOOL WINAPI EvtNext(EVT_HANDLE result_set, DWORD size, EVT_HANDLE *events, + DWORD timeout, DWORD flags, PDWORD returned) +{ + (void)result_set; (void)size; (void)events; (void)timeout; + (void)flags; (void)returned; + return fail_query() != NULL; +} + +BOOL WINAPI EvtRender(EVT_HANDLE context, EVT_HANDLE fragment, DWORD flags, + DWORD buffer_size, PVOID buffer, PDWORD buffer_used, + PDWORD property_count) +{ + (void)context; (void)fragment; (void)flags; (void)buffer_size; + (void)buffer; (void)buffer_used; (void)property_count; + SetLastError(ERROR_EVT_QUERY_RESULT_STALE); + return FALSE; +} + +BOOL WINAPI EvtGetExtendedStatus(DWORD buffer_size, LPWSTR buffer, + PDWORD buffer_used) +{ + (void)buffer_size; (void)buffer; (void)buffer_used; + SetLastError(ERROR_SUCCESS); + return FALSE; +} + +EVT_HANDLE WINAPI EvtCreateBookmark(LPCWSTR bookmark_xml) +{ + (void)bookmark_xml; + return (EVT_HANDLE)fail_query(); +} diff --git a/hook/wevtapi.def b/hook/wevtapi.def new file mode 100644 index 0000000..8faeb7a --- /dev/null +++ b/hook/wevtapi.def @@ -0,0 +1,14 @@ +LIBRARY wevtapi +EXPORTS + EvtCancel + EvtClose + EvtCreateBookmark + EvtGetExtendedStatus + EvtNext + EvtOpenChannelEnum + EvtOpenLog + EvtOpenPublisherEnum + EvtOpenPublisherMetadata + EvtQuery + EvtRender + EvtSubscribe diff --git a/hook/winlogon.c b/hook/winlogon.c new file mode 100644 index 0000000..f814f5c --- /dev/null +++ b/hook/winlogon.c @@ -0,0 +1,21 @@ +/* + * winlogon.exe — session presence marker. + * + * GameViewerService enumerates processes for a winlogon session token + * source before it initialises; under plain Wine none exists and the + * service never leaves its initial state (the launcher waits at the + * splash forever). This process only needs to exist with that name. + */ + +#include + +int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR command_line, + int show_command) +{ + (void)instance; + (void)previous; + (void)command_line; + (void)show_command; + Sleep(INFINITE); + return 0; +} diff --git a/hook/wtsapi32.c b/hook/wtsapi32.c new file mode 100644 index 0000000..1670c19 --- /dev/null +++ b/hook/wtsapi32.c @@ -0,0 +1,262 @@ +/* Minimal WTS provider for UU Remote under Wine's single interactive login. */ +#define WIN32_LEAN_AND_MEAN +#define _WIN32_WINNT 0x0A00 +#include +#include + +#include + +/* Ubuntu 22.04 ships MinGW-w64 headers that predate the Windows 8 WTS + * additions used by current UU builds. Keep the provider ABI self-contained + * instead of making the package depend on a particular MinGW header release. */ +#define UUR_WTS_SESSION_INFO_EX ((WTS_INFO_CLASS)25) +#define UUR_WTS_IS_REMOTE_SESSION ((WTS_INFO_CLASS)29) +#define UUR_WTS_SESSIONSTATE_UNLOCK 0x00000001L + +typedef struct uur_wtsinfoex_level1_w { + ULONG SessionId; + WTS_CONNECTSTATE_CLASS SessionState; + LONG SessionFlags; + WCHAR WinStationName[WINSTATIONNAME_LENGTH + 1]; + WCHAR UserName[USERNAME_LENGTH + 1]; + WCHAR DomainName[DOMAIN_LENGTH + 1]; + LARGE_INTEGER LogonTime; + LARGE_INTEGER ConnectTime; + LARGE_INTEGER DisconnectTime; + LARGE_INTEGER LastInputTime; + LARGE_INTEGER CurrentTime; + DWORD IncomingBytes; + DWORD OutgoingBytes; + DWORD IncomingFrames; + DWORD OutgoingFrames; + DWORD IncomingCompressedBytes; + DWORD OutgoingCompressedBytes; +} UUR_WTSINFOEX_LEVEL1_W; + +typedef struct uur_wtsinfoex_w { + DWORD Level; + union { + UUR_WTSINFOEX_LEVEL1_W WTSInfoExLevel1; + } Data; +} UUR_WTSINFOEXW, *PUUR_WTSINFOEXW; + +_Static_assert(sizeof(UUR_WTSINFOEXW) == 232, + "WTSINFOEXW x64 ABI layout changed"); + +static DWORD active_session(void) +{ + DWORD session = WTSGetActiveConsoleSessionId(); + return session == 0xffffffff ? 1 : session; +} + +static DWORD normalized_session(DWORD session) +{ + return session == WTS_CURRENT_SESSION ? active_session() : session; +} + +static void *allocate(DWORD size) +{ + return HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size); +} + +static BOOL string_result(LPCWSTR value, LPWSTR *buffer, DWORD *bytes) +{ + DWORD size; + LPWSTR copy; + if (buffer == NULL || bytes == NULL) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + size = ((DWORD)lstrlenW(value) + 1) * sizeof(WCHAR); + copy = allocate(size); + if (copy == NULL) { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + memcpy(copy, value, size); + *buffer = copy; + *bytes = size; + return TRUE; +} + +__declspec(dllexport) BOOL WINAPI WTSEnumerateSessionsW( + HANDLE server, DWORD reserved, DWORD version, + PWTS_SESSION_INFOW *sessions, DWORD *count) +{ + static const WCHAR station[] = L"Console"; + DWORD size; + PWTS_SESSION_INFOW result; + LPWSTR name; + (void)server; + (void)reserved; + (void)version; + if (sessions == NULL || count == NULL) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + size = sizeof(*result) + sizeof(station); + result = allocate(size); + if (result == NULL) { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } + name = (LPWSTR)(result + 1); + memcpy(name, station, sizeof(station)); + result->SessionId = active_session(); + result->pWinStationName = name; + result->State = WTSActive; + *sessions = result; + *count = 1; + return TRUE; +} + +__declspec(dllexport) BOOL WINAPI WTSQuerySessionInformationW( + HANDLE server, DWORD session, WTS_INFO_CLASS info_class, + LPWSTR *buffer, DWORD *bytes) +{ + WCHAR value[256]; + DWORD size; + (void)server; + if (buffer == NULL || bytes == NULL) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + session = normalized_session(session); + switch ((int)info_class) { + case WTSSessionId: { + DWORD *result = allocate(sizeof(*result)); + if (result == NULL) + break; + *result = session; + *buffer = (LPWSTR)result; + *bytes = sizeof(*result); + return TRUE; + } + case WTSUserName: + size = sizeof(value) / sizeof(value[0]); + if (GetUserNameW(value, &size)) + return string_result(value, buffer, bytes); + break; + case WTSWinStationName: + return string_result(L"Console", buffer, bytes); + case WTSDomainName: + size = sizeof(value) / sizeof(value[0]); + if (GetComputerNameW(value, &size)) + return string_result(value, buffer, bytes); + break; + case WTSConnectState: { + WTS_CONNECTSTATE_CLASS *result = allocate(sizeof(*result)); + if (result == NULL) + break; + *result = WTSActive; + *buffer = (LPWSTR)result; + *bytes = sizeof(*result); + return TRUE; + } + case WTSClientProtocolType: { + USHORT *result = allocate(sizeof(*result)); + if (result == NULL) + break; + *result = 0; + *buffer = (LPWSTR)result; + *bytes = sizeof(*result); + return TRUE; + } + case UUR_WTS_SESSION_INFO_EX: { + PUUR_WTSINFOEXW result = allocate(sizeof(*result)); + FILETIME now; + DWORD length; + if (result == NULL) + break; + result->Level = 1; + result->Data.WTSInfoExLevel1.SessionId = session; + result->Data.WTSInfoExLevel1.SessionState = WTSActive; + result->Data.WTSInfoExLevel1.SessionFlags = + UUR_WTS_SESSIONSTATE_UNLOCK; + lstrcpynW(result->Data.WTSInfoExLevel1.WinStationName, L"Console", + WINSTATIONNAME_LENGTH + 1); + length = USERNAME_LENGTH + 1; + GetUserNameW(result->Data.WTSInfoExLevel1.UserName, &length); + length = DOMAIN_LENGTH + 1; + GetComputerNameW(result->Data.WTSInfoExLevel1.DomainName, &length); + GetSystemTimeAsFileTime(&now); + result->Data.WTSInfoExLevel1.CurrentTime.LowPart = now.dwLowDateTime; + result->Data.WTSInfoExLevel1.CurrentTime.HighPart = now.dwHighDateTime; + *buffer = (LPWSTR)result; + *bytes = sizeof(*result); + return TRUE; + } + case UUR_WTS_IS_REMOTE_SESSION: { + BOOL *result = allocate(sizeof(*result)); + if (result == NULL) + break; + *result = FALSE; + *buffer = (LPWSTR)result; + *bytes = sizeof(*result); + return TRUE; + } + default: + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; + } + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; +} + +__declspec(dllexport) BOOL WINAPI WTSQueryUserToken(ULONG session, PHANDLE token) +{ + HANDLE current = NULL; + (void)session; + if (token == NULL) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + if (!OpenProcessToken(GetCurrentProcess(), + TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY, + ¤t)) + return FALSE; + if (!DuplicateTokenEx(current, MAXIMUM_ALLOWED, NULL, + SecurityImpersonation, TokenPrimary, token)) { + CloseHandle(current); + return FALSE; + } + CloseHandle(current); + return TRUE; +} + +__declspec(dllexport) VOID WINAPI WTSFreeMemory(PVOID memory) +{ + if (memory != NULL) + HeapFree(GetProcessHeap(), 0, memory); +} + +__declspec(dllexport) BOOL WINAPI WTSRegisterSessionNotification(HWND window, DWORD flags) +{ + (void)window; + (void)flags; + return TRUE; +} + +__declspec(dllexport) BOOL WINAPI WTSUnRegisterSessionNotification(HWND window) +{ + (void)window; + return TRUE; +} + +__declspec(dllexport) BOOL WINAPI WTSConnectSessionW( + ULONG logon_id, ULONG target_logon_id, PWSTR password, BOOL wait) +{ + (void)logon_id; + (void)target_logon_id; + (void)password; + (void)wait; + return TRUE; +} + +BOOL WINAPI DllMain(HINSTANCE instance, DWORD reason, LPVOID reserved) +{ + (void)instance; + (void)reason; + (void)reserved; + return TRUE; +} diff --git a/locales/en.yml b/locales/en.yml new file mode 100644 index 0000000..b177143 --- /dev/null +++ b/locales/en.yml @@ -0,0 +1,93 @@ +doctor: + header: "uur environment report" + install_hint: "not installed — install wine/pipewire per your distro" + no_portal_backend: "no xdg-desktop-portal backend found (Wayland capture/input unavailable)" + present: "present" + backend_x11: "X11 session: XTEST injection" + backend_wayland: "Wayland session: kernel uinput injection (portal path in development)" + backend_portal: "Wayland session: standard RemoteDesktop portal" + backend_none: "no graphical session detected" + uinput_module: "device present but kernel module not loaded (install the packaged udev rule + modules-load entry, then reboot)" + uinput_permission: "not writable by this user (needs the uur udev uaccess rule or the input group)" + uinput_missing: "/dev/uinput missing from this kernel" + portal_capture_missing: "ScreenCast interface unavailable in the active portal backend" + portal_input_missing: "RemoteDesktop interface unavailable; uinput can provide the fallback" + terminal_missing: "Win64 terminal proxy missing; reinstall uur" + launcher_missing: "Win64 Quick Launch proxy missing; reinstall uur" + xdg_launcher_missing: "install GLib's gio or gtk-launch" + wallpaper_missing: "not detected; set UUR_WALLPAPER to an image path" + footer: "Everything above is advisory. Run `uur setup` to provision the managed client." + +input: + portal_unavailable: "Wayland portal input is not available in this session" + no_display: "no graphical session detected (DISPLAY and WAYLAND_DISPLAY are unset)" + uinput_unavailable: "uinput not writable — falling back to XTEST (XWayland scope only; load the uinput module or add the udev rule for full coverage)" + +bridge: + listening: "input bridge listening on 127.0.0.1:%{port}" + session_summary: "%{count} input records injected" + connected: "hook connected; injecting via %{backend}" + disconnected_clean: "hook disconnected; held keys released" + disconnected_error: "hook error: %{error}" + bad_token_fingerprint: "connection rejected: bridge token mismatch (received prefix %{prefix}…)" + bad_token: "connection rejected: bridge token mismatch" + stop_requested: "stop requested" + +upstream: + unreachable: "cannot reach NetEase's official release feed" + unparsable: "cannot parse the release feed response: %{url}" + latest: "latest official release: %{version} (%{filename})" + up_to_date: "the provisioned client is up to date" + newer_available: "installed %{local}; upstream now has %{upstream}" + not_provisioned: "no provisioned client found; run `uur setup`" + +capture: + session_ready: "portal session ready (video node %{node}); streaming to the private runtime transport" + helper_failed: "the capture helper exited with an error" + +session: + already_running: "a session is already running - use it, or run `uur stop` first" + server_running: "GameViewerServer is running" + launching_client: "starting the managed client (capture and bridge are live)" + client_exited: "client exited (code %{code}); session ended" + capture_error: "capture unavailable: %{error}" + webview_missing: "WebView2 bootstrapper missing from the client directory; the management UI cannot start" + webview_failed: "WebView2 installation failed" + quick_launch_ready: "%{count} Linux applications exported to UU Quick Launch" + audio_backend: "Wine audio backend: %{backend}" + +setup: + eula_prompt: "The official UU Remote client will be downloaded from NetEase and is governed by their EULA: %{url}\nRe-run with --accept-eula to continue." + eula_required: "EULA acceptance is required before provisioning" + eula_recorded: "EULA acceptance recorded" + already_provisioned: "client already provisioned" + downloading: "downloading the official installer from %{url}" + download_failed: "the official installer download failed" + initializing_prefix: "initializing the managed Wine prefix" + installing_client: "installing the official client (silent mode)" + silent_install_unavailable: "the installer ignored silent mode; complete its window manually if it opened" + done: "provisioned into %{path}" + +autostart: + enabled: "login autostart enabled: %{path}" + disabled: "login autostart disabled" + status_enabled: "login autostart is enabled: %{path}" + status_disabled: "login autostart is disabled" + +wol: + interface: "interface: %{interface}" + mac: "MAC address: %{mac}" + magic_support: "Magic Packet support: %{state}" + magic_enabled: "Magic Packet enabled: %{state}" + connection: "NetworkManager connection: %{connection}" + yes: "yes" + no: "no" + unknown_ethtool: "unknown (install ethtool)" + unsupported: "%{interface} does not advertise Magic Packet wake support" + verify_failed: "Wake-on-LAN state could not be verified on %{interface}" + enabled: "Magic Packet wake enabled on %{interface}" + disabled: "Magic Packet wake disabled on %{interface}" + +display: + status: "Wayland capture source: %{source}" + changed: "Wayland capture source changed to %{source}; the portal will ask for a new selection on the next run" diff --git a/locales/zh-CN.yml b/locales/zh-CN.yml new file mode 100644 index 0000000..c1aadde --- /dev/null +++ b/locales/zh-CN.yml @@ -0,0 +1,93 @@ +doctor: + header: "uur 环境报告" + install_hint: "未安装 —— 请按发行版说明安装 wine/pipewire" + no_portal_backend: "未找到 xdg-desktop-portal 后端(Wayland 捕获/注入不可用)" + present: "已就绪" + backend_x11: "X11 会话:XTEST 注入" + backend_wayland: "Wayland 会话:内核 uinput 注入" + backend_portal: "Wayland 会话:标准 RemoteDesktop Portal" + backend_none: "未检测到图形会话" + uinput_module: "设备存在但内核模块未加载(安装包内附的 udev 规则与 modules-load 条目,然后重启)" + uinput_permission: "当前用户不可写(需要 uur 的 uaccess udev 规则或 input 组)" + uinput_missing: "此内核没有 /dev/uinput" + portal_capture_missing: "当前 Portal 后端未提供 ScreenCast 接口" + portal_input_missing: "当前 Portal 后端未提供 RemoteDesktop 接口;可回退到 uinput" + terminal_missing: "缺少 Win64 终端代理;请重新安装 uur" + launcher_missing: "缺少 Win64 快速启动代理;请重新安装 uur" + xdg_launcher_missing: "请安装 GLib 的 gio 或 gtk-launch" + wallpaper_missing: "未检测到;可将 UUR_WALLPAPER 设为图片路径" + footer: "以上均为提示性检查。运行 `uur setup` 安装受管客户端。" + +input: + portal_unavailable: "当前会话中 Wayland Portal 输入不可用" + no_display: "未检测到图形会话(DISPLAY 与 WAYLAND_DISPLAY 均未设置)" + uinput_unavailable: "uinput 不可写 —— 回退到 XTEST(仅 XWayland 范围;请加载 uinput 模块或安装 udev 规则以获得完整覆盖)" + +bridge: + listening: "输入桥监听于 127.0.0.1:%{port}" + session_summary: "已注入 %{count} 条输入记录" + connected: "钩子已连接;经 %{backend} 注入" + disconnected_clean: "钩子断开;已释放按住的按键" + disconnected_error: "钩子错误:%{error}" + bad_token_fingerprint: "连接被拒绝:桥接令牌不匹配(收到的令牌前缀 %{prefix}…)" + bad_token: "连接被拒绝:桥接令牌不匹配" + stop_requested: "已请求停止" + +session: + already_running: "会话已在运行 —— 直接使用它,或先执行 `uur stop`" + server_running: "GameViewerServer 正在运行" + launching_client: "正在启动受管客户端(捕获与输入桥已就绪)" + client_exited: "客户端已退出(代码 %{code});会话结束" + capture_error: "画面捕获不可用:%{error}" + webview_missing: "客户端目录中缺少 WebView2 安装器,管理界面无法启动" + webview_failed: "WebView2 安装失败" + quick_launch_ready: "已向 UU 快速启动导出 %{count} 个 Linux 应用" + audio_backend: "Wine 音频后端:%{backend}" + +upstream: + unreachable: "无法访问网易官方发布接口" + unparsable: "无法解析发布接口响应:%{url}" + latest: "官方最新版本:%{version}(%{filename})" + up_to_date: "受管客户端已是最新" + newer_available: "当前安装 %{local};官方已发布 %{upstream}" + not_provisioned: "尚未安装受管客户端;请运行 `uur setup`" + +capture: + session_ready: "Portal 会话已建立(视频节点 %{node});正在写入私有运行时传输" + helper_failed: "捕获助手异常退出" + +setup: + eula_prompt: "官方 UU 远程客户端将从网易官方渠道下载,并受其最终用户协议约束:%{url}\n使用 --accept-eula 重新运行以继续。" + eula_required: "需要先接受最终用户协议才能继续安装" + eula_recorded: "已记录协议接受状态" + already_provisioned: "客户端已安装" + downloading: "正在从 %{url} 下载官方安装包" + download_failed: "官方安装包下载失败" + initializing_prefix: "正在初始化受管 Wine 前缀" + installing_client: "正在安装官方客户端(静默模式)" + silent_install_unavailable: "安装包忽略静默模式;若弹出窗口请手动完成安装" + done: "已安装至 %{path}" + +autostart: + enabled: "已启用登录自启动:%{path}" + disabled: "已禁用登录自启动" + status_enabled: "登录自启动已启用:%{path}" + status_disabled: "登录自启动未启用" + +wol: + interface: "网卡:%{interface}" + mac: "MAC 地址:%{mac}" + magic_support: "Magic Packet 支持:%{state}" + magic_enabled: "Magic Packet 已启用:%{state}" + connection: "NetworkManager 连接:%{connection}" + yes: "是" + no: "否" + unknown_ethtool: "未知(请安装 ethtool)" + unsupported: "%{interface} 未声明支持 Magic Packet 唤醒" + verify_failed: "无法验证 %{interface} 的网络唤醒状态" + enabled: "已在 %{interface} 上启用 Magic Packet 唤醒" + disabled: "已在 %{interface} 上禁用 Magic Packet 唤醒" + +display: + status: "Wayland 捕获源:%{source}" + changed: "Wayland 捕获源已切换为 %{source};下次运行时 Portal 会请求新的选择" diff --git a/nix/module.nix b/nix/module.nix new file mode 100644 index 0000000..c803f81 --- /dev/null +++ b/nix/module.nix @@ -0,0 +1,31 @@ +{ + self, +}: +{ + config, + lib, + pkgs, + ... +}: + +let + cfg = config.programs.uur; + defaultPackage = self.packages.${pkgs.stdenv.hostPlatform.system}.default; +in +{ + options.programs.uur = { + enable = lib.mkEnableOption "UU Remote Linux compatibility layer"; + package = lib.mkOption { + type = lib.types.package; + default = defaultPackage; + defaultText = lib.literalExpression "inputs.uur.packages.${pkgs.system}.default"; + description = "The uur package to install."; + }; + }; + + config = lib.mkIf cfg.enable { + environment.systemPackages = [ cfg.package ]; + boot.kernelModules = [ "uinput" ]; + services.udev.packages = [ cfg.package ]; + }; +} diff --git a/nix/package.nix b/nix/package.nix new file mode 100644 index 0000000..d59cfb1 --- /dev/null +++ b/nix/package.nix @@ -0,0 +1,75 @@ +{ + lib, + stdenv, + runtimeShell, + rustPlatform, + pkg-config, + makeWrapper, + bash, + pipewire, + pulseaudio, + curl, + glib, + wineWow64Packages, + ethtool, + networkmanager, + pkgsCross, +}: + +let + windowsCC = pkgsCross.mingwW64.stdenv.cc; + windowsBinutils = pkgsCross.mingwW64.buildPackages.binutils; + targetPrefix = windowsCC.targetPrefix; +in +rustPlatform.buildRustPackage { + pname = "uur"; + version = "0.1.0"; + + src = lib.cleanSource ../.; + cargoLock.lockFile = ../Cargo.lock; + + nativeBuildInputs = [ + pkg-config + makeWrapper + windowsCC + windowsBinutils + bash + ]; + buildInputs = [ pipewire ]; + + CC = "${stdenv.cc}/bin/cc"; + UUR_BUILD_SHELL = runtimeShell; + doCheck = false; + + postBuild = '' + UU_MINGW_CC=${windowsCC}/bin/${targetPrefix}cc \ + UU_MINGW_STRIP=${windowsBinutils}/bin/${targetPrefix}strip \ + UU_MINGW_DLLTOOL=${windowsBinutils}/bin/${targetPrefix}dlltool \ + ./hook/build.sh + ./capture/build.sh + ''; + + installPhase = '' + runHook preInstall + ./packaging/stage.sh "$out" "" + wrapProgram "$out/bin/uur" \ + --prefix PATH : ${lib.makeBinPath [ + curl + bash + glib + pulseaudio + wineWow64Packages.stable + ethtool + networkmanager + ]} + runHook postInstall + ''; + + meta = { + description = "Native Linux companion for NetEase UU Remote"; + homepage = "https://github.com/panxuc/uur"; + license = lib.licenses.mit; + mainProgram = "uur"; + platforms = [ "x86_64-linux" ]; + }; +} diff --git a/packaging/60-uur-uinput.rules b/packaging/60-uur-uinput.rules new file mode 100644 index 0000000..fa204f2 --- /dev/null +++ b/packaging/60-uur-uinput.rules @@ -0,0 +1,3 @@ +# uur injects input through the kernel uinput device on Wayland. +# uaccess grants the active seat user access without a group. +KERNEL=="uinput", SUBSYSTEM=="misc", TAG+="uaccess", OPTIONS+="static_node=uinput" diff --git a/packaging/alpine/APKBUILD b/packaging/alpine/APKBUILD new file mode 100644 index 0000000..a6c8101 --- /dev/null +++ b/packaging/alpine/APKBUILD @@ -0,0 +1,31 @@ +# Contributor: uur contributors +# Maintainer: uur contributors +pkgname=uur +pkgver=0.1.0 +pkgrel=0 +pkgdesc="Native Linux companion for NetEase UU Remote" +url="https://github.com/panxuc/uur" +arch="x86_64" +license="MIT" +depends="bash wine curl glib pulseaudio-utils xdg-desktop-portal" +makedepends="cargo rust gcc musl-dev pipewire-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" + +build() { + cargo build --release --locked + ./hook/build.sh + ./capture/build.sh +} + +check() { + cargo test --release --locked +} + +package() { + ./packaging/stage.sh "$pkgdir" +} + +# Release automation replaces this with the source archive's sha512 digest. +sha512sums="SKIP" diff --git a/packaging/alpine/Dockerfile b/packaging/alpine/Dockerfile new file mode 100644 index 0000000..a9d2c8d --- /dev/null +++ b/packaging/alpine/Dockerfile @@ -0,0 +1,21 @@ +FROM alpine:edge AS build + +RUN apk add --no-cache \ + bash cargo rust gcc musl-dev pipewire-dev pkgconf \ + mingw-w64-gcc mingw-w64-binutils + +WORKDIR /src +COPY . . +RUN --mount=type=cache,target=/root/.cargo/registry \ + --mount=type=cache,target=/src/target \ + cargo test --release --locked \ + && cargo build --release --locked \ + && ./hook/build.sh \ + && ./capture/build.sh \ + && ./packaging/stage.sh /out + +FROM alpine:edge +RUN apk add --no-cache \ + bash ca-certificates curl glib pipewire-libs pulseaudio-utils wine xdg-desktop-portal +COPY --from=build /out/ / +ENTRYPOINT ["/usr/bin/uur"] diff --git a/packaging/arch/PKGBUILD.in b/packaging/arch/PKGBUILD.in new file mode 100644 index 0000000..c599c40 --- /dev/null +++ b/packaging/arch/PKGBUILD.in @@ -0,0 +1,27 @@ +pkgname=uur +pkgver=@UUR_VERSION@ +pkgrel=1 +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' 'xdg-desktop-portal') +optdepends=( + 'xdg-desktop-portal-gnome: GNOME-compatible Wayland capture and input' + 'xdg-desktop-portal-kde: Plasma Wayland capture and input' + 'xdg-desktop-portal-hyprland: Hyprland screen capture' + 'xdg-desktop-portal-wlr: wlroots screen capture' + 'xwayland-satellite: X11 application support on compositors without XWayland' + 'ethtool: inspect and configure Wake-on-LAN' + 'networkmanager: persist Wake-on-LAN for NetworkManager connections' + 'pulseaudio: legacy PulseAudio server for Wine audio' + 'pipewire-pulse: PulseAudio-compatible Wine audio on PipeWire' + 'libva-utils: VA-API capability diagnostics' + 'vulkan-tools: Vulkan and Vulkan Video capability diagnostics' + 'nvidia-utils: NVENC and NVDEC capability diagnostics on NVIDIA GPUs' +) +install=uur.install + +package() { + "@UUR_PROJECT_ROOT@/packaging/stage.sh" "$pkgdir" +} diff --git a/packaging/aur/.SRCINFO b/packaging/aur/.SRCINFO new file mode 100644 index 0000000..6485a25 --- /dev/null +++ b/packaging/aur/.SRCINFO @@ -0,0 +1,37 @@ +pkgbase = uur + pkgdesc = Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge) + pkgver = 0.1.0 + pkgrel = 1 + url = https://github.com/panxuc/uur + install = uur.install + arch = x86_64 + license = MIT + makedepends = cargo + makedepends = gcc + makedepends = pkgconf + makedepends = mingw-w64-gcc + makedepends = mingw-w64-binutils + depends = glibc + depends = gcc-libs + depends = glib2 + depends = wine + depends = curl + depends = pipewire + depends = xdg-desktop-portal + optdepends = osslsigncode: Authenticode verification of official updater downloads + optdepends = xdg-desktop-portal-gnome: GNOME, niri, and compatible Wayland capture/input + optdepends = xdg-desktop-portal-kde: KDE Plasma Wayland capture/input + optdepends = xdg-desktop-portal-hyprland: Hyprland screen capture (input uses uinput) + optdepends = xdg-desktop-portal-wlr: wlroots screen capture (input uses uinput) + optdepends = xwayland-satellite: X11 application support on niri + optdepends = ethtool: inspect and configure Wake-on-LAN + optdepends = networkmanager: persist Wake-on-LAN for NetworkManager connections + optdepends = pulseaudio: legacy PulseAudio server for Wine audio + optdepends = pipewire-pulse: PulseAudio-compatible Wine audio on PipeWire + optdepends = libva-utils: VA-API capability diagnostics + optdepends = vulkan-tools: Vulkan and Vulkan Video capability diagnostics + optdepends = nvidia-utils: NVENC and NVDEC capability diagnostics on NVIDIA GPUs + source = uur-0.1.0.tar.gz::https://github.com/panxuc/uur/archive/refs/tags/v0.1.0.tar.gz + sha256sums = SKIP + +pkgname = uur diff --git a/packaging/aur/PKGBUILD b/packaging/aur/PKGBUILD new file mode 100644 index 0000000..eeacd37 --- /dev/null +++ b/packaging/aur/PKGBUILD @@ -0,0 +1,62 @@ +# Maintainer: panxuc +# +# uur — native Linux companion for NetEase UU Remote. +# Installs a regular desktop application: the uur binary, the Windows PE +# hook components built with mingw, and desktop entries. Nothing touches +# the user's system at runtime except the managed per-user Wine prefix; +# the NetEase client itself is downloaded from the official feed on first +# `uur setup` (it is never redistributed by this package). + +pkgname=uur +pkgver=0.1.0 +pkgrel=1 +pkgdesc="Native Linux companion for NetEase UU Remote (X11/Wayland input and capture bridge)" +arch=('x86_64') +url="https://github.com/panxuc/uur" +license=('MIT') +depends=( + 'glibc' + 'gcc-libs' + 'glib2' + 'wine' + 'curl' + 'pipewire' + 'xdg-desktop-portal' +) +makedepends=('cargo' 'gcc' 'pkgconf' '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' + 'xdg-desktop-portal-kde: KDE Plasma Wayland capture/input' + 'xdg-desktop-portal-hyprland: Hyprland screen capture (input uses uinput)' + 'xdg-desktop-portal-wlr: wlroots screen capture (input uses uinput)' + 'xwayland-satellite: X11 application support on niri' + 'ethtool: inspect and configure Wake-on-LAN' + 'networkmanager: persist Wake-on-LAN for NetworkManager connections' + 'pulseaudio: legacy PulseAudio server for Wine audio' + 'pipewire-pulse: PulseAudio-compatible Wine audio on PipeWire' + 'libva-utils: VA-API capability diagnostics' + 'vulkan-tools: Vulkan and Vulkan Video capability diagnostics' + 'nvidia-utils: NVENC and NVDEC capability diagnostics on NVIDIA GPUs' +) +source=("${pkgname}-${pkgver}.tar.gz::${url}/archive/refs/tags/v${pkgver}.tar.gz") +sha256sums=('SKIP') # filled by the release workflow +install=uur.install + +build() { + cd "${srcdir}/${pkgname}-${pkgver}" + export CARGO_TARGET_DIR=target + cargo build --release --locked + ./hook/build.sh + ./capture/build.sh +} + +check() { + cd "${srcdir}/${pkgname}-${pkgver}" + cargo test --release --locked +} + +package() { + cd "${srcdir}/${pkgname}-${pkgver}" + ./packaging/stage.sh "${pkgdir}" +} diff --git a/packaging/aur/uur.install b/packaging/aur/uur.install new file mode 100644 index 0000000..f6a99ca --- /dev/null +++ b/packaging/aur/uur.install @@ -0,0 +1,15 @@ +post_install() { + update-desktop-database -q /usr/share/applications 2>/dev/null || true + /usr/lib/uur/post-install-message 2>/dev/null || { + echo "Next: uur doctor; uur setup --accept-eula; uur run" + } +} + +post_upgrade() { + update-desktop-database -q /usr/share/applications 2>/dev/null || true + /usr/lib/uur/post-install-message 2>/dev/null || true +} + +post_remove() { + update-desktop-database -q /usr/share/applications 2>/dev/null || true +} diff --git a/packaging/build-arch-package.sh b/packaging/build-arch-package.sh new file mode 100755 index 0000000..471ca0d --- /dev/null +++ b/packaging/build-arch-package.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +set -euo pipefail + +project_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +version=$(sed -n 's/^version = "\([^"]*\)"/\1/p' "$project_root/Cargo.toml" | head -n1) +output=${1:-$project_root/dist} +build_dir=$(mktemp -d "${TMPDIR:-/tmp}/uur-makepkg.XXXXXX") +trap 'rm -rf -- "$build_dir"' EXIT + +command -v makepkg >/dev/null 2>&1 || { + printf 'makepkg is required to build the Arch package\n' >&2 + exit 2 +} + +mkdir -p "$output" +sed -e "s|@UUR_VERSION@|$version|g" \ + -e "s|@UUR_PROJECT_ROOT@|$project_root|g" \ + "$project_root/packaging/arch/PKGBUILD.in" >"$build_dir/PKGBUILD" +cp "$project_root/packaging/aur/uur.install" "$build_dir/uur.install" + +( + cd "$build_dir" + PKGDEST="$output" makepkg --force --nodeps --noconfirm +) diff --git a/packaging/build-packages.sh b/packaging/build-packages.sh new file mode 100755 index 0000000..0aeae08 --- /dev/null +++ b/packaging/build-packages.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail + +project_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +version=$(sed -n 's/^version = "\([^"]*\)"/\1/p' "$project_root/Cargo.toml" | head -n1) +output="$project_root/dist" +stage="$output/root" + +mkdir -p "$output" "$stage" +find "$stage" -mindepth 1 -delete +find "$output" -maxdepth 1 -type f \ + \( -name 'uur-*.tar.zst' -o -name 'uur-*.rpm' -o -name 'uur_*.deb' \ + -o -name 'uur_*.apk' -o -name 'SHA256SUMS' \) -delete + +cargo build --manifest-path "$project_root/Cargo.toml" --release --locked +"$project_root/hook/build.sh" +"$project_root/capture/build.sh" +"$project_root/packaging/stage.sh" "$stage" + +tar --zstd -C "$stage" -cf "$output/uur-${version}-linux-x86_64.tar.zst" . + +if command -v nfpm >/dev/null 2>&1; then + nfpm_config="$output/nfpm.yaml" + sed -e "s|@UUR_VERSION@|$version|g" \ + -e "s|@UUR_STAGE@|$stage|g" \ + -e "s|@UUR_PROJECT_ROOT@|$project_root|g" \ + "$project_root/packaging/nfpm.yaml" >"$nfpm_config" + for format in deb rpm; do + nfpm package \ + --config "$nfpm_config" \ + --packager "$format" \ + --target "$output/" + done +else + printf 'nfpm not found; created only the portable tar.zst bundle\n' >&2 +fi + +if command -v makepkg >/dev/null 2>&1; then + "$project_root/packaging/build-arch-package.sh" "$output" +else + printf 'makepkg not found; Arch package was not created\n' >&2 +fi + +artifacts=() +while IFS= read -r -d '' artifact; do + artifacts+=("$artifact") +done < <( + find "$output" -maxdepth 1 -type f \ + \( -name "uur-${version}*.tar.zst" -o \ + -name "uur-${version}*.rpm" -o \ + -name "uur_${version}*.deb" -o \ + -name "uur_${version}*.apk" \) \ + -print0 | sort -z +) +((${#artifacts[@]} > 0)) || { + printf 'no release artifacts were produced\n' >&2 + exit 1 +} +artifact_names=() +for artifact in "${artifacts[@]}"; do + artifact_names+=("${artifact##*/}") +done +( + cd "$output" + sha256sum "${artifact_names[@]}" >SHA256SUMS +) diff --git a/packaging/io.github.panxuc.uur.metainfo.xml b/packaging/io.github.panxuc.uur.metainfo.xml new file mode 100644 index 0000000..fb6c9dd --- /dev/null +++ b/packaging/io.github.panxuc.uur.metainfo.xml @@ -0,0 +1,16 @@ + + + io.github.panxuc.uur + CC0-1.0 + MIT + UU Remote + Run UU Remote with native Linux capture and input + +

The uur utility runs the official UU Remote client in a managed Wine prefix and bridges screen capture and input through standard Linux desktop interfaces.

+
+ uur contributors + uur.desktop + https://github.com/panxuc/uur + uur + +
diff --git a/packaging/modules-load.conf b/packaging/modules-load.conf new file mode 100644 index 0000000..42bc005 --- /dev/null +++ b/packaging/modules-load.conf @@ -0,0 +1 @@ +uinput diff --git a/packaging/nfpm.yaml b/packaging/nfpm.yaml new file mode 100644 index 0000000..4d2b4bd --- /dev/null +++ b/packaging/nfpm.yaml @@ -0,0 +1,49 @@ +name: uur +arch: amd64 +platform: linux +version: "@UUR_VERSION@" +section: net +priority: optional +maintainer: panxuc +description: Native Linux companion for NetEase UU Remote +vendor: uur contributors +homepage: https://github.com/panxuc/uur +license: MIT +scripts: + postinstall: "@UUR_PROJECT_ROOT@/packaging/package-postinstall.sh" +contents: + - src: "@UUR_STAGE@/" + dst: / + type: tree +overrides: + deb: + depends: + - libc6 + - libgcc-s1 + - libglib2.0-bin + - wine + - curl + - libpipewire-0.3-0 + - xdg-desktop-portal + recommends: + - xdg-desktop-portal-gnome | xdg-desktop-portal-kde | xdg-desktop-portal-wlr + - ethtool + - network-manager + - pulseaudio-utils + - vainfo + - vulkan-tools + rpm: + depends: + - glibc + - libgcc + - glib2 + - wine + - curl + - pipewire-libs + - xdg-desktop-portal + recommends: + - ethtool + - NetworkManager + - pulseaudio-utils + - libva-utils + - vulkan-tools diff --git a/packaging/package-postinstall.sh b/packaging/package-postinstall.sh new file mode 100755 index 0000000..5e08600 --- /dev/null +++ b/packaging/package-postinstall.sh @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu + +if [ -x /usr/lib/uur/post-install-message ]; then + /usr/lib/uur/post-install-message +fi diff --git a/packaging/post-install-message b/packaging/post-install-message new file mode 100755 index 0000000..a73e1b1 --- /dev/null +++ b/packaging/post-install-message @@ -0,0 +1,15 @@ +#!/bin/sh +set -eu + +command_name=${UUR_COMMAND:-uur} + +printf '\n%s\n' 'UU Remote for Linux (uur) was installed successfully.' +printf '%s\n' 'Complete these steps in order:' +printf ' 1. %s doctor\n' "$command_name" +printf ' 2. %s setup --accept-eula\n' "$command_name" +printf ' 3. %s run\n' "$command_name" +printf '%s\n' \ + 'The setup command downloads the official client from NetEase.' \ + 'The --accept-eula flag records that you accepted the upstream EULA.' \ + 'Run setup without that flag only when you want to read the EULA URL first.' +printf '\n' diff --git a/packaging/stage.sh b/packaging/stage.sh new file mode 100755 index 0000000..4f14ae1 --- /dev/null +++ b/packaging/stage.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +set -euo pipefail + +project_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +destination=${1:?usage: packaging/stage.sh DESTDIR [PREFIX]} +prefix=${2-/usr} + +install -Dm0755 "$project_root/target/release/uur" \ + "$destination$prefix/bin/uur" +install -Dm0755 "$project_root/capture/uur-pw-capture" \ + "$destination$prefix/lib/uur/uur-pw-capture" +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 + install -Dm0644 "$project_root/build/hook/$component" \ + "$destination$prefix/lib/uur/hook/$component" +done +install -Dm0644 "$project_root/packaging/uur.desktop" \ + "$destination$prefix/share/applications/uur.desktop" +install -Dm0644 "$project_root/packaging/uur-icon.png" \ + "$destination$prefix/share/icons/hicolor/256x256/apps/uur.png" +install -Dm0644 "$project_root/packaging/io.github.panxuc.uur.metainfo.xml" \ + "$destination$prefix/share/metainfo/io.github.panxuc.uur.metainfo.xml" +install -Dm0644 "$project_root/packaging/60-uur-uinput.rules" \ + "$destination$prefix/lib/udev/rules.d/60-uur-uinput.rules" +install -Dm0644 "$project_root/packaging/modules-load.conf" \ + "$destination$prefix/lib/modules-load.d/uur.conf" +install -Dm0644 "$project_root/LICENSE" \ + "$destination$prefix/share/licenses/uur/LICENSE" +install -Dm0644 "$project_root/NOTICE" \ + "$destination$prefix/share/licenses/uur/NOTICE" diff --git a/packaging/uur-icon.png b/packaging/uur-icon.png new file mode 100644 index 0000000..10ca799 Binary files /dev/null and b/packaging/uur-icon.png differ diff --git a/packaging/uur.desktop b/packaging/uur.desktop new file mode 100644 index 0000000..70638d1 --- /dev/null +++ b/packaging/uur.desktop @@ -0,0 +1,14 @@ +[Desktop Entry] +Type=Application +Name=UU Remote +Name[zh_CN]=UU远程 +GenericName=Remote Desktop Client +GenericName[zh_CN]=远程桌面客户端 +Comment=Start the full UU Remote session on this Linux desktop +Comment[zh_CN]=在本 Linux 桌面启动完整的 UU 远程会话 +Exec=uur run +TryExec=uur +Icon=uur +Terminal=false +Categories=Network;RemoteAccess; +Keywords=remote;desktop;uu;网易;远程; diff --git a/scripts/check.sh b/scripts/check.sh new file mode 100755 index 0000000..cd7860c --- /dev/null +++ b/scripts/check.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +set -euo pipefail + +project_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +temporary=$(mktemp -d "${TMPDIR:-/tmp}/uur-check.XXXXXX") +trap 'rm -rf -- "$temporary"' EXIT + +cargo fmt --manifest-path "$project_root/Cargo.toml" --check +cargo clippy --manifest-path "$project_root/Cargo.toml" \ + --all-targets -- -D warnings +cargo test --manifest-path "$project_root/Cargo.toml" --all-targets +cc -std=c11 -O2 -Wall -Wextra -Werror \ + "$project_root/tests/frame-protocol.c" -o "$temporary/frame-protocol" +"$temporary/frame-protocol" +"$project_root/hook/build.sh" +"$project_root/capture/build.sh" diff --git a/scripts/extract-version.sh b/scripts/extract-version.sh new file mode 100755 index 0000000..898aa9a --- /dev/null +++ b/scripts/extract-version.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# Print the dotted version inside an installer filename such as +# UURemote_Setup_4.39.1.1375_0902062520_gwqd.exe or uuyc_4.33.0.exe. +set -euo pipefail + +[[ $# == 1 ]] || { printf 'usage: %s \n' "$0" >&2; exit 2; } + +grep -oE '[0-9]+(\.[0-9]+)+' <<<"$1" | head -n 1 diff --git a/scripts/install-user.sh b/scripts/install-user.sh new file mode 100755 index 0000000..b35997b --- /dev/null +++ b/scripts/install-user.sh @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Install uur into ~/.local: binary, hook DLLs, icon and an application +# menu entry. Clicking "UU Remote" in the launcher then runs the whole +# stack; no PATH edits are needed (the desktop entry uses absolute paths). +set -euo pipefail + +root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +readonly root +prefix="${UUR_INSTALL_PREFIX:-$HOME/.local}" + +[[ -x "$root/target/release/uur" ]] || { + printf 'missing %s — run: cargo build --release\n' \ + "$root/target/release/uur" >&2 + exit 1 +} +[[ -f "$root/build/hook/wevtapi.dll" && -f "$root/build/hook/uur-hook.dll" ]] || { + printf 'missing hook DLLs — run: ./hook/build.sh\n' >&2 + exit 1 +} +[[ -f "$root/capture/uur-pw-capture" ]] || { + printf 'missing capture helper — run: ./capture/build.sh\n' >&2 + exit 1 +} + +install -Dm0755 "$root/target/release/uur" "$prefix/bin/uur" +for helper in uur-pw-capture; do + install -Dm0755 "$root/capture/$helper" "$prefix/lib/uur/$helper" +done +for dll in wevtapi.dll uur-hook.dll winlogon.exe uur-terminal-proxy.exe; do + install -Dm0644 "$root/build/hook/$dll" "$prefix/lib/uur/hook/$dll" +done + +# Menu entry: absolute Exec path so the user's PATH is irrelevant. +install -Dm0644 "$root/packaging/uur.desktop" \ + "$prefix/share/applications/uur.desktop" +sed -i "s|^Exec=.*|Exec=$prefix/bin/uur run|; s|^TryExec=.*|TryExec=$prefix/bin/uur|" \ + "$prefix/share/applications/uur.desktop" +if [[ -f "$root/packaging/uur-icon.png" ]]; then + install -Dm0644 "$root/packaging/uur-icon.png" \ + "$prefix/share/icons/hicolor/256x256/apps/uur.png" +fi + +printf 'installed:\n %s/bin/uur\n %s/lib/uur/\n %s/share/applications/uur.desktop\n' \ + "$prefix" "$prefix" "$prefix" +UUR_COMMAND="$prefix/bin/uur" "$root/packaging/post-install-message" diff --git a/scripts/latest-installer-url.sh b/scripts/latest-installer-url.sh new file mode 100755 index 0000000..5bf8e32 --- /dev/null +++ b/scripts/latest-installer-url.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# Resolve the official NetEase UU Remote installer URL (curl, redirects). +set -euo pipefail + +readonly feed_url="https://api.nrd.nie.163.com/api/v1/release/dl/1?channel=gwqd" + +curl -fsIL --max-time 20 -o /dev/null -w '%{url_effective}' "$feed_url" diff --git a/scripts/probe-upstream.sh b/scripts/probe-upstream.sh new file mode 100755 index 0000000..fe19f07 --- /dev/null +++ b/scripts/probe-upstream.sh @@ -0,0 +1,75 @@ +#!/usr/bin/env bash +set -euo pipefail + +input=${1:?usage: scripts/probe-upstream.sh INSTALLER_OR_CLIENT_TREE} +work=$(mktemp -d "${TMPDIR:-/tmp}/uur-probe.XXXXXX") +trap 'rm -rf -- "$work"' EXIT + +for tool in 7z objdump find strings; do + command -v "$tool" >/dev/null 2>&1 || { + printf 'missing probe dependency: %s\n' "$tool" >&2 + exit 2 + } +done + +scan_root=$input +if [[ -f $input ]] && command -v osslsigncode >/dev/null 2>&1; then + osslsigncode verify -in "$input" >"$work/signature.log" 2>&1 || { + printf 'the upstream installer has no valid Authenticode signature\n' >&2 + exit 1 + } +fi + +if [[ -f $input ]]; then + 7z x -y -o"$work/payload" "$input" >"$work/extract.log" || true + scan_root="$work/payload" +fi +mapfile -d '' pe_files < <( + find "$scan_root" -type f \( -iname '*.exe' -o -iname '*.dll' \) -print0 +) +if ((${#pe_files[@]} == 0)) && [[ -f $input ]]; then + for tool in wine wineboot xvfb-run timeout; do + command -v "$tool" >/dev/null 2>&1 || { + printf 'installer extraction is opaque and %s is unavailable for the Wine probe\n' \ + "$tool" >&2 + exit 2 + } + done + export WINEPREFIX="$work/wine" + export WINEDEBUG=-all + xvfb-run -a wineboot --init >"$work/wineboot.log" 2>&1 + timeout 240s xvfb-run -a wine "$input" /S >"$work/install.log" 2>&1 || true + scan_root="$WINEPREFIX/drive_c" + mapfile -d '' pe_files < <( + find "$scan_root" -type f \( -iname '*.exe' -o -iname '*.dll' \) -print0 + ) +fi +((${#pe_files[@]} > 0)) || { + printf 'no PE payload was available after extraction and Wine installation\n' >&2 + exit 1 +} + +imports="$work/imports.txt" +strings_file="$work/strings.txt" +for file in "${pe_files[@]}"; do + objdump -p "$file" >>"$imports" 2>/dev/null || true + strings -a "$file" >>"$strings_file" 2>/dev/null || true +done + +require_symbol() { + local symbol=$1 + if ! grep -Fqi "$symbol" "$imports" && ! grep -Fqi "$symbol" "$strings_file"; then + printf 'missing upstream API contract: %s\n' "$symbol" >&2 + return 1 + fi +} + +require_symbol SendInput +require_symbol EvtOpenPublisherMetadata +if ! grep -Eqi 'BitBlt|StretchBlt|CreateDXGIFactory1|DuplicateOutput' \ + "$imports" "$strings_file"; then + printf 'missing every supported desktop capture API contract\n' >&2 + exit 1 +fi + +printf 'upstream static contracts passed (%d PE files)\n' "${#pe_files[@]}" diff --git a/src/audio.rs b/src/audio.rs new file mode 100644 index 0000000..ec15c77 --- /dev/null +++ b/src/audio.rs @@ -0,0 +1,120 @@ +//! Capability-selected Wine audio backend. + +use anyhow::{Context, Result}; +use std::path::Path; +use std::process::{Command, Stdio}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Backend { + PipeWirePulse, + PulseAudio, + PipeWireNative, + Alsa, + None, +} + +impl Backend { + pub fn label(self) -> &'static str { + match self { + Self::PipeWirePulse => "PulseAudio protocol on PipeWire", + Self::PulseAudio => "PulseAudio", + Self::PipeWireNative => "PipeWire (no PulseAudio compatibility detected)", + Self::Alsa => "ALSA", + Self::None => "no audio server detected", + } + } +} + +pub fn detect() -> Backend { + if let Some(server) = pactl_server() { + return if server.to_ascii_lowercase().contains("pipewire") { + Backend::PipeWirePulse + } else { + Backend::PulseAudio + }; + } + if command_succeeds("wpctl", &["status"]) { + return Backend::PipeWireNative; + } + if Path::new("/proc/asound/cards").is_file() { + return Backend::Alsa; + } + Backend::None +} + +/// Select a Wine driver only when a usable host backend is observable. Wine's +/// pulse driver works with both a real PulseAudio daemon and pipewire-pulse. +pub fn sync_wine(prefix: &Path) -> Result { + let backend = detect(); + let driver = match backend { + Backend::PipeWirePulse | Backend::PulseAudio => Some("pulse"), + Backend::PipeWireNative | Backend::Alsa => Some("alsa"), + Backend::None => None, + }; + if let Some(driver) = driver { + let status = Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", "-all") + .args([ + "reg", + "add", + r"HKCU\Software\Wine\Drivers", + "/v", + "Audio", + "/t", + "REG_SZ", + "/d", + driver, + "/f", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .context("selecting the Wine audio driver")?; + if !status.success() { + anyhow::bail!("Wine rejected the {driver} audio driver setting"); + } + } + Ok(backend) +} + +fn pactl_server() -> Option { + let output = Command::new("pactl") + .arg("info") + .env("LC_ALL", "C") + .stdin(Stdio::null()) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let text = String::from_utf8_lossy(&output.stdout); + text.lines() + .find_map(|line| { + line.split_once(':') + .filter(|(key, _)| key.trim() == "Server Name") + }) + .map(|(_, value)| value.trim().to_string()) +} + +fn command_succeeds(program: &str, arguments: &[&str]) -> bool { + Command::new(program) + .args(arguments) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|status| status.success()) +} + +#[cfg(test)] +mod tests { + use super::Backend; + + #[test] + fn backend_labels_are_user_facing() { + assert_eq!(Backend::PulseAudio.label(), "PulseAudio"); + assert!(Backend::PipeWirePulse.label().contains("PipeWire")); + } +} diff --git a/src/autostart.rs b/src/autostart.rs new file mode 100644 index 0000000..3b008ee --- /dev/null +++ b/src/autostart.rs @@ -0,0 +1,79 @@ +//! Optional XDG login autostart, independent of desktop environment. + +use anyhow::{Context, Result}; +use std::path::PathBuf; + +pub fn enable() -> Result<()> { + let path = desktop_path()?; + let parent = path.parent().context("autostart path has no parent")?; + std::fs::create_dir_all(parent)?; + let executable = std::env::current_exe().context("resolving uur executable")?; + let exec = desktop_exec_argument(&executable.to_string_lossy()); + std::fs::write( + &path, + format!( + "[Desktop Entry]\nType=Application\nName=UU Remote\nComment=Start the managed UU Remote session\nExec={exec} run\nIcon=uur\nTerminal=false\nX-GNOME-Autostart-enabled=true\n" + ), + )?; + println!( + "{}", + t!("autostart.enabled", path = path.display().to_string()) + ); + Ok(()) +} + +pub fn disable() -> Result<()> { + let path = desktop_path()?; + if path.exists() { + std::fs::remove_file(&path)?; + } + println!("{}", t!("autostart.disabled")); + Ok(()) +} + +pub fn status() -> Result<()> { + let path = desktop_path()?; + println!( + "{}", + if path.is_file() { + t!( + "autostart.status_enabled", + path = path.display().to_string() + ) + } else { + t!("autostart.status_disabled") + } + ); + Ok(()) +} + +fn desktop_path() -> Result { + let base = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config"))) + .context("cannot determine XDG configuration directory")?; + Ok(base.join("autostart/uur.desktop")) +} + +fn desktop_exec_argument(value: &str) -> String { + if value.bytes().all(|byte| { + byte.is_ascii_alphanumeric() || matches!(byte, b'/' | b'_' | b'-' | b'.' | b':') + }) { + return value.to_string(); + } + format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\"")) +} + +#[cfg(test)] +mod tests { + use super::desktop_exec_argument; + + #[test] + fn desktop_exec_paths_are_quoted_only_when_needed() { + assert_eq!(desktop_exec_argument("/usr/bin/uur"), "/usr/bin/uur"); + assert_eq!( + desktop_exec_argument("/opt/UU Remote/uur"), + "\"/opt/UU Remote/uur\"" + ); + } +} diff --git a/src/bridge.rs b/src/bridge.rs new file mode 100644 index 0000000..3b25a9e --- /dev/null +++ b/src/bridge.rs @@ -0,0 +1,167 @@ +use anyhow::{Context, Result}; +use std::io::Read; +use std::net::{TcpListener, TcpStream}; +use std::thread; + +use crate::config::Config; +use crate::input; +use crate::protocol::{self, RECORD_BYTES, RECORD_HELLO}; + +/// Print the X11 pointer position — the before/after observable for hook +/// verification. +pub fn print_pointer() -> Result<()> { + use x11rb::connection::Connection; + use x11rb::protocol::xproto::ConnectionExt; + let (conn, screen) = x11rb::connect(None).context("connecting to X display")?; + let root = conn.setup().roots[screen].root; + let reply = conn.query_pointer(root)?.reply()?; + println!("{} {}", reply.root_x, reply.root_y); + Ok(()) +} + +/// Serve the in-client hook: one authenticated loopback connection at a +/// time, records dispatched to the selected input backend. +pub fn serve() -> Result<()> { + let config = Config::load()?; + let preferred = + std::env::var("UUR_INPUT_BACKEND").unwrap_or_else(|_| config.input_backend.clone()); + let selected = input::select(&preferred)?; + if let Some(path) = std::env::var_os("UUR_BACKEND_STATUS") { + std::fs::write(path, selected.name()).context("writing backend status")?; + } + let backend = std::sync::Arc::new(std::sync::Mutex::new(selected)); + let backend_handle = backend.clone(); + let addr = format!("127.0.0.1:{}", config.bridge_port); + let listener = TcpListener::bind(&addr).with_context(|| format!("binding {addr}"))?; + println!("{}", t!("bridge.listening", port = config.bridge_port)); + + // The service process hooks itself too, so multiple authenticated + // connections coexist; each gets its own thread. Injection is + // serialized through the single backend. + for stream in listener.incoming() { + let stream = match stream { + Ok(s) => s, + Err(_) => continue, + }; + let config = config.clone(); + let backend_handle = backend_handle.clone(); + thread::spawn(move || { + let mut stream = stream; + match authenticate(&mut stream, &config) { + Ok(true) => {} + Ok(false) => return, + Err(_) => return, + } + let mut guard = backend_handle.lock().unwrap(); + println!("{}", t!("bridge.connected", backend = guard.name())); + match pump(&mut stream, guard.as_mut()) { + Ok(count) => { + println!("{}", t!("bridge.session_summary", count = count)); + println!("{}", t!("bridge.disconnected_clean")); + } + Err(error) => { + eprintln!( + "{}", + t!("bridge.disconnected_error", error = error.to_string()) + ); + } + } + let _ = guard.release_all(); + }); + } + Ok(()) +} + +fn authenticate(stream: &mut TcpStream, config: &Config) -> Result { + let mut header = [0u8; protocol::HEADER_BYTES]; + stream.read_exact(&mut header).context("reading header")?; + let header = protocol::read_header(&header); + if header.magic != protocol::MAGIC + || header.version != protocol::VERSION + || header.kind != RECORD_HELLO + { + return Ok(false); + } + let expected: [u8; 32] = decode_token(&config.bridge_token); + let mut token = [0u8; 32]; + stream.read_exact(&mut token)?; + if tokens_differ(&token, &expected) { + let shown: String = token[..4].iter().map(|b| format!("{b:02x}")).collect(); + eprintln!("{}", t!("bridge.bad_token_fingerprint", prefix = shown)); + return Ok(false); + } + Ok(true) +} + +fn pump(stream: &mut TcpStream, backend: &mut dyn input::InputBackend) -> Result { + let mut header = [0u8; protocol::HEADER_BYTES]; + let mut record = [0u8; RECORD_BYTES]; + let mut injected: u64 = 0; + loop { + // EOF is the hook exiting: a clean disconnect, not an error. + match stream.read_exact(&mut header) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::UnexpectedEof => { + return Ok(injected); + } + Err(error) => return Err(error.into()), + } + let header = protocol::read_header(&header); + if header.magic != protocol::MAGIC { + anyhow::bail!("bad magic"); + } + match header.kind { + protocol::RECORD_MOUSE | protocol::RECORD_KEYBOARD => { + stream.read_exact(&mut record)?; + let record = protocol::read_record(&record); + dispatch(backend, &record)?; + injected += 1; + } + _ => { + // Unknown record: skip its payload if any, stay in sync. + for _ in 0..(header.length / RECORD_BYTES as u32) { + stream.read_exact(&mut record)?; + } + } + } + } +} + +fn dispatch(backend: &mut dyn input::InputBackend, record: &protocol::Record) -> Result<()> { + match record.kind { + protocol::RECORD_KEYBOARD => backend.key(record.code, record.state == 1)?, + protocol::RECORD_MOUSE => { + // a/b carry motion deltas or absolute coordinates; the wheel + // selector reuses `code`. + const MOTION: u16 = 0xffff; + const WHEEL: u16 = 0xfffe; + match record.code { + MOTION => backend.motion(record.state == 1, record.a, record.b)?, + WHEEL => backend.wheel(record.a != 0, record.b)?, + _ => backend.button(record.code, record.state == 1)?, + } + } + _ => {} + } + Ok(()) +} + +fn decode_token(token: &str) -> [u8; 32] { + let mut out = [0u8; 32]; + for (index, chunk) in token.as_bytes().chunks(2).take(32).enumerate() { + if let Ok(value) = u8::from_str_radix(std::str::from_utf8(chunk).unwrap_or("0"), 16) { + out[index] = value; + } + } + out +} + +/// Branch-free comparison; the token never leaves loopback but avoid +/// handing timing data to same-user processes anyway. +fn tokens_differ(a: &[u8; 32], b: &[u8; 32]) -> bool { + let mut diff = 0u8; + for (x, y) in a.iter().zip(b.iter()) { + diff |= x ^ y; + } + diff != 0 +} diff --git a/src/capture.rs b/src/capture.rs new file mode 100644 index 0000000..ac1f3be --- /dev/null +++ b/src/capture.rs @@ -0,0 +1,190 @@ +//! Portal side of the capture path. +//! +//! Negotiates an xdg-desktop-portal ScreenCast session, obtains a private +//! PipeWire file descriptor and the video node id, then hands both to the +//! C capture helper (`uur-pw-capture`) which runs the PipeWire stream and +//! publishes frames into a private XDG runtime file (see +//! docs/capture-protocol.md). +//! +//! Consent: the first run shows the compositor's share dialog once. The +//! returned restore token is stored in uur's config; every later run hands +//! it back with PersistMode::Persistent and the portal restores the choice +//! silently — no dialog, no local interaction, which is the whole point on +//! a headless remote host. + +use anyhow::{anyhow, Context, Result}; +use std::os::fd::AsRawFd; +use std::os::fd::OwnedFd; +use std::path::PathBuf; +use std::process::{Child, Command}; + +use crate::config::Config; + +/// Run the capture path until interrupted. +pub fn run() -> Result<()> { + let mut config = Config::load()?; + let (pw_fd, node) = portal_session(&mut config)?; + println!("{}", t!("capture.session_ready", node = node)); + + let mut helper = spawn_helper(pw_fd, node)?; + let status = helper.wait().context("waiting for capture helper")?; + if !status.success() { + anyhow::bail!("{}", t!("capture.helper_failed")); + } + Ok(()) +} + +/// Start the native PipeWire consumer with a portal-owned descriptor. The +/// descriptor remains private to the child and is never reopened by path. +pub(crate) fn spawn_helper(pw_fd: OwnedFd, node: u32) -> Result { + // The helper inherits this descriptor: strip close-on-exec and keep the + // OwnedFd alive across the spawn (closing it would invalidate the number + // the child receives). + let raw = pw_fd.as_raw_fd(); + unsafe { + let flags = libc::fcntl(raw, libc::F_GETFD); + if flags < 0 { + return Err(std::io::Error::last_os_error()).context("fcntl F_GETFD"); + } + if libc::fcntl(raw, libc::F_SETFD, flags & !libc::FD_CLOEXEC) < 0 { + return Err(std::io::Error::last_os_error()).context("fcntl F_SETFD"); + } + } + + let helper = find_helper()?; + let mut command = Command::new(&helper); + command + .env("UUR_PW_FD", raw.to_string()) + .env("UUR_PW_NODE", node.to_string()) + .env("UUR_FRAME_PATH", frame_path()?); + if let Ok(debug) = std::env::var("UUR_PW_DEBUG") { + command.env("PIPEWIRE_DEBUG", debug); + } + let child = command + .spawn() + .with_context(|| format!("running {}", helper.display()))?; + Ok(child) +} + +fn frame_path() -> Result { + if let Some(path) = std::env::var_os("UUR_FRAME_PATH") { + return Ok(PathBuf::from(path)); + } + Ok(crate::config::runtime_dir()?.join("frames.v1")) +} + +/// Open the portal session and return (inherited fd number, node id). +/// First attempt reuses the stored restore token; if that fails (stale +/// token, monitor changed, compositor restart) fall back to one +/// interactive attempt and store the fresh token. +#[allow(clippy::type_complexity)] +fn portal_session(config: &mut Config) -> Result<(OwnedFd, u32)> { + let saved_token = config.capture_restore_token.clone(); + let runtime = tokio::runtime::Runtime::new().context("creating tokio runtime")?; + runtime.block_on(async move { + let screencast = ashpd::desktop::screencast::Screencast::new() + .await + .context("connecting to the ScreenCast portal")?; + + let mut last_error = None; + let source = source_type(&config.capture_source); + for token in [saved_token.clone(), None] { + match negotiate(&screencast, source, token.as_deref()).await { + Ok((fd, node, fresh_token)) => { + if fresh_token != saved_token { + config.capture_restore_token = fresh_token; + config.store().context("storing the new restore token")?; + } + return Ok((fd, node)); + } + Err(error) => { + last_error = Some(error); + } + } + } + Err(last_error.unwrap_or_else(|| anyhow!("portal session failed"))) + }) +} + +/// One full portal handshake. Returns the PipeWire fd, the video node id +/// and the restore token the portal issued for this selection. +async fn negotiate( + screencast: &ashpd::desktop::screencast::Screencast<'_>, + source: ashpd::desktop::screencast::SourceType, + restore_token: Option<&str>, +) -> Result<(OwnedFd, u32, Option)> { + use ashpd::desktop::screencast::CursorMode; + use ashpd::desktop::PersistMode; + + let session = screencast.create_session().await?; + + screencast + .select_sources( + &session, + CursorMode::Embedded, + source.into(), + false, + restore_token, + PersistMode::ExplicitlyRevoked, + ) + .await?; + + let response = screencast.start(&session, None).await?; + let streams_response = response.response()?; + let streams = streams_response.streams(); + let stream = streams.first().context("no monitor selected")?; + let node = stream.pipe_wire_node_id(); + let fresh_token = streams_response.restore_token().map(String::from); + + let fd = screencast + .open_pipe_wire_remote(&session) + .await + .context("opening the PipeWire remote")?; + Ok((fd, node, fresh_token)) +} + +pub(crate) fn source_type(value: &str) -> ashpd::desktop::screencast::SourceType { + use ashpd::desktop::screencast::SourceType; + match value { + "window" => SourceType::Window, + "virtual" => SourceType::Virtual, + _ => SourceType::Monitor, + } +} + +fn find_helper() -> Result { + let mut candidates = vec![ + PathBuf::from("/usr/lib/uur/uur-pw-capture"), + PathBuf::from("/usr/local/lib/uur/uur-pw-capture"), + ]; + if let Ok(home) = std::env::var("HOME") { + candidates.push(PathBuf::from(home).join(".local/lib/uur/uur-pw-capture")); + } + if let Ok(exe) = std::env::current_exe() { + // dev checkout: target/debug/uur -> capture/uur-pw-capture + if let Some(dir) = exe.parent() { + candidates.push(dir.join("../lib/uur/uur-pw-capture")); + candidates.push(dir.join("../../capture/uur-pw-capture")); + candidates.push(dir.join("uur-pw-capture")); + } + } + if let Ok(cwd) = std::env::current_dir() { + candidates.push(cwd.join("capture/uur-pw-capture")); + } + candidates.into_iter().find(|p| p.is_file()).ok_or_else(|| { + anyhow!("capture helper uur-pw-capture not found (build with capture/build.sh)") + }) +} + +#[cfg(test)] +mod tests { + use super::source_type; + use ashpd::desktop::screencast::SourceType; + + #[test] + fn configured_portal_source_is_mapped() { + assert_eq!(source_type("monitor"), SourceType::Monitor); + assert_eq!(source_type("window"), SourceType::Window); + assert_eq!(source_type("virtual"), SourceType::Virtual); + } +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..f8b4d90 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,162 @@ +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use std::path::PathBuf; + +/// Persistent user configuration. Everything lives under the XDG state and +/// config directories; the managed Wine prefix lives under data. +#[derive(Serialize, Deserialize, Clone)] +#[serde(default)] +pub struct Config { + /// EULA acceptance recorded during `uur setup`. + pub eula_accepted: bool, + /// Loopback port the in-client hook connects to. + pub bridge_port: u16, + /// Random per-install token the hook must present on HELLO. + pub bridge_token: String, + /// Preferred input backend: "auto" | "xtest" | "portal". + pub input_backend: String, + /// Release channel pinned for provisioning. + pub pinned_version: Option, + /// ScreenCast portal restore token: after the first consent the portal + /// restores the monitor selection silently. + pub capture_restore_token: Option, + /// Persistent permission for the standard RemoteDesktop input portal. + pub remote_desktop_restore_token: Option, + /// Portal source type: monitor, window, or virtual. + pub capture_source: String, +} + +impl Default for Config { + fn default() -> Self { + Self { + eula_accepted: false, + bridge_port: 47010, + bridge_token: generate_token(), + input_backend: "auto".into(), + pinned_version: None, + capture_restore_token: None, + remote_desktop_restore_token: None, + capture_source: "monitor".into(), + } + } +} + +fn generate_token() -> String { + let mut bytes = [0u8; 32]; + // Read EXACTLY 32 bytes. Never `fs::read` a character device like + // /dev/urandom: it has no EOF, so fs::read would loop forever and + // consume all memory (this actually caused an OOM once). + let filled = std::fs::OpenOptions::new() + .read(true) + .open("/dev/urandom") + .and_then(|mut f| { + use std::io::Read; + f.read_exact(&mut bytes) + }) + .is_ok(); + if !filled { + // No OS entropy available: derive a weak token from the clock so + // the tool still functions on loopback. Logged as a condition, + // not a crash. + let t = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let mut state = t as u64 | 1; + for byte in bytes.iter_mut() { + // xorshift64 — not cryptographic, only a stopgap. + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + *byte = state as u8; + } + } + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +pub fn config_path() -> Result { + let base = std::env::var("XDG_CONFIG_HOME") + .map(PathBuf::from) + .or_else(|_| std::env::var("HOME").map(|h| PathBuf::from(h).join(".config"))) + .context("cannot determine config directory")?; + Ok(base.join("uur").join("config.toml")) +} + +pub fn data_dir() -> Result { + let base = std::env::var("XDG_DATA_HOME") + .map(PathBuf::from) + .or_else(|_| std::env::var("HOME").map(|h| PathBuf::from(h).join(".local/share"))) + .context("cannot determine data directory")?; + Ok(base.join("uur")) +} + +/// Private per-login runtime state. Capture frames are sensitive and must not +/// live in a world-readable global /dev/shm name shared by every user. +pub fn runtime_dir() -> Result { + let base = std::env::var("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(format!("/tmp/uur-{}", unsafe { libc::geteuid() }))); + let dir = base.join("uur"); + std::fs::create_dir_all(&dir) + .with_context(|| format!("creating runtime directory {}", dir.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700))?; + } + Ok(dir) +} + +impl Config { + pub fn load() -> Result { + let path = config_path()?; + if !path.exists() { + let config = Self::default(); + config.store()?; + return Ok(config); + } + let raw = std::fs::read_to_string(&path) + .with_context(|| format!("reading {}", path.display()))?; + toml::from_str(&raw).context("parsing config.toml") + } + + pub fn store(&self) -> Result<()> { + let path = config_path()?; + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent) + .with_context(|| format!("creating {}", parent.display()))?; + } + std::fs::write(&path, toml::to_string_pretty(self)?) + .with_context(|| format!("writing {}", path.display())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_generation_terminates_and_is_wellformed() { + // Regression: generate_token once used fs::read on /dev/urandom, + // which never returns EOF and consumed all memory. + let token = generate_token(); + assert_eq!(token.len(), 64); + assert!(token.chars().all(|c| c.is_ascii_hexdigit())); + } + + #[test] + fn older_configuration_gets_new_defaults() { + let config: Config = toml::from_str( + r#" +eula_accepted = true +bridge_port = 47010 +bridge_token = "00" +input_backend = "auto" +"#, + ) + .unwrap(); + assert!(config.remote_desktop_restore_token.is_none()); + assert!(config.capture_restore_token.is_none()); + assert_eq!(config.capture_source, "monitor"); + } +} diff --git a/src/doctor.rs b/src/doctor.rs new file mode 100644 index 0000000..f794a81 --- /dev/null +++ b/src/doctor.rs @@ -0,0 +1,354 @@ +use anyhow::Result; + +fn line(status: &str, label: &str, detail: &str) { + println!("{status:<8} {label:<28} {detail}"); +} + +fn ok(missing: bool) -> &'static str { + if missing { + "MISS" + } else { + "ok" + } +} + +fn command_present(name: &str) -> bool { + std::env::var("PATH") + .map(|path| { + path.split(':') + .any(|dir| std::path::Path::new(dir).join(name).exists()) + }) + .unwrap_or(false) +} + +fn wine_version() -> Option { + let output = std::process::Command::new("wine") + .arg("--version") + .output() + .ok()?; + let text = String::from_utf8_lossy(&output.stdout).trim().to_string(); + Some(text) +} + +fn distro() -> String { + let raw = std::fs::read_to_string("/etc/os-release").unwrap_or_default(); + let field = |key: &str| { + raw.lines().find(|l| l.starts_with(key)).map(|l| { + l.split('=') + .nth(1) + .unwrap_or("") + .trim_matches('"') + .to_string() + }) + }; + match (field("PRETTY_NAME"), field("ID")) { + (Some(pretty), _) => pretty, + (None, Some(id)) => id, + _ => "unknown".into(), + } +} + +fn portal_backends() -> Vec { + let mut found = Vec::new(); + let mut directories = vec![ + std::path::PathBuf::from("/usr/lib/xdg-desktop-portal/portals"), + std::path::PathBuf::from("/usr/share/xdg-desktop-portal/portals"), + ]; + directories.extend( + std::env::var("XDG_DATA_DIRS") + .unwrap_or_else(|_| "/usr/local/share:/usr/share".into()) + .split(':') + .filter(|entry| !entry.is_empty()) + .map(|entry| std::path::Path::new(entry).join("xdg-desktop-portal/portals")), + ); + for dir in directories { + if let Ok(entries) = std::fs::read_dir(dir) { + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + let short = name + .trim_end_matches(".portal") + .trim_start_matches("portal-") + .to_string(); + if !found.contains(&short) { + found.push(short); + } + } + } + } + found.sort(); + found +} + +fn library_present(soname: &str) -> bool { + // `ldconfig -p` output is small; capture fully to avoid SIGPIPE races. + let cache = std::process::Command::new("ldconfig") + .arg("-p") + .output() + .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) + .unwrap_or_default(); + cache.contains(soname) + || ["/lib", "/usr/lib", "/usr/local/lib"] + .iter() + .any(|directory| { + std::fs::read_dir(directory) + .ok() + .into_iter() + .flatten() + .flatten() + .any(|entry| entry.file_name().to_string_lossy().contains(soname)) + }) +} + +fn runtime_component_present(name: &str) -> bool { + let mut candidates = vec![ + std::path::PathBuf::from("/usr/lib/uur/hook").join(name), + std::path::PathBuf::from("/usr/local/lib/uur/hook").join(name), + ]; + if let Ok(home) = std::env::var("HOME") { + candidates.push( + std::path::PathBuf::from(home) + .join(".local/lib/uur/hook") + .join(name), + ); + } + if let Ok(executable) = std::env::current_exe() { + if let Some(directory) = executable.parent() { + candidates.push(directory.join("../lib/uur/hook").join(name)); + candidates.push(directory.join("../../build/hook").join(name)); + } + } + if let Ok(directory) = std::env::current_dir() { + candidates.push(directory.join("build/hook").join(name)); + } + candidates.into_iter().any(|path| path.is_file()) +} + +fn portal_capabilities() -> (bool, bool, String) { + let Ok(runtime) = tokio::runtime::Runtime::new() else { + return (false, false, "unavailable".into()); + }; + runtime.block_on(async { + let (capture, sources) = match ashpd::desktop::screencast::Screencast::new().await { + Ok(portal) => match portal.available_source_types().await { + Ok(types) => (true, format!("{types:?}")), + Err(_) => (false, "unavailable".into()), + }, + Err(_) => (false, "unavailable".into()), + }; + let input = match ashpd::desktop::remote_desktop::RemoteDesktop::new().await { + Ok(portal) => portal.available_device_types().await.is_ok(), + Err(_) => false, + }; + (capture, input, sources) + }) +} + +/// Environment report. Everything is advisory: doctor never gates. +pub fn report() -> Result<()> { + println!("{}", t!("doctor.header")); + println!(); + + line("info", "distro", &distro()); + line( + "info", + "session", + &format!( + "type={} desktop={}", + std::env::var("XDG_SESSION_TYPE").unwrap_or_else(|_| "unknown".into()), + std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_else(|_| "unknown".into()), + ), + ); + line( + "info", + "display", + &format!( + "DISPLAY={} WAYLAND_DISPLAY={}", + std::env::var("DISPLAY").unwrap_or_else(|_| "-".into()), + std::env::var("WAYLAND_DISPLAY").unwrap_or_else(|_| "-".into()), + ), + ); + println!(); + + let missing_wine = !command_present("wine"); + let wine_detail: String = match (!missing_wine).then(wine_version).flatten() { + Some(version) => version, + None => t!("doctor.install_hint").to_string(), + }; + line(ok(missing_wine), "wine", &wine_detail); + + let backends = portal_backends(); + let has_portal_impl = !backends.is_empty(); + let portal_detail = if backends.is_empty() { + t!("doctor.no_portal_backend").to_string() + } else { + backends.join(", ") + }; + line(ok(!has_portal_impl), "xdg-desktop-portal", &portal_detail); + + let (portal_capture, portal_input, portal_sources) = portal_capabilities(); + let portal_capture_detail = if portal_capture { + t!("doctor.present").to_string() + } else { + t!("doctor.portal_capture_missing").to_string() + }; + line( + ok(!portal_capture), + "portal ScreenCast", + &portal_capture_detail, + ); + line("info", "portal source types", &portal_sources); + let portal_input_detail = if portal_input { + t!("doctor.present").to_string() + } else { + t!("doctor.portal_input_missing").to_string() + }; + line( + ok(!portal_input), + "portal RemoteDesktop", + &portal_input_detail, + ); + + let missing_pw = !library_present("libpipewire"); + let pw_detail = if missing_pw { + t!("doctor.install_hint").to_string() + } else { + t!("doctor.present").to_string() + }; + line(ok(missing_pw), "PipeWire", &pw_detail); + + let audio = crate::audio::detect(); + line("info", "audio backend", audio.label()); + + let video = crate::video::detect(); + line( + "info", + "DRM render node", + crate::video::describe(video.render_node, "present", "not detected"), + ); + line( + "info", + "VA-API capability", + crate::video::describe(video.va_api, "available", "not probed; install vainfo"), + ); + line( + "info", + "Vulkan capability", + crate::video::describe(video.vulkan, "available", "not probed; install vulkaninfo"), + ); + line( + "info", + "Vulkan Video", + crate::video::describe(video.vulkan_video, "video queue available", "not detected"), + ); + line( + "info", + "NVENC / NVDEC", + &format!( + "encode={} decode={}", + crate::video::describe(video.nvenc, "available", "missing"), + crate::video::describe(video.nvdec, "available", "missing") + ), + ); + + let terminal_proxy = runtime_component_present("uur-terminal-proxy.exe"); + let terminal_detail = if terminal_proxy { + t!("doctor.present").to_string() + } else { + t!("doctor.terminal_missing").to_string() + }; + line( + ok(!terminal_proxy), + "native terminal adapter", + &terminal_detail, + ); + + let mux_proxy = runtime_component_present("uur-mux-proxy.exe"); + let mux_detail = if mux_proxy { + t!("doctor.present").to_string() + } else { + t!("doctor.terminal_missing").to_string() + }; + line(ok(!mux_proxy), "terminal session adapter", &mux_detail); + + let launch_proxy = runtime_component_present("uur-launch-proxy.exe"); + let launch_detail = if launch_proxy { + t!("doctor.present").to_string() + } else { + t!("doctor.launcher_missing").to_string() + }; + line(ok(!launch_proxy), "UU Quick Launch adapter", &launch_detail); + let has_application_launcher = command_present("gio") || command_present("gtk-launch"); + let application_launcher_detail = if has_application_launcher { + t!("doctor.present").to_string() + } else { + t!("doctor.xdg_launcher_missing").to_string() + }; + line( + ok(!has_application_launcher), + "XDG application launcher", + &application_launcher_detail, + ); + + let wallpaper = crate::wallpaper::detect(); + let wallpaper_detail = wallpaper + .as_ref() + .map(|wallpaper| format!("{} ({})", wallpaper.path.display(), wallpaper.provider)) + .unwrap_or_else(|| t!("doctor.wallpaper_missing").to_string()); + line( + ok(wallpaper.is_none()), + "desktop wallpaper", + &wallpaper_detail, + ); + + // /dev/uinput: the Wayland injection path. Three states matter: + // missing file, module not loaded (ENODEV), and permission (EACCES). + let uinput_detail = match std::fs::OpenOptions::new().write(true).open("/dev/uinput") { + Ok(_) => t!("doctor.present").to_string(), + Err(error) => match error.raw_os_error() { + Some(19) => t!("doctor.uinput_module").to_string(), + Some(13) => t!("doctor.uinput_permission").to_string(), + _ => t!("doctor.uinput_missing").to_string(), + }, + }; + let uinput_missing = uinput_detail != t!("doctor.present"); + line(ok(uinput_missing), "uinput (/dev/uinput)", &uinput_detail); + + // Mirror the real auto policy in input::select. + let session_type = std::env::var("XDG_SESSION_TYPE").unwrap_or_default(); + let (backend, backend_note) = if session_type == "wayland" && portal_input { + ("portal", t!("doctor.backend_portal").to_string()) + } else if session_type == "wayland" && !uinput_missing { + ("uinput", t!("doctor.backend_wayland").to_string()) + } else if std::env::var("DISPLAY").is_ok() { + ("xtest", t!("doctor.backend_x11").to_string()) + } else { + ("none", t!("doctor.backend_none").to_string()) + }; + line( + "info", + "input backend", + &format!("{backend} ({backend_note})"), + ); + + match crate::wol::inspect(None) { + Ok(state) => line( + "info", + "Wake-on-LAN", + &format!( + "{} {} ({})", + state.interface, + state.mac, + match state.enabled { + Some(true) => "enabled", + Some(false) => "disabled", + None => "unknown; install ethtool", + } + ), + ), + Err(error) => line("info", "Wake-on-LAN", &error.to_string()), + } + + println!(); + println!("{}", t!("doctor.footer")); + Ok(()) +} diff --git a/src/i18n.rs b/src/i18n.rs new file mode 100644 index 0000000..92d8551 --- /dev/null +++ b/src/i18n.rs @@ -0,0 +1,19 @@ +/// Locale support. English is the source language; catalogs live in +/// `locales/`. Set `LANG`/`LC_ALL` or `UUR_LANG` to switch. The +/// `i18n!` macro itself lives at the crate root. +pub fn init() { + let requested = std::env::var("UUR_LANG") + .or_else(|_| std::env::var("LC_ALL")) + .or_else(|_| std::env::var("LANG")) + .unwrap_or_else(|_| "en".into()); + let code = requested.split('.').next().unwrap_or("en").to_string(); + let best = available() + .into_iter() + .find(|available| code.starts_with(available.as_str())) + .unwrap_or_else(|| "en".into()); + rust_i18n::set_locale(&best); +} + +fn available() -> Vec { + vec!["en".into(), "zh-CN".into()] +} diff --git a/src/inhibit.rs b/src/inhibit.rs new file mode 100644 index 0000000..c837e6d --- /dev/null +++ b/src/inhibit.rs @@ -0,0 +1,33 @@ +//! Keep the desktop session awake only while the managed UU session is alive. + +use anyhow::Result; +use ashpd::desktop::inhibit::{InhibitFlags, InhibitProxy}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +pub fn serve() -> Result<()> { + let stopping = Arc::new(AtomicBool::new(false)); + signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?; + signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?; + signal_hook::flag::register(signal_hook::consts::SIGHUP, stopping.clone())?; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; + runtime.block_on(async move { + let proxy = InhibitProxy::new().await?; + let request = proxy + .inhibit( + None, + InhibitFlags::Suspend | InhibitFlags::Idle, + "An active UU Remote session is running", + ) + .await?; + request.response()?; + println!("desktop suspend and idle inhibition active"); + while !stopping.load(Ordering::Relaxed) { + tokio::time::sleep(Duration::from_secs(1)).await; + } + Ok(()) + }) +} diff --git a/src/input/mod.rs b/src/input/mod.rs new file mode 100644 index 0000000..44c049e --- /dev/null +++ b/src/input/mod.rs @@ -0,0 +1,71 @@ +pub mod portal; +pub mod uinput; +pub mod xtest; + +use anyhow::Result; + +/// A desktop input sink. Records arrive already normalized by `protocol`. +pub trait InputBackend: Send { + fn name(&self) -> &'static str; + + fn key(&mut self, vkey: u16, down: bool) -> Result<()>; + fn button(&mut self, button: u16, down: bool) -> Result<()>; + /// Absolute (normalized 0..65535) or relative pointer motion. + fn motion(&mut self, absolute: bool, x: i32, y: i32) -> Result<()>; + fn wheel(&mut self, horizontal: bool, delta: i32) -> Result<()>; + + /// Release everything currently held (called when the hook disconnects). + fn release_all(&mut self) -> Result<()>; +} + +/// Choose the backend for this session: +/// +/// - Wayland sessions prefer the standard RemoteDesktop portal, then use the +/// kernel-level uinput device when the compositor only provides ScreenCast. +/// - X11 sessions use XTEST, which needs no extra privileges. +pub fn select(preferred: &str) -> Result> { + let on_wayland = std::env::var("WAYLAND_DISPLAY").is_ok(); + + if preferred == "portal" || (preferred == "auto" && on_wayland) { + match portal::PortalBackend::connect() { + Ok(backend) => return Ok(Box::new(backend)), + Err(error) if preferred == "portal" => return Err(error), + Err(error) => eprintln!("{}: {error}", t!("input.portal_unavailable")), + } + } + if preferred == "uinput" || (preferred == "auto" && on_wayland) { + match uinput::UinputBackend::connect() { + Ok(backend) => return Ok(Box::new(backend)), + Err(error) if preferred == "uinput" => return Err(error), + Err(error) => { + eprintln!("{}: {error}", t!("input.uinput_unavailable")); + // fall through to XTEST: partial reachability beats nothing + } + } + } + if std::env::var("DISPLAY").is_ok() { + return Ok(Box::new(xtest::XtestBackend::connect()?)); + } + anyhow::bail!("{}", t!("input.no_display")); +} + +pub(crate) fn wheel_steps(delta: i32) -> i32 { + if delta.abs() >= 120 { + (delta / 120).clamp(-16, 16) + } else { + delta.signum() + } +} + +#[cfg(test)] +mod tests { + use super::wheel_steps; + + #[test] + fn windows_wheel_units_are_normalized() { + assert_eq!(wheel_steps(120), 1); + assert_eq!(wheel_steps(-240), -2); + assert_eq!(wheel_steps(1), 1); + assert_eq!(wheel_steps(0), 0); + } +} diff --git a/src/input/portal.rs b/src/input/portal.rs new file mode 100644 index 0000000..8f3d003 --- /dev/null +++ b/src/input/portal.rs @@ -0,0 +1,387 @@ +use anyhow::{anyhow, Context, Result}; +use ashpd::desktop::remote_desktop::{Axis, DeviceType, KeyState, RemoteDesktop}; +use ashpd::desktop::screencast::{CursorMode, Screencast}; +use ashpd::desktop::PersistMode; +use std::collections::HashSet; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{self, SyncSender}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender}; + +use super::InputBackend; + +type Reply = SyncSender>; + +enum Event { + Key(i32, bool, Reply), + Button(i32, bool, Reply), + FlushMotion, + Wheel(Axis, i32, Reply), + Shutdown, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Motion { + absolute: bool, + x: f64, + y: f64, +} + +struct CaptureGuard(std::process::Child); + +impl Drop for CaptureGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +/// Wayland input through the freedesktop RemoteDesktop portal. The actual +/// backend can be GNOME, KDE, COSMIC, or any future implementation; uur never +/// branches on a desktop name. +pub struct PortalBackend { + sender: UnboundedSender, + pending_motion: Arc>>, + motion_queued: Arc, + held_keys: HashSet, + held_buttons: HashSet, +} + +impl PortalBackend { + pub fn connect() -> Result { + let mut config = crate::config::Config::load()?; + let restore_token = config.remote_desktop_restore_token.clone(); + let (sender, receiver) = unbounded_channel(); + let (ready_sender, ready_receiver) = mpsc::sync_channel(1); + let pending_motion = Arc::new(Mutex::new(None)); + let motion_queued = Arc::new(AtomicBool::new(false)); + let worker_motion = pending_motion.clone(); + let worker_queued = motion_queued.clone(); + + std::thread::Builder::new() + .name("uur-portal-input".into()) + .spawn(move || { + let result = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(anyhow::Error::from) + .and_then(|runtime| { + runtime.block_on(portal_worker( + receiver, + ready_sender.clone(), + restore_token, + worker_motion, + worker_queued, + )) + }); + if let Err(error) = result { + let _ = ready_sender.send(Err(error.to_string())); + } + }) + .context("starting portal input worker")?; + + let fresh_token = ready_receiver + .recv() + .context("portal input worker stopped during setup")? + .map_err(|error| anyhow!(error))?; + if fresh_token != config.remote_desktop_restore_token { + config.remote_desktop_restore_token = fresh_token; + config.store()?; + } + + Ok(Self { + sender, + pending_motion, + motion_queued, + held_keys: HashSet::new(), + held_buttons: HashSet::new(), + }) + } + + fn submit(&self, event: impl FnOnce(Reply) -> Event) -> Result<()> { + let (reply_sender, reply_receiver) = mpsc::sync_channel(1); + self.sender + .send(event(reply_sender)) + .map_err(|_| anyhow!("portal input session closed"))?; + reply_receiver + .recv_timeout(Duration::from_secs(3)) + .context("portal input request timed out")? + .map_err(|error| anyhow!(error)) + } +} + +async fn portal_worker( + mut receiver: UnboundedReceiver, + ready: SyncSender, String>>, + restore_token: Option, + pending_motion: Arc>>, + motion_queued: Arc, +) -> Result<()> { + let portal = RemoteDesktop::new().await?; + let screencast = Screencast::new().await?; + let configured = crate::config::Config::load()?; + let source = crate::capture::source_type(&configured.capture_source); + let available = portal.available_device_types().await?; + if !available.contains(DeviceType::Keyboard) || !available.contains(DeviceType::Pointer) { + anyhow::bail!("RemoteDesktop portal does not provide keyboard and pointer devices"); + } + + let session = portal.create_session().await?; + portal + .select_devices( + &session, + DeviceType::Keyboard | DeviceType::Pointer, + restore_token.as_deref(), + PersistMode::ExplicitlyRevoked, + ) + .await? + .response()?; + screencast + .select_sources( + &session, + CursorMode::Embedded, + source.into(), + false, + None, + PersistMode::DoNot, + ) + .await? + .response()?; + let selection = portal.start(&session, None).await?.response()?; + let stream = selection + .streams() + .and_then(|streams| streams.first()) + .context("RemoteDesktop portal returned no screen stream")?; + let stream_id = stream.pipe_wire_node_id(); + let (logical_width, logical_height) = stream.size().unwrap_or((65535, 65535)); + let pipewire = screencast.open_pipe_wire_remote(&session).await?; + let _capture = CaptureGuard(crate::capture::spawn_helper(pipewire, stream_id)?); + let token = selection.restore_token().map(ToOwned::to_owned); + ready + .send(Ok(token)) + .map_err(|_| anyhow!("portal setup receiver closed"))?; + + while let Some(event) = receiver.recv().await { + match event { + Event::Key(code, down, reply) => { + let result = portal + .notify_keyboard_keycode( + &session, + code, + if down { + KeyState::Pressed + } else { + KeyState::Released + }, + ) + .await; + answer(reply, result)?; + } + Event::Button(button, down, reply) => { + let result = portal + .notify_pointer_button( + &session, + button, + if down { + KeyState::Pressed + } else { + KeyState::Released + }, + ) + .await; + answer(reply, result)?; + } + Event::FlushMotion => loop { + let motion = pending_motion.lock().unwrap().take(); + let Some(motion) = motion else { + motion_queued.store(false, Ordering::Release); + let has_new_motion = pending_motion.lock().unwrap().is_some(); + if has_new_motion + && motion_queued + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .is_ok() + { + continue; + } + break; + }; + let result = if motion.absolute { + let logical_x = motion.x.clamp(0.0, 65535.0) * logical_width as f64 / 65535.0; + let logical_y = motion.y.clamp(0.0, 65535.0) * logical_height as f64 / 65535.0; + portal + .notify_pointer_motion_absolute(&session, stream_id, logical_x, logical_y) + .await + } else { + portal + .notify_pointer_motion(&session, motion.x, motion.y) + .await + }; + if let Err(error) = result { + eprintln!("portal pointer motion failed: {error}"); + } + }, + Event::Wheel(axis, steps, reply) => { + answer( + reply, + portal + .notify_pointer_axis_discrete(&session, axis, steps) + .await, + )?; + } + Event::Shutdown => break, + } + } + Ok(()) +} + +fn answer(reply: Reply, result: std::result::Result) -> Result<()> { + let failure = result.as_ref().err().map(ToString::to_string); + let _ = reply.send(result.map(|_| ()).map_err(|error| error.to_string())); + failure.map_or(Ok(()), |error| Err(anyhow!(error))) +} + +impl InputBackend for PortalBackend { + fn name(&self) -> &'static str { + "portal" + } + + fn key(&mut self, vkey: u16, down: bool) -> Result<()> { + let code = super::uinput::vk_to_linux_key(vkey) as i32; + if code == 0 { + anyhow::bail!("Windows virtual key 0x{vkey:02x} has no evdev mapping"); + } + self.submit(|reply| Event::Key(code, down, reply))?; + if down { + self.held_keys.insert(code); + } else { + self.held_keys.remove(&code); + } + Ok(()) + } + + fn button(&mut self, button: u16, down: bool) -> Result<()> { + let evdev = match button { + 1 => input_linux_sys::BTN_LEFT, + 2 => input_linux_sys::BTN_RIGHT, + 3 => input_linux_sys::BTN_MIDDLE, + 8 => input_linux_sys::BTN_SIDE, + 9 => input_linux_sys::BTN_EXTRA, + _ => anyhow::bail!("unsupported pointer button {button}"), + } as i32; + self.submit(|reply| Event::Button(evdev, down, reply))?; + if down { + self.held_buttons.insert(evdev); + } else { + self.held_buttons.remove(&evdev); + } + Ok(()) + } + + fn motion(&mut self, absolute: bool, x: i32, y: i32) -> Result<()> { + let mut pending = self.pending_motion.lock().unwrap(); + merge_motion( + &mut pending, + Motion { + absolute, + x: x as f64, + y: y as f64, + }, + ); + drop(pending); + if !self.motion_queued.swap(true, Ordering::AcqRel) + && self.sender.send(Event::FlushMotion).is_err() + { + self.motion_queued.store(false, Ordering::Release); + anyhow::bail!("portal input session closed"); + } + Ok(()) + } + + fn wheel(&mut self, horizontal: bool, delta: i32) -> Result<()> { + let axis = if horizontal { + Axis::Horizontal + } else { + Axis::Vertical + }; + let steps = super::wheel_steps(delta); + self.submit(|reply| Event::Wheel(axis, steps, reply)) + } + + fn release_all(&mut self) -> Result<()> { + self.pending_motion.lock().unwrap().take(); + for key in self.held_keys.clone() { + let _ = self.submit(|reply| Event::Key(key, false, reply)); + } + self.held_keys.clear(); + for button in self.held_buttons.clone() { + let _ = self.submit(|reply| Event::Button(button, false, reply)); + } + self.held_buttons.clear(); + Ok(()) + } +} + +fn merge_motion(pending: &mut Option, next: Motion) { + if !next.absolute { + if let Some(current) = pending.as_mut().filter(|motion| !motion.absolute) { + current.x += next.x; + current.y += next.y; + return; + } + } + *pending = Some(next); +} + +impl Drop for PortalBackend { + fn drop(&mut self) { + let _ = self.release_all(); + let _ = self.sender.send(Event::Shutdown); + } +} + +#[cfg(test)] +mod tests { + use super::{merge_motion, Motion}; + + #[test] + fn absolute_motion_keeps_only_the_latest_position() { + let mut pending = Some(Motion { + absolute: true, + x: 10.0, + y: 20.0, + }); + let latest = Motion { + absolute: true, + x: 30.0, + y: 40.0, + }; + merge_motion(&mut pending, latest); + assert_eq!(pending, Some(latest)); + } + + #[test] + fn relative_motion_accumulates_without_building_a_queue() { + let mut pending = Some(Motion { + absolute: false, + x: 3.0, + y: -2.0, + }); + merge_motion( + &mut pending, + Motion { + absolute: false, + x: 4.0, + y: 5.0, + }, + ); + assert_eq!( + pending, + Some(Motion { + absolute: false, + x: 7.0, + y: 3.0, + }) + ); + } +} diff --git a/src/input/uinput.rs b/src/input/uinput.rs new file mode 100644 index 0000000..61b31af --- /dev/null +++ b/src/input/uinput.rs @@ -0,0 +1,537 @@ +use anyhow::{Context, Result}; +use input_linux_sys as linux; +use std::collections::HashSet; +use std::fs::{File, OpenOptions}; +use std::io::Write; +use std::os::unix::io::AsRawFd; + +use super::InputBackend; + +// /dev/uinput interface constants (linux/uinput.h, linux/input-event-codes.h) +const UI_SET_EVBIT: libc::Ioctl = 0x4004_5564_u64 as libc::Ioctl; +const UI_SET_KEYBIT: libc::Ioctl = 0x4004_5565_u64 as libc::Ioctl; +const UI_SET_RELBIT: libc::Ioctl = 0x4004_5566_u64 as libc::Ioctl; +const UI_SET_ABSBIT: libc::Ioctl = 0x4004_5567_u64 as libc::Ioctl; +// struct uinput_setup = name[80] + input_id(8) + ff_effects_max(4) = 92 bytes +const UI_DEV_SETUP: libc::Ioctl = 0x405C_5503_u64 as libc::Ioctl; +// struct uinput_abs_setup = u16 code + input_absinfo(24) = 28 bytes +const UI_ABS_SETUP: libc::Ioctl = 0x401C_5504_u64 as libc::Ioctl; +const UI_DEV_CREATE: libc::Ioctl = 0x5501_u64 as libc::Ioctl; +const UI_DEV_DESTROY: libc::Ioctl = 0x5502_u64 as libc::Ioctl; + +const EV_SYN: u16 = 0x00; +const EV_KEY: u16 = 0x01; +const EV_REL: u16 = 0x02; +const EV_ABS: u16 = 0x03; + +const SYN_REPORT: u16 = 0; + +const REL_X: u16 = 0x00; +const REL_Y: u16 = 0x01; +const REL_WHEEL: u16 = 0x08; +const REL_HWHEEL: u16 = 0x09; + +const ABS_X: u16 = 0x00; +const ABS_Y: u16 = 0x01; + +const BTN_LEFT: u16 = 0x110; +const BTN_RIGHT: u16 = 0x111; +const BTN_MIDDLE: u16 = 0x112; +const BTN_SIDE: u16 = 0x116; +const BTN_EXTRA: u16 = 0x117; +const BTN_TOOL_PEN: u16 = 0x140; + +const BUS_VIRTUAL: u16 = 0x06; + +/// struct input_event, 64-bit time_t layout. +#[repr(C)] +struct InputEvent { + tv_sec: i64, + tv_usec: i64, + type_: u16, + code: u16, + value: i32, +} + +/// struct uinput_setup: name[80] + input_id(4×u16) + ff_effects_max(u32). +#[repr(C)] +struct UinputSetup { + name: [u8; 80], + bustype: u16, + vendor: u16, + product: u16, + version: u16, + ff_effects_max: u32, +} + +/// struct uinput_abs_setup: u16 code (+padding) + input_absinfo (6×i32). +#[repr(C)] +struct UinputAbsSetup { + code: u16, + pad: u16, + value: i32, + minimum: i32, + maximum: i32, + fuzz: i32, + flat: i32, + resolution: i32, +} + +fn open_device() -> Result { + OpenOptions::new() + .write(true) + .open("/dev/uinput") + .context("opening /dev/uinput") +} + +fn ioctl_u32(file: &File, request: libc::Ioctl, value: u32) -> Result<()> { + let rc = unsafe { libc::ioctl(file.as_raw_fd(), request, value) }; + if rc < 0 { + return Err(std::io::Error::last_os_error()).context("uinput ioctl"); + } + Ok(()) +} + +/// One kernel virtual input device. +struct UinputDevice { + file: File, +} + +impl UinputDevice { + fn create(name: &'static str, product: u16) -> Result { + let file = open_device()?; + unsafe { + let mut setup_name = [0u8; 80]; + let label = name.as_bytes(); + let len = label.len().min(79); + setup_name[..len].copy_from_slice(&label[..len]); + let rc = libc::ioctl( + file.as_raw_fd(), + UI_DEV_SETUP, + &UinputSetup { + name: setup_name, + bustype: BUS_VIRTUAL, + vendor: 0x1, + product, + version: 1, + ff_effects_max: 0, + }, + ); + if rc < 0 { + return Err(std::io::Error::last_os_error()).context("uinput UI_DEV_SETUP"); + } + } + Ok(Self { file }) + } + + fn keybit(&self, code: u16) -> Result<()> { + ioctl_u32(&self.file, UI_SET_KEYBIT, code as u32) + } + + fn relbit(&self, code: u16) -> Result<()> { + ioctl_u32(&self.file, UI_SET_RELBIT, code as u32) + } + + fn absbit(&self, code: u16, maximum: i32) -> Result<()> { + ioctl_u32(&self.file, UI_SET_ABSBIT, code as u32)?; + let setup = UinputAbsSetup { + code, + pad: 0, + value: 0, + minimum: 0, + maximum, + fuzz: 0, + flat: 0, + resolution: 0, + }; + let rc = unsafe { libc::ioctl(self.file.as_raw_fd(), UI_ABS_SETUP, &setup) }; + if rc < 0 { + return Err(std::io::Error::last_os_error()).context("uinput UI_ABS_SETUP"); + } + Ok(()) + } + + fn finish(&self) -> Result<()> { + let rc = unsafe { libc::ioctl(self.file.as_raw_fd(), UI_DEV_CREATE) }; + if rc < 0 { + return Err(std::io::Error::last_os_error()).context("uinput UI_DEV_CREATE"); + } + Ok(()) + } + + fn emit(&self, type_: u16, code: u16, value: i32) -> Result<()> { + let event = InputEvent { + tv_sec: 0, + tv_usec: 0, + type_, + code, + value, + }; + let bytes = unsafe { + std::slice::from_raw_parts( + &event as *const InputEvent as *const u8, + std::mem::size_of::(), + ) + }; + // File implements Write through a shared reference. + let mut file = &self.file; + file.write_all(bytes)?; + Ok(()) + } + + fn syn(&self) -> Result<()> { + self.emit(EV_SYN, SYN_REPORT, 0) + } +} + +impl Drop for UinputDevice { + fn drop(&mut self) { + unsafe { + libc::ioctl(self.file.as_raw_fd(), UI_DEV_DESTROY); + } + } +} + +/// Kernel-level input injection through /dev/uinput. Works identically on +/// every Wayland compositor and every X11 session, because the events enter +/// the input stack like real hardware. Requires write access to +/// /dev/uinput (udev `uaccess` tag or the `input` group). +/// +/// Devices are deliberately split so libinput classifies each one cleanly: +/// mixing REL and ABS axes on one device makes compositors treat it as a +/// mouse and silently drop its absolute events (verified on KWin). +struct Devices { + keyboard: UinputDevice, + pointer: UinputDevice, + tablet: UinputDevice, +} + +impl Devices { + fn create() -> Result { + let keyboard = UinputDevice::create("uur virtual keyboard", 1)?; + ioctl_u32(&keyboard.file, UI_SET_EVBIT, EV_KEY as u32)?; + ioctl_u32(&keyboard.file, UI_SET_EVBIT, EV_SYN as u32)?; + for code in 1..=0xffu16 { + keyboard.keybit(code)?; + } + keyboard.finish()?; + + let pointer = UinputDevice::create("uur virtual pointer", 2)?; + ioctl_u32(&pointer.file, UI_SET_EVBIT, EV_KEY as u32)?; + ioctl_u32(&pointer.file, UI_SET_EVBIT, EV_REL as u32)?; + ioctl_u32(&pointer.file, UI_SET_EVBIT, EV_SYN as u32)?; + for button in [BTN_LEFT, BTN_RIGHT, BTN_MIDDLE, BTN_SIDE, BTN_EXTRA] { + pointer.keybit(button)?; + } + for rel in [REL_X, REL_Y, REL_WHEEL, REL_HWHEEL] { + pointer.relbit(rel)?; + } + pointer.finish()?; + + // An absolute pointer must look like a pen tablet, otherwise + // libinput treats it as a mouse and ignores absolute motion. + let tablet = UinputDevice::create("uur virtual tablet", 3)?; + ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_KEY as u32)?; + ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_ABS as u32)?; + ioctl_u32(&tablet.file, UI_SET_EVBIT, EV_SYN as u32)?; + tablet.keybit(BTN_TOOL_PEN)?; + tablet.absbit(ABS_X, 65535)?; + tablet.absbit(ABS_Y, 65535)?; + tablet.finish()?; + // Stay in proximity so hover motion keeps updating the cursor. + tablet.emit(EV_KEY, BTN_TOOL_PEN, 1)?; + tablet.syn()?; + + Ok(Self { + keyboard, + pointer, + tablet, + }) + } +} + +pub struct UinputBackend { + devices: Devices, + held_keys: HashSet, + held_buttons: HashSet, +} + +impl UinputBackend { + pub fn connect() -> Result { + let devices = Devices::create()?; + Ok(Self { + devices, + held_keys: HashSet::new(), + held_buttons: HashSet::new(), + }) + } +} + +impl InputBackend for UinputBackend { + fn name(&self) -> &'static str { + "uinput" + } + + fn key(&mut self, vkey: u16, down: bool) -> Result<()> { + let code = vk_to_linux_key(vkey); + if code == 0 { + return Ok(()); // not representable on this layout; drop quietly + } + let value = if down { 1 } else { 0 }; + self.devices.keyboard.emit(EV_KEY, code, value)?; + self.devices.keyboard.syn()?; + if down { + self.held_keys.insert(code); + } else { + self.held_keys.remove(&code); + } + Ok(()) + } + + fn button(&mut self, button: u16, down: bool) -> Result<()> { + let code = match button { + 1 => BTN_LEFT, + 2 => BTN_RIGHT, + 3 => BTN_MIDDLE, + 8 => BTN_SIDE, + 9 => BTN_EXTRA, + _ => return Ok(()), // unknown buttons are dropped, not fatal + }; + let value = if down { 1 } else { 0 }; + self.devices.pointer.emit(EV_KEY, code, value)?; + self.devices.pointer.syn()?; + if down { + self.held_buttons.insert(code); + } else { + self.held_buttons.remove(&code); + } + Ok(()) + } + + fn motion(&mut self, absolute: bool, x: i32, y: i32) -> Result<()> { + if absolute { + self.devices.tablet.emit(EV_ABS, ABS_X, x.clamp(0, 65535))?; + self.devices.tablet.emit(EV_ABS, ABS_Y, y.clamp(0, 65535))?; + self.devices.tablet.syn()?; + } else { + self.devices.pointer.emit(EV_REL, REL_X, x)?; + self.devices.pointer.emit(EV_REL, REL_Y, y)?; + self.devices.pointer.syn()?; + } + Ok(()) + } + + fn wheel(&mut self, horizontal: bool, delta: i32) -> Result<()> { + self.devices.pointer.emit( + EV_REL, + if horizontal { REL_HWHEEL } else { REL_WHEEL }, + super::wheel_steps(delta), + )?; + self.devices.pointer.syn() + } + + fn release_all(&mut self) -> Result<()> { + for code in self.held_keys.clone() { + self.devices.keyboard.emit(EV_KEY, code, 0)?; + } + self.held_keys.clear(); + for code in self.held_buttons.clone() { + self.devices.pointer.emit(EV_KEY, code, 0)?; + } + self.held_buttons.clear(); + self.devices.keyboard.syn()?; + self.devices.pointer.syn() + } +} + +/// Windows virtual-key code -> Linux input keycode, invariant subset. +/// The layout-aware remainder arrives with the Phase 2 semantic text path. +pub(crate) fn vk_to_linux_key(vkey: u16) -> u16 { + let base = vkey & 0xff; + let extended = vkey & 0x100 != 0; + let code = match base { + 0x08 => linux::KEY_BACKSPACE, + 0x09 => linux::KEY_TAB, + 0x0d if extended => linux::KEY_KPENTER, + 0x0d => linux::KEY_ENTER, + 0x10 | 0xa0 => linux::KEY_LEFTSHIFT, + 0xa1 => linux::KEY_RIGHTSHIFT, + 0x11 | 0xa2 if extended => linux::KEY_RIGHTCTRL, + 0x11 | 0xa2 => linux::KEY_LEFTCTRL, + 0xa3 => linux::KEY_RIGHTCTRL, + 0x12 | 0xa4 if extended => linux::KEY_RIGHTALT, + 0x12 | 0xa4 => linux::KEY_LEFTALT, + 0xa5 => linux::KEY_RIGHTALT, + 0x13 => linux::KEY_PAUSE, + 0x14 => linux::KEY_CAPSLOCK, + 0x1b => linux::KEY_ESC, + 0x20 => linux::KEY_SPACE, + 0x21 => linux::KEY_PAGEUP, + 0x22 => linux::KEY_PAGEDOWN, + 0x23 => linux::KEY_END, + 0x24 => linux::KEY_HOME, + 0x25 => linux::KEY_LEFT, + 0x26 => linux::KEY_UP, + 0x27 => linux::KEY_RIGHT, + 0x28 => linux::KEY_DOWN, + 0x2d => linux::KEY_INSERT, + 0x2e => linux::KEY_DELETE, + 0x30 => linux::KEY_0, + 0x31 => linux::KEY_1, + 0x32 => linux::KEY_2, + 0x33 => linux::KEY_3, + 0x34 => linux::KEY_4, + 0x35 => linux::KEY_5, + 0x36 => linux::KEY_6, + 0x37 => linux::KEY_7, + 0x38 => linux::KEY_8, + 0x39 => linux::KEY_9, + 0x41 => linux::KEY_A, + 0x42 => linux::KEY_B, + 0x43 => linux::KEY_C, + 0x44 => linux::KEY_D, + 0x45 => linux::KEY_E, + 0x46 => linux::KEY_F, + 0x47 => linux::KEY_G, + 0x48 => linux::KEY_H, + 0x49 => linux::KEY_I, + 0x4a => linux::KEY_J, + 0x4b => linux::KEY_K, + 0x4c => linux::KEY_L, + 0x4d => linux::KEY_M, + 0x4e => linux::KEY_N, + 0x4f => linux::KEY_O, + 0x50 => linux::KEY_P, + 0x51 => linux::KEY_Q, + 0x52 => linux::KEY_R, + 0x53 => linux::KEY_S, + 0x54 => linux::KEY_T, + 0x55 => linux::KEY_U, + 0x56 => linux::KEY_V, + 0x57 => linux::KEY_W, + 0x58 => linux::KEY_X, + 0x59 => linux::KEY_Y, + 0x5a => linux::KEY_Z, + 0x5b => linux::KEY_LEFTMETA, + 0x5c => linux::KEY_RIGHTMETA, + 0x60 => linux::KEY_KP0, + 0x61 => linux::KEY_KP1, + 0x62 => linux::KEY_KP2, + 0x63 => linux::KEY_KP3, + 0x64 => linux::KEY_KP4, + 0x65 => linux::KEY_KP5, + 0x66 => linux::KEY_KP6, + 0x67 => linux::KEY_KP7, + 0x68 => linux::KEY_KP8, + 0x69 => linux::KEY_KP9, + 0x6a => linux::KEY_KPASTERISK, + 0x6b => linux::KEY_KPPLUS, + 0x6d => linux::KEY_KPMINUS, + 0x6e => linux::KEY_KPDOT, + 0x6f => linux::KEY_KPSLASH, + 0x70 => linux::KEY_F1, + 0x71 => linux::KEY_F2, + 0x72 => linux::KEY_F3, + 0x73 => linux::KEY_F4, + 0x74 => linux::KEY_F5, + 0x75 => linux::KEY_F6, + 0x76 => linux::KEY_F7, + 0x77 => linux::KEY_F8, + 0x78 => linux::KEY_F9, + 0x79 => linux::KEY_F10, + 0x7a => linux::KEY_F11, + 0x7b => linux::KEY_F12, + 0xba => linux::KEY_SEMICOLON, + 0xbb => linux::KEY_EQUAL, + 0xbc => linux::KEY_COMMA, + 0xbd => linux::KEY_MINUS, + 0xbe => linux::KEY_DOT, + 0xbf => linux::KEY_SLASH, + 0xc0 => linux::KEY_GRAVE, + 0xdb => linux::KEY_LEFTBRACE, + 0xdc => linux::KEY_BACKSLASH, + 0xdd => linux::KEY_RIGHTBRACE, + 0xde => linux::KEY_APOSTROPHE, + _ => return 0, + }; + code as u16 +} + +#[cfg(test)] +mod tests { + use super::vk_to_linux_key; + use input_linux_sys as linux; + + #[test] + fn qwerty_row_uses_evdev_physical_positions() { + let mapped: Vec = "QWERTYUIOP" + .bytes() + .map(|key| vk_to_linux_key(key.into())) + .collect(); + assert_eq!( + mapped, + [ + linux::KEY_Q, + linux::KEY_W, + linux::KEY_E, + linux::KEY_R, + linux::KEY_T, + linux::KEY_Y, + linux::KEY_U, + linux::KEY_I, + linux::KEY_O, + linux::KEY_P, + ] + .map(|code| code as u16) + ); + } + + #[test] + fn alphabet_is_not_assumed_contiguous() { + let mapped: Vec = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + .bytes() + .map(|key| vk_to_linux_key(key.into())) + .collect(); + assert_eq!( + mapped, + [ + linux::KEY_A, + linux::KEY_B, + linux::KEY_C, + linux::KEY_D, + linux::KEY_E, + linux::KEY_F, + linux::KEY_G, + linux::KEY_H, + linux::KEY_I, + linux::KEY_J, + linux::KEY_K, + linux::KEY_L, + linux::KEY_M, + linux::KEY_N, + linux::KEY_O, + linux::KEY_P, + linux::KEY_Q, + linux::KEY_R, + linux::KEY_S, + linux::KEY_T, + linux::KEY_U, + linux::KEY_V, + linux::KEY_W, + linux::KEY_X, + linux::KEY_Y, + linux::KEY_Z, + ] + .map(|code| code as u16) + ); + } + + #[test] + fn non_contiguous_function_keys_and_extended_modifiers_are_preserved() { + assert_eq!(vk_to_linux_key(0x7a), linux::KEY_F11 as u16); + assert_eq!(vk_to_linux_key(0x7b), linux::KEY_F12 as u16); + assert_eq!(vk_to_linux_key(0x111), linux::KEY_RIGHTCTRL as u16); + assert_eq!(vk_to_linux_key(0x112), linux::KEY_RIGHTALT as u16); + assert_eq!(vk_to_linux_key(0x10d), linux::KEY_KPENTER as u16); + } +} diff --git a/src/input/xtest.rs b/src/input/xtest.rs new file mode 100644 index 0000000..3349869 --- /dev/null +++ b/src/input/xtest.rs @@ -0,0 +1,218 @@ +use anyhow::{Context, Result}; +use std::collections::HashSet; +use x11rb::connection::Connection; +use x11rb::protocol::xproto::{ConnectionExt, Keycode}; +use x11rb::protocol::xtest::ConnectionExt as XtestExt; +use x11rb::rust_connection::RustConnection; + +use super::InputBackend; + +const FAKE_KEY_PRESS: u8 = 2; +const FAKE_KEY_RELEASE: u8 = 3; +const FAKE_BUTTON_PRESS: u8 = 4; +const FAKE_BUTTON_RELEASE: u8 = 5; +const FAKE_MOTION: u8 = 6; +/// XTEST detail for motion: 0 = absolute, 1 = relative. +const MOTION_RELATIVE: u8 = 1; + +/// 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. +pub struct XtestBackend { + conn: RustConnection, + screen: usize, + held_keys: HashSet, + held_buttons: HashSet, +} + +impl XtestBackend { + pub fn connect() -> Result { + let (conn, screen) = x11rb::connect(None).context("connecting to X display")?; + Ok(Self { + conn, + screen, + held_keys: HashSet::new(), + held_buttons: HashSet::new(), + }) + } + + fn root(&self) -> x11rb::protocol::xproto::Window { + self.conn.setup().roots[self.screen].root + } + + fn screen_size(&self) -> (i16, i16) { + let root = &self.conn.setup().roots[self.screen]; + (root.width_in_pixels as i16, root.height_in_pixels as i16) + } + + fn fake(&self, kind: u8, detail: u8, x: i16, y: i16) -> Result<()> { + self.conn + .xtest_fake_input(kind, detail, 0, self.root(), x, y, 0) + .context("XTestFakeInput")?; + self.conn.flush()?; + Ok(()) + } +} + +impl InputBackend for XtestBackend { + fn name(&self) -> &'static str { + "xtest" + } + + fn key(&mut self, vkey: u16, down: bool) -> Result<()> { + let keycode = self.vkey_to_keycode(vkey)?; + self.fake( + if down { + FAKE_KEY_PRESS + } else { + FAKE_KEY_RELEASE + }, + keycode, + 0, + 0, + )?; + if down { + self.held_keys.insert(keycode); + } else { + self.held_keys.remove(&keycode); + } + Ok(()) + } + + fn button(&mut self, button: u16, down: bool) -> Result<()> { + // Windows and X11 agree on 1-based button numbering. + self.fake( + if down { + FAKE_BUTTON_PRESS + } else { + FAKE_BUTTON_RELEASE + }, + button as u8, + 0, + 0, + )?; + if down { + self.held_buttons.insert(button as u8); + } else { + self.held_buttons.remove(&(button as u8)); + } + Ok(()) + } + + fn motion(&mut self, absolute: bool, x: i32, y: i32) -> Result<()> { + if absolute { + let (width, height) = self.screen_size(); + let clamped_x = ((x.clamp(0, 65535) as i64 * (width as i64 - 1)) / 65535) as i16; + let clamped_y = ((y.clamp(0, 65535) as i64 * (height as i64 - 1)) / 65535) as i16; + self.fake(FAKE_MOTION, 0, clamped_x, clamped_y)?; + } else { + self.fake(FAKE_MOTION, MOTION_RELATIVE, x as i16, y as i16)?; + } + Ok(()) + } + + fn wheel(&mut self, horizontal: bool, delta: i32) -> Result<()> { + // X11 has no wheel concept: synthesize button 4/5 (vertical) and + // 6/7 (horizontal) presses, one per notch. + let (up_button, down_button) = if horizontal { (7u8, 6u8) } else { (4u8, 5u8) }; + let steps = super::wheel_steps(delta); + for _ in 0..steps.unsigned_abs() { + let button = if steps > 0 { up_button } else { down_button }; + self.fake(FAKE_BUTTON_PRESS, button, 0, 0)?; + self.fake(FAKE_BUTTON_RELEASE, button, 0, 0)?; + } + Ok(()) + } + + fn release_all(&mut self) -> Result<()> { + for keycode in self.held_keys.clone() { + self.fake(FAKE_KEY_RELEASE, keycode, 0, 0)?; + } + self.held_keys.clear(); + for button in self.held_buttons.clone() { + self.fake(FAKE_BUTTON_RELEASE, button, 0, 0)?; + } + self.held_buttons.clear(); + self.conn.flush()?; + Ok(()) + } +} + +impl XtestBackend { + /// Map a Windows virtual-key code onto this server's keymap via the + /// invariant keysym subset. Layout-aware remapping for non-representable + /// keys is Phase 2 together with the semantic text path. + fn vkey_to_keycode(&self, vkey: u16) -> Result { + let base = (vkey & 0xff) as u32; + + let keysym: u32 = match base { + 0x08 => 0xff08, // BackSpace + 0x09 => 0xff09, // Tab + 0x0d => 0xff0d, // Return + 0x13 => 0xff13, // Pause + 0x14 => 0xffe5, // Caps Lock + 0x1b => 0xff1b, // Escape + 0x20 => 0x0020, // Space + 0x21 => 0xff55, // Prior + 0x22 => 0xff56, // Next + 0x23 => 0xff57, // End + 0x24 => 0xff50, // Home + 0x25 => 0xff51, // Left + 0x26 => 0xff52, // Up + 0x27 => 0xff53, // Right + 0x28 => 0xff54, // Down + 0x2d => 0xffff, // Insert + 0x2e => 0xff9f, // Delete (keypad-style) + 0x30..=0x39 => base, // 0-9 + 0x41..=0x5a => base + 0x20, // A-Z -> lowercase keysyms + 0x60..=0x69 => 0xffb0 + (base - 0x60), // KP_0..KP_9 + 0x6a => 0xffaa, // KP multiply + 0x6b => 0xffab, // KP add + 0x6d => 0xffad, // KP subtract + 0x6e => 0xffae, // KP decimal + 0x6f => 0xffaf, // KP divide + 0x70..=0x87 => 0xffbe + (base - 0x70), // F1..F24 + 0xa0 => 0xffe1, // Shift L + 0xa1 => 0xffe2, // Shift R + 0xa2 => 0xffe3, // Control L + 0xa3 => 0xffe4, // Control R + 0xa4 => 0xffe9, // Alt L + 0xa5 => 0xffea, // Alt R + 0x5b => 0xffeb, // Meta L + 0x5c => 0xffec, // Meta R + 0xba => 0x3b, // ; + 0xbb => 0x3d, // = + 0xbc => 0x2c, // , + 0xbd => 0x2d, // - + 0xbe => 0x2e, // . + 0xbf => 0x2f, // / + 0xc0 => 0x60, // ` + 0xdb => 0x5b, // [ + 0xdc => 0x5c, // backslash + 0xdd => 0x5d, // ] + 0xde => 0x27, // ' + _ => 0, + }; + + let setup = self.conn.setup(); + let min = setup.min_keycode; + let max = setup.max_keycode; + let map = self + .conn + .get_keyboard_mapping(min, max - min + 1)? + .reply()?; + + if keysym != 0 { + let per = map.keysyms_per_keycode.max(1) as usize; + for (index, chunk) in map.keysyms.chunks(per).enumerate() { + if chunk.contains(&keysym) { + return Ok(min + index as Keycode); + } + } + } + + // Layout does not represent this key: nearest identity fallback + // keeps events flowing instead of dropping them silently. + Ok(base as Keycode) + } +} diff --git a/src/launcher.rs b/src/launcher.rs new file mode 100644 index 0000000..4e3eda6 --- /dev/null +++ b/src/launcher.rs @@ -0,0 +1,308 @@ +//! XDG desktop application bridge for UU's Windows quick-launch scanner. + +use anyhow::{Context, Result}; +use std::collections::BTreeMap; +use std::fs::{File, OpenOptions}; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Arc; + +const MAGIC: u32 = 0x5555_4c41; +const TOKEN_BYTES: usize = 64; +const MAX_APPS: usize = 128; + +#[derive(Clone)] +struct DesktopApp { + id: String, + name: String, + path: PathBuf, +} + +pub fn prepare(prefix: &Path, proxy: &Path) -> Result { + let apps = catalog(); + let root = prefix.join("drive_c/uur-linux-apps"); + if root.exists() { + std::fs::remove_dir_all(&root).context("replacing Linux quick-launch staging")?; + } + std::fs::create_dir_all(&root)?; + + let old_keys = std::fs::read_to_string(root.with_extension("keys")).unwrap_or_default(); + let mut registry = String::from("Windows Registry Editor Version 5.00\r\n\r\n"); + for key in old_keys.lines().filter(|key| !key.is_empty()) { + registry.push_str(&format!("[-HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{key}]\r\n\r\n")); + } + + let mut keys = Vec::new(); + for app in apps.values().take(MAX_APPS) { + let hash = fnv1a(app.id.as_bytes()); + let key = format!("UURLinux_{hash:016x}"); + let directory = root.join(format!("{hash:016x}")); + std::fs::create_dir_all(&directory)?; + std::fs::copy(proxy, directory.join("launcher.exe"))?; + std::fs::write(directory.join("app-id.txt"), format!("{}\n", app.id))?; + let windows_directory = format!(r"C:\uur-linux-apps\{hash:016x}"); + let executable = format!(r"{windows_directory}\launcher.exe"); + registry.push_str(&format!( + "[HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{key}]\r\n\ + \"DisplayName\"=\"{}\"\r\n\ + \"DisplayVersion\"=\"1\"\r\n\ + \"Publisher\"=\"Linux desktop\"\r\n\ + \"InstallLocation\"=\"{}\"\r\n\ + \"InstallSource\"=\"XDG Desktop Entry\"\r\n\ + \"DisplayIcon\"=\"{}\"\r\n\ + \"UninstallString\"=\"{}\"\r\n\ + \"NoModify\"=dword:00000001\r\n\ + \"NoRepair\"=dword:00000001\r\n\r\n", + reg_escape(&app.name), + reg_escape(&windows_directory), + reg_escape(&executable), + reg_escape(&executable), + )); + keys.push(key); + } + 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(®istry_path, ®istry)?; + let status = Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", "-all") + .args(["reg", "import"]) + .arg(®istry_path) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .context("importing Linux quick-launch applications")?; + if !status.success() { + anyhow::bail!("Wine rejected the Linux quick-launch registry"); + } + Ok(keys.len()) +} + +pub fn serve() -> Result<()> { + let prefix = crate::config::data_dir()?.join("wine"); + let config_path = runtime_config(&prefix); + let apps = Arc::new(catalog()); + let token = random_token()?; + let listener = TcpListener::bind(("127.0.0.1", 0))?; + write_config(&config_path, listener.local_addr()?.port(), &token)?; + println!( + "native quick-launch service ready with {} applications", + apps.len() + ); + for stream in listener.incoming().flatten() { + let apps = apps.clone(); + let token = token.clone(); + std::thread::spawn(move || { + if let Err(error) = handle(stream, &token, &apps) { + eprintln!("quick-launch request failed: {error:#}"); + } + }); + } + Ok(()) +} + +pub fn runtime_config(prefix: &Path) -> PathBuf { + prefix.join("drive_c/uur-launcher.runtime") +} + +fn handle( + mut stream: TcpStream, + expected_token: &str, + apps: &BTreeMap, +) -> Result<()> { + let mut header = [0u8; 12]; + stream.read_exact(&mut header)?; + let magic = u32::from_be_bytes(header[0..4].try_into().unwrap()); + let version = u16::from_be_bytes(header[4..6].try_into().unwrap()); + let token_length = u16::from_be_bytes(header[6..8].try_into().unwrap()) as usize; + let id_length = u16::from_be_bytes(header[8..10].try_into().unwrap()) as usize; + if magic != MAGIC + || version != 1 + || token_length != TOKEN_BYTES + || id_length == 0 + || id_length > 500 + { + anyhow::bail!("invalid quick-launch handshake"); + } + let mut token = [0u8; TOKEN_BYTES]; + stream.read_exact(&mut token)?; + if !constant_time_equal(&token, expected_token.as_bytes()) { + anyhow::bail!("quick-launch authentication failed"); + } + let mut id = vec![0u8; id_length]; + stream.read_exact(&mut id)?; + let id = std::str::from_utf8(&id)?; + let accepted = apps.get(id).is_some_and(launch); + stream.write_all(&[accepted as u8])?; + Ok(()) +} + +fn launch(app: &DesktopApp) -> bool { + let gio = Command::new("gio") + .arg("launch") + .arg(&app.path) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn(); + if gio.is_ok() { + return true; + } + Command::new("gtk-launch") + .arg(app.id.trim_end_matches(".desktop")) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn() + .is_ok() +} + +fn catalog() -> BTreeMap { + let mut apps = BTreeMap::new(); + for directory in data_directories() { + collect_desktop_entries(&directory.join("applications"), &mut apps); + } + apps +} + +fn data_directories() -> Vec { + let mut directories: Vec = std::env::var("XDG_DATA_DIRS") + .unwrap_or_else(|_| "/usr/local/share:/usr/share".into()) + .split(':') + .filter(|entry| !entry.is_empty()) + .map(PathBuf::from) + .collect(); + if let Some(user) = std::env::var_os("XDG_DATA_HOME") + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".local/share"))) + { + directories.push(user); + } + directories +} + +fn collect_desktop_entries(directory: &Path, apps: &mut BTreeMap) { + let Ok(entries) = std::fs::read_dir(directory) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + collect_desktop_entries(&path, apps); + continue; + } + if path.extension().and_then(|extension| extension.to_str()) != Some("desktop") + || path + .components() + .any(|component| component.as_os_str() == "wine") + { + continue; + } + let Some(id) = path + .file_name() + .and_then(|name| name.to_str()) + .map(str::to_string) + else { + continue; + }; + let Ok(content) = std::fs::read_to_string(&path) else { + continue; + }; + let mut in_desktop = false; + let mut kind = ""; + let mut name = None; + let mut hidden = false; + for line in content.lines() { + let line = line.trim(); + if line.starts_with('[') { + in_desktop = line == "[Desktop Entry]"; + continue; + } + if !in_desktop { + continue; + } + if let Some(value) = line.strip_prefix("Type=") { + kind = value; + } else if let Some(value) = line.strip_prefix("Name=") { + name = Some(value.trim().to_string()); + } else if line == "Hidden=true" || line == "NoDisplay=true" { + hidden = true; + } + } + if kind == "Application" && !hidden { + if let Some(name) = name.filter(|name| !name.is_empty()) { + apps.insert(id.clone(), DesktopApp { id, name, path }); + } + } + } +} + +fn write_config(path: &Path, port: u16, token: &str) -> Result<()> { + let mut file = OpenOptions::new() + .create(true) + .truncate(true) + .write(true) + .mode(0o600) + .open(path)?; + writeln!(file, "version=1")?; + writeln!(file, "port={port}")?; + writeln!(file, "token={token}")?; + file.sync_all()?; + Ok(()) +} + +fn random_token() -> Result { + let mut bytes = [0u8; 32]; + File::open("/dev/urandom")?.read_exact(&mut bytes)?; + Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect()) +} + +fn constant_time_equal(left: &[u8], right: &[u8]) -> bool { + if left.len() != right.len() { + return false; + } + left.iter() + .zip(right) + .fold(0u8, |difference, (left, right)| difference | (left ^ right)) + == 0 +} + +fn fnv1a(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf2_9ce4_8422_2325, |hash, byte| { + (hash ^ u64::from(*byte)).wrapping_mul(0x100_0000_01b3) + }) +} + +fn reg_escape(value: &str) -> String { + value.replace('\\', "\\\\").replace('"', "\\\"") +} + +fn write_utf16_registry(path: &Path, content: &str) -> Result<()> { + let mut bytes = vec![0xff, 0xfe]; + for unit in content.encode_utf16() { + bytes.extend_from_slice(&unit.to_le_bytes()); + } + std::fs::write(path, bytes)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::{fnv1a, reg_escape}; + + #[test] + fn registry_values_are_escaped() { + assert_eq!(reg_escape(r#"A\B"C"#), r#"A\\B\"C"#); + } + + #[test] + fn application_hash_is_stable() { + let first = fnv1a(b"org.example.App.desktop"); + assert_eq!(first, fnv1a(b"org.example.App.desktop")); + assert_ne!(first, fnv1a(b"org.example.Other.desktop")); + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..c73223a --- /dev/null +++ b/src/main.rs @@ -0,0 +1,211 @@ +#[macro_use] +extern crate rust_i18n; + +mod audio; +mod autostart; +mod bridge; +mod capture; +mod config; +mod doctor; +mod i18n; +mod inhibit; +mod input; +mod launcher; +mod protocol; +mod proxy; +mod session; +mod terminal; +mod upstream; +mod video; +mod wallpaper; +mod wine; +mod wol; + +use anyhow::Result; +use clap::{Parser, Subcommand, ValueEnum}; + +// Locale catalogs are embedded from `locales/` at the crate root. +i18n!("locales", fallback = "en"); + +/// Native Linux companion for NetEase UU Remote. +/// +/// uur runs the official Windows client inside a managed Wine prefix and +/// bridges its input and screen capture onto the real Linux desktop through +/// X11 XTest or the Wayland RemoteDesktop portal. +#[derive(Parser)] +#[command(name = "uur", version, about, arg_required_else_help = true)] +struct Cli { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand)] +enum Command { + /// One-time provisioning: EULA gate, Wine prefix, official client download. + Setup { + /// Accept the NetEase UU Remote EULA non-interactively. + #[arg(long)] + accept_eula: bool, + }, + /// Print the live environment report (sessions, wine, portals, backends). + Doctor, + /// Print the current X11 pointer position (verification helper). + Pointer, + /// Capture the desktop through the ScreenCast portal (video path). + Capture, + /// Start a full session: capture + bridge + the managed client. + Run, + /// Stop every uur-owned process and the managed Wine prefix. + Stop, + /// Manage optional XDG login autostart. + Autostart { + #[command(subcommand)] + action: AutostartAction, + }, + /// Inspect or configure host Wake-on-LAN. + Wol { + #[command(subcommand)] + action: WolAction, + }, + /// Select the portal capture source used on Wayland. + Display { + #[command(subcommand)] + action: DisplayAction, + }, + /// Internal input bridge process. Not part of the public CLI. + #[command(hide = true, name = "__bridge")] + InternalBridge, + /// Internal capture process. Not part of the public CLI. + #[command(hide = true, name = "__capture")] + InternalCapture, + /// Internal native PTY bridge. Not part of the public CLI. + #[command(hide = true, name = "__terminal")] + InternalTerminal, + /// Internal Linux wallpaper synchronizer. Not part of the public CLI. + #[command(hide = true, name = "__wallpaper")] + InternalWallpaper, + /// Internal desktop suspend/idle inhibitor. Not part of the public CLI. + #[command(hide = true, name = "__inhibit")] + InternalInhibit, + /// Internal authenticated XDG application launcher. + #[command(hide = true, name = "__launcher")] + InternalLauncher, + /// Query NetEase's official release feed. + Upstream { + #[command(subcommand)] + action: UpstreamAction, + }, +} + +#[derive(Subcommand)] +enum UpstreamAction { + /// Print the latest official UU Remote release known to NetEase. + Check, +} + +#[derive(Subcommand)] +enum AutostartAction { + /// Start the managed session after graphical login. + Enable, + /// Remove the login autostart entry. + Disable, + /// Report whether login autostart is enabled. + Status, +} + +#[derive(Subcommand)] +enum WolAction { + /// Report the selected physical wired adapter and Magic Packet state. + Status { + #[arg(long)] + interface: Option, + }, + /// Enable Magic Packet wake for the adapter and its NetworkManager profile. + Enable { + #[arg(long)] + interface: Option, + }, + /// Disable Magic Packet wake for the adapter and its NetworkManager profile. + Disable { + #[arg(long)] + interface: Option, + }, +} + +#[derive(Subcommand)] +enum DisplayAction { + /// Show the configured source type. + Status, + /// Use a monitor, one window, or a portal-provided virtual display. + Source { source: DisplaySource }, +} + +#[derive(Clone, ValueEnum)] +enum DisplaySource { + Monitor, + Window, + Virtual, +} + +impl DisplaySource { + fn as_str(&self) -> &'static str { + match self { + Self::Monitor => "monitor", + Self::Window => "window", + Self::Virtual => "virtual", + } + } +} + +fn main() -> Result<()> { + // CLI output is routinely piped; a closed pipe is not an error. + unsafe { + libc::signal(libc::SIGPIPE, libc::SIG_DFL); + } + i18n::init(); + let cli = Cli::parse(); + match cli.command { + Command::Setup { accept_eula } => wine::setup(accept_eula), + Command::Doctor => doctor::report(), + Command::Pointer => bridge::print_pointer(), + Command::Capture => capture::run(), + Command::Run => session::start(), + Command::Stop => session::stop(), + Command::Autostart { action } => match action { + AutostartAction::Enable => autostart::enable(), + AutostartAction::Disable => autostart::disable(), + AutostartAction::Status => autostart::status(), + }, + Command::Wol { action } => match action { + WolAction::Status { interface } => wol::status(interface.as_deref()), + WolAction::Enable { interface } => wol::configure(interface.as_deref(), true), + WolAction::Disable { interface } => wol::configure(interface.as_deref(), false), + }, + Command::Display { action } => { + let mut config = config::Config::load()?; + match action { + DisplayAction::Status => { + println!("{}", t!("display.status", source = config.capture_source)); + Ok(()) + } + DisplayAction::Source { source } => { + config.capture_source = source.as_str().to_string(); + config.capture_restore_token = None; + config.remote_desktop_restore_token = None; + config.store()?; + println!("{}", t!("display.changed", source = source.as_str())); + Ok(()) + } + } + } + Command::InternalBridge => bridge::serve(), + Command::InternalCapture => capture::run(), + Command::InternalTerminal => terminal::serve(), + Command::InternalWallpaper => wallpaper::serve(), + Command::InternalInhibit => inhibit::serve(), + Command::InternalLauncher => launcher::serve(), + Command::Upstream { + action: UpstreamAction::Check, + } => upstream::check(), + } +} diff --git a/src/protocol.rs b/src/protocol.rs new file mode 100644 index 0000000..8551119 --- /dev/null +++ b/src/protocol.rs @@ -0,0 +1,88 @@ +//! Wire protocol spoken between the in-client PE hook (`hook/`) and the host +//! bridge. Kept in one place so both sides stay in lock-step. + +pub const MAGIC: u32 = 0x50495555; // "UUIP" little-endian +pub const VERSION: u32 = 1; + +pub const RECORD_HELLO: u32 = 1; +pub const RECORD_MOUSE: u32 = 2; +pub const RECORD_KEYBOARD: u32 = 3; + +/// One input record. Fixed 16-byte payload after the 16-byte header keeps +/// parsing trivial on both sides. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Record { + pub kind: u32, + /// Keyboard: Windows virtual-key code (as sent by SendInput). + /// Mouse: button number for press/release, axis selector for motion. + pub code: u16, + /// Keyboard: 1 = key-down, 0 = key-up. + /// Mouse motion: 1 = absolute, 0 = relative. + pub state: u16, + pub a: i32, + pub b: i32, +} + +pub const HEADER_BYTES: usize = 16; +pub const RECORD_BYTES: usize = 16; + +#[derive(Debug)] +pub struct Header { + pub magic: u32, + pub version: u32, + pub kind: u32, + pub length: u32, +} + +pub fn read_header(buf: &[u8; HEADER_BYTES]) -> Header { + Header { + magic: u32::from_le_bytes(buf[0..4].try_into().unwrap()), + version: u32::from_le_bytes(buf[4..8].try_into().unwrap()), + kind: u32::from_le_bytes(buf[8..12].try_into().unwrap()), + length: u32::from_le_bytes(buf[12..16].try_into().unwrap()), + } +} + +pub fn read_record(buf: &[u8; RECORD_BYTES]) -> Record { + Record { + kind: u32::from_le_bytes(buf[0..4].try_into().unwrap()), + code: u16::from_le_bytes(buf[4..6].try_into().unwrap()), + state: u16::from_le_bytes(buf[6..8].try_into().unwrap()), + a: i32::from_le_bytes(buf[8..12].try_into().unwrap()), + b: i32::from_le_bytes(buf[12..16].try_into().unwrap()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn header_roundtrip() { + let mut buf = [0u8; HEADER_BYTES]; + buf[0..4].copy_from_slice(&MAGIC.to_le_bytes()); + buf[4..8].copy_from_slice(&VERSION.to_le_bytes()); + buf[8..12].copy_from_slice(&RECORD_MOUSE.to_le_bytes()); + buf[12..16].copy_from_slice(&16u32.to_le_bytes()); + let header = read_header(&buf); + assert_eq!(header.magic, MAGIC); + assert_eq!(header.kind, RECORD_MOUSE); + assert_eq!(header.length, 16); + } + + #[test] + fn record_roundtrip() { + let mut buf = [0u8; RECORD_BYTES]; + buf[0..4].copy_from_slice(&RECORD_KEYBOARD.to_le_bytes()); + buf[4..6].copy_from_slice(&0x41u16.to_le_bytes()); + buf[6..8].copy_from_slice(&1u16.to_le_bytes()); + buf[8..12].copy_from_slice(&(-5i32).to_le_bytes()); + buf[12..16].copy_from_slice(&(7i32).to_le_bytes()); + let record = read_record(&buf); + assert_eq!(record.kind, RECORD_KEYBOARD); + assert_eq!(record.code, 0x41); + assert_eq!(record.state, 1); + assert_eq!(record.a, -5); + assert_eq!(record.b, 7); + } +} diff --git a/src/proxy.rs b/src/proxy.rs new file mode 100644 index 0000000..8688046 --- /dev/null +++ b/src/proxy.rs @@ -0,0 +1,104 @@ +//! Import standard Linux proxy environment into Wine's WinINet settings. + +use anyhow::{Context, Result}; +use std::path::Path; +use std::process::{Command, Stdio}; + +pub fn sync(prefix: &Path) -> Result> { + let http = environment_proxy("HTTP_PROXY", "http_proxy"); + let https = environment_proxy("HTTPS_PROXY", "https_proxy"); + if http.is_none() && https.is_none() { + return Ok(None); + } + let mut entries = Vec::new(); + if let Some(endpoint) = http { + entries.push(format!("http={endpoint}")); + } + if let Some(endpoint) = https { + entries.push(format!("https={endpoint}")); + } + let server = entries.join(";"); + reg_add(prefix, "ProxyEnable", "REG_DWORD", "1")?; + reg_add(prefix, "ProxyServer", "REG_SZ", &server)?; + if let Some(no_proxy) = std::env::var("NO_PROXY") + .ok() + .or_else(|| std::env::var("no_proxy").ok()) + { + let bypass = no_proxy + .split(',') + .map(str::trim) + .filter(|entry| !entry.is_empty()) + .collect::>() + .join(";"); + if !bypass.is_empty() { + reg_add(prefix, "ProxyOverride", "REG_SZ", &bypass)?; + } + } + Ok(Some(server)) +} + +fn environment_proxy(upper: &str, lower: &str) -> Option { + std::env::var(upper) + .ok() + .or_else(|| std::env::var(lower).ok()) + .and_then(|value| proxy_endpoint(&value)) +} + +fn proxy_endpoint(value: &str) -> Option { + let value = value.trim(); + let authority = value + .split_once("://") + .map(|(_, rest)| rest) + .unwrap_or(value) + .split('/') + .next()?; + let endpoint = authority + .rsplit_once('@') + .map(|(_, host)| host) + .unwrap_or(authority); + (!endpoint.is_empty()).then(|| endpoint.to_string()) +} + +fn reg_add(prefix: &Path, value: &str, kind: &str, data: &str) -> Result<()> { + let status = Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", "-all") + .args([ + "reg", + "add", + r"HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings", + "/v", + value, + "/t", + kind, + "/d", + data, + "/f", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .with_context(|| format!("writing WinINet proxy value {value}"))?; + if !status.success() { + anyhow::bail!("Wine rejected WinINet proxy value {value}"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::proxy_endpoint; + + #[test] + fn proxy_url_is_reduced_without_leaking_credentials() { + assert_eq!( + proxy_endpoint("http://user:secret@127.0.0.1:7890/path"), + Some("127.0.0.1:7890".into()) + ); + assert_eq!( + proxy_endpoint("proxy.local:8080"), + Some("proxy.local:8080".into()) + ); + } +} diff --git a/src/session.rs b/src/session.rs new file mode 100644 index 0000000..52b6a23 --- /dev/null +++ b/src/session.rs @@ -0,0 +1,740 @@ +//! Session orchestration: one command starts everything for a remote +//! session — desktop capture (portal, silent after first consent), the +//! input bridge, and the managed UU client. When the client exits, the +//! session ends. + +use anyhow::{Context, Result}; +use std::io::{Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::thread; + +use crate::config::{data_dir, Config}; + +fn rotate_session_log() { + let state = std::env::var("XDG_STATE_HOME") + .map(PathBuf::from) + .or_else(|_| std::env::var("HOME").map(|h| PathBuf::from(h).join(".local/state"))) + .unwrap_or_else(|_| PathBuf::from("/tmp")); + let _ = std::fs::create_dir_all(state.join("uur")); + let _ = std::fs::rename( + state.join("uur/session.log"), + state.join("uur/session.log.1"), + ); +} + +/// Locate the packaged hook DLLs. Packaged installs use /usr/lib/uur/hook; +/// a dev checkout falls back to build/hook next to the sources. +const HOOK_COMPONENTS: &[&str] = &[ + "winlogon.exe", + "wevtapi.dll", + "uur-hook.dll", + "wtsapi32.dll", + "uur-terminal-proxy.exe", + "uur-mux-proxy.exe", + "uur-launch-proxy.exe", +]; + +fn complete_hook_directory(dir: &Path) -> bool { + HOOK_COMPONENTS + .iter() + .all(|component| dir.join(component).is_file()) +} + +fn hook_dir() -> Result { + let mut candidates = vec![ + PathBuf::from("/usr/lib/uur/hook"), + PathBuf::from("/usr/local/lib/uur/hook"), + ]; + if let Ok(home) = std::env::var("HOME") { + candidates.push(PathBuf::from(home).join(".local/lib/uur/hook")); + } + if let Ok(exe) = std::env::current_exe() { + if let Some(dir) = exe.parent() { + candidates.push(dir.join("../lib/uur/hook")); + candidates.push(dir.join("../../build/hook")); + candidates.push(dir.to_path_buf()); + } + } + candidates + .into_iter() + .find(|dir| complete_hook_directory(dir)) + .context("complete hook runtime not found (run the build first)") +} + +fn hook_source_dir() -> Result { + let mut candidates = vec![PathBuf::from("/usr/lib/uur/hook")]; + if let Ok(home) = std::env::var("HOME") { + candidates.push(PathBuf::from(home).join(".local/lib/uur/hook")); + } + candidates.push( + std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|d| d.join("../lib/uur/hook"))) + .unwrap_or_default(), + ); + candidates.push( + std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|d| d.join("../../build/hook"))) + .unwrap_or_default(), + ); + candidates.push( + std::env::current_dir() + .ok() + .map(|dir| dir.join("build/hook")) + .unwrap_or_default(), + ); + candidates + .into_iter() + .find(|dir| complete_hook_directory(dir)) + .context("hook DLLs not found (run the build first)") +} + +/// Install the native preload DLLs in the managed prefix, outside the +/// proprietary application directory. Wine's native override resolves them +/// from system32, so client updates never overwrite uur and uur never edits an +/// official executable or DLL. +fn deploy_hooks(prefix: &Path) -> Result<()> { + let source = hook_source_dir()?; + let target = prefix.join("drive_c/windows/system32"); + std::fs::create_dir_all(&target)?; + for dll in ["wevtapi.dll", "uur-hook.dll", "wtsapi32.dll"] { + let from = source.join(dll); + let to = target.join(dll); + std::fs::copy(&from, &to) + .with_context(|| format!("deploying {} to {}", dll, target.display()))?; + } + Ok(()) +} + +/// Replace UU's Windows ConPTY transport at its documented command-line ABI. +/// The adapter receives UU's inherited stdin/stdout handles and forwards them +/// to the native Linux PTY service. The official binary is retained for +/// recovery, and an obsolete powershell-level adapter is removed on upgrade. +fn deploy_terminal_proxy(install_dir: &Path) -> Result { + let source_dir = hook_source_dir()?; + let source = source_dir.join("uur-terminal-proxy.exe"); + let mux_source = source_dir.join("uur-mux-proxy.exe"); + let bin = install_dir.join("bin"); + std::fs::create_dir_all(&bin)?; + for status in ["uur-terminal-adapter.status", "uur-mux-adapter.status"] { + let _ = std::fs::remove_file(bin.join(status)); + } + if let Ok(entries) = std::fs::read_dir(&bin) { + for entry in entries.flatten() { + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name.starts_with("uur-terminal-session-") && name.ends_with(".active") { + let _ = std::fs::remove_file(entry.path()); + } + } + } + + let legacy_target = bin.join("powershell.exe"); + let legacy_backup = bin.join("powershell.exe.uur-original"); + let legacy_marker = bin.join("powershell.exe.uur-managed"); + if legacy_marker.exists() { + let _ = std::fs::remove_file(&legacy_target); + if legacy_backup.exists() { + std::fs::rename(&legacy_backup, &legacy_target) + .with_context(|| format!("restoring {}", legacy_target.display()))?; + } + let _ = std::fs::remove_file(&legacy_marker); + } + + let target = bin.join("conpty_bridge.exe"); + let backup = bin.join("conpty_bridge.exe.uur-original"); + let marker = bin.join("conpty_bridge.exe.uur-managed"); + if target.exists() && !marker.exists() && !backup.exists() { + std::fs::copy(&target, &backup) + .with_context(|| format!("backing up {}", target.display()))?; + } + std::fs::copy(&source, &target) + .with_context(|| format!("deploying native terminal proxy to {}", target.display()))?; + std::fs::write(marker, b"managed by uur\n")?; + + let mux_target = bin.join("uuyc-mux.exe"); + let mux_backup = bin.join("uuyc-mux.exe.uur-original"); + let mux_marker = bin.join("uuyc-mux.exe.uur-managed"); + if mux_target.exists() && !mux_marker.exists() && !mux_backup.exists() { + std::fs::copy(&mux_target, &mux_backup) + .with_context(|| format!("backing up {}", mux_target.display()))?; + } + std::fs::copy(&mux_source, &mux_target) + .with_context(|| format!("deploying native mux proxy to {}", mux_target.display()))?; + std::fs::write(mux_marker, b"managed by uur\n")?; + Ok(bin.join("uu-terminal-bridge.runtime")) +} + +/// The client UI needs the Evergreen WebView2 runtime; the official +/// bootstrapper ships inside the client's bin directory. +fn ensure_webview2(prefix: &Path, install_dir: &Path) -> Result<()> { + let marker = prefix.join("drive_c/Program Files (x86)/Microsoft/EdgeWebView/Application"); + if marker.exists() { + return Ok(()); + } + let bootstrapper = install_dir + .join("bin") + .join("MicrosoftEdgeWebview2Setup.exe"); + if !bootstrapper.is_file() { + anyhow::bail!("{}", t!("session.webview_missing")); + } + println!("{}", t!("session.installing_webview")); + let status = Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", wine_debug()) + .arg(bootstrapper.to_string_lossy().as_ref()) + .args(["/silent", "/install"]) + .status() + .context("running the WebView2 bootstrapper")?; + if !status.success() { + anyhow::bail!("{}", t!("session.webview_failed")); + } + Ok(()) +} + +/// Single-instance guard: an flock held for the lifetime of the session. +/// A second click on the launcher exits with a clear message instead of +/// fighting over the bridge port. +fn acquire_session_lock() -> Result { + use std::os::unix::io::AsRawFd; + let state = std::env::var("XDG_STATE_HOME") + .map(PathBuf::from) + .or_else(|_| std::env::var("HOME").map(|h| PathBuf::from(h).join(".local/state"))) + .unwrap_or_else(|_| PathBuf::from("/tmp")); + let dir = state.join("uur"); + std::fs::create_dir_all(&dir).context("creating state directory")?; + let file = std::fs::OpenOptions::new() + .create(true) + .truncate(false) + .write(true) + .open(dir.join("session.lock")) + .context("opening session.lock")?; + let rc = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }; + if rc != 0 { + anyhow::bail!("{}", t!("session.already_running")); + } + let mut file = file; + file.set_len(0)?; + writeln!( + file, + "{} {}", + std::process::id(), + process_start_time(std::process::id())? + )?; + file.sync_data()?; + Ok(file) +} + +struct ManagedChild { + child: Child, + terminated: bool, +} + +impl ManagedChild { + fn spawn_internal(argument: &str, log: &std::fs::File) -> Result { + use std::os::unix::process::CommandExt; + + let executable = std::env::current_exe().context("resolving uur executable")?; + let mut command = Command::new(executable); + command + .arg(argument) + .stdin(Stdio::null()) + .stdout(Stdio::from(log.try_clone()?)) + .stderr(Stdio::from(log.try_clone()?)) + .process_group(0); + let child = command + .spawn() + .with_context(|| format!("starting internal helper {argument}"))?; + Ok(Self { + child, + terminated: false, + }) + } + + fn terminate(&mut self) { + if self.terminated { + return; + } + self.terminated = true; + let group = -(self.child.id() as i32); + unsafe { + libc::kill(group, libc::SIGTERM); + } + for _ in 0..20 { + if self.child.try_wait().ok().flatten().is_some() { + return; + } + thread::sleep(std::time::Duration::from_millis(50)); + } + unsafe { + libc::kill(group, libc::SIGKILL); + } + let _ = self.child.wait(); + } +} + +impl Drop for ManagedChild { + fn drop(&mut self) { + self.terminate(); + } +} + +struct SessionResources { + prefix: PathBuf, + helpers: Vec, + cleanup_files: Vec, + cleaned: bool, +} + +impl SessionResources { + fn new(prefix: PathBuf) -> Self { + Self { + prefix, + helpers: Vec::new(), + cleanup_files: Vec::new(), + cleaned: false, + } + } + + fn shutdown(&mut self) { + if self.cleaned { + return; + } + self.cleaned = true; + for helper in self.helpers.iter_mut().rev() { + helper.terminate(); + } + self.helpers.clear(); + for path in self.cleanup_files.drain(..) { + let _ = std::fs::remove_file(path); + } + stop_wineserver(&self.prefix); + if let Ok(path) = frame_path() { + let _ = std::fs::remove_file(path); + } + } +} + +impl Drop for SessionResources { + fn drop(&mut self) { + self.shutdown(); + } +} + +/// Start everything and block until the client exits. +pub fn start() -> Result<()> { + let _session_lock = acquire_session_lock()?; + rotate_session_log(); + let config = Config::load()?; + let prefix = data_dir()?.join("wine"); + let install_dir = crate::wine::find_client_dir(&prefix) + .context("client not provisioned; run `uur setup` first")?; + deploy_hooks(&prefix)?; + crate::wine::set_dll_override(&prefix, "wtsapi32", "native")?; + // Re-apply migrations on every launch so an updated uur package repairs + // an existing prefix without requiring destructive reprovisioning. + crate::wine::apply_registry_compat(&prefix)?; + if let Some(proxy) = crate::proxy::sync(&prefix)? { + println!("WinINet proxy synchronized: {proxy}"); + } + let audio = crate::audio::sync_wine(&prefix)?; + println!("{}", t!("session.audio_backend", backend = audio.label())); + + // Bridge configuration as a file inside the prefix: any process the + // Wine service manager respawns reads it, env or not. + let frames = frame_path()?; + let backend_status = crate::config::runtime_dir()?.join("backend"); + let _ = std::fs::remove_file(&backend_status); + std::env::set_var("UUR_FRAME_PATH", &frames); + std::env::set_var("UUR_BACKEND_STATUS", &backend_status); + std::fs::write( + prefix.join("drive_c/uur-bridge.ini"), + format!( + "[bridge]\nport={}\ntoken={}\nframe_path={}\n", + config.bridge_port, + config.bridge_token, + unix_path_to_wine(&frames) + ), + ) + .context("writing uur-bridge.ini")?; + + let terminal_config = deploy_terminal_proxy(&install_dir)?; + let launch_proxy = hook_source_dir()?.join("uur-launch-proxy.exe"); + let application_count = crate::launcher::prepare(&prefix, &launch_proxy)?; + println!( + "{}", + t!("session.quick_launch_ready", count = application_count) + ); + // Keep the start-menu entry pointing at the full session even if the + // installer or an update regenerated it meanwhile. + let _ = crate::wine::adopt_shortcut( + &prefix, + &std::env::current_exe().unwrap_or_else(|_| PathBuf::from("uur")), + ); + ensure_webview2(&prefix, &install_dir)?; + + let stopping = Arc::new(AtomicBool::new(false)); + signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?; + signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?; + signal_hook::flag::register(signal_hook::consts::SIGHUP, stopping.clone())?; + + let log = open_session_log()?; + let mut resources = SessionResources::new(prefix.clone()); + let _ = std::fs::remove_file(&terminal_config); + std::env::set_var("UUR_TERMINAL_CONFIG", &terminal_config); + resources.cleanup_files.push(terminal_config.clone()); + resources + .helpers + .push(ManagedChild::spawn_internal("__terminal", &log)?); + wait_for_runtime_file(&terminal_config, &stopping)?; + let launcher_config = crate::launcher::runtime_config(&prefix); + let _ = std::fs::remove_file(&launcher_config); + resources.cleanup_files.push(launcher_config.clone()); + resources + .helpers + .push(ManagedChild::spawn_internal("__launcher", &log)?); + wait_for_runtime_file(&launcher_config, &stopping)?; + resources + .helpers + .push(ManagedChild::spawn_internal("__wallpaper", &log)?); + match ManagedChild::spawn_internal("__inhibit", &log) { + Ok(helper) => resources.helpers.push(helper), + Err(error) => eprintln!("desktop inhibition unavailable: {error}"), + } + resources + .helpers + .push(ManagedChild::spawn_internal("__bridge", &log)?); + wait_for_bridge(config.bridge_port, &stopping)?; + let selected_backend = std::fs::read_to_string(&backend_status).unwrap_or_default(); + let _ = std::fs::remove_file(&backend_status); + if std::env::var_os("WAYLAND_DISPLAY").is_some() && selected_backend.trim() != "portal" { + resources + .helpers + .push(ManagedChild::spawn_internal("__capture", &log)?); + } + + // The service enumerates processes for a winlogon session token source + // before it initialises; under plain Wine none exists. A sleeping + // process with that name satisfies the check. + let marker = hook_dir()?.join("winlogon.exe"); + let _ = Command::new("wine") + .env("WINEPREFIX", &prefix) + .env("WINEDEBUG", wine_debug()) + .env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n") + .env("UUR_HOOK_LOG", log_path()?) + .env("UUR_BRIDGE_PORT", config.bridge_port.to_string()) + .env("UUR_BRIDGE_TOKEN", config.bridge_token.clone()) + .stdout(Stdio::from(log.try_clone()?)) + .stderr(Stdio::from(log.try_clone()?)) + .arg(marker.to_string_lossy().as_ref()) + .spawn(); + + // The launcher talks to the service through the Windows Service Control + // Manager, so the service must be started through `sc start` — a + // directly spawned --service process is invisible to it and the UI + // waits forever. + if !service_running(&prefix) { + let _ = Command::new("wine") + .env("WINEPREFIX", &prefix) + .env("WINEDEBUG", wine_debug()) + .stdout(Stdio::from(log.try_clone()?)) + .stderr(Stdio::from(log.try_clone()?)) + .args(["sc", "start", "GameViewerService"]) + .status(); + } + for _ in 0..150 { + if service_running(&prefix) { + break; + } + thread::sleep(std::time::Duration::from_millis(200)); + } + + println!("{}", t!("session.launching_client")); + let ui = install_dir.join("GameViewer.exe"); + let launch = || -> Result { + Command::new("wine") + .env("WINEPREFIX", &prefix) + .env("WINEDEBUG", wine_debug()) + .current_dir(&install_dir) + .env("WINEDLLOVERRIDES", "wevtapi=n,wtsapi32=n") + .env("UUR_HOOK_LOG", log_path().unwrap_or_default()) + .env("UUR_BRIDGE_PORT", config.bridge_port.to_string()) + .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") + }; + + // Start the client detached: it IS the session's lifetime anchor. + let mut client = launch()?; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(45); + let mut seen_client = false; + let mut missing_checks = 0u8; + let mut relaunches = 0; + while !stopping.load(Ordering::Relaxed) { + let running = wine_client_process_exists(&prefix); + if running { + seen_client = true; + missing_checks = 0; + } else if seen_client { + missing_checks = missing_checks.saturating_add(1); + // UU hands off between short-lived launchers and its real Qt + // process. Require a sustained absence before treating it as a + // user-requested exit. + if missing_checks >= 6 { + break; + } + } + if !seen_client && std::time::Instant::now() >= deadline { + anyhow::bail!("UU Remote did not create its client process within 45 seconds"); + } + if !seen_client && client.try_wait()?.is_some() && relaunches < 2 { + relaunches += 1; + thread::sleep(std::time::Duration::from_secs(2)); + client = launch()?; + } + thread::sleep(std::time::Duration::from_millis(500)); + } + + println!("{}", t!("session.client_exited", code = 0)); + + resources.shutdown(); + Ok(()) +} + +/// Query the Windows process table belonging to this exact Wine prefix. +/// Modern Wine may host a Windows process in a Linux process whose `/proc` +/// cmdline names another image, so Linux process-name matching is not a valid +/// lifecycle boundary. +fn wine_client_process_exists(prefix: &Path) -> bool { + let output = run_with_timeout( + Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", wine_debug()) + .args([ + "tasklist", + "/NH", + "/FO", + "CSV", + "/FI", + "IMAGENAME eq GameViewer.exe", + ]), + std::time::Duration::from_secs(5), + ); + output.is_some_and(|text| tasklist_contains_image(&text, "GameViewer.exe")) +} + +/// Run a command with a hard timeout, returning its stdout (None on +/// timeout or failure). `wine sc query` has been observed to hang +/// indefinitely against a freshly booted wineserver; without a deadline +/// the whole session startup would block forever. +fn run_with_timeout(command: &mut Command, timeout: std::time::Duration) -> Option { + use std::process::Stdio; + + let mut child = command + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let deadline = std::time::Instant::now() + timeout; + loop { + match child.try_wait() { + Ok(Some(_)) => break, + Ok(None) => { + if std::time::Instant::now() >= deadline { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + Err(_) => return None, + } + thread::sleep(std::time::Duration::from_millis(50)); + } + let mut stdout = String::new(); + if let Some(mut pipe) = child.stdout.take() { + let _ = pipe.read_to_string(&mut stdout); + } + Some(stdout) +} + +/// 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") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", wine_debug()) + .args(["sc", "query", "GameViewerService"]), + std::time::Duration::from_secs(10), + ); + match output { + Some(text) => text.lines().any(|line| { + let line = line.trim(); + line.starts_with("STATE") && line.contains("RUNNING") + }), + None => false, + } +} + +fn tasklist_contains_image(output: &str, image: &str) -> bool { + output.lines().any(|line| { + line.split(',') + .next() + .map(|field| field.trim().trim_matches('"').eq_ignore_ascii_case(image)) + .unwrap_or(false) + }) +} + +fn log_path() -> Result { + Ok(data_dir()?.join("hook.log")) +} + +/// End the session: stop the capture helper, terminate the managed prefix's +/// Wine processes, and drop the bridge connection. +pub fn stop() -> Result<()> { + let prefix = data_dir()?.join("wine"); + if let Some((pid, start)) = read_session_identity()? { + if process_start_time(pid).ok() == Some(start) { + unsafe { + libc::kill(pid as i32, libc::SIGTERM); + } + for _ in 0..100 { + if process_start_time(pid).is_err() { + println!("{}", t!("bridge.stop_requested")); + return Ok(()); + } + thread::sleep(std::time::Duration::from_millis(100)); + } + } + } + stop_wineserver(&prefix); + if let Ok(path) = frame_path() { + let _ = std::fs::remove_file(path); + } + println!("{}", t!("bridge.stop_requested")); + Ok(()) +} + +fn state_dir() -> PathBuf { + std::env::var("XDG_STATE_HOME") + .map(PathBuf::from) + .or_else(|_| std::env::var("HOME").map(|home| PathBuf::from(home).join(".local/state"))) + .unwrap_or_else(|_| PathBuf::from("/tmp")) + .join("uur") +} + +fn open_session_log() -> Result { + let dir = state_dir(); + std::fs::create_dir_all(&dir)?; + std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(dir.join("session.log")) + .context("opening session log") +} + +fn read_session_identity() -> Result> { + let path = state_dir().join("session.lock"); + let Ok(contents) = std::fs::read_to_string(path) else { + return Ok(None); + }; + let mut fields = contents.split_whitespace(); + let Some(pid) = fields.next().and_then(|value| value.parse().ok()) else { + return Ok(None); + }; + let Some(start) = fields.next().and_then(|value| value.parse().ok()) else { + return Ok(None); + }; + Ok(Some((pid, start))) +} + +fn process_start_time(pid: u32) -> Result { + let stat = std::fs::read_to_string(format!("/proc/{pid}/stat"))?; + let end = stat.rfind(") ").context("malformed /proc stat")?; + stat[end + 2..] + .split_whitespace() + .nth(19) + .context("missing process start time")? + .parse() + .context("invalid process start time") +} + +fn frame_path() -> Result { + Ok(crate::config::runtime_dir()?.join("frames.v1")) +} + +fn unix_path_to_wine(path: &Path) -> String { + format!("Z:{}", path.display()).replace('/', "\\") +} + +fn wait_for_bridge(port: u16, stopping: &AtomicBool) -> Result<()> { + // The first RemoteDesktop portal grant is intentionally interactive. + // Keep the supervisor alive while the user chooses a monitor instead of + // treating a two-second consent delay as a bridge failure. + for _ in 0..6000 { + if stopping.load(Ordering::Relaxed) { + anyhow::bail!("session startup cancelled"); + } + if std::net::TcpStream::connect(("127.0.0.1", port)).is_ok() { + return Ok(()); + } + thread::sleep(std::time::Duration::from_millis(20)); + } + anyhow::bail!("input bridge did not become ready") +} + +fn wait_for_runtime_file(path: &Path, stopping: &AtomicBool) -> Result<()> { + for _ in 0..250 { + if stopping.load(Ordering::Relaxed) { + anyhow::bail!("session startup cancelled"); + } + if std::fs::metadata(path).is_ok_and(|metadata| metadata.len() > 0) { + return Ok(()); + } + thread::sleep(std::time::Duration::from_millis(20)); + } + anyhow::bail!("native terminal bridge did not become ready") +} + +fn stop_wineserver(prefix: &Path) { + let _ = Command::new("wineserver") + .env("WINEPREFIX", prefix) + .arg("-k") + .status(); +} + +fn wine_debug() -> String { + std::env::var("WINEDEBUG").unwrap_or_else(|_| "-all".to_string()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn tasklist_parser_matches_the_exact_image() { + let output = "\"GameViewer.exe\",\"456\",\"Console\",\"1\"\n\ + \"GameViewerServer.exe\",\"464\",\"Console\",\"1\"\n"; + assert!(tasklist_contains_image(output, "GameViewer.exe")); + assert!(!tasklist_contains_image(output, "GameViewerService.exe")); + } + + #[test] + fn current_process_identity_is_readable() { + assert!(process_start_time(std::process::id()).unwrap() > 0); + } + + #[test] + fn runtime_path_converts_to_a_wine_z_path() { + assert_eq!( + unix_path_to_wine(Path::new("/run/user/1000/uur/frames.v1")), + r"Z:\run\user\1000\uur\frames.v1" + ); + } +} diff --git a/src/terminal.rs b/src/terminal.rs new file mode 100644 index 0000000..4a1b0aa --- /dev/null +++ b/src/terminal.rs @@ -0,0 +1,287 @@ +//! Native PTY service for UU Remote's terminal feature. +//! +//! The Windows compatibility proxy keeps UU's existing ConPTY-facing stdio +//! contract. This service authenticates that proxy and attaches it to the +//! current Linux user's login shell through a real pseudoterminal. + +use anyhow::{Context, Result}; +use std::fs::{File, OpenOptions}; +use std::io::{Read, Write}; +use std::net::{Shutdown, TcpListener, TcpStream}; +use std::os::fd::{AsRawFd, FromRawFd}; +use std::os::unix::fs::OpenOptionsExt; +use std::os::unix::process::CommandExt; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; +use std::thread; +use std::time::Duration; + +const MAGIC: u32 = 0x5555_5242; +const VERSION: u16 = 1; +const TOKEN_BYTES: usize = 64; +const MAX_FRAME: usize = 64 * 1024; +const MAX_SESSIONS: usize = 4; +const ACCEPTED: u8 = 0x06; +const FRAME_DATA: u8 = 1; +const FRAME_RESIZE: u8 = 2; +const FRAME_EOF: u8 = 3; + +#[link(name = "util")] +unsafe extern "C" { + fn openpty( + master: *mut libc::c_int, + slave: *mut libc::c_int, + name: *mut libc::c_char, + termios: *const libc::termios, + winsize: *const libc::winsize, + ) -> libc::c_int; +} + +pub fn serve() -> Result<()> { + let config_path = std::env::var_os("UUR_TERMINAL_CONFIG") + .map(PathBuf::from) + .context("UUR_TERMINAL_CONFIG is not set")?; + let token = random_token()?; + let listener = TcpListener::bind(("127.0.0.1", 0)).context("binding terminal bridge")?; + let port = listener.local_addr()?.port(); + write_runtime_config(&config_path, port, &token)?; + + let active = Arc::new(AtomicUsize::new(0)); + for connection in listener.incoming() { + let Ok(stream) = connection else { + continue; + }; + if active.fetch_add(1, Ordering::AcqRel) >= MAX_SESSIONS { + active.fetch_sub(1, Ordering::AcqRel); + continue; + } + let token = token.clone(); + let active = active.clone(); + thread::spawn(move || { + let _guard = SessionCount(active); + if let Err(error) = handle_connection(stream, &token) { + eprintln!("terminal adapter connection failed: {error:#}"); + } + }); + } + Ok(()) +} + +struct SessionCount(Arc); + +impl Drop for SessionCount { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::AcqRel); + } +} + +fn handle_connection(mut stream: TcpStream, expected_token: &str) -> Result<()> { + stream.set_read_timeout(Some(Duration::from_secs(5)))?; + let mut hello = [0u8; 12]; + stream.read_exact(&mut hello)?; + if u32::from_be_bytes(hello[0..4].try_into().unwrap()) != MAGIC + || u16::from_be_bytes(hello[4..6].try_into().unwrap()) != VERSION + || u16::from_be_bytes(hello[6..8].try_into().unwrap()) as usize != TOKEN_BYTES + { + anyhow::bail!("invalid terminal handshake"); + } + let columns = u16::from_be_bytes(hello[8..10].try_into().unwrap()).clamp(20, 1000); + let rows = u16::from_be_bytes(hello[10..12].try_into().unwrap()).clamp(5, 500); + let mut supplied = [0u8; TOKEN_BYTES]; + stream.read_exact(&mut supplied)?; + if !constant_time_equal(&supplied, expected_token.as_bytes()) { + anyhow::bail!("terminal authentication failed"); + } + stream.write_all(&[ACCEPTED])?; + stream.set_read_timeout(Some(Duration::from_millis(500)))?; + + let (mut master, mut child) = spawn_shell(columns, rows)?; + let mut output = master.try_clone()?; + let mut output_socket = stream.try_clone()?; + let output_thread = thread::spawn(move || { + let mut buffer = [0u8; 16 * 1024]; + while let Ok(count) = output.read(&mut buffer) { + if count == 0 || output_socket.write_all(&buffer[..count]).is_err() { + break; + } + } + let _ = output_socket.shutdown(Shutdown::Write); + }); + + loop { + let mut header = [0u8; 8]; + match stream.read_exact(&mut header) { + Ok(()) => {} + Err(error) + if matches!( + error.kind(), + std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut + ) => + { + if child.try_wait()?.is_some() { + break; + } + continue; + } + Err(_) => break, + } + let frame_type = header[0]; + let length = u32::from_be_bytes(header[4..8].try_into().unwrap()) as usize; + if length > MAX_FRAME { + anyhow::bail!("terminal frame exceeds limit"); + } + let mut payload = vec![0u8; length]; + stream.read_exact(&mut payload)?; + match frame_type { + FRAME_DATA => master.write_all(&payload)?, + FRAME_RESIZE if payload.len() == 4 => { + let columns = u16::from_be_bytes(payload[0..2].try_into().unwrap()); + let rows = u16::from_be_bytes(payload[2..4].try_into().unwrap()); + resize_pty(&master, columns, rows)?; + } + FRAME_EOF => break, + _ => anyhow::bail!("invalid terminal frame"), + } + } + + unsafe { + libc::kill(child.id() as i32, libc::SIGHUP); + } + let _ = child.wait(); + drop(master); + let _ = output_thread.join(); + Ok(()) +} + +fn spawn_shell(columns: u16, rows: u16) -> Result<(File, std::process::Child)> { + let size = libc::winsize { + ws_row: rows, + ws_col: columns, + ws_xpixel: 0, + ws_ypixel: 0, + }; + let mut master_fd = -1; + let mut slave_fd = -1; + let result = unsafe { + openpty( + &mut master_fd, + &mut slave_fd, + std::ptr::null_mut(), + std::ptr::null(), + &size, + ) + }; + if result != 0 { + return Err(std::io::Error::last_os_error()).context("openpty"); + } + + let master = unsafe { File::from_raw_fd(master_fd) }; + let slave = unsafe { File::from_raw_fd(slave_fd) }; + let shell = std::env::var("SHELL") + .ok() + .filter(|path| Path::new(path).is_absolute() && Path::new(path).is_file()) + .or_else(|| { + option_env!("UUR_BUILD_SHELL") + .filter(|path| Path::new(path).is_file()) + .map(ToOwned::to_owned) + }) + .unwrap_or_else(|| "bash".to_string()); + let mut command = Command::new(shell); + command + .arg("-l") + .env("TERM", "xterm-256color") + .stdin(Stdio::from(slave.try_clone()?)) + .stdout(Stdio::from(slave.try_clone()?)) + .stderr(Stdio::from(slave.try_clone()?)); + if let Some(home) = std::env::var_os("HOME").filter(|path| Path::new(path).is_absolute()) { + command.current_dir(home); + } + unsafe { + command.pre_exec(|| { + if libc::setsid() < 0 { + return Err(std::io::Error::last_os_error()); + } + if libc::ioctl(0, libc::TIOCSCTTY, 0) < 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let child = command.spawn().context("starting login shell")?; + drop(slave); + Ok((master, child)) +} + +fn resize_pty(master: &File, columns: u16, rows: u16) -> Result<()> { + let size = libc::winsize { + ws_row: rows.clamp(5, 500), + ws_col: columns.clamp(20, 1000), + ws_xpixel: 0, + ws_ypixel: 0, + }; + let result = unsafe { libc::ioctl(master.as_raw_fd(), libc::TIOCSWINSZ, &size) }; + if result < 0 { + return Err(std::io::Error::last_os_error()).context("resizing PTY"); + } + Ok(()) +} + +fn write_runtime_config(path: &Path, port: u16, token: &str) -> Result<()> { + let parent = path.parent().context("terminal config has no parent")?; + std::fs::create_dir_all(parent)?; + let temporary = path.with_extension(format!("tmp.{}", std::process::id())); + let mut file = OpenOptions::new() + .create_new(true) + .write(true) + .mode(0o600) + .open(&temporary)?; + writeln!(file, "version=1")?; + writeln!(file, "port={port}")?; + writeln!(file, "token={token}")?; + file.sync_all()?; + std::fs::rename(temporary, path)?; + Ok(()) +} + +fn random_token() -> Result { + let mut random = [0u8; 32]; + File::open("/dev/urandom")?.read_exact(&mut random)?; + Ok(random.iter().map(|byte| format!("{byte:02x}")).collect()) +} + +fn constant_time_equal(left: &[u8], right: &[u8]) -> bool { + if left.len() != right.len() { + return false; + } + let mut difference = 0u8; + for (left, right) in left.iter().zip(right) { + difference |= left ^ right; + } + difference == 0 +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn token_shape_and_comparison() { + let token = random_token().unwrap(); + assert_eq!(token.len(), TOKEN_BYTES); + assert!(token.bytes().all(|byte| byte.is_ascii_hexdigit())); + assert!(constant_time_equal(token.as_bytes(), token.as_bytes())); + assert!(!constant_time_equal(token.as_bytes(), &[b'0'; TOKEN_BYTES])); + } + + #[test] + fn pty_starts_a_real_shell() { + let (mut pty, mut child) = spawn_shell(80, 24).unwrap(); + pty.write_all(b"printf UUR_PTY_OK\\n\nexit\n").unwrap(); + let mut output = Vec::new(); + pty.read_to_end(&mut output).ok(); + let _ = child.wait(); + assert!(String::from_utf8_lossy(&output).contains("UUR_PTY_OK")); + } +} diff --git a/src/upstream.rs b/src/upstream.rs new file mode 100644 index 0000000..88f469b --- /dev/null +++ b/src/upstream.rs @@ -0,0 +1,123 @@ +use anyhow::{Context, Result}; +use std::process::Command; + +const OFFICIAL_DOWNLOAD_URL: &str = "https://api.nrd.nie.163.com/api/v1/release/dl/1?channel=gwqd"; + +/// The latest official release filename, e.g. `uuyc_4.38.3.exe`, resolved +/// from the same feed the official client uses. `uur` never mirrors the +/// binary; it only learns what upstream shipped. +fn latest_filename() -> Result { + // Follow redirects and stop at the headers: the feed answers with a + // Location carrying the signed CDN path whose final component names the + // installer version. + let output = Command::new("curl") + .args([ + "-fsIL", + "--max-time", + "20", + "-o", + "/dev/null", + "-w", + "%{url_effective}", + OFFICIAL_DOWNLOAD_URL, + ]) + .output() + .context("running curl")?; + if !output.status.success() { + anyhow::bail!("{}", t!("upstream.unreachable")); + } + let url = String::from_utf8_lossy(&output.stdout).into_owned(); + let filename = url + .rsplit('/') + .next() + .unwrap_or("") + .split('?') + .next() + .unwrap_or("") + .to_string(); + if filename.is_empty() { + anyhow::bail!("{}", t!("upstream.unparsable", url = url)); + } + Ok(filename) +} + +fn extract_version(filename: &str) -> Option { + let stem = filename.trim_end_matches(".exe"); + let bytes = stem.as_bytes(); + let mut start = None; + let mut end = 0usize; + let mut in_run = false; + let mut run_start = 0usize; + for (index, byte) in bytes.iter().enumerate() { + let is_part = byte.is_ascii_digit() || *byte == b'.'; + if is_part && !in_run { + in_run = true; + run_start = index; + } else if !is_part && in_run { + in_run = false; + if stem[run_start..index].contains('.') { + start = Some(run_start); + end = index; + break; + } + } + } + if in_run && start.is_none() && stem[run_start..].contains('.') { + return Some(stem[run_start..].to_string()); + } + start.map(|s| stem[s..end].to_string()) +} + +fn installed_version() -> Option { + let prefix = crate::config::data_dir().ok()?.join("wine"); + crate::wine::find_client_dir(&prefix)?; + let output = Command::new("wine") + .env("WINEPREFIX", &prefix) + .env("WINEDEBUG", "-all") + .args([ + "reg", + "query", + r"HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall\GameViewer", + "/v", + "DisplayVersion", + ]) + .output() + .ok()?; + if !output.status.success() { + return None; + } + String::from_utf8_lossy(&output.stdout) + .lines() + .find(|line| line.contains("DisplayVersion") && line.contains("REG_SZ")) + .and_then(|line| line.split("REG_SZ").nth(1)) + .map(str::trim) + .filter(|version| !version.is_empty()) + .map(ToOwned::to_owned) +} + +pub fn check() -> Result<()> { + let filename = latest_filename()?; + // Filenames observed upstream: `uuyc_4.33.0.exe`, + // `UURemote_Setup_4.39.1.1375__gwqd.exe`. Take the first + // dotted-numeric run as the version. + let upstream = + extract_version(&filename).with_context(|| format!("no version in {}", filename))?; + + println!( + "{}", + t!("upstream.latest", version = upstream, filename = filename) + ); + match installed_version() { + Some(local) if local == upstream => println!("{}", t!("upstream.up_to_date")), + Some(local) => println!( + "{}", + t!( + "upstream.newer_available", + local = local, + upstream = upstream + ) + ), + None => println!("{}", t!("upstream.not_provisioned")), + } + Ok(()) +} diff --git a/src/video.rs b/src/video.rs new file mode 100644 index 0000000..8ef5b4d --- /dev/null +++ b/src/video.rs @@ -0,0 +1,106 @@ +//! Native video acceleration capability inventory. +//! +//! This module reports host APIs independently from UU's Windows encoder. +//! It is the selection boundary for future native frame encoders and decoders. + +use std::process::{Command, Stdio}; + +#[derive(Debug)] +pub struct Capabilities { + pub render_node: bool, + pub va_api: bool, + pub vulkan: bool, + pub vulkan_video: bool, + pub nvenc: bool, + pub nvdec: bool, +} + +pub fn detect() -> Capabilities { + let vulkan = command_output("vulkaninfo", &[]); + Capabilities { + render_node: render_node_present(), + va_api: command_succeeds("vainfo", &["--display", "drm"]), + vulkan: vulkan.is_some(), + vulkan_video: vulkan + .as_deref() + .is_some_and(|text| text.contains("VK_KHR_video_queue")), + nvenc: library_present("libnvidia-encode.so"), + nvdec: library_present("libnvcuvid.so"), + } +} + +fn command_output(program: &str, arguments: &[&str]) -> Option { + let output = Command::new(program) + .args(arguments) + .env("DISPLAY", std::env::var("DISPLAY").unwrap_or_default()) + .stdin(Stdio::null()) + .stderr(Stdio::null()) + .output() + .ok()?; + output + .status + .success() + .then(|| String::from_utf8_lossy(&output.stdout).into_owned()) +} + +pub fn describe<'a>(value: bool, available: &'a str, unavailable: &'a str) -> &'a str { + if value { + available + } else { + unavailable + } +} + +fn render_node_present() -> bool { + std::fs::read_dir("/dev/dri") + .ok() + .into_iter() + .flatten() + .flatten() + .any(|entry| entry.file_name().to_string_lossy().starts_with("renderD")) +} + +fn command_succeeds(program: &str, arguments: &[&str]) -> bool { + Command::new(program) + .args(arguments) + .env("DISPLAY", std::env::var("DISPLAY").unwrap_or_default()) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|status| status.success()) +} + +fn library_present(needle: &str) -> bool { + let cache = Command::new("ldconfig") + .arg("-p") + .stdin(Stdio::null()) + .output() + .ok() + .map(|output| String::from_utf8_lossy(&output.stdout).into_owned()) + .unwrap_or_default(); + if cache.contains(needle) { + return true; + } + ["/usr/lib", "/usr/local/lib", "/lib"] + .iter() + .any(|directory| { + std::fs::read_dir(directory) + .ok() + .into_iter() + .flatten() + .flatten() + .any(|entry| entry.file_name().to_string_lossy().starts_with(needle)) + }) +} + +#[cfg(test)] +mod tests { + use super::describe; + + #[test] + fn capability_description_selects_the_correct_branch() { + assert_eq!(describe(true, "available", "missing"), "available"); + assert_eq!(describe(false, "available", "missing"), "missing"); + } +} diff --git a/src/wallpaper.rs b/src/wallpaper.rs new file mode 100644 index 0000000..dfae4bd --- /dev/null +++ b/src/wallpaper.rs @@ -0,0 +1,571 @@ +//! Desktop-neutral wallpaper discovery and Wine registry synchronization. +//! +//! UU reads the standard Windows `Control Panel\\Desktop\\Wallpaper` value. +//! Providers below discover the active Linux wallpaper without making the +//! session supervisor depend on a particular desktop environment. + +use anyhow::{Context, Result}; +use std::cmp::Ordering; +use std::ffi::OsStr; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering}; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Wallpaper { + pub path: PathBuf, + pub provider: &'static str, +} + +pub fn detect() -> Option { + if let Some(value) = std::env::var_os("UUR_WALLPAPER") { + if let Some(path) = resolve_candidate(PathBuf::from(value)) { + return Some(Wallpaper { + path, + provider: "environment", + }); + } + } + + if let Some(path) = detect_runtime_provider() { + return Some(Wallpaper { + path, + provider: "wallpaper daemon", + }); + } + + let desktop = std::env::var("XDG_CURRENT_DESKTOP") + .unwrap_or_default() + .to_ascii_lowercase(); + let mut providers: Vec Option> = Vec::new(); + if desktop.contains("kde") || desktop.contains("plasma") { + providers.push(detect_kde); + } + if desktop.contains("gnome") + || desktop.contains("unity") + || desktop.contains("budgie") + || desktop.contains("pantheon") + { + providers.push(detect_gnome_family); + } + if desktop.contains("cinnamon") { + providers.push(detect_cinnamon); + } + if desktop.contains("mate") { + providers.push(detect_mate); + } + if desktop.contains("xfce") { + providers.push(detect_xfce); + } + if desktop.contains("lxqt") || desktop.contains("lxde") { + providers.push(detect_pcmanfm); + } + + for fallback in [ + detect_kde as fn() -> Option, + detect_gnome_family, + detect_cinnamon, + detect_mate, + detect_xfce, + detect_pcmanfm, + detect_nitrogen, + detect_feh, + ] { + if !providers + .iter() + .any(|provider| std::ptr::fn_addr_eq(*provider, fallback)) + { + providers.push(fallback); + } + } + providers.into_iter().find_map(|provider| provider()) +} + +pub fn sync(prefix: &Path) -> Result> { + let Some(wallpaper) = detect() else { + return Ok(None); + }; + let compatible = windows_compatible_path(&wallpaper.path)?; + let windows_path = format!("Z:{}", compatible.display()).replace('/', "\\"); + let status = Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", "-all") + .args([ + "reg", + "add", + r"HKCU\Control Panel\Desktop", + "/v", + "Wallpaper", + "/t", + "REG_SZ", + "/d", + &windows_path, + "/f", + ]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .context("updating Wine wallpaper registry value")?; + if !status.success() { + anyhow::bail!("Wine rejected the wallpaper registry update"); + } + Ok(Some(wallpaper)) +} + +pub fn serve() -> Result<()> { + let prefix = crate::config::data_dir()?.join("wine"); + let stopping = Arc::new(AtomicBool::new(false)); + signal_hook::flag::register(signal_hook::consts::SIGTERM, stopping.clone())?; + signal_hook::flag::register(signal_hook::consts::SIGINT, stopping.clone())?; + signal_hook::flag::register(signal_hook::consts::SIGHUP, stopping.clone())?; + + let mut previous: Option<(PathBuf, Option)> = None; + while !stopping.load(AtomicOrdering::Relaxed) { + if let Some(current) = detect() { + let modified = current + .path + .metadata() + .ok() + .and_then(|metadata| metadata.modified().ok()); + let fingerprint = (current.path.clone(), modified); + if previous.as_ref() != Some(&fingerprint) { + if let Err(error) = sync(&prefix) { + eprintln!("wallpaper synchronization failed: {error:#}"); + } else { + println!( + "wallpaper synchronized via {}: {}", + current.provider, + current.path.display() + ); + previous = Some(fingerprint); + } + } + } + for _ in 0..20 { + if stopping.load(AtomicOrdering::Relaxed) { + return Ok(()); + } + std::thread::sleep(Duration::from_secs(1)); + } + } + Ok(()) +} + +fn detect_kde() -> Option { + let content = + std::fs::read_to_string(config_home().join("plasma-org.kde.plasma.desktop-appletsrc")) + .ok()?; + let value = content + .lines() + .find_map(|line| line.strip_prefix("Image="))?; + wallpaper_from_value(value, "KDE Plasma") +} + +fn detect_gnome_family() -> Option { + let dark = command_value( + "gsettings", + &["get", "org.gnome.desktop.background", "picture-uri-dark"], + ); + let regular = command_value( + "gsettings", + &["get", "org.gnome.desktop.background", "picture-uri"], + ); + dark.or(regular) + .and_then(|value| wallpaper_from_value(&value, "GNOME settings")) +} + +fn detect_cinnamon() -> Option { + command_value( + "gsettings", + &["get", "org.cinnamon.desktop.background", "picture-uri"], + ) + .and_then(|value| wallpaper_from_value(&value, "Cinnamon settings")) +} + +fn detect_mate() -> Option { + command_value( + "gsettings", + &["get", "org.mate.background", "picture-filename"], + ) + .and_then(|value| wallpaper_from_value(&value, "MATE settings")) +} + +fn detect_xfce() -> Option { + let output = command_value("xfconf-query", &["-c", "xfce4-desktop", "-l", "-v"])?; + output + .lines() + .filter(|line| line.contains("last-image")) + .filter_map(|line| line.split_whitespace().last()) + .find_map(|value| wallpaper_from_value(value, "Xfce settings")) +} + +fn detect_pcmanfm() -> Option { + for relative in [ + "pcmanfm-qt/lxqt/settings.conf", + "pcmanfm/LXDE/desktop-items-0.conf", + "pcmanfm/default/desktop-items-0.conf", + ] { + let Ok(content) = std::fs::read_to_string(config_home().join(relative)) else { + continue; + }; + if let Some(value) = content.lines().find_map(|line| { + line.strip_prefix("Wallpaper=") + .or_else(|| line.strip_prefix("wallpaper=")) + }) { + if let Some(found) = wallpaper_from_value(value, "PCManFM settings") { + return Some(found); + } + } + } + None +} + +fn detect_nitrogen() -> Option { + let content = std::fs::read_to_string(config_home().join("nitrogen/bg-saved.cfg")).ok()?; + let value = content + .lines() + .find_map(|line| line.strip_prefix("file="))?; + wallpaper_from_value(value, "Nitrogen settings") +} + +fn detect_feh() -> Option { + let content = std::fs::read_to_string(home_dir().join(".fehbg")).ok()?; + content + .split(['\'', '"']) + .find_map(|part| wallpaper_from_value(part, "feh configuration")) +} + +fn detect_runtime_provider() -> Option { + for (command, arguments) in [ + ("swww", &["query"][..]), + ("hyprctl", &["hyprpaper", "listactive"][..]), + ] { + if let Some(output) = command_value(command, arguments) { + if let Some(path) = output.lines().find_map(path_from_runtime_line) { + return Some(path); + } + } + } + + for entry in std::fs::read_dir("/proc").ok()? { + let Ok(entry) = entry else { + continue; + }; + if !entry + .file_name() + .to_string_lossy() + .bytes() + .all(|byte| byte.is_ascii_digit()) + { + continue; + } + let Ok(bytes) = std::fs::read(entry.path().join("cmdline")) else { + continue; + }; + let arguments: Vec<_> = bytes + .split(|byte| *byte == 0) + .filter(|part| !part.is_empty()) + .map(|part| String::from_utf8_lossy(part).into_owned()) + .collect(); + let executable = arguments + .first() + .and_then(|path| Path::new(path).file_name()) + .and_then(OsStr::to_str) + .unwrap_or_default(); + let candidate = match executable { + "swaybg" => argument_after(&arguments, "-i"), + "xwallpaper" => arguments.last().cloned(), + "mpvpaper" => arguments.last().cloned(), + _ => None, + }; + if let Some(path) = candidate.and_then(|value| resolve_candidate(PathBuf::from(value))) { + return Some(path); + } + } + None +} + +fn path_from_runtime_line(line: &str) -> Option { + let value = line + .split_once("image:") + .map(|(_, value)| value) + .or_else(|| line.rsplit_once(" = ").map(|(_, value)| value))?; + resolve_candidate(PathBuf::from(value.trim())) +} + +fn argument_after(arguments: &[String], option: &str) -> Option { + arguments + .windows(2) + .find(|pair| pair[0] == option) + .map(|pair| pair[1].clone()) +} + +fn wallpaper_from_value(value: &str, provider: &'static str) -> Option { + let value = value.trim().trim_matches(['\'', '"']); + if value.is_empty() { + return None; + } + let decoded = value + .strip_prefix("file://") + .map(percent_decode) + .unwrap_or_else(|| value.to_string()); + resolve_candidate(PathBuf::from(decoded)).map(|path| Wallpaper { path, provider }) +} + +fn resolve_candidate(path: PathBuf) -> Option { + let path = path.canonicalize().ok()?; + if path.is_file() { + return Some(path); + } + if !path.is_dir() { + return None; + } + best_image_in_directory(&path, 4) +} + +fn best_image_in_directory(root: &Path, depth: usize) -> Option { + let mut files = Vec::new(); + collect_images(root, depth, &mut files); + let target_ratio = display_ratio().unwrap_or(16.0 / 9.0); + files.into_iter().max_by(|left, right| { + image_score(left, target_ratio) + .partial_cmp(&image_score(right, target_ratio)) + .unwrap_or(Ordering::Equal) + }) +} + +fn collect_images(directory: &Path, depth: usize, output: &mut Vec) { + if depth == 0 { + return; + } + let Ok(entries) = std::fs::read_dir(directory) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + collect_images(&path, depth - 1, output); + } else if supported_image(&path) { + output.push(path); + } + } +} + +fn supported_image(path: &Path) -> bool { + matches!( + path.extension() + .and_then(OsStr::to_str) + .unwrap_or_default() + .to_ascii_lowercase() + .as_str(), + "jpg" | "jpeg" | "png" | "bmp" | "webp" | "jxl" + ) +} + +fn image_score(path: &Path, target_ratio: f64) -> f64 { + let dimensions = path + .file_stem() + .and_then(OsStr::to_str) + .and_then(parse_dimensions); + if let Some((width, height)) = dimensions { + let ratio_error = (width as f64 / height as f64 - target_ratio).abs(); + return 1_000_000_000.0 - ratio_error * 100_000_000.0 + + (width as f64 * height as f64).sqrt(); + } + path.metadata() + .map(|metadata| metadata.len() as f64) + .unwrap_or(0.0) +} + +fn parse_dimensions(value: &str) -> Option<(u32, u32)> { + let (width, height) = value.split_once('x')?; + Some((width.parse().ok()?, height.parse().ok()?)) +} + +fn display_ratio() -> Option { + let output = command_value("xrandr", &["--current"])?; + let current = output.split("current ").nth(1)?; + let mut words = current.split_whitespace(); + let width: f64 = words.next()?.parse().ok()?; + if words.next()? != "x" { + return None; + } + let height: f64 = words.next()?.trim_end_matches(',').parse().ok()?; + (height > 0.0).then_some(width / height) +} + +fn command_value(program: &str, arguments: &[&str]) -> Option { + let mut child = Command::new(program) + .args(arguments) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let deadline = std::time::Instant::now() + Duration::from_secs(2); + let status = loop { + match child.try_wait().ok()? { + Some(status) => break status, + None if std::time::Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(20)); + } + None => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + }; + if !status.success() { + return None; + } + let mut output = String::new(); + child.stdout.take()?.read_to_string(&mut output).ok()?; + let output = output.trim().to_string(); + (!output.is_empty()).then_some(output) +} + +fn windows_compatible_path(source: &Path) -> Result { + let metadata = source + .metadata() + .with_context(|| format!("reading wallpaper metadata for {}", source.display()))?; + let extension = source + .extension() + .and_then(OsStr::to_str) + .unwrap_or_default() + .to_ascii_lowercase(); + if matches!(extension.as_str(), "jpg" | "jpeg" | "png" | "bmp") + && metadata.len() <= 5 * 1024 * 1024 + { + return Ok(source.to_path_buf()); + } + + let modified = metadata + .modified() + .ok() + .and_then(|time| time.duration_since(SystemTime::UNIX_EPOCH).ok()) + .map(|duration| duration.as_secs()) + .unwrap_or(0); + let cache = crate::config::data_dir()?.join("wallpaper-cache"); + std::fs::create_dir_all(&cache)?; + let stem = format!("wallpaper-{}-{modified}", metadata.len()); + let jpeg = cache.join(format!("{stem}.jpg")); + if jpeg.is_file() { + return Ok(jpeg); + } + + let temporary_jpeg = cache.join(format!("{stem}.tmp.jpg")); + let converted = Command::new("magick") + .arg(source) + .args([ + "-auto-orient", + "-resize", + "3840x2160>", + "-strip", + "-quality", + "88", + ]) + .arg(&temporary_jpeg) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|status| status.success() && temporary_jpeg.is_file()); + if converted { + std::fs::rename(&temporary_jpeg, &jpeg)?; + remove_old_cache_files(&cache, &jpeg); + return Ok(jpeg); + } + let _ = std::fs::remove_file(&temporary_jpeg); + + let png = cache.join(format!("{stem}.png")); + let temporary_png = cache.join(format!("{stem}.tmp.png")); + let input_uri = format!("file://{}", source.display()); + let converted = Command::new("glycin-thumbnailer") + .args(["--input", &input_uri, "--size", "3840", "--output"]) + .arg(&temporary_png) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|status| status.success() && temporary_png.is_file()); + if converted { + std::fs::rename(&temporary_png, &png)?; + remove_old_cache_files(&cache, &png); + return Ok(png); + } + let _ = std::fs::remove_file(&temporary_png); + + // UU may support the source codec through its own image stack. Returning + // the original is more useful than suppressing wallpaper publication. + Ok(source.to_path_buf()) +} + +fn remove_old_cache_files(directory: &Path, keep: &Path) { + let Ok(entries) = std::fs::read_dir(directory) else { + return; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path != keep + && path + .file_name() + .and_then(OsStr::to_str) + .is_some_and(|name| name.starts_with("wallpaper-")) + { + let _ = std::fs::remove_file(path); + } + } +} + +fn percent_decode(value: &str) -> String { + let bytes = value.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + if bytes[index] == b'%' && index + 2 < bytes.len() { + if let Ok(byte) = u8::from_str_radix(&value[index + 1..index + 3], 16) { + decoded.push(byte); + index += 3; + continue; + } + } + decoded.push(bytes[index]); + index += 1; + } + String::from_utf8_lossy(&decoded).into_owned() +} + +fn config_home() -> PathBuf { + std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| home_dir().join(".config")) +} + +fn home_dir() -> PathBuf { + std::env::var_os("HOME") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("/")) +} + +#[cfg(test)] +mod tests { + use super::{parse_dimensions, percent_decode}; + + #[test] + fn file_uri_percent_encoding_is_decoded() { + assert_eq!( + percent_decode("/Pictures/My%20Wallpaper%23one.png"), + "/Pictures/My Wallpaper#one.png" + ); + } + + #[test] + fn package_image_dimensions_are_recognized() { + assert_eq!(parse_dimensions("5120x2880"), Some((5120, 2880))); + assert_eq!(parse_dimensions("wallpaper"), None); + } +} diff --git a/src/wine.rs b/src/wine.rs new file mode 100644 index 0000000..4cd4d8a --- /dev/null +++ b/src/wine.rs @@ -0,0 +1,409 @@ +use anyhow::{Context, Result}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +use crate::config::Config; + +const OFFICIAL_DOWNLOAD_URL: &str = "https://api.nrd.nie.163.com/api/v1/release/dl/1?channel=gwqd"; +const EULA_URL: &str = "https://uuyc.163.com/contact/20240402/40294_1146065.html"; + +/// One-time provisioning. Deliberately quiet: progress on stdout, nothing +/// else. NetEase binaries are never redistributed — they are fetched from +/// the official feed into a per-user prefix. +pub fn setup(accept_eula: bool) -> Result<()> { + let mut config = Config::load()?; + + if !config.eula_accepted { + if !accept_eula { + println!("{}", t!("setup.eula_prompt", url = EULA_URL)); + anyhow::bail!("{}", t!("setup.eula_required")); + } + config.eula_accepted = true; + config.store()?; + println!("{}", t!("setup.eula_recorded")); + } + + let data = crate::config::data_dir()?; + let prefix = data.join("wine"); + std::fs::create_dir_all(&prefix).context("creating wine prefix directory")?; + + let cache = data.join("cache"); + std::fs::create_dir_all(&cache).context("creating cache directory")?; + + if find_client_dir(&prefix).is_some() { + apply_registry_compat(&prefix)?; + let uur_bin = std::env::current_exe().unwrap_or_default(); + let _ = adopt_shortcut(&prefix, &uur_bin); + println!("{}", t!("setup.already_provisioned")); + stop_wineserver(&prefix); + return Ok(()); + } + + println!("{}", t!("setup.downloading", url = OFFICIAL_DOWNLOAD_URL)); + let installer = cache.join("uu-remote-setup.exe"); + let status = Command::new("curl") + .args([ + "-fL", + "--retry", + "3", + "--progress-bar", + "-o", + installer.to_string_lossy().as_ref(), + OFFICIAL_DOWNLOAD_URL, + ]) + .status() + .context("running curl")?; + if !status.success() { + anyhow::bail!("{}", t!("setup.download_failed")); + } + + println!("{}", t!("setup.initializing_prefix")); + let _ = Command::new("wineboot") + .env("WINEPREFIX", &prefix) + .env("WINEDEBUG", wine_debug()) + .arg("--init") + .status() + .context("running wineboot")?; + + // The preload chain only works if Wine resolves wevtapi to the native + // shim in the application directory instead of its builtin. + let _ = Command::new("wine") + .env("WINEPREFIX", &prefix) + .env("WINEDEBUG", wine_debug()) + .args([ + "reg", + "add", + r"HKCU\Software\Wine\DllOverrides", + "/v", + "wevtapi", + "/t", + "REG_SZ", + "/d", + "native", + "/f", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .context("registering wevtapi dll override")?; + + println!("{}", t!("setup.installing_client")); + let status = Command::new("wine") + .env("WINEPREFIX", &prefix) + .env("WINEDEBUG", wine_debug()) + .arg(installer.to_string_lossy().as_ref()) + .arg("/S") + .status() + .context("launching installer")?; + if !status.success() { + println!("{}", t!("setup.silent_install_unavailable")); + } + + // winemenubuilder generated its entries during the install: adopt the + // start-menu one for the full session, then stop it from producing raw + // shortcuts ever again, and sweep desktop copies. + let _ = Command::new("wine") + .env("WINEPREFIX", &prefix) + .env("WINEDEBUG", wine_debug()) + .args([ + "reg", + "add", + r"HKCU\Software\Wine\DllOverrides", + "/v", + "winemenubuilder", + "/t", + "REG_SZ", + "/d", + "", + "/f", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .context("disabling winemenubuilder")?; + apply_registry_compat(&prefix)?; + let uur_bin = std::env::current_exe().unwrap_or_default(); + let _ = adopt_shortcut(&prefix, &uur_bin); + purge_wine_shortcuts(); + + println!("{}", t!("setup.done", path = prefix.display().to_string())); + stop_wineserver(&prefix); + Ok(()) +} + +/// Registry compatibility profile, ported from the field-tested reference +/// implementation: +/// +/// - msedgewebview2.exe runs under Wine only with a win8 app-compat +/// override — without it the WebView2 process never spawns; +/// - GameViewerServer.exe sees Windows 10 because current UU terminal builds +/// gate their ConPTY transport on the OS version. Native input and display +/// adapters handle the hardware capabilities separately; +/// - the service must auto-start; +/// - X11 focus/XIM tuning and CJK font substitution keep the controller +/// usable. +type RegistryEntry = (String, Vec<(&'static str, &'static str, &'static str)>); + +pub fn apply_registry_compat(prefix: &Path) -> Result<()> { + let entries: Vec = vec![ + ( + r#"Software\Wine\AppDefaults\msedgewebview2.exe"#.to_string(), + vec![("Version", "REG_SZ", "win8")], + ), + ( + r#"Software\Wine\AppDefaults\GameViewerServer.exe"#.to_string(), + vec![("Version", "REG_SZ", "win10")], + ), + ( + r"System\CurrentControlSet\Services\GameViewerService".to_string(), + vec![("Start", "REG_DWORD", "2")], + ), + ( + r"Software\Wine\X11 Driver".to_string(), + vec![("UseTakeFocus", "REG_SZ", "N")], + ), + ( + r"Software\Wine\AppDefaults\gameviewer.exe\X11 Driver".to_string(), + vec![("UseXIM", "REG_SZ", "N"), ("UseTakeFocus", "REG_SZ", "Y")], + ), + ( + r"Software\Microsoft\Windows NT\CurrentVersion\FontSubstitutes".to_string(), + vec![ + ("MS Shell Dlg", "REG_SZ", "Noto Sans CJK SC"), + ("MS Shell Dlg 2", "REG_SZ", "Noto Sans CJK SC"), + ], + ), + ]; + + for (key, values) in &entries { + let full = if key.starts_with("System") { + format!("HKLM\\{key}") + } else { + format!("HKCU\\{key}") + }; + for (value, reg_type, data) in values { + let _ = Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", wine_debug()) + .args([ + "reg", "add", &full, "/v", value, "/t", reg_type, "/d", data, "/f", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .with_context(|| format!("reg add {full} /v {value}"))?; + } + } + Ok(()) +} + +pub fn set_dll_override(prefix: &Path, name: &str, mode: &str) -> Result<()> { + let status = Command::new("wine") + .env("WINEPREFIX", prefix) + .env("WINEDEBUG", wine_debug()) + .args([ + "reg", + "add", + r"HKCU\Software\Wine\DllOverrides", + "/v", + name, + "/t", + "REG_SZ", + "/d", + mode, + "/f", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .with_context(|| format!("registering {name} dll override"))?; + if !status.success() { + anyhow::bail!("Wine rejected the {name} DLL override"); + } + Ok(()) +} + +fn wine_debug() -> String { + std::env::var("WINEDEBUG").unwrap_or_else(|_| "-all".to_string()) +} + +fn stop_wineserver(prefix: &Path) { + let _ = Command::new("wineserver") + .env("WINEPREFIX", prefix) + .arg("-k") + .status(); +} + +/// Locate the installed client directory regardless of how NetEase spells +/// the vendor folder ("Netease", "NetEase", ...). Case matters on Linux. +pub fn find_client_dir(prefix: &Path) -> Option { + let program_files = prefix.join("drive_c").join("Program Files"); + let entries = std::fs::read_dir(&program_files).ok()?; + for entry in entries.flatten() { + let name = entry.file_name(); + if name.to_string_lossy().eq_ignore_ascii_case("netease") { + let vendor = entry.path(); + if let Some(found) = find_dir_recursive(&vendor, "GameViewerServer.exe", 4) { + let bin = found.parent()?; + if bin + .file_name() + .is_some_and(|name| name.eq_ignore_ascii_case("bin")) + { + return bin.parent().map(Path::to_path_buf); + } + return Some(bin.to_path_buf()); + } + return Some(vendor); + } + } + None +} + +fn find_dir_recursive(start: &Path, needle: &str, depth: u8) -> Option { + if depth == 0 { + return None; + } + let entries = std::fs::read_dir(start).ok()?; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_file() && path.file_name().map(|n| n == needle).unwrap_or(false) { + return Some(path); + } + if path.is_dir() { + if let Some(found) = find_dir_recursive(&path, needle, depth - 1) { + return Some(found); + } + } + } + None +} + +/// Preserve an existing Wine-generated launcher as a hidden compatibility +/// alias. Previously pinned desktop icons keep working, but the packaged +/// `uur.desktop` remains the one visible menu entry. +pub fn adopt_shortcut(prefix: &Path, uur_bin: &Path) -> Result<()> { + use std::fs; + + let mut name = None; + let users = prefix.join("drive_c/users"); + if let Ok(entries) = fs::read_dir(&users) { + 'outer: for user in entries.flatten() { + let programs = user + .path() + .join("AppData/Roaming/Microsoft/Windows/Start Menu/Programs"); + let Ok(items) = fs::read_dir(&programs) else { + continue; + }; + for item in items.flatten() { + let file_name = item.file_name().to_string_lossy().into_owned(); + if file_name.ends_with(".lnk") && shortcut_targets_gameviewer(&item.path()) { + name = Some(file_name.trim_end_matches(".lnk").to_string()); + break 'outer; + } + } + } + } + let Some(name) = name else { + return Ok(()); + }; + + let mut icon_name = String::new(); + let home = std::env::var("HOME").unwrap_or_default(); + let icons = PathBuf::from(home).join(".local/share/icons"); + let mut best = 0u32; + if let Ok(sizes) = fs::read_dir(icons.join("hicolor")) { + for size in sizes.flatten() { + let size_name = size.file_name().to_string_lossy().into_owned(); + let Ok(width) = size_name.split('x').next().unwrap_or("").parse::() else { + continue; + }; + let Ok(apps) = fs::read_dir(size.path().join("apps")) else { + continue; + }; + for app in apps.flatten() { + let file_name = app.file_name().to_string_lossy().into_owned(); + if file_name.contains("GameViewer") && width > best { + best = width; + icon_name = file_name + .trim_end_matches(".png") + .trim_end_matches(".0") + .to_string(); + } + } + } + } + + let applications = std::env::var("HOME") + .map(|h| PathBuf::from(h).join(".local/share/applications")) + .context("no home")?; + std::fs::create_dir_all(&applications)?; + let entry = applications.join(format!("{name}.desktop")); + let exec = uur_bin.display(); + let icon_line = if icon_name.is_empty() { + String::new() + } else { + format!("Icon={icon_name}\n") + }; + std::fs::write( + &entry, + format!( + "[Desktop Entry]\n\ + Type=Application\n\ + Name={name}\n\ + Comment=UU Remote for Linux (uur)\n\ + Exec={exec} run\n\ + TryExec={exec}\n\ + {icon_line}Terminal=false\n\ + NoDisplay=true\n\ + X-UUR-Managed=true\n\ + Categories=Network;RemoteAccess;\n" + ), + ) + .with_context(|| format!("writing {}", entry.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let _ = fs::set_permissions(&entry, fs::Permissions::from_mode(0o755)); + } + Ok(()) +} + +fn shortcut_targets_gameviewer(path: &Path) -> bool { + let Ok(bytes) = std::fs::read(path) else { + return false; + }; + let searchable: String = bytes + .into_iter() + .filter(|byte| *byte != 0) + .map(|byte| byte as char) + .collect::() + .to_ascii_lowercase(); + searchable.contains("gameviewer") +} + +/// Remove Wine-generated desktop copies of the client. The start-menu +/// entry is ours and correct; only Desktop copies are swept. +fn purge_wine_shortcuts() { + let home = match std::env::var("HOME") { + Ok(home) => PathBuf::from(home), + Err(_) => return, + }; + let matches = |name: &str| { + let lower = name.to_lowercase(); + lower.contains("uuremote") || lower.contains("gameviewer") || lower.contains("uu remote") + }; + let dir = home.join("Desktop"); + let Ok(entries) = std::fs::read_dir(&dir) else { + return; + }; + for entry in entries.flatten() { + let name = entry.file_name().to_string_lossy().into_owned(); + if matches(&name) { + let _ = std::fs::remove_file(entry.path()); + } + } +} diff --git a/src/wol.rs b/src/wol.rs new file mode 100644 index 0000000..a5dbf29 --- /dev/null +++ b/src/wol.rs @@ -0,0 +1,211 @@ +//! Host Wake-on-LAN configuration without a desktop- or distro-specific policy. + +use anyhow::{Context, Result}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; + +#[derive(Debug, Clone)] +pub struct State { + pub interface: String, + pub mac: String, + pub supported: Option, + pub enabled: Option, + pub connection: Option, +} + +pub fn status(requested: Option<&str>) -> Result<()> { + let state = inspect(requested)?; + println!("{}", t!("wol.interface", interface = state.interface)); + println!("{}", t!("wol.mac", mac = state.mac)); + println!( + "{}", + t!("wol.magic_support", state = tri_state(state.supported)) + ); + println!( + "{}", + t!("wol.magic_enabled", state = tri_state(state.enabled)) + ); + println!( + "{}", + t!( + "wol.connection", + connection = state.connection.as_deref().unwrap_or("-") + ) + ); + Ok(()) +} + +pub fn configure(requested: Option<&str>, enabled: bool) -> Result<()> { + let before = inspect(requested)?; + if enabled && before.supported == Some(false) { + anyhow::bail!("{}", t!("wol.unsupported", interface = before.interface)); + } + + if let Some(connection) = &before.connection { + let value = if enabled { "magic" } else { "0" }; + checked( + Command::new("nmcli") + .args([ + "connection", + "modify", + connection, + "802-3-ethernet.wake-on-lan", + value, + ]) + .stdin(Stdio::null()), + "updating the NetworkManager Wake-on-LAN profile", + )?; + } + + let mode = if enabled { "g" } else { "d" }; + checked( + Command::new("ethtool") + .args(["-s", &before.interface, "wol", mode]) + .stdin(Stdio::null()), + &format!( + "setting Wake-on-LAN on {} (run this command as root or through an authorized Polkit session)", + before.interface + ), + )?; + + let after = inspect(Some(&before.interface))?; + if after.enabled != Some(enabled) { + anyhow::bail!("{}", t!("wol.verify_failed", interface = before.interface)); + } + println!( + "{}", + if enabled { + t!("wol.enabled", interface = before.interface) + } else { + t!("wol.disabled", interface = before.interface) + } + ); + Ok(()) +} + +pub fn inspect(requested: Option<&str>) -> Result { + let interface = select_interface(requested)?; + let base = Path::new("/sys/class/net").join(&interface); + let mac = std::fs::read_to_string(base.join("address")) + .unwrap_or_else(|_| "unknown".into()) + .trim() + .to_string(); + let properties = Command::new("ethtool") + .arg(&interface) + .stdin(Stdio::null()) + .output() + .ok() + .filter(|output| output.status.success()) + .map(|output| String::from_utf8_lossy(&output.stdout).into_owned()); + let supported = properties + .as_deref() + .and_then(|text| property(text, "Supports Wake-on:").map(|value| value.contains('g'))); + let enabled = properties + .as_deref() + .and_then(|text| property(text, "Wake-on:").map(|value| value.contains('g'))); + Ok(State { + interface: interface.clone(), + mac, + supported, + enabled, + connection: active_connection(&interface), + }) +} + +fn select_interface(requested: Option<&str>) -> Result { + if let Some(interface) = requested { + validate_interface(interface)?; + return Ok(interface.to_string()); + } + if let Some(interface) = default_route_interface().filter(|name| is_wired_physical(name)) { + return Ok(interface); + } + let mut candidates = std::fs::read_dir("/sys/class/net") + .context("enumerating network interfaces")? + .flatten() + .filter_map(|entry| entry.file_name().into_string().ok()) + .filter(|name| is_wired_physical(name)) + .collect::>(); + candidates.sort(); + candidates + .into_iter() + .next() + .context("no physical wired network interface found") +} + +fn validate_interface(interface: &str) -> Result<()> { + if interface.is_empty() + || !interface + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-' | b'.' | b':')) + || !is_wired_physical(interface) + { + anyhow::bail!("invalid or non-wired physical interface: {interface}"); + } + Ok(()) +} + +fn is_wired_physical(interface: &str) -> bool { + let base = PathBuf::from("/sys/class/net").join(interface); + base.join("device").exists() && !base.join("wireless").exists() +} + +fn default_route_interface() -> Option { + let output = Command::new("ip") + .args(["-o", "route", "show", "default"]) + .stdin(Stdio::null()) + .output() + .ok()?; + let text = String::from_utf8_lossy(&output.stdout); + let fields = text.split_whitespace().collect::>(); + let index = fields.iter().position(|field| *field == "dev")?; + fields.get(index + 1).map(|value| value.to_string()) +} + +fn active_connection(interface: &str) -> Option { + let output = Command::new("nmcli") + .args(["-g", "GENERAL.CONNECTION", "device", "show", interface]) + .stdin(Stdio::null()) + .output() + .ok()?; + if !output.status.success() { + return None; + } + let value = String::from_utf8_lossy(&output.stdout).trim().to_string(); + (!value.is_empty() && value != "--").then_some(value) +} + +fn property<'a>(text: &'a str, name: &str) -> Option<&'a str> { + text.lines() + .map(str::trim) + .find_map(|line| line.strip_prefix(name).map(str::trim)) +} + +fn checked(command: &mut Command, context: &str) -> Result<()> { + let output = command.output().with_context(|| context.to_string())?; + if output.status.success() { + return Ok(()); + } + let detail = String::from_utf8_lossy(&output.stderr).trim().to_string(); + anyhow::bail!("{context}: {detail}") +} + +fn tri_state(value: Option) -> String { + match value { + Some(true) => t!("wol.yes").to_string(), + Some(false) => t!("wol.no").to_string(), + None => t!("wol.unknown_ethtool").to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::property; + + #[test] + fn parses_ethtool_wake_properties_without_confusing_them() { + let sample = "Supports Wake-on: pumbg\nWake-on: g\n"; + assert_eq!(property(sample, "Supports Wake-on:"), Some("pumbg")); + assert_eq!(property(sample, "Wake-on:"), Some("g")); + } +} diff --git a/tests/frame-protocol.c b/tests/frame-protocol.c new file mode 100644 index 0000000..d288cbb --- /dev/null +++ b/tests/frame-protocol.c @@ -0,0 +1,19 @@ +#include +#include +#include + +#include "../hook/frame-protocol.h" + +int main(void) +{ + const size_t slot_bytes = 8u + 1920u * 1080u * 4u; + for (uint64_t sequence = 1; sequence < 1000; ++sequence) { + size_t writer = uurf_slot_offset(sequence, slot_bytes); + size_t reader = UURF_HEADER_BYTES + + (size_t)(sequence % UURF_SLOT_COUNT) * slot_bytes; + assert(writer == reader); + assert(writer + slot_bytes <= + UURF_HEADER_BYTES + UURF_SLOT_COUNT * slot_bytes); + } + return 0; +} diff --git a/tests/hook-smoke.sh b/tests/hook-smoke.sh new file mode 100755 index 0000000..12a7fa6 --- /dev/null +++ b/tests/hook-smoke.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +set -euo pipefail + +project_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +prefix=$(mktemp -d "${TMPDIR:-/tmp}/uur-wine-test.XXXXXX") +trap 'WINEPREFIX="$prefix" wineserver -k >/dev/null 2>&1 || true; rm -rf -- "$prefix"' EXIT + +for tool in wine wineboot wineserver xvfb-run timeout; do + command -v "$tool" >/dev/null 2>&1 || { + printf 'missing hook smoke-test dependency: %s\n' "$tool" >&2 + exit 2 + } +done + +WINEPREFIX="$prefix" WINEDEBUG=-all xvfb-run -a wineboot --init +set +e +output=$( + cd "$project_root/build/hook" && + WINEPREFIX="$prefix" WINEDEBUG=-all WINEDLLOVERRIDES=wevtapi=n \ + timeout 30s xvfb-run -a wine ./selftest.exe 2>&1 +) +status=$? +set -e + +printf '%s\n' "$output" + +# Some xvfb-run versions return 1 when their Xvfb child has already exited during +# cleanup, even though the wrapped process completed successfully. Keep checking +# the self-test's terminal success marker so genuine Wine or hook failures remain +# fatal without turning that cleanup race into a CI failure. +if ((status != 0)) && [[ "$output" != *"hook capture and input smoke test passed"* ]]; then + exit "$status" +fi diff --git a/tests/terminal-smoke.sh b/tests/terminal-smoke.sh new file mode 100755 index 0000000..2114546 --- /dev/null +++ b/tests/terminal-smoke.sh @@ -0,0 +1,65 @@ +#!/usr/bin/env bash +set -euo pipefail + +project_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P) +temporary=$(mktemp -d "${TMPDIR:-/tmp}/uur-terminal-test.XXXXXX") +prefix="$temporary/wine" +proxy="$temporary/powershell.exe" +config="$temporary/uu-terminal-bridge.runtime" +server_pid="" + +cleanup() { + if [[ -n $server_pid ]]; then + kill "$server_pid" >/dev/null 2>&1 || true + wait "$server_pid" 2>/dev/null || true + fi + WINEPREFIX="$prefix" wineserver -k >/dev/null 2>&1 || true + rm -rf -- "$temporary" +} +trap cleanup EXIT + +for tool in wine wineboot wineserver xvfb-run timeout; do + command -v "$tool" >/dev/null 2>&1 || { + printf 'missing terminal smoke-test dependency: %s\n' "$tool" >&2 + exit 2 + } +done + +uur="$project_root/target/debug/uur" +[[ -x $uur ]] || uur="$project_root/target/release/uur" +[[ -x $uur ]] || { + printf 'build uur before running the terminal smoke test\n' >&2 + exit 2 +} +[[ -f $project_root/build/hook/uur-terminal-proxy.exe ]] || + "$project_root/hook/build.sh" +cp "$project_root/build/hook/uur-terminal-proxy.exe" "$proxy" + +SHELL=/bin/sh UUR_TERMINAL_CONFIG="$config" "$uur" __terminal \ + >"$temporary/server.log" 2>&1 & +server_pid=$! +for _ in {1..250}; do + [[ -s $config ]] && break + kill -0 "$server_pid" 2>/dev/null || { + cat "$temporary/server.log" >&2 + exit 1 + } + sleep 0.02 +done +[[ -s $config ]] || { + printf 'terminal server did not publish its runtime configuration\n' >&2 + exit 1 +} + +WINEPREFIX="$prefix" WINEDEBUG=-all xvfb-run -a wineboot --init +{ + printf 'echo UUR_NATIVE_TERMINAL_OK\nexit\n' + sleep 2 +} | WINEPREFIX="$prefix" WINEDEBUG=-all \ + timeout 30s xvfb-run -a wine "$proxy" >"$temporary/output" 2>&1 + +grep -Fq UUR_NATIVE_TERMINAL_OK "$temporary/output" || { + cat "$temporary/output" >&2 + exit 1 +} +printf 'native terminal Wine/PTY round-trip passed\n'