mirror of
https://github.com/VallierDev/uu-remote-linux.git
synced 2026-11-16 16:50:41 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
edd4c9250c | ||
|
|
ca49232674 | ||
|
|
cb8253febf | ||
|
|
696cf10e33 | ||
|
|
a9433b73be | ||
|
|
c9e5fec175 | ||
|
|
380a08e293 | ||
|
|
63ebb3e78a | ||
|
|
e4a2cc4698 | ||
|
|
8fb57b421d | ||
|
|
72c1e6101f | ||
|
|
a67731052f | ||
|
|
e6089bfb46 | ||
|
|
aa2a341d15 | ||
|
|
9622bf4c1e | ||
|
|
d7e52a098b | ||
|
|
94ff1f1c02 | ||
|
|
aafc17e626 | ||
|
|
cd6df7f03f | ||
|
|
2815a01569 |
No files matched your search
@@ -6,6 +6,16 @@ on:
|
|||||||
pull_request:
|
pull_request:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
test-macos-ssh-paste:
|
||||||
|
runs-on: macos-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- run: python3 -m unittest discover -s contrib/macos-ssh -p 'test_*.py' -v
|
||||||
|
- name: Test file-URL clipboard reader on a private pasteboard
|
||||||
|
run: |
|
||||||
|
swiftc -O contrib/macos-ssh/clipboard-files.swift -o "$RUNNER_TEMP/clipboard-files"
|
||||||
|
"$RUNNER_TEMP/clipboard-files" --self-test
|
||||||
|
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-22.04
|
runs-on: ubuntu-22.04
|
||||||
steps:
|
steps:
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ on:
|
|||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
packages: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
release:
|
release:
|
||||||
@@ -37,3 +38,23 @@ jobs:
|
|||||||
files: |
|
files: |
|
||||||
uu-remote-linux-*.tar.gz
|
uu-remote-linux-*.tar.gz
|
||||||
uu-remote-linux-*.tar.gz.sha256
|
uu-remote-linux-*.tar.gz.sha256
|
||||||
|
|
||||||
|
# Headless NAS image (docker/), built from the release tarball published by the job above.
|
||||||
|
docker:
|
||||||
|
needs: release
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{ github.actor }}
|
||||||
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
- uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: docker
|
||||||
|
build-args: VERSION=${{ github.ref_name }}
|
||||||
|
push: true
|
||||||
|
tags: |
|
||||||
|
ghcr.io/vallierdev/uu-remote-linux:${{ github.ref_name }}
|
||||||
|
ghcr.io/vallierdev/uu-remote-linux:latest
|
||||||
@@ -146,7 +146,7 @@ every 60 s.
|
|||||||
| `c_engine/x11_engine.c`, `c_engine/clipboard.c` | X11 capture/input/selection |
|
| `c_engine/x11_engine.c`, `c_engine/clipboard.c` | X11 capture/input/selection |
|
||||||
| `c_engine/wayland_engine.c`, `c_engine/portal_engine.c` | Wayland and portal engines |
|
| `c_engine/wayland_engine.c`, `c_engine/portal_engine.c` | Wayland and portal engines |
|
||||||
| `src/assist.rs`, `c_engine/assist_window.c` | remote assistance (guest + account) and the unified GTK main window (assist + account/QR card) |
|
| `src/assist.rs`, `c_engine/assist_window.c` | remote assistance (guest + account) and the unified GTK main window (assist + account/QR card) |
|
||||||
| `src/viewer_main.rs`, `src/viewer/` | experimental viewer (`--features native-viewer,viewer-sdl`): cloud join, WebRTC offer side, SDL desktop window (ffmpeg CLI decode), files/terminal/portmap/power/assist tools, GTK launcher |
|
| `src/viewer_main.rs`, `src/viewer/` | experimental viewer (`--features native-viewer,viewer-sdl`): cloud join, WebRTC offer side, SDL desktop window (ffmpeg CLI decode), files/terminal/portmap/power/assist tools, device removal (`POST /api/v1/device/{id}/unbind`, verified live; shared devices use `/api/v1/device/share/{id}/unbind`, strings only), GTK launcher |
|
||||||
| `c_engine/viewer_window.c`, `c_engine/viewer_tools.c` | viewer GTK launcher and tool windows (files, port mapping, terminal list) |
|
| `c_engine/viewer_window.c`, `c_engine/viewer_tools.c` | viewer GTK launcher and tool windows (files, port mapping, terminal list) |
|
||||||
|
|
||||||
Diagnostic subcommands: `login [--no-gui]`, `unlock-check` (password on stdin, prints only accepted/rejected),
|
Diagnostic subcommands: `login [--no-gui]`, `unlock-check` (password on stdin, prints only accepted/rejected),
|
||||||
|
|||||||
Generated
+1
-1
@@ -2741,7 +2741,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uu-remote-linux"
|
name = "uu-remote-linux"
|
||||||
version = "0.2.3"
|
version = "0.2.9"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "uu-remote-linux"
|
name = "uu-remote-linux"
|
||||||
version = "0.2.3"
|
version = "0.2.9"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
default-run = "uuremote-server"
|
default-run = "uuremote-server"
|
||||||
authors = ["uu-remote-linux contributors"]
|
authors = ["uu-remote-linux contributors"]
|
||||||
|
|||||||
+38
-5
@@ -1,4 +1,4 @@
|
|||||||
# uu-remote-linux · Unofficial Linux host for NetEase UU Remote
|
# uu-remote-linux · Unofficial Linux host and viewer for NetEase UU Remote
|
||||||
|
|
||||||
[简体中文](README.md) | **English**
|
[简体中文](README.md) | **English**
|
||||||
|
|
||||||
@@ -7,13 +7,21 @@
|
|||||||
> NetEase UU Remote (网易 UU 远程) is a great remote-desktop tool, but there is no Linux version on its
|
> NetEase UU Remote (网易 UU 远程) is a great remote-desktop tool, but there is no Linux version on its
|
||||||
> official website. So, with the help of Claude and Codex, I wrote this open-source Linux host: install it,
|
> official website. So, with the help of Claude and Codex, I wrote this open-source Linux host: install it,
|
||||||
> and you can control your Linux machine from the official Mac / Windows / mobile UU Remote clients.
|
> and you can control your Linux machine from the official Mac / Windows / mobile UU Remote clients.
|
||||||
|
> It now also ships an **experimental Linux viewer**, `uuremote-viewer`, that controls official Windows / Mac hosts or this
|
||||||
|
> project's host from Linux (desktop, file transfer, terminal, port mapping, remote assistance; see
|
||||||
|
> [below](#experimental-native-viewer-uuremote-viewer)).
|
||||||
|
> Desktop-less **Synology / NAS** boxes can run it in Docker: [deployment guide](docs/deploy-nas-docker.md#english), image
|
||||||
|
> [`ghcr.io/vallierdev/uu-remote-linux`](https://github.com/VallierDev/uu-remote-linux/pkgs/container/uu-remote-linux).
|
||||||
>
|
>
|
||||||
> This is a personal hobby project. **It is not affiliated with NetEase and is not an official client.**
|
> This is a personal hobby project. **It is not affiliated with NetEase and is not an official client.**
|
||||||
> If NetEase considers this project infringing or inappropriate, please DM me on X
|
> If NetEase considers this project infringing or inappropriate, please DM me on X
|
||||||
> **[@ai_fengshou](https://x.com/ai_fengshou)** and I will take it down right away.
|
> **[@ai_fengshou](https://x.com/ai_fengshou)** and I will take it down right away.
|
||||||
|
|
||||||
|
<p align="center"><img src="docs/images/viewer-window.png" width="720" alt="Linux viewer launcher: device list (device names redacted)"></p>
|
||||||
|
<p align="center"><sub>Linux viewer: device list (device names redacted)</sub></p>
|
||||||
|
|
||||||
<p align="center"><img src="docs/images/main-window.png" width="620" alt="Host main window: remote assistance and account"></p>
|
<p align="center"><img src="docs/images/main-window.png" width="620" alt="Host main window: remote assistance and account"></p>
|
||||||
<p align="center"><sub>The QR login window shown on first run (QR code blurred). The UI is in Chinese, like the official app.</sub></p>
|
<p align="center"><sub>Linux host main window: remote assistance and account (device ID, code and account redacted). The UI is in Chinese, like the official app.</sub></p>
|
||||||
|
|
||||||
<!-- Screenshot placeholder: the Linux desktop controlled from the official client. Take your own
|
<!-- Screenshot placeholder: the Linux desktop controlled from the official client. Take your own
|
||||||
screenshot, remove account/device details and NetEase logos, save it as docs/images/remote-desktop.png
|
screenshot, remove account/device details and NetEase logos, save it as docs/images/remote-desktop.png
|
||||||
@@ -230,6 +238,17 @@ service and run `loginctl enable-linger $USER`, so the systemd user manager (wit
|
|||||||
starts at boot without a login. The viewer's remote desktop keeps showing "connecting" in this mode; that is expected.
|
starts at boot without a login. The viewer's remote desktop keeps showing "connecting" in this mode; that is expected.
|
||||||
Log in once with `uuremote-server login --no-gui` (QR in the terminal).
|
Log in once with `uuremote-server login --no-gui` (QR in the terminal).
|
||||||
|
|
||||||
|
**Synology / NAS (Docker)**: run headless mode in a container on a desktop-less NAS (file transfer, terminal, port
|
||||||
|
mapping): image [`ghcr.io/vallierdev/uu-remote-linux`](https://github.com/VallierDev/uu-remote-linux/pkgs/container/uu-remote-linux),
|
||||||
|
see the [NAS deployment guide](docs/deploy-nas-docker.md#english). Verified on Synology DSM 7.3 (x86_64).
|
||||||
|
|
||||||
|
**Paste files from a Mac terminal**: when using Ghostty over UU's SSH port mapping,
|
||||||
|
the optional [Mac SSH paste companion](contrib/macos-ssh/README.md) uploads files
|
||||||
|
copied in Finder before inserting their remote paths. Text and mouse reports pass
|
||||||
|
through. Ghostty's title and progress bar show upload progress, transferred size,
|
||||||
|
speed and elapsed time. It does not change the official UU terminal; folders, drag-and-drop and
|
||||||
|
raw screenshot clipboard data are not supported.
|
||||||
|
|
||||||
**Virtual desktop**: for a full remote desktop, run a desktop session (Xfce recommended) on an Xvfb screen:
|
**Virtual desktop**: for a full remote desktop, run a desktop session (Xfce recommended) on an Xvfb screen:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -261,6 +280,7 @@ Common environment variables:
|
|||||||
| `UU_INPUT_BACKEND` | `auto` (default: uinput on Wayland when accessible) / `uinput` / `native` |
|
| `UU_INPUT_BACKEND` | `auto` (default: uinput on Wayland when accessible) / `uinput` / `native` |
|
||||||
| `UU_TERMINAL_SHORTCUTS=0` | Disable the Ctrl+V paste rewrite in terminal windows |
|
| `UU_TERMINAL_SHORTCUTS=0` | Disable the Ctrl+V paste rewrite in terminal windows |
|
||||||
| `UU_VIDEO_ENCODER` | `cpu`: libx264; `vaapi`: opt-in Intel/AMD; `nvenc`: force NVENC; unset: NVENC only when an NVIDIA driver is loaded, else CPU |
|
| `UU_VIDEO_ENCODER` | `cpu`: libx264; `vaapi`: opt-in Intel/AMD; `nvenc`: force NVENC; unset: NVENC only when an NVIDIA driver is loaded, else CPU |
|
||||||
|
| `UU_VAAPI_BUFFER_MS` | VAAPI VBV buffer in ms (10-1000, VAAPI only); raise it when keyframes are squeezed into a blur at high resolution |
|
||||||
| `UU_FFMPEG_ROOT` | Use FFmpeg from this prefix |
|
| `UU_FFMPEG_ROOT` | Use FFmpeg from this prefix |
|
||||||
| `UU_AUDIO=0` | Disable sound; `UU_AUDIO_SOURCE` picks the PulseAudio source |
|
| `UU_AUDIO=0` | Disable sound; `UU_AUDIO_SOURCE` picks the PulseAudio source |
|
||||||
| `UU_REMOTE_ASSIST=0` | Disable remote assistance (no guest assistance before sign-in either) |
|
| `UU_REMOTE_ASSIST=0` | Disable remote assistance (no guest assistance before sign-in either) |
|
||||||
@@ -333,8 +353,14 @@ capability lists; the official Mac viewer lists H265 first in its SDP). The firs
|
|||||||
synthetic frame and announces encoder support with CodecNegotiation. `hevc_nvenc`, `libx265` and explicit
|
synthetic frame and announces encoder support with CodecNegotiation. `hevc_nvenc`, `libx265` and explicit
|
||||||
`UU_VIDEO_ENCODER=vaapi` (`hevc_vaapi`); hardware failure falls back to software HEVC, then to H.264.
|
`UU_VIDEO_ENCODER=vaapi` (`hevc_vaapi`); hardware failure falls back to software HEVC, then to H.264.
|
||||||
`UU_VIDEO_CODEC=h264` forces H.264. 8-bit; true color 4:4:4 uses hevc_nvenc `rext` / libx265 `main444-8`.
|
`UU_VIDEO_CODEC=h264` forces H.264. 8-bit; true color 4:4:4 uses hevc_nvenc `rext` / libx265 `main444-8`.
|
||||||
Verified with the official Mac viewer on an RTX 3090 (hevc_nvenc, including 4:4:4); libx265, hevc_vaapi and
|
Verified with the official Mac viewer on an RTX 3090 (hevc_nvenc, including 4:4:4) and with the official Android
|
||||||
other viewers are not hardware-verified.
|
viewer on Intel Alder Lake-P (iHD): 2560x1440 fully hardware-encoded, 58 fps decoded at about 10 ms. libx265 is
|
||||||
|
still not verified against a real viewer.
|
||||||
|
|
||||||
|
HEVC access units are split on RFC 7798 picture boundaries instead of AUDs: `hevc_vaapi` with `-aud 1` writes an
|
||||||
|
AUD only at IRAPs and drops every other picture from the bitstream, so an AUD-based reader turns a whole GOP into
|
||||||
|
one "frame" and the IRAP gate then rejects all of them: the connection stalls at "transferring" while the host
|
||||||
|
sends about 12 kbit/s. `UU_VIDEO_CODEC=h265` selects H.265 explicitly for A/B diagnosis.
|
||||||
|
|
||||||
### VAAPI (opt-in / 显式启用)
|
### VAAPI (opt-in / 显式启用)
|
||||||
|
|
||||||
@@ -347,6 +373,13 @@ with a warning. Accepted on Intel UHD 770 (iHD) with the default FFmpeg process
|
|||||||
viewer (presets, fps, scaling, reconnect; no fallback, ~40% less CPU than libx264). AMD and the `inproc-av`
|
viewer (presets, fps, scaling, reconnect; no fallback, ~40% less CPU than libx264). AMD and the `inproc-av`
|
||||||
VAAPI path are not hardware-verified.
|
VAAPI path are not hardware-verified.
|
||||||
|
|
||||||
|
The default VAAPI VBV buffer (100-500 kbit) squeezes keyframes hard at high resolution: on a 2560x1440
|
||||||
|
H.264 VAAPI stream capped at 30 Mbit/s the first IDR measured 59,910 bytes and the picture blurred at
|
||||||
|
every GOP before sharpening back. `UU_VAAPI_BUFFER_MS=250` (buffer = bitrate cap x ms/1000) restored that
|
||||||
|
first IDR to 142,397 bytes and raised the worst-frame Y-SSIM from 0.9492 to 0.9933 without raising the
|
||||||
|
average bitrate. Off by default; unset or out of the 10-1000 ms range keeps the old buffer. Larger
|
||||||
|
keyframes can queue briefly on a weak link, so start at 250 ms.
|
||||||
|
|
||||||
### Virtual audio / 虚拟声卡
|
### Virtual audio / 虚拟声卡
|
||||||
|
|
||||||
The viewer's 静音运行 switch creates the null sink `uu-remote-sink`,
|
The viewer's 静音运行 switch creates the null sink `uu-remote-sink`,
|
||||||
@@ -427,7 +460,7 @@ GNOME-to-official-Mac bidirectional clipboard synchronization is still unverifie
|
|||||||
machine with the same identity**; other devices are fine.
|
machine with the same identity**; other devices are fine.
|
||||||
- `uuremote-viewer ui`: launcher listing your devices: desktop, view-only, files, terminal, port mapping, reboot/shutdown, assistance.
|
- `uuremote-viewer ui`: launcher listing your devices: desktop, view-only, files, terminal, port mapping, reboot/shutdown, assistance.
|
||||||
- CLI: `connect DEVICE false - echo legacy [--view-only]` (desktop), `files DEVICE ls|get|put …`, `terminal DEVICE [SESSION]`,
|
- CLI: `connect DEVICE false - echo legacy [--view-only]` (desktop), `files DEVICE ls|get|put …`, `terminal DEVICE [SESSION]`,
|
||||||
`terminal-ui DEVICE NAME`, `portmap DEVICE LOCAL_PORT HOST PORT` (listens on 127.0.0.1 only), `power DEVICE reboot|shutdown`,
|
`terminal-ui DEVICE NAME`, `portmap DEVICE LOCAL_PORT HOST PORT` (listens on 127.0.0.1 only), `power DEVICE reboot|shutdown`, `unbind DEVICE` (remove a device from the account; also under "More tools" in the launcher),
|
||||||
`assist CONNECT_ID` (the code is read from one stdin line, never an argument). See `uuremote-viewer --help`.
|
`assist CONNECT_ID` (the code is read from one stdin line, never an argument). See `uuremote-viewer --help`.
|
||||||
- Ctrl+Alt+F in the desktop window opens the files window on the same connection. `UU_VIEWER_AUDIO=0` disables sound,
|
- Ctrl+Alt+F in the desktop window opens the files window on the same connection. `UU_VIEWER_AUDIO=0` disables sound,
|
||||||
`UU_VIEWER_CLIPBOARD=0` the clipboard, `UU_VIEWER_VIEW_ONLY=1` input; `UU_VIEWER_FFMPEG` selects the ffmpeg binary.
|
`UU_VIEWER_CLIPBOARD=0` the clipboard, `UU_VIEWER_VIEW_ONLY=1` input; `UU_VIEWER_FFMPEG` selects the ffmpeg binary.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
# uu-remote-linux · UU 远程 Linux 被控端(非官方)
|
# uu-remote-linux · UU 远程 Linux 被控端 + 控制端(非官方)
|
||||||
|
|
||||||
**简体中文** | [English](README.en.md)
|
**简体中文** | [English](README.en.md)
|
||||||
|
|
||||||
@@ -6,12 +6,18 @@
|
|||||||
>
|
>
|
||||||
> 网易 UU 远程非常好用,但官网一直没有 Linux 版本。于是我借助 Claude 和 Codex,写了这个开源的 Linux 被控端:
|
> 网易 UU 远程非常好用,但官网一直没有 Linux 版本。于是我借助 Claude 和 Codex,写了这个开源的 Linux 被控端:
|
||||||
> 装上之后,就能用官方的 Mac / Windows / 手机客户端远程控制你的 Linux 电脑。
|
> 装上之后,就能用官方的 Mac / Windows / 手机客户端远程控制你的 Linux 电脑。
|
||||||
|
> 现在还附带一个**实验性 Linux 控制端** `uuremote-viewer`:在 Linux 上用 UU 账号远控官方 Windows / Mac 被控端或本项目主机
|
||||||
|
> (桌面、文件传输、终端、端口映射、远程协助,详见[下文](#实验性原生控制端uuremote-viewer))。
|
||||||
|
> 没有桌面的**群晖 / NAS** 也能用 Docker 部署:[部署指南](docs/deploy-nas-docker.md),镜像 [`ghcr.io/vallierdev/uu-remote-linux`](https://github.com/VallierDev/uu-remote-linux/pkgs/container/uu-remote-linux)。
|
||||||
>
|
>
|
||||||
> 这是个人兴趣项目,**与网易无关,也不是官方客户端**。如果网易认为本项目侵权或有不妥,
|
> 这是个人兴趣项目,**与网易无关,也不是官方客户端**。如果网易认为本项目侵权或有不妥,
|
||||||
> 请在推特私信我 **[@ai_fengshou](https://x.com/ai_fengshou)**,我会第一时间自行下架。
|
> 请在推特私信我 **[@ai_fengshou](https://x.com/ai_fengshou)**,我会第一时间自行下架。
|
||||||
|
|
||||||
|
<p align="center"><img src="docs/images/viewer-window.png" width="720" alt="Linux 控制端启动窗口:设备列表(设备名已打码)"></p>
|
||||||
|
<p align="center"><sub>Linux 控制端:设备列表(设备名已打码)</sub></p>
|
||||||
|
|
||||||
<p align="center"><img src="docs/images/main-window.png" width="620" alt="Linux 主机主窗口:远程协助与账号"></p>
|
<p align="center"><img src="docs/images/main-window.png" width="620" alt="Linux 主机主窗口:远程协助与账号"></p>
|
||||||
<p align="center"><sub>首次运行时弹出的扫码登录窗口(二维码已打码)</sub></p>
|
<p align="center"><sub>Linux 被控端主窗口:远程协助与账号(设备 ID、验证码和账号已打码)</sub></p>
|
||||||
|
|
||||||
<!-- 截图占位:在官方客户端里远控 Linux 桌面的效果图。请自行截图并去掉账号、设备名等信息后放到
|
<!-- 截图占位:在官方客户端里远控 Linux 桌面的效果图。请自行截图并去掉账号、设备名等信息后放到
|
||||||
docs/images/remote-desktop.png,再取消下面这行的注释。注意不要截入网易的图标和品牌素材。 -->
|
docs/images/remote-desktop.png,再取消下面这行的注释。注意不要截入网易的图标和品牌素材。 -->
|
||||||
@@ -204,6 +210,16 @@ install -Dm644 contrib/desktop/uu-remote-linux.desktop ~/.local/share/applicatio
|
|||||||
再执行 `loginctl enable-linger $USER`,这样开机后不用登录,systemd 用户服务(以及 `XDG_RUNTIME_DIR`、用户 D-Bus)也会自动启动。
|
再执行 `loginctl enable-linger $USER`,这样开机后不用登录,systemd 用户服务(以及 `XDG_RUNTIME_DIR`、用户 D-Bus)也会自动启动。
|
||||||
无头模式下控制端点「远程桌面」会一直显示正在连接,这是正常的。首次登录用 `uuremote-server login --no-gui` 在终端里扫码。
|
无头模式下控制端点「远程桌面」会一直显示正在连接,这是正常的。首次登录用 `uuremote-server login --no-gui` 在终端里扫码。
|
||||||
|
|
||||||
|
**群晖 / NAS(Docker)**:没有桌面的 NAS 可以用容器运行无头模式(文件传输、终端、端口映射)。
|
||||||
|
镜像 [`ghcr.io/vallierdev/uu-remote-linux`](https://github.com/VallierDev/uu-remote-linux/pkgs/container/uu-remote-linux),
|
||||||
|
**部署步骤见 [群晖 / NAS 部署指南](docs/deploy-nas-docker.md)**。已在群晖 DSM 7.3(x86_64)上实测三项功能。
|
||||||
|
|
||||||
|
**Mac 终端粘贴文件**:使用 Ghostty 通过 UU 端口映射连接 SSH 时,可安装
|
||||||
|
[Mac SSH 粘贴助手](contrib/macos-ssh/README.md)。在 Finder 复制文件后按 Command-V,
|
||||||
|
助手先通过同一个 SSH 别名上传文件,再插入服务器路径;普通文本和鼠标报告正常透传。
|
||||||
|
Ghostty 标题栏和进度条显示上传进度、已传大小、速度和耗时。
|
||||||
|
这是可选的 Mac 端工具,不会改变官方 UU 内置终端;暂不支持文件夹、拖放或原始截图剪贴板。
|
||||||
|
|
||||||
**虚拟桌面**:需要完整的远程桌面时,用 Xvfb 创建一块虚拟屏幕,再在上面跑一个桌面环境(推荐 Xfce):
|
**虚拟桌面**:需要完整的远程桌面时,用 Xvfb 创建一块虚拟屏幕,再在上面跑一个桌面环境(推荐 Xfce):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -234,6 +250,7 @@ systemctl --user restart uuremote-native.service
|
|||||||
| `UU_INPUT_BACKEND` | `auto`(默认,Wayland 下可用时用 uinput)/ `uinput` / `native` |
|
| `UU_INPUT_BACKEND` | `auto`(默认,Wayland 下可用时用 uinput)/ `uinput` / `native` |
|
||||||
| `UU_TERMINAL_SHORTCUTS=0` | 关闭终端窗口里的 Ctrl+V 粘贴转换 |
|
| `UU_TERMINAL_SHORTCUTS=0` | 关闭终端窗口里的 Ctrl+V 粘贴转换 |
|
||||||
| `UU_VIDEO_ENCODER` | `cpu` 强制 CPU;`vaapi` 显式启用 Intel/AMD 硬编;`nvenc` 强制 NVENC;未设置时检测到 NVIDIA 驱动才用 NVENC,否则用 CPU |
|
| `UU_VIDEO_ENCODER` | `cpu` 强制 CPU;`vaapi` 显式启用 Intel/AMD 硬编;`nvenc` 强制 NVENC;未设置时检测到 NVIDIA 驱动才用 NVENC,否则用 CPU |
|
||||||
|
| `UU_VAAPI_BUFFER_MS` | VAAPI 的 VBV 缓冲(10–1000 ms,仅 `UU_VIDEO_ENCODER=vaapi` 时生效);高分辨率下关键帧被压糊时用它换稳定画质 |
|
||||||
| `UU_FFMPEG_ROOT` | 使用指定目录下的 FFmpeg |
|
| `UU_FFMPEG_ROOT` | 使用指定目录下的 FFmpeg |
|
||||||
| `UU_AUDIO=0` | 关闭声音转发;`UU_AUDIO_SOURCE` 指定 PulseAudio 采集源 |
|
| `UU_AUDIO=0` | 关闭声音转发;`UU_AUDIO_SOURCE` 指定 PulseAudio 采集源 |
|
||||||
| `UU_LOGIN_WINDOW=0` | 凭证缺失时不自动弹出登录窗口 |
|
| `UU_LOGIN_WINDOW=0` | 凭证缺失时不自动弹出登录窗口 |
|
||||||
@@ -297,7 +314,12 @@ flowchart LR
|
|||||||
中优先列出 H.265)。首次桌面连接会用合成帧探测实际编码能力,并通过 CodecNegotiation 告知客户端。支持 `hevc_nvenc`、
|
中优先列出 H.265)。首次桌面连接会用合成帧探测实际编码能力,并通过 CodecNegotiation 告知客户端。支持 `hevc_nvenc`、
|
||||||
`libx265`、显式 `UU_VIDEO_ENCODER=vaapi` 的 `hevc_vaapi`;硬件失败先回落软件 HEVC,再回落 H.264。
|
`libx265`、显式 `UU_VIDEO_ENCODER=vaapi` 的 `hevc_vaapi`;硬件失败先回落软件 HEVC,再回落 H.264。
|
||||||
`UU_VIDEO_CODEC=h264` 强制使用 H.264。8-bit;真彩 4:4:4 使用 hevc_nvenc `rext` / libx265 `main444-8`。
|
`UU_VIDEO_CODEC=h264` 强制使用 H.264。8-bit;真彩 4:4:4 使用 hevc_nvenc `rext` / libx265 `main444-8`。
|
||||||
已用官方 Mac 客户端在 RTX 3090(hevc_nvenc,含 4:4:4)实机验收;libx265、hevc_vaapi 及其他客户端尚未实机验证。
|
已用官方 Mac 客户端在 RTX 3090(hevc_nvenc,含 4:4:4)实机验收;`hevc_vaapi` 配官方 Android 客户端也已实机验收
|
||||||
|
(Intel Alder Lake-P / iHD,2560×1440 全程硬件编码,客户端 58 fps 解码、约 10 ms 延迟);`libx265` 仍未经控制端验收。
|
||||||
|
|
||||||
|
HEVC 的访问单元按 RFC 7798 的图片边界切分,不依赖 AUD:`hevc_vaapi` 带 `-aud 1` 时只在 IRAP 处写 AUD,并把其余
|
||||||
|
画面从码流里丢掉,读取端按 AUD 切分就会把整个 GOP 当成一帧,再被 IRAP 门控全部拒绝——对外表现为连接停在
|
||||||
|
「正在传输画面」,而主机侧只有约 12 kbit/s。`UU_VIDEO_CODEC=h265` 可显式选中 H.265,便于对照排查。
|
||||||
|
|
||||||
### VAAPI 硬件编码(显式启用)
|
### VAAPI 硬件编码(显式启用)
|
||||||
|
|
||||||
@@ -307,6 +329,12 @@ flowchart LR
|
|||||||
VBR 使用控制端码率预设及 CQ 对应的最小 QP,无 B 帧、async depth=1,并保留现有 GOP/VFR 规则。
|
VBR 使用控制端码率预设及 CQ 对应的最小 QP,无 B 帧、async depth=1,并保留现有 GOP/VFR 规则。
|
||||||
Intel 核显(UHD 770,iHD 驱动)已实机验收:默认的外部 FFmpeg 管线用官方 Mac 控制端测试了各档画质、帧率、缩放和重连,全程硬件编码、无回退,CPU 占用比 libx264 低约 40%。**AMD 显卡和 `--features inproc-av` 管线的 VAAPI 尚未实机验证。**
|
Intel 核显(UHD 770,iHD 驱动)已实机验收:默认的外部 FFmpeg 管线用官方 Mac 控制端测试了各档画质、帧率、缩放和重连,全程硬件编码、无回退,CPU 占用比 libx264 低约 40%。**AMD 显卡和 `--features inproc-av` 管线的 VAAPI 尚未实机验证。**
|
||||||
|
|
||||||
|
高分辨率下 VAAPI 的默认 VBV 缓冲(100–500 kbit)会把关键帧压得过狠:2560×1440 H.264 VAAPI、30M
|
||||||
|
上限、静止画面上实测首个 IDR 只有 59,910 字节,画面每隔一个 GOP 糊一下再慢慢恢复。设
|
||||||
|
`UU_VAAPI_BUFFER_MS=250`(按 `码率上限 × 毫秒 / 1000` 放大 VBV)后首个 IDR 为 142,397 字节,
|
||||||
|
最低帧 Y-SSIM 从 0.9492 升到 0.9933,平均码率没有上升。默认不启用,未设置或超出 10–1000 ms
|
||||||
|
仍用原缓冲;代价是关键帧变大,弱网下可能出现瞬时排队,建议从 250 ms 试起。
|
||||||
|
|
||||||
### 静音运行与虚拟声卡
|
### 静音运行与虚拟声卡
|
||||||
|
|
||||||
控制端开启「静音运行」后,程序创建虚拟输出 `uu-remote-sink`,保存原默认输出,
|
控制端开启「静音运行」后,程序创建虚拟输出 `uu-remote-sink`,保存原默认输出,
|
||||||
@@ -390,7 +418,7 @@ GNOME 与官方 Mac 被控端的双向剪贴板尚未验证通过;此修改不
|
|||||||
`~/.config/uuremote/config.json`(可用 `UU_CONFIG` 另指定),因此**不能用同一身份连接本机上的主机**;控制其他设备不受影响。
|
`~/.config/uuremote/config.json`(可用 `UU_CONFIG` 另指定),因此**不能用同一身份连接本机上的主机**;控制其他设备不受影响。
|
||||||
- `uuremote-viewer ui`:启动窗口,列出账号下的设备,可进入桌面、只看模式、文件传输、终端、端口映射、重启/关机、远程协助。
|
- `uuremote-viewer ui`:启动窗口,列出账号下的设备,可进入桌面、只看模式、文件传输、终端、端口映射、重启/关机、远程协助。
|
||||||
- 命令行:`connect DEVICE false - echo legacy [--view-only]`(桌面)、`files DEVICE ls|get|put …`、`terminal DEVICE [SESSION]`、
|
- 命令行:`connect DEVICE false - echo legacy [--view-only]`(桌面)、`files DEVICE ls|get|put …`、`terminal DEVICE [SESSION]`、
|
||||||
`terminal-ui DEVICE NAME`、`portmap DEVICE LOCAL_PORT HOST PORT`(只监听 127.0.0.1)、`power DEVICE reboot|shutdown`、
|
`terminal-ui DEVICE NAME`、`portmap DEVICE LOCAL_PORT HOST PORT`(只监听 127.0.0.1)、`power DEVICE reboot|shutdown`、`unbind DEVICE`(从账号删除设备,启动窗口「更多工具」里也有)、
|
||||||
`assist CONNECT_ID`(验证码从 stdin 读取一行,不能作为参数传入)。`uuremote-viewer --help` 查看全部参数。
|
`assist CONNECT_ID`(验证码从 stdin 读取一行,不能作为参数传入)。`uuremote-viewer --help` 查看全部参数。
|
||||||
- 桌面窗口中按 Ctrl+Alt+F 打开文件窗口(复用同一连接)。`UU_VIEWER_AUDIO=0` 关闭声音,`UU_VIEWER_CLIPBOARD=0` 关闭剪贴板,
|
- 桌面窗口中按 Ctrl+Alt+F 打开文件窗口(复用同一连接)。`UU_VIEWER_AUDIO=0` 关闭声音,`UU_VIEWER_CLIPBOARD=0` 关闭剪贴板,
|
||||||
`UU_VIEWER_VIEW_ONLY=1` 只看不控,`UU_VIEWER_FFMPEG` 指定 ffmpeg 路径。
|
`UU_VIEWER_VIEW_ONLY=1` 只看不控,`UU_VIEWER_FFMPEG` 指定 ffmpeg 路径。
|
||||||
|
|||||||
@@ -475,6 +475,8 @@ static void build_window(void) {
|
|||||||
static void *ui_main(void *arg) {
|
static void *ui_main(void *arg) {
|
||||||
(void)arg;
|
(void)arg;
|
||||||
int ok = gtk_init_check(NULL, NULL);
|
int ok = gtk_init_check(NULL, NULL);
|
||||||
|
// The CSS hard-codes a light palette; a dark system theme would turn unstyled text white on white (#43).
|
||||||
|
if (ok) g_object_set(gtk_settings_get_default(), "gtk-theme-name", "Adwaita", "gtk-application-prefer-dark-theme", FALSE, NULL);
|
||||||
if (ok) build_window();
|
if (ok) build_window();
|
||||||
pthread_mutex_lock(&init_lock);
|
pthread_mutex_lock(&init_lock);
|
||||||
init_state = ok ? 1 : -1;
|
init_state = ok ? 1 : -1;
|
||||||
|
|||||||
@@ -474,6 +474,8 @@ static gboolean show_window(gpointer d) {
|
|||||||
static void *ui_thread(void *d) {
|
static void *ui_thread(void *d) {
|
||||||
(void)d;
|
(void)d;
|
||||||
if (!gtk_init_check(NULL, NULL)) { pthread_mutex_lock(&init_lock); init_state = -1; pthread_cond_signal(&init_cond); pthread_mutex_unlock(&init_lock); return NULL; }
|
if (!gtk_init_check(NULL, NULL)) { pthread_mutex_lock(&init_lock); init_state = -1; pthread_cond_signal(&init_cond); pthread_mutex_unlock(&init_lock); return NULL; }
|
||||||
|
// Light palette in CSS; keep a dark system theme from making unstyled text white on white (#43).
|
||||||
|
g_object_set(gtk_settings_get_default(), "gtk-theme-name", "Adwaita", "gtk-application-prefer-dark-theme", FALSE, NULL);
|
||||||
show_window(NULL); gtk_main(); return NULL;
|
show_window(NULL); gtk_main(); return NULL;
|
||||||
}
|
}
|
||||||
/* Hidden windows retain their widgets so queued idle callbacks stay valid. */
|
/* Hidden windows retain their widgets so queued idle callbacks stay valid. */
|
||||||
|
|||||||
@@ -117,6 +117,15 @@ static void more_item(GtkButton *b, gpointer kind) {
|
|||||||
if (ok) { connect_kind(k); show_toast("正在发送电源指令…"); }
|
if (ok) { connect_kind(k); show_toast("正在发送电源指令…"); }
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!strcmp(k, "unbind")) {
|
||||||
|
GtkWidget *d = gtk_message_dialog_new(GTK_WINDOW(dialog), GTK_DIALOG_MODAL, GTK_MESSAGE_WARNING, GTK_BUTTONS_NONE,
|
||||||
|
"确定要从账号中删除该设备吗?");
|
||||||
|
gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(d), "删除后需要在该设备上重新登录才能再次远控。");
|
||||||
|
gtk_dialog_add_buttons(GTK_DIALOG(d), "取消", GTK_RESPONSE_CANCEL, "删除", GTK_RESPONSE_OK, NULL);
|
||||||
|
int ok = gtk_dialog_run(GTK_DIALOG(d)) == GTK_RESPONSE_OK; gtk_widget_destroy(d);
|
||||||
|
if (ok) { gtk_widget_destroy(dialog); connect_kind(k); show_toast("正在删除设备…"); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
gtk_widget_destroy(dialog);
|
gtk_widget_destroy(dialog);
|
||||||
on_tool(NULL, kind);
|
on_tool(NULL, kind);
|
||||||
}
|
}
|
||||||
@@ -126,9 +135,9 @@ static void open_more(void) {
|
|||||||
GtkWidget *area = gtk_dialog_get_content_area(GTK_DIALOG(dialog)), *box = vbox(10);
|
GtkWidget *area = gtk_dialog_get_content_area(GTK_DIALOG(dialog)), *box = vbox(10);
|
||||||
gtk_container_set_border_width(GTK_CONTAINER(box), 22);
|
gtk_container_set_border_width(GTK_CONTAINER(box), 22);
|
||||||
gtk_box_pack_start(GTK_BOX(box), label("更多工具", "h2"), FALSE, FALSE, 6);
|
gtk_box_pack_start(GTK_BOX(box), label("更多工具", "h2"), FALSE, FALSE, 6);
|
||||||
const char *names[] = {"🗂 文件传输", "▶ 观看模式", "⌨ 终端", "⇄ 端口映射", "⏻ 远程开机", "↻ 重启", "⏻ 关机"};
|
const char *names[] = {"🗂 文件传输", "▶ 观看模式", "⌨ 终端", "⇄ 端口映射", "⏻ 远程开机", "↻ 重启", "⏻ 关机", "🗑 删除设备"};
|
||||||
const char *kinds[] = {"file", "watch", "terminal", "portmap", "wol", "reboot", "shutdown"};
|
const char *kinds[] = {"file", "watch", "terminal", "portmap", "wol", "reboot", "shutdown", "unbind"};
|
||||||
for (int i = 0; i < 7; i++) {
|
for (int i = 0; i < 8; i++) {
|
||||||
GtkWidget *b = gtk_button_new(), *line = hbox(10); add_class(b, "cardbtn");
|
GtkWidget *b = gtk_button_new(), *line = hbox(10); add_class(b, "cardbtn");
|
||||||
gtk_box_pack_start(GTK_BOX(line), label(names[i], "devname"), TRUE, TRUE, 0);
|
gtk_box_pack_start(GTK_BOX(line), label(names[i], "devname"), TRUE, TRUE, 0);
|
||||||
gtk_box_pack_end(GTK_BOX(line), label("›", "hint"), FALSE, FALSE, 0);
|
gtk_box_pack_end(GTK_BOX(line), label("›", "hint"), FALSE, FALSE, 0);
|
||||||
@@ -581,6 +590,8 @@ static gboolean on_delete(GtkWidget *w, GdkEvent *e, gpointer d) { (void)w; (voi
|
|||||||
static void *run(void *arg) {
|
static void *run(void *arg) {
|
||||||
(void)arg;
|
(void)arg;
|
||||||
int ok = gtk_init_check(NULL, NULL);
|
int ok = gtk_init_check(NULL, NULL);
|
||||||
|
// The CSS hard-codes a light palette; a dark system theme would turn unstyled text white on white (#43).
|
||||||
|
if (ok) g_object_set(gtk_settings_get_default(), "gtk-theme-name", "Adwaita", "gtk-application-prefer-dark-theme", FALSE, NULL);
|
||||||
if (ok) {
|
if (ok) {
|
||||||
GtkCssProvider *css = gtk_css_provider_new();
|
GtkCssProvider *css = gtk_css_provider_new();
|
||||||
gtk_css_provider_load_from_data(css, CSS, -1, NULL);
|
gtk_css_provider_load_from_data(css, CSS, -1, NULL);
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
* Zero-Wine dependency, zero-overhead, thread-safe.
|
* Zero-Wine dependency, zero-overhead, thread-safe.
|
||||||
*/
|
*/
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
|
#include <unistd.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <sys/shm.h>
|
#include <sys/shm.h>
|
||||||
@@ -218,6 +219,54 @@ int x11_key_symbol(unsigned long symbol, int is_press) {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Type UTF-8 text the way xdotool does: bind each character's keysym to a spare (unmapped) keycode, press it,
|
||||||
|
* then restore the keycode. Works for CJK text from mobile input methods. Never logs the text. */
|
||||||
|
int x11_type_utf8(const char *text) {
|
||||||
|
if (!g_display || !text) return -1;
|
||||||
|
int min_kc = 0, max_kc = 0, per = 0;
|
||||||
|
XDisplayKeycodes(g_display, &min_kc, &max_kc);
|
||||||
|
KeySym *map = XGetKeyboardMapping(g_display, (KeyCode)min_kc, max_kc - min_kc + 1, &per);
|
||||||
|
if (!map) return -2;
|
||||||
|
int spare = 0;
|
||||||
|
for (int kc = max_kc; kc >= min_kc && !spare; kc--) {
|
||||||
|
int empty = 1;
|
||||||
|
for (int i = 0; i < per; i++) if (map[(kc - min_kc) * per + i] != NoSymbol) { empty = 0; break; }
|
||||||
|
if (empty) spare = kc;
|
||||||
|
}
|
||||||
|
XFree(map);
|
||||||
|
if (!spare) return -3;
|
||||||
|
int typed = 0;
|
||||||
|
const unsigned char *p = (const unsigned char *)text;
|
||||||
|
while (*p) {
|
||||||
|
unsigned cp; int n;
|
||||||
|
if (*p < 0x80) { cp = *p; n = 1; }
|
||||||
|
else if ((*p & 0xE0) == 0xC0 && (p[1] & 0xC0) == 0x80) { cp = ((p[0] & 0x1F) << 6) | (p[1] & 0x3F); n = 2; }
|
||||||
|
else if ((*p & 0xF0) == 0xE0 && (p[1] & 0xC0) == 0x80 && (p[2] & 0xC0) == 0x80) { cp = ((p[0] & 0x0F) << 12) | ((p[1] & 0x3F) << 6) | (p[2] & 0x3F); n = 3; }
|
||||||
|
else if ((*p & 0xF8) == 0xF0 && (p[1] & 0xC0) == 0x80 && (p[2] & 0xC0) == 0x80 && (p[3] & 0xC0) == 0x80) { cp = ((p[0] & 0x07) << 18) | ((p[1] & 0x3F) << 12) | ((p[2] & 0x3F) << 6) | (p[3] & 0x3F); n = 4; }
|
||||||
|
else { p++; continue; }
|
||||||
|
p += n;
|
||||||
|
KeySym sym;
|
||||||
|
if (cp == '\n') sym = 0xff0d; /* Return */
|
||||||
|
else if (cp == '\t') sym = 0xff09; /* Tab */
|
||||||
|
else if (cp < 0x20 || cp == 0x7f || (cp >= 0x80 && cp < 0xa0)) continue;
|
||||||
|
else if (cp < 0x100) sym = cp; /* Latin-1 keysyms equal the code point */
|
||||||
|
else sym = 0x1000000 | cp; /* Unicode keysym */
|
||||||
|
KeySym syms[2] = { sym, sym };
|
||||||
|
XChangeKeyboardMapping(g_display, spare, 2, syms, 1);
|
||||||
|
XSync(g_display, False);
|
||||||
|
usleep(8000); /* let clients see the MappingNotify before the key */
|
||||||
|
XTestFakeKeyEvent(g_display, spare, True, CurrentTime);
|
||||||
|
XTestFakeKeyEvent(g_display, spare, False, CurrentTime);
|
||||||
|
XSync(g_display, False);
|
||||||
|
usleep(8000);
|
||||||
|
typed++;
|
||||||
|
}
|
||||||
|
KeySym none[2] = { NoSymbol, NoSymbol };
|
||||||
|
XChangeKeyboardMapping(g_display, spare, 2, none, 1);
|
||||||
|
XSync(g_display, False);
|
||||||
|
return typed;
|
||||||
|
}
|
||||||
|
|
||||||
int x11_key_event(int keycode, int is_press) {
|
int x11_key_event(int keycode, int is_press) {
|
||||||
if (!g_display) return -1;
|
if (!g_display) return -1;
|
||||||
if (is_press) track_injected_key(keycode, 1);
|
if (is_press) track_injected_key(keycode, 1);
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
__pycache__/
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
# Paste copied files into a UU-mapped SSH terminal on macOS
|
||||||
|
|
||||||
|
This optional Mac companion uploads files copied in Finder when you paste them
|
||||||
|
into Ghostty, then inserts shell-quoted **remote** paths into the terminal.
|
||||||
|
For example, copy an image in Finder, connect with `uu-ssh-paste`, and press
|
||||||
|
Command-V at a remote shell prompt or in a terminal application's text field.
|
||||||
|
The file is available on the server before its path is inserted. No Enter is sent.
|
||||||
|
|
||||||
|
The connection is Ghostty → OpenSSH → your existing UU TCP mapping → the Linux
|
||||||
|
host's SSH server. Both terminal traffic and uploads use the same SSH alias.
|
||||||
|
The companion does not create a mapping or fall back to a public network route.
|
||||||
|
The official Mac UU application's built-in terminal is unaffected.
|
||||||
|
|
||||||
|
## Install and connect
|
||||||
|
|
||||||
|
On the controlling Mac, install Python 3 and Apple's command-line developer
|
||||||
|
tools (for `swiftc`), then run from this repository:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sh contrib/macos-ssh/install.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
Enable port mapping on your Linux UU host (`UU_PORT_MAPPING=1`); in the official
|
||||||
|
Mac UU app, map a **local loopback** port to `127.0.0.1:22` on that host. Keep
|
||||||
|
the mapping connected. Configure an SSH alias for that local port, using your
|
||||||
|
existing key and the server's verified host key. For example:
|
||||||
|
|
||||||
|
```sshconfig
|
||||||
|
Host uu-server
|
||||||
|
HostName 127.0.0.1
|
||||||
|
Port 22243
|
||||||
|
User your-linux-user
|
||||||
|
IdentityFile ~/.ssh/id_ed25519
|
||||||
|
IdentitiesOnly yes
|
||||||
|
HostKeyAlias your-existing-server-host-key-name
|
||||||
|
StrictHostKeyChecking yes
|
||||||
|
ProxyCommand none
|
||||||
|
ProxyJump none
|
||||||
|
```
|
||||||
|
|
||||||
|
In Ghostty, connect using that alias:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
uu-ssh-paste uu-server
|
||||||
|
# Or use a separate SSH config:
|
||||||
|
uu-ssh-paste -F ~/.config/your-uu-ssh.conf uu-server
|
||||||
|
```
|
||||||
|
|
||||||
|
Copy one or several files in Finder with Command-C, switch to the connected
|
||||||
|
terminal, and press Command-V. Each paste creates a unique mode-0700 directory
|
||||||
|
under `~/.local/share/uuremote/uploads/` on the server. Files remain there until
|
||||||
|
you remove them. Filenames with spaces, Unicode and shell metacharacters are
|
||||||
|
supported. Existing files are never overwritten by another paste batch.
|
||||||
|
|
||||||
|
Text paste, SSH exit statuses, terminal resizing and mouse reports pass through.
|
||||||
|
The remote application still controls whether it receives bracketed paste and
|
||||||
|
mouse movement. Ctrl-C during a transfer cancels that paste. Input typed while
|
||||||
|
the upload is running is queued, so Enter cannot overtake the uploaded path.
|
||||||
|
|
||||||
|
Ghostty's title bar shows the connection phase, upload percentage, transferred
|
||||||
|
size, transfer speed and elapsed time. Its progress indicator tracks the upload
|
||||||
|
too. Progress is derived from OpenSSH's transfer meter, aggregated across copied
|
||||||
|
files; it is not a simulated timer. The original terminal title is restored when
|
||||||
|
the upload finishes, fails or is cancelled, and no terminal cells are overwritten.
|
||||||
|
Filename and error output from SCP stays private; only numeric progress is shown.
|
||||||
|
|
||||||
|
## Scope and failure behavior
|
||||||
|
|
||||||
|
- Only file-URL clipboard entries copied in Finder are uploaded, and only when
|
||||||
|
they match the complete pasted path list. Pasting a textual local path or a
|
||||||
|
command does not upload anything. The clipboard is never modified or polled
|
||||||
|
in the background; file URLs are read only during a potential file paste.
|
||||||
|
- Folder paste, drag-and-drop and raw screenshot/image clipboard data are not
|
||||||
|
supported. Save an image as a file and copy that file in Finder first.
|
||||||
|
- The SSH server must support SFTP. Upload authentication is noninteractive
|
||||||
|
(`BatchMode=yes`); the alias must already work with a key or SSH agent.
|
||||||
|
- Missing files, duplicate basenames in a batch, control characters in filenames,
|
||||||
|
failed uploads and clipboard-reader failures do not insert a misleading path.
|
||||||
|
Failed transfer directories are removed on a best-effort basis. No file names,
|
||||||
|
clipboard contents, file contents, terminal input or SSH error text are logged.
|
||||||
|
- A paste is limited to 256 files and 8 MiB of pasted path/text data. Transfers
|
||||||
|
time out after five minutes. File sizes themselves are not limited to 8 MiB.
|
||||||
|
- The companion keeps local bracketed-paste framing enabled while the session
|
||||||
|
runs and removes framing for remote applications that have not requested it.
|
||||||
|
No global Ghostty configuration, remote desktop or Wine component is needed.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
```sh
|
||||||
|
python3 -m unittest discover -s contrib/macos-ssh -p 'test_*.py' -v
|
||||||
|
swiftc -O contrib/macos-ssh/clipboard-files.swift -o /tmp/clipboard-files
|
||||||
|
/tmp/clipboard-files --self-test
|
||||||
|
# Optional real SSH/SFTP acceptance test over an already connected UU mapping:
|
||||||
|
UU_PASTE_TEST_HOST=uu-server UU_PASTE_TEST_CONFIG="$HOME/.config/your-uu-ssh.conf" \
|
||||||
|
python3 -m unittest discover -s contrib/macos-ssh -p 'test_*.py' -v
|
||||||
|
```
|
||||||
|
|
||||||
|
The Swift test uses a private pasteboard and never touches the user's clipboard.
|
||||||
|
Python tests exercise fragmented paste framing, shell quoting, plain text,
|
||||||
|
mouse reports, failed uploads, queued Enter, PTY restoration and exit status.
|
||||||
|
The optional live tests transfer synthetic binary files and verify hashes,
|
||||||
|
including a throttled upload that must report intermediate byte progress.
|
||||||
|
Physical Command-C/Command-V behavior in Finder/Ghostty remains a manual check.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import AppKit
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
// Only file URLs are read. Text, images and the general pasteboard are never
|
||||||
|
// written, and the result is consumed privately by the SSH companion.
|
||||||
|
func filePaths(_ board: NSPasteboard) -> [String] {
|
||||||
|
let options: [NSPasteboard.ReadingOptionKey: Any] = [.urlReadingFileURLsOnly: true]
|
||||||
|
return (board.readObjects(forClasses: [NSURL.self], options: options) as? [URL] ?? [])
|
||||||
|
.filter { $0.isFileURL }.map { $0.path }
|
||||||
|
}
|
||||||
|
|
||||||
|
if CommandLine.arguments.dropFirst().first == "--self-test" {
|
||||||
|
// An isolated pasteboard: tests never read or overwrite the user's clipboard.
|
||||||
|
let board = NSPasteboard.withUniqueName()
|
||||||
|
defer { board.releaseGlobally() }
|
||||||
|
let paths = ["/tmp/space and 中文.png", "/tmp/quote'$(literal).txt"]
|
||||||
|
board.writeObjects(paths.map { NSURL(fileURLWithPath: $0) })
|
||||||
|
precondition(filePaths(board) == paths)
|
||||||
|
board.clearContents()
|
||||||
|
board.setString("/tmp/text-is-not-a-file", forType: .string)
|
||||||
|
precondition(filePaths(board).isEmpty)
|
||||||
|
board.clearContents()
|
||||||
|
board.writeObjects([NSURL(string: "https://example.invalid/file")!])
|
||||||
|
precondition(filePaths(board).isEmpty)
|
||||||
|
print("Private pasteboard tests passed")
|
||||||
|
} else {
|
||||||
|
let data = try JSONSerialization.data(withJSONObject: filePaths(.general))
|
||||||
|
FileHandle.standardOutput.write(data)
|
||||||
|
}
|
||||||
Executable
+27
@@ -0,0 +1,27 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
if [ "$(uname -s)" != Darwin ]; then
|
||||||
|
echo 'Install this companion on the controlling Mac.' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
command -v python3 >/dev/null
|
||||||
|
source_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||||
|
data_dir="$HOME/.local/share/uuremote/macos-ssh"
|
||||||
|
bin_dir="$HOME/.local/bin"
|
||||||
|
mkdir -p "$data_dir" "$bin_dir"
|
||||||
|
scratch=$(mktemp -d)
|
||||||
|
trap 'rm -rf "$scratch"' EXIT HUP INT TERM
|
||||||
|
swiftc -O "$source_dir/clipboard-files.swift" -o "$scratch/clipboard-files"
|
||||||
|
"$scratch/clipboard-files" --self-test
|
||||||
|
install -m 755 "$scratch/clipboard-files" "$data_dir/clipboard-files"
|
||||||
|
install -m 755 "$source_dir/uu-ssh-paste" "$data_dir/uu-ssh-paste"
|
||||||
|
if [ -e "$bin_dir/uu-ssh-paste" ] && [ ! -L "$bin_dir/uu-ssh-paste" ]; then
|
||||||
|
echo 'An existing uu-ssh-paste file was preserved; inspect it before replacing it.' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if [ -L "$bin_dir/uu-ssh-paste" ] && [ "$(readlink "$bin_dir/uu-ssh-paste")" != "$data_dir/uu-ssh-paste" ]; then
|
||||||
|
echo 'An unrelated uu-ssh-paste symlink was preserved; inspect it before replacing it.' >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
ln -sfn "$data_dir/uu-ssh-paste" "$bin_dir/uu-ssh-paste"
|
||||||
|
echo 'Installed uu-ssh-paste. Connect using your existing UU SSH alias.'
|
||||||
@@ -0,0 +1,472 @@
|
|||||||
|
"""Synthetic fixtures only; never inspect or change the general pasteboard."""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import errno
|
||||||
|
import hashlib
|
||||||
|
import importlib.machinery
|
||||||
|
import importlib.util
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import pty
|
||||||
|
import select
|
||||||
|
import shlex
|
||||||
|
import signal
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import termios
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
|
||||||
|
SCRIPT = Path(__file__).with_name("uu-ssh-paste")
|
||||||
|
loader = importlib.machinery.SourceFileLoader("uu_paste", str(SCRIPT))
|
||||||
|
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||||
|
paste = importlib.util.module_from_spec(spec)
|
||||||
|
loader.exec_module(paste)
|
||||||
|
|
||||||
|
|
||||||
|
class FramingTests(unittest.TestCase):
|
||||||
|
def test_paste_at_every_fragment_boundary_and_multiple_pastes(self):
|
||||||
|
wire = b"key" + paste.START + b"hello\nworld" + paste.END + b"\r"
|
||||||
|
expected = [("data", b"key"), ("paste", b"hello\nworld"), ("data", b"\r")]
|
||||||
|
for split in range(len(wire) + 1):
|
||||||
|
frames = paste.InputFrames()
|
||||||
|
events = frames.feed(wire[:split]) + frames.feed(wire[split:])
|
||||||
|
merged = []
|
||||||
|
for kind, data in events:
|
||||||
|
if kind == "data" and merged and merged[-1][0] == "data":
|
||||||
|
merged[-1] = (kind, merged[-1][1] + data)
|
||||||
|
else:
|
||||||
|
merged.append((kind, data))
|
||||||
|
self.assertEqual(merged, expected)
|
||||||
|
frames = paste.InputFrames()
|
||||||
|
self.assertEqual(frames.feed(paste.START + b"a" + paste.END + paste.START + b"b" + paste.END),
|
||||||
|
[("paste", b"a"), ("paste", b"b")])
|
||||||
|
|
||||||
|
def test_mouse_and_arrow_bytes_and_standalone_escape(self):
|
||||||
|
raw = b"\x1b[<2;12;4M\x1b[<2;12;4m\x1b[<35;13;5M\x1b[A\x1b"
|
||||||
|
frames = paste.InputFrames()
|
||||||
|
output = b"".join(data for kind, data in frames.feed(raw) if kind == "data")
|
||||||
|
self.assertEqual(output + frames.flush_key(), raw)
|
||||||
|
|
||||||
|
def test_oversized_paste_is_discarded_and_parser_recovers(self):
|
||||||
|
frames = paste.InputFrames()
|
||||||
|
with mock.patch.object(paste, "MAX_PASTE", 16):
|
||||||
|
self.assertEqual(frames.feed(paste.START + b"x" * 40), [])
|
||||||
|
self.assertEqual(frames.feed(paste.END + b"next")[-1], ("data", b"next"))
|
||||||
|
self.assertFalse(frames.pasting)
|
||||||
|
self.assertLess(len(frames.buffer), 16)
|
||||||
|
|
||||||
|
def test_remote_modes_track_split_sequences_without_disabling_local_framing(self):
|
||||||
|
for split in range(len(paste.DISABLE) + 1):
|
||||||
|
modes = paste.OutputModes()
|
||||||
|
modes.bracketed = True
|
||||||
|
result = modes.feed(paste.DISABLE[:split]) + modes.feed(paste.DISABLE[split:])
|
||||||
|
self.assertEqual(result, paste.ENABLE)
|
||||||
|
self.assertFalse(modes.bracketed)
|
||||||
|
modes = paste.OutputModes()
|
||||||
|
self.assertEqual(modes.feed(b"\x1b[?1;2004h"), b"\x1b[?1h" + paste.ENABLE)
|
||||||
|
self.assertTrue(modes.bracketed)
|
||||||
|
self.assertEqual(modes.feed(b"\x1b[?2004;25l"), b"\x1b[?25l" + paste.ENABLE)
|
||||||
|
self.assertFalse(modes.bracketed)
|
||||||
|
self.assertEqual(modes.feed(b"\x1bc"), b"\x1bc" + paste.ENABLE)
|
||||||
|
raw = b"\x1b[31mhello\x1b[0m\x1b]0;title\x07"
|
||||||
|
self.assertEqual(modes.feed(raw), raw)
|
||||||
|
|
||||||
|
|
||||||
|
class FileTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.temp = tempfile.TemporaryDirectory()
|
||||||
|
self.addCleanup(self.temp.cleanup)
|
||||||
|
self.root = Path(self.temp.name)
|
||||||
|
self.files = [self.root / "space 中文.png", self.root / "quote'$(literal);.txt"]
|
||||||
|
for path in self.files:
|
||||||
|
path.write_bytes(os.urandom(1025))
|
||||||
|
self.paths = [str(p) for p in self.files]
|
||||||
|
# Ghostty uses backslash escaping rather than POSIX single quotes.
|
||||||
|
escape = "\\ ()[]{}<>\"'`!#$&;|*?\t"
|
||||||
|
self.payload = " ".join("".join("\\" + c if c in escape else c for c in p)
|
||||||
|
for p in self.paths).encode()
|
||||||
|
|
||||||
|
def test_finder_files_match_ghostty_escaping(self):
|
||||||
|
self.assertEqual(paste.copied_files(self.payload, lambda: self.paths), self.paths)
|
||||||
|
|
||||||
|
def test_plain_text_and_pasted_commands_do_not_upload(self):
|
||||||
|
clipboard = mock.Mock(return_value=[])
|
||||||
|
for value in (b"hello\nworld", b"cat /tmp/file", b"\xff", b"'unterminated"):
|
||||||
|
self.assertIsNone(paste.copied_files(value, clipboard))
|
||||||
|
clipboard.assert_not_called()
|
||||||
|
self.assertIsNone(paste.copied_files(self.payload, lambda: []))
|
||||||
|
self.assertIsNone(paste.copied_files(self.payload, lambda: self.paths[::-1]))
|
||||||
|
|
||||||
|
def test_missing_files_folders_duplicate_names_and_control_characters_rejected(self):
|
||||||
|
cases = [[str(self.root)], [str(self.root / "missing")]]
|
||||||
|
newline = self.root / "bad\nname"
|
||||||
|
newline.write_text("synthetic")
|
||||||
|
cases.append([str(newline)])
|
||||||
|
folder = self.root / "another"
|
||||||
|
folder.mkdir()
|
||||||
|
duplicate = folder / self.files[0].name
|
||||||
|
duplicate.write_text("synthetic")
|
||||||
|
cases.append([self.paths[0], str(duplicate)])
|
||||||
|
for paths in cases:
|
||||||
|
with self.assertRaises(paste.PasteError):
|
||||||
|
paste.copied_files(shlex.join(paths).encode(), lambda: paths)
|
||||||
|
|
||||||
|
def test_upload_paths_are_quoted_and_failed_batch_is_cleaned(self):
|
||||||
|
uploader = paste.Uploader(self.root / "config with spaces", "uu-test")
|
||||||
|
directory = b"/home/test user/.local/share/uuremote/uploads/paste.ABCD1234\n"
|
||||||
|
with mock.patch.object(paste, "run_private", side_effect=[directory, b""]) as run:
|
||||||
|
result = uploader.upload(self.paths, threading.Event())
|
||||||
|
self.assertEqual(shlex.split(result.decode()),
|
||||||
|
[directory.decode().strip() + "/" + p.name for p in self.files])
|
||||||
|
self.assertEqual(run.call_args_list[1].args[0][-3:-1], self.paths)
|
||||||
|
self.assertNotIn("-O", run.call_args_list[1].args[0])
|
||||||
|
self.assertIn("BatchMode=yes", run.call_args_list[1].args[0])
|
||||||
|
with mock.patch.object(paste, "run_private", side_effect=[directory, paste.PasteError("failed"), b""]) as run:
|
||||||
|
with self.assertRaises(paste.PasteError):
|
||||||
|
uploader.upload(self.paths, threading.Event())
|
||||||
|
cleanup = run.call_args_list[2].args[0][-1]
|
||||||
|
self.assertEqual(shlex.split(cleanup), ["rm", "-rf", "--", directory.decode().strip()])
|
||||||
|
|
||||||
|
def test_bad_destination_and_bad_clipboard_fail_without_content_in_error(self):
|
||||||
|
uploader = paste.Uploader(None, "uu-test")
|
||||||
|
for output in (b"relative", b"/tmp/invalid", b"/tmp/paste.abc\nextra", b"\xff"):
|
||||||
|
with mock.patch.object(paste, "run_private", return_value=output):
|
||||||
|
with self.assertRaises(paste.PasteError):
|
||||||
|
uploader.upload(self.paths, threading.Event())
|
||||||
|
with mock.patch.object(paste.subprocess, "run", return_value=subprocess.CompletedProcess([], 0, b"{}")):
|
||||||
|
with self.assertRaises(paste.PasteError):
|
||||||
|
paste.clipboard_paths("helper")
|
||||||
|
|
||||||
|
def test_cancellation_stops_transfer(self):
|
||||||
|
cancel = threading.Event()
|
||||||
|
cancel.set()
|
||||||
|
with self.assertRaisesRegex(paste.PasteError, "cancelled"):
|
||||||
|
paste.run_private([sys.executable, "-c", "import time;time.sleep(30)"], cancel, 3)
|
||||||
|
|
||||||
|
|
||||||
|
class ProgressTests(unittest.TestCase):
|
||||||
|
def test_numeric_meter_handles_fragments_multiple_files_and_rounding(self):
|
||||||
|
for fragment in (1, 7, 9999):
|
||||||
|
reports = []
|
||||||
|
meter = paste.SCPMeter([1048576, 1025], lambda *args: reports.append(args))
|
||||||
|
wire = (b"\rprivate-file 0% 0 0.0KB/s --:-- ETA"
|
||||||
|
b"\rprivate-file 50% 512KB 128.0KB/s 00:04 ETA"
|
||||||
|
b"\rprivate-file 100% 1024KB 128.0KB/s 00:08\r\n"
|
||||||
|
b"\rsecret-other 0% 0 0.0KB/s --:-- ETA"
|
||||||
|
b"\rsecret-other 100% 1025 64.0KB/s 00:00\r\n")
|
||||||
|
for offset in range(0, len(wire), fragment):
|
||||||
|
meter.feed(wire[offset:offset + fragment])
|
||||||
|
self.assertIn(("uploading", 524288, 1049601, 131072), reports)
|
||||||
|
self.assertEqual(reports[-1], ("uploading", 1049601, 1049601, 65536))
|
||||||
|
self.assertEqual(meter.index, 2)
|
||||||
|
self.assertEqual([p[1] for p in reports], sorted(p[1] for p in reports))
|
||||||
|
self.assertNotIn("private-file", repr(reports))
|
||||||
|
self.assertNotIn("secret-other", repr(reports))
|
||||||
|
|
||||||
|
def test_unrecognized_output_is_not_displayed_and_buffer_is_bounded(self):
|
||||||
|
reports = []
|
||||||
|
meter = paste.SCPMeter([10], lambda *args: reports.append(args))
|
||||||
|
meter.feed(b"private error " * 10000 + b" 999% 5 1.0KB/s 00:00\n")
|
||||||
|
self.assertEqual(reports, [])
|
||||||
|
self.assertLessEqual(len(meter.buffer), 512)
|
||||||
|
|
||||||
|
def test_metered_process_captures_progress_privately_and_preserves_failure_cancellation(self):
|
||||||
|
reports = []
|
||||||
|
code = ("import os;assert os.isatty(1);assert os.tcgetpgrp(1)==os.getpgrp();"
|
||||||
|
"os.write(1,b'\\rprivate-file 100% 1025 64.0KB/s 00:00\\n')")
|
||||||
|
paste.run_metered([sys.executable, "-c", code], threading.Event(), 5,
|
||||||
|
paste.SCPMeter([1025], lambda *args: reports.append(args)))
|
||||||
|
self.assertEqual(reports[-1], ("uploading", 1025, 1025, 65536))
|
||||||
|
with self.assertRaises(paste.PasteError):
|
||||||
|
paste.run_metered([sys.executable, "-c", "raise SystemExit(2)"], threading.Event(), 5,
|
||||||
|
paste.SCPMeter([1], lambda *_: None))
|
||||||
|
cancel = threading.Event()
|
||||||
|
cancel.set()
|
||||||
|
with self.assertRaises(paste.PasteError):
|
||||||
|
paste.run_metered([sys.executable, "-c", "import time;time.sleep(30)"], cancel, 5,
|
||||||
|
paste.SCPMeter([1], lambda *_: None))
|
||||||
|
|
||||||
|
def test_display_restores_split_remote_title_and_never_changes_terminal_cells(self):
|
||||||
|
output = []
|
||||||
|
display = paste.UploadDisplay(output.append)
|
||||||
|
for byte in b"\x1b]2;remote app title\x1b\\":
|
||||||
|
display.observe(bytes([byte]))
|
||||||
|
with mock.patch.object(paste.time, "monotonic", return_value=10):
|
||||||
|
display.start(1048576)
|
||||||
|
with mock.patch.object(paste.time, "monotonic", return_value=13):
|
||||||
|
display.update("uploading", 524288, 1048576, 131072)
|
||||||
|
display.render()
|
||||||
|
display.render() # Throttled, not a second display update.
|
||||||
|
self.assertEqual(len(output), 2)
|
||||||
|
self.assertIn(b"Connecting", output[0])
|
||||||
|
self.assertIn(b"Uploading 50% | 512.0 KiB/1.0 MiB | 128.0 KiB/s | 3s", output[1])
|
||||||
|
self.assertIn(b"\x1b]9;4;1;50\x1b\\", output[1])
|
||||||
|
display.observe(b"\x1b]0;new remote title\x07")
|
||||||
|
display.finish()
|
||||||
|
self.assertEqual(output[-1], b"\x1b]9;4;0\x1b\\\x1b]2;new remote title\x1b\\")
|
||||||
|
display.finish()
|
||||||
|
self.assertEqual(len(output), 3)
|
||||||
|
self.assertTrue(all(b"\n" not in item and b"\r" not in item for item in output))
|
||||||
|
|
||||||
|
|
||||||
|
HARNESS = r'''
|
||||||
|
import os, runpy, sys, time, json
|
||||||
|
h = runpy.run_path(sys.argv[1])
|
||||||
|
paths, remote, mode, fail = json.loads(sys.argv[2])
|
||||||
|
class Upload:
|
||||||
|
def upload(self, files, cancel, progress):
|
||||||
|
assert files == paths
|
||||||
|
progress('uploading',512,1024,256)
|
||||||
|
time.sleep(0.1)
|
||||||
|
if fail == 'cancel':
|
||||||
|
assert cancel.wait(5)
|
||||||
|
if fail:
|
||||||
|
raise h['PasteError']('synthetic failure')
|
||||||
|
return remote.encode()
|
||||||
|
child = """import os,tty,base64
|
||||||
|
tty.setraw(0)
|
||||||
|
os.write(1, %r + b'CHILD_READY')
|
||||||
|
data=b''
|
||||||
|
while not data.endswith(b'\\r'):
|
||||||
|
part=os.read(0,65536)
|
||||||
|
if not part: break
|
||||||
|
data+=part
|
||||||
|
os.write(1,b'RECEIVED:' + base64.b64encode(data) + b':DONE')
|
||||||
|
raise SystemExit(7)
|
||||||
|
""" % (h['ENABLE'] if mode else h['DISABLE'])
|
||||||
|
raise SystemExit(h['relay']([sys.executable,'-c',child], lambda: paths, Upload()))
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
class RelayTests(unittest.TestCase):
|
||||||
|
def test_resize_and_signal_shutdown_restore_terminal(self):
|
||||||
|
child = r'''
|
||||||
|
import fcntl,os,signal,struct,termios,tty
|
||||||
|
tty.setraw(0)
|
||||||
|
def resized(*_):
|
||||||
|
rows,cols,_,_=struct.unpack('HHHH',fcntl.ioctl(0,termios.TIOCGWINSZ,bytes(8)))
|
||||||
|
os.write(1,('SIZE:%d,%d;'%(rows,cols)).encode())
|
||||||
|
signal.signal(signal.SIGWINCH,resized)
|
||||||
|
resized()
|
||||||
|
while True: signal.pause()
|
||||||
|
'''
|
||||||
|
harness = "import runpy,sys;h=runpy.run_path(sys.argv[1]);h['relay']([sys.executable,'-c',sys.argv[2]],lambda:[],None)"
|
||||||
|
master, slave = pty.openpty()
|
||||||
|
original = termios.tcgetattr(slave)
|
||||||
|
import fcntl
|
||||||
|
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 80, 0, 0))
|
||||||
|
proc = subprocess.Popen([sys.executable, "-c", harness, str(SCRIPT), child],
|
||||||
|
stdin=slave, stdout=slave, stderr=slave)
|
||||||
|
output = bytearray()
|
||||||
|
|
||||||
|
def until(marker):
|
||||||
|
deadline = time.monotonic() + 5
|
||||||
|
while marker not in output:
|
||||||
|
self.assertLess(time.monotonic(), deadline, "Resize was not forwarded")
|
||||||
|
if select.select([master], [], [], 0.1)[0]:
|
||||||
|
output.extend(os.read(master, 65536))
|
||||||
|
try:
|
||||||
|
until(b"SIZE:24,80;")
|
||||||
|
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 31, 110, 0, 0))
|
||||||
|
proc.send_signal(signal.SIGWINCH)
|
||||||
|
until(b"SIZE:31,110;")
|
||||||
|
proc.send_signal(signal.SIGTERM)
|
||||||
|
self.assertEqual(proc.wait(timeout=5), 128 + signal.SIGTERM)
|
||||||
|
restored = termios.tcgetattr(slave)
|
||||||
|
restored[3] &= ~getattr(termios, "PENDIN", 0)
|
||||||
|
original[3] &= ~getattr(termios, "PENDIN", 0)
|
||||||
|
self.assertEqual(restored, original)
|
||||||
|
finally:
|
||||||
|
if proc.poll() is None:
|
||||||
|
proc.kill()
|
||||||
|
proc.wait()
|
||||||
|
os.close(master)
|
||||||
|
os.close(slave)
|
||||||
|
|
||||||
|
def test_real_pty_upload_order_mouse_text_failure_exit_status_and_restoration(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
file = Path(tmp) / "paste space 中文.txt"
|
||||||
|
file.write_text("synthetic fixture")
|
||||||
|
mouse = b"\x1b[<2;2;3M\x1b[<2;2;3m\x1b[<35;3;4M"
|
||||||
|
for mode, fail, ordinary in ((False, False, False), (True, False, False),
|
||||||
|
(True, True, False), (False, False, True),
|
||||||
|
(True, False, True), (True, 'cancel', False)):
|
||||||
|
with self.subTest(mode=mode, fail=fail, ordinary=ordinary):
|
||||||
|
master, slave = pty.openpty()
|
||||||
|
original = termios.tcgetattr(slave)
|
||||||
|
remote = shlex.quote("/home/test/.local/share/uuremote/uploads/paste.test/space 中文.txt")
|
||||||
|
config = json.dumps([[str(file)], remote, mode, fail])
|
||||||
|
proc = subprocess.Popen([sys.executable, "-c", HARNESS, str(SCRIPT), config],
|
||||||
|
stdin=slave, stdout=slave, stderr=slave)
|
||||||
|
output = bytearray()
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic() + 10
|
||||||
|
while b"CHILD_READY" not in output:
|
||||||
|
self.assertLess(time.monotonic(), deadline, "PTY harness did not start")
|
||||||
|
if select.select([master], [], [], 0.1)[0]:
|
||||||
|
output.extend(os.read(master, 65536))
|
||||||
|
payload = b"ordinary\ntext" if ordinary else shlex.quote(str(file)).encode()
|
||||||
|
wire = mouse + paste.START + payload + paste.END
|
||||||
|
wire += b"\x03\r" if fail == 'cancel' else b"\r"
|
||||||
|
for byte in wire:
|
||||||
|
os.write(master, bytes([byte]))
|
||||||
|
while proc.poll() is None or select.select([master], [], [], 0)[0]:
|
||||||
|
self.assertLess(time.monotonic(), deadline, "PTY relay did not exit")
|
||||||
|
if select.select([master], [], [], 0.1)[0]:
|
||||||
|
try:
|
||||||
|
chunk = os.read(master, 65536)
|
||||||
|
except OSError as error:
|
||||||
|
if error.errno == errno.EIO:
|
||||||
|
break
|
||||||
|
raise
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
output.extend(chunk)
|
||||||
|
self.assertEqual(proc.wait(timeout=2), 7)
|
||||||
|
encoded = bytes(output).split(b"RECEIVED:", 1)[1].split(b":DONE", 1)[0]
|
||||||
|
expected = b"" if fail else paste.paste_bytes(payload if ordinary else remote.encode(), mode)
|
||||||
|
interrupt = b"\x03" if fail == 'cancel' else b""
|
||||||
|
self.assertEqual(base64.b64decode(encoded), mouse + expected + interrupt + b"\r")
|
||||||
|
restored = termios.tcgetattr(slave)
|
||||||
|
# macOS sets PENDIN when restoring canonical input. It
|
||||||
|
# is kernel bookkeeping, not an unrestored user mode.
|
||||||
|
restored[3] &= ~getattr(termios, "PENDIN", 0)
|
||||||
|
original[3] &= ~getattr(termios, "PENDIN", 0)
|
||||||
|
self.assertEqual(restored, original)
|
||||||
|
if fail:
|
||||||
|
self.assertNotIn(str(file).encode(), output)
|
||||||
|
if not ordinary:
|
||||||
|
self.assertIn(b"UU upload: Connecting", output)
|
||||||
|
self.assertIn(b"\x1b]9;4;0\x1b\\", output)
|
||||||
|
if fail == 'cancel':
|
||||||
|
self.assertIn(b"UU upload: Cancelling", output)
|
||||||
|
finally:
|
||||||
|
if proc.poll() is None:
|
||||||
|
proc.kill()
|
||||||
|
proc.wait()
|
||||||
|
os.close(master)
|
||||||
|
os.close(slave)
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(os.environ.get("UU_PASTE_TEST_HOST"), "set UU_PASTE_TEST_HOST for a real mapped SSH test")
|
||||||
|
class MappedSSHTests(unittest.TestCase):
|
||||||
|
def test_live_upload_reports_intermediate_progress_and_verified_completion(self):
|
||||||
|
host = os.environ["UU_PASTE_TEST_HOST"]
|
||||||
|
uploader = paste.Uploader(os.environ.get("UU_PASTE_TEST_CONFIG"), host)
|
||||||
|
uploader.scp.extend(["-l", "1024"]) # Deliberately slow a synthetic transfer.
|
||||||
|
reports = []
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
source = Path(tmp) / "private progress 中文.bin"
|
||||||
|
source.write_bytes(os.urandom(1024 * 1024))
|
||||||
|
paths = shlex.split(uploader.upload([str(source)], threading.Event(),
|
||||||
|
lambda *args: reports.append(args)).decode())
|
||||||
|
try:
|
||||||
|
total = source.stat().st_size
|
||||||
|
self.assertEqual(reports[0], ("connecting", 0, total, 0))
|
||||||
|
self.assertTrue(any(0 < done < total and speed > 0
|
||||||
|
for stage, done, size, speed in reports if stage == "uploading"))
|
||||||
|
self.assertEqual(reports[-1], ("finishing", total, total, 0))
|
||||||
|
self.assertNotIn(source.name, repr(reports))
|
||||||
|
remote = paste.run_private([*uploader.ssh, "sha256sum -- " + shlex.quote(paths[0])],
|
||||||
|
threading.Event(), 30)
|
||||||
|
self.assertEqual(remote.split()[0].decode(), hashlib.sha256(source.read_bytes()).hexdigest())
|
||||||
|
finally:
|
||||||
|
paste.run_private([*uploader.ssh, "rm -rf -- " + shlex.quote(str(Path(paths[0]).parent))],
|
||||||
|
threading.Event(), 30)
|
||||||
|
|
||||||
|
def test_paste_through_real_pty_and_uu_ssh_opens_uploaded_files(self):
|
||||||
|
host = os.environ["UU_PASTE_TEST_HOST"]
|
||||||
|
config = os.environ.get("UU_PASTE_TEST_CONFIG")
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
files = [Path(tmp) / "copied file 中文.bin", Path(tmp) / "literal'$(echo nope);.bin"]
|
||||||
|
for file in files:
|
||||||
|
file.write_bytes(os.urandom(65569))
|
||||||
|
hashes = [hashlib.sha256(f.read_bytes()).hexdigest() for f in files]
|
||||||
|
mouse = b"\x1b[<2;2;3M\x1b[<2;2;3m\x1b[<35;3;4M"
|
||||||
|
remote = r'''
|
||||||
|
import os,tty,shlex,hashlib,json,shutil
|
||||||
|
from pathlib import Path
|
||||||
|
tty.setraw(0)
|
||||||
|
os.write(1,b'\x1b[?2004hLIVE_READY')
|
||||||
|
data=b''
|
||||||
|
while not data.endswith(b'\r'):
|
||||||
|
data+=os.read(0,65536)
|
||||||
|
mouse=b'\x1b[<2;2;3M\x1b[<2;2;3m\x1b[<35;3;4M'
|
||||||
|
assert data.startswith(mouse+b'\x1b[200~') and data.endswith(b'\x1b[201~\r')
|
||||||
|
paths=shlex.split(data[len(mouse)+6:-7].decode())
|
||||||
|
assert len(paths)==2
|
||||||
|
hashes=[hashlib.sha256(Path(p).read_bytes()).hexdigest() for p in paths]
|
||||||
|
for directory in {Path(p).parent for p in paths}:
|
||||||
|
assert directory.parent==Path.home()/'.local/share/uuremote/uploads'
|
||||||
|
assert directory.name.startswith('paste.')
|
||||||
|
shutil.rmtree(directory)
|
||||||
|
os.write(1,b'LIVE_HASHES:'+json.dumps(hashes).encode()+b':DONE')
|
||||||
|
'''
|
||||||
|
harness = r'''
|
||||||
|
import runpy,sys,json
|
||||||
|
h=runpy.run_path(sys.argv[1])
|
||||||
|
host,config,paths,remote=json.loads(sys.argv[2])
|
||||||
|
uploader=h['Uploader'](config,host)
|
||||||
|
common=['-F',config] if config else []
|
||||||
|
raise SystemExit(h['relay'](['/usr/bin/ssh',*common,'-tt',host,remote],lambda:paths,uploader))
|
||||||
|
'''
|
||||||
|
args = json.dumps([host, config, [str(p) for p in files], "python3 -c " + shlex.quote(remote)])
|
||||||
|
master, slave = pty.openpty()
|
||||||
|
process = subprocess.Popen([sys.executable, "-c", harness, str(SCRIPT), args],
|
||||||
|
stdin=slave, stdout=slave, stderr=slave)
|
||||||
|
output = bytearray()
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic() + 60
|
||||||
|
sent = False
|
||||||
|
while process.poll() is None or select.select([master], [], [], 0)[0]:
|
||||||
|
self.assertLess(time.monotonic(), deadline, "Live paste timed out")
|
||||||
|
if select.select([master], [], [], 0.1)[0]:
|
||||||
|
output.extend(os.read(master, 65536))
|
||||||
|
if b"LIVE_READY" in output and not sent:
|
||||||
|
payload = shlex.join([str(p) for p in files]).encode()
|
||||||
|
os.write(master, mouse + paste.START + payload + paste.END + b"\r")
|
||||||
|
sent = True
|
||||||
|
self.assertEqual(process.wait(timeout=2), 0)
|
||||||
|
received = bytes(output).split(b"LIVE_HASHES:", 1)[1].split(b":DONE", 1)[0]
|
||||||
|
self.assertEqual(json.loads(received), hashes)
|
||||||
|
finally:
|
||||||
|
if process.poll() is None:
|
||||||
|
process.kill()
|
||||||
|
process.wait()
|
||||||
|
os.close(master)
|
||||||
|
os.close(slave)
|
||||||
|
|
||||||
|
def test_real_upload_roundtrip_binary_unicode_and_shell_metacharacters(self):
|
||||||
|
host = os.environ["UU_PASTE_TEST_HOST"]
|
||||||
|
config = os.environ.get("UU_PASTE_TEST_CONFIG")
|
||||||
|
uploader = paste.Uploader(config, host)
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
root = Path(tmp)
|
||||||
|
files = [root / "space 中文.bin", root / "literal'$(echo nope);.bin"]
|
||||||
|
for file in files:
|
||||||
|
file.write_bytes(os.urandom(65569))
|
||||||
|
paths = shlex.split(uploader.upload([str(f) for f in files], threading.Event()).decode())
|
||||||
|
try:
|
||||||
|
for index, (source, remote) in enumerate(zip(files, paths)):
|
||||||
|
dest = root / ("download-" + str(index))
|
||||||
|
paste.run_private([*uploader.scp, f"{host}:{remote}", str(dest)], threading.Event(), 60)
|
||||||
|
self.assertEqual(hashlib.sha256(source.read_bytes()).digest(),
|
||||||
|
hashlib.sha256(dest.read_bytes()).digest())
|
||||||
|
directory = str(Path(paths[0]).parent)
|
||||||
|
mode = paste.run_private([*uploader.ssh, "stat -c %a -- " + shlex.quote(directory)],
|
||||||
|
threading.Event(), 30)
|
||||||
|
self.assertEqual(mode.strip(), b"700")
|
||||||
|
finally:
|
||||||
|
paste.run_private([*uploader.ssh, "rm -rf -- " + shlex.quote(str(Path(paths[0]).parent))],
|
||||||
|
threading.Event(), 30)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Executable
+594
@@ -0,0 +1,594 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Paste Finder files into an SSH terminal through an existing UU TCP mapping."""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import collections
|
||||||
|
import errno
|
||||||
|
import fcntl
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import pty
|
||||||
|
import queue
|
||||||
|
import re
|
||||||
|
import select
|
||||||
|
import shlex
|
||||||
|
import signal
|
||||||
|
import stat
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import termios
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import tty
|
||||||
|
|
||||||
|
START, END = b"\x1b[200~", b"\x1b[201~"
|
||||||
|
ENABLE, DISABLE = b"\x1b[?2004h", b"\x1b[?2004l"
|
||||||
|
MAX_PASTE = 8 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
|
class PasteError(Exception):
|
||||||
|
"""Messages must not include clipboard contents, paths or subprocess output."""
|
||||||
|
|
||||||
|
|
||||||
|
def prefix_tail(data, marker):
|
||||||
|
for length in range(min(len(data), len(marker) - 1), 0, -1):
|
||||||
|
if data.endswith(marker[:length]):
|
||||||
|
return length
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
class InputFrames:
|
||||||
|
"""Recognize bracketed pastes across arbitrary PTY read boundaries."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.buffer = b""
|
||||||
|
self.pasting = False
|
||||||
|
self.overflow = False
|
||||||
|
|
||||||
|
def feed(self, data):
|
||||||
|
self.buffer += data
|
||||||
|
events = []
|
||||||
|
while self.buffer:
|
||||||
|
if self.pasting:
|
||||||
|
end = self.buffer.find(END)
|
||||||
|
if end < 0:
|
||||||
|
if len(self.buffer) > MAX_PASTE:
|
||||||
|
self.overflow = True
|
||||||
|
tail = prefix_tail(self.buffer, END)
|
||||||
|
self.buffer = self.buffer[-tail:] if tail else b""
|
||||||
|
break
|
||||||
|
payload, self.buffer = self.buffer[:end], self.buffer[end + len(END):]
|
||||||
|
events.append(("error" if self.overflow or len(payload) > MAX_PASTE else "paste", payload))
|
||||||
|
self.pasting = self.overflow = False
|
||||||
|
else:
|
||||||
|
start = self.buffer.find(START)
|
||||||
|
if start >= 0:
|
||||||
|
if start:
|
||||||
|
events.append(("data", self.buffer[:start]))
|
||||||
|
self.buffer = self.buffer[start + len(START):]
|
||||||
|
self.pasting = True
|
||||||
|
else:
|
||||||
|
tail = prefix_tail(self.buffer, START)
|
||||||
|
size = len(self.buffer) - tail
|
||||||
|
if size:
|
||||||
|
events.append(("data", self.buffer[:size]))
|
||||||
|
self.buffer = self.buffer[size:]
|
||||||
|
break
|
||||||
|
return events
|
||||||
|
|
||||||
|
def flush_key(self):
|
||||||
|
# A standalone Escape must not wait indefinitely for another key.
|
||||||
|
if not self.pasting:
|
||||||
|
result, self.buffer = self.buffer, b""
|
||||||
|
return result
|
||||||
|
return b""
|
||||||
|
|
||||||
|
|
||||||
|
class OutputModes:
|
||||||
|
"""Keep local paste framing on; retain the remote app's requested mode."""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.buffer = b""
|
||||||
|
self.bracketed = False
|
||||||
|
|
||||||
|
def feed(self, data):
|
||||||
|
self.buffer += data
|
||||||
|
output = bytearray()
|
||||||
|
while self.buffer:
|
||||||
|
index = self.buffer.find(b"\x1b")
|
||||||
|
if index < 0:
|
||||||
|
output.extend(self.buffer)
|
||||||
|
self.buffer = b""
|
||||||
|
break
|
||||||
|
output.extend(self.buffer[:index])
|
||||||
|
self.buffer = self.buffer[index:]
|
||||||
|
if self.buffer.startswith(b"\x1bc"):
|
||||||
|
output.extend(b"\x1bc" + ENABLE)
|
||||||
|
self.bracketed = False
|
||||||
|
self.buffer = self.buffer[2:]
|
||||||
|
continue
|
||||||
|
match = re.match(rb"\x1b\[\?([0-9;]+)([hl])", self.buffer)
|
||||||
|
if match:
|
||||||
|
params = match[1].split(b";")
|
||||||
|
if b"2004" in params:
|
||||||
|
self.bracketed = match[2] == b"h"
|
||||||
|
others = [p for p in params if p != b"2004"]
|
||||||
|
if others:
|
||||||
|
output.extend(b"\x1b[?" + b";".join(others) + match[2])
|
||||||
|
output.extend(ENABLE)
|
||||||
|
else:
|
||||||
|
output.extend(match[0])
|
||||||
|
self.buffer = self.buffer[match.end():]
|
||||||
|
elif len(self.buffer) < 128 and re.fullmatch(rb"\x1b(?:\[(?:\?[0-9;]*)?)?", self.buffer):
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
output.extend(self.buffer[:1])
|
||||||
|
self.buffer = self.buffer[1:]
|
||||||
|
return bytes(output)
|
||||||
|
|
||||||
|
|
||||||
|
def paste_bytes(data, bracketed):
|
||||||
|
return START + data + END if bracketed else data
|
||||||
|
|
||||||
|
|
||||||
|
def clipboard_paths(helper):
|
||||||
|
try:
|
||||||
|
result = subprocess.run([str(helper)], capture_output=True, timeout=3, check=True)
|
||||||
|
paths = json.loads(result.stdout)
|
||||||
|
if not isinstance(paths, list) or not all(isinstance(p, str) for p in paths):
|
||||||
|
raise ValueError()
|
||||||
|
return paths
|
||||||
|
except (OSError, ValueError, subprocess.SubprocessError):
|
||||||
|
raise PasteError("Cannot check copied files; paste was not sent.") from None
|
||||||
|
|
||||||
|
|
||||||
|
def copied_files(data, read_clipboard):
|
||||||
|
try:
|
||||||
|
text = data.decode("utf-8")
|
||||||
|
paths = shlex.split(text)
|
||||||
|
except (UnicodeError, ValueError):
|
||||||
|
return None
|
||||||
|
if not paths or not all(p.startswith("/") for p in paths):
|
||||||
|
return None
|
||||||
|
# Ordinary text that happens to name a local file must never upload it.
|
||||||
|
# Ghostty 1.3.1 getOpinionatedStringContents escapes Finder file paths;
|
||||||
|
# require the entire pasted path list to match actual file-URL clipboard data.
|
||||||
|
if paths != read_clipboard():
|
||||||
|
return None
|
||||||
|
if len(paths) > 256:
|
||||||
|
raise PasteError("Too many copied files (maximum 256).")
|
||||||
|
for path in paths:
|
||||||
|
if any(ord(c) < 32 or ord(c) == 127 for c in path):
|
||||||
|
raise PasteError("A copied filename contains unsupported control characters.")
|
||||||
|
try:
|
||||||
|
if not stat.S_ISREG(os.stat(path).st_mode):
|
||||||
|
raise PasteError("Copy files individually; folder pasting is not supported.")
|
||||||
|
except OSError:
|
||||||
|
raise PasteError("A copied file is no longer readable.") from None
|
||||||
|
if len({Path(p).name for p in paths}) != len(paths):
|
||||||
|
raise PasteError("Copied files must have distinct filenames; paste them separately.")
|
||||||
|
return paths
|
||||||
|
|
||||||
|
|
||||||
|
class SCPMeter:
|
||||||
|
"""Reduce OpenSSH's private progress output to numeric batch counters."""
|
||||||
|
|
||||||
|
# OpenSSH progressmeter.c writes: filename percent size rate time [ETA].
|
||||||
|
# Anchor at the numeric suffix; filenames and errors are never displayed.
|
||||||
|
record = re.compile(rb" (\d{1,3})%\s+(\d{1,20}(?:[KMGT]B)?)\s+"
|
||||||
|
rb"(\d{1,20}(?:\.\d{1,10})?[KMGT]B)/s\s+"
|
||||||
|
rb"(?:\d+:\d\d(?::\d\d)?(?: ETA)?|--:-- ETA|- stalled -)\s*$")
|
||||||
|
|
||||||
|
def __init__(self, sizes, report):
|
||||||
|
self.sizes, self.report = sizes, report
|
||||||
|
self.buffer, self.index, self.finished = b"", 0, 0
|
||||||
|
self.current, self.percent = 0, 0
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def amount(token):
|
||||||
|
match = re.fullmatch(rb"(\d+(?:\.\d+)?)([KMGT])?B?", token)
|
||||||
|
return int(float(match[1]) * 1024 ** (b" KMGT".index(match[2]) if match[2] else 0))
|
||||||
|
|
||||||
|
def parse(self, line):
|
||||||
|
match = self.record.search(line)
|
||||||
|
if not match or self.index >= len(self.sizes):
|
||||||
|
return
|
||||||
|
percent = int(match[1])
|
||||||
|
if percent > 100:
|
||||||
|
return
|
||||||
|
self.percent = max(self.percent, percent)
|
||||||
|
size = self.sizes[self.index]
|
||||||
|
self.current = max(self.current, min(size, self.amount(match[2])))
|
||||||
|
if percent == 100:
|
||||||
|
self.current = size
|
||||||
|
self.report("uploading", self.finished + self.current, sum(self.sizes), self.amount(match[3]))
|
||||||
|
|
||||||
|
def feed(self, data):
|
||||||
|
for piece in re.split(rb"([\r\n])", data):
|
||||||
|
if piece in (b"\r", b"\n"):
|
||||||
|
self.parse(self.buffer)
|
||||||
|
self.buffer = b""
|
||||||
|
if piece == b"\n" and self.percent == 100:
|
||||||
|
self.finished += self.sizes[self.index]
|
||||||
|
self.index += 1
|
||||||
|
self.current = self.percent = 0
|
||||||
|
else:
|
||||||
|
# Keep only enough for a numeric suffix, not unlimited errors.
|
||||||
|
self.buffer = (self.buffer + piece)[-512:]
|
||||||
|
self.parse(self.buffer)
|
||||||
|
|
||||||
|
|
||||||
|
def run_metered(args, cancel, timeout, meter):
|
||||||
|
master, slave = pty.openpty()
|
||||||
|
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 24, 120, 0, 0))
|
||||||
|
|
||||||
|
try:
|
||||||
|
# The upload runs on a worker thread, so avoid Python preexec_fn after
|
||||||
|
# fork. Acquire the private controlling TTY in a fresh interpreter.
|
||||||
|
launch = ("import fcntl,os,sys,termios;fcntl.ioctl(1,termios.TIOCSCTTY,0);"
|
||||||
|
"os.execv(sys.argv[1],sys.argv[1:])")
|
||||||
|
with subprocess.Popen([sys.executable, "-c", launch, *args],
|
||||||
|
stdin=subprocess.DEVNULL, stdout=slave, stderr=slave,
|
||||||
|
start_new_session=True) as process:
|
||||||
|
os.close(slave)
|
||||||
|
slave = None
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
try:
|
||||||
|
while True:
|
||||||
|
if cancel.is_set() or time.monotonic() > deadline:
|
||||||
|
raise PasteError("Upload cancelled or timed out; paste was not sent.")
|
||||||
|
if select.select([master], [], [], 0.1)[0]:
|
||||||
|
try:
|
||||||
|
data = os.read(master, 65536)
|
||||||
|
except OSError as error:
|
||||||
|
if error.errno != errno.EIO:
|
||||||
|
raise
|
||||||
|
data = b""
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
meter.feed(data)
|
||||||
|
elif process.poll() is not None:
|
||||||
|
break
|
||||||
|
try:
|
||||||
|
status = process.wait(timeout=max(0.1, deadline - time.monotonic()))
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
raise PasteError("Upload timed out; paste was not sent.") from None
|
||||||
|
if status:
|
||||||
|
raise PasteError("Upload failed; paste was not sent.")
|
||||||
|
finally:
|
||||||
|
if process.poll() is None:
|
||||||
|
os.killpg(process.pid, signal.SIGKILL)
|
||||||
|
process.wait()
|
||||||
|
finally:
|
||||||
|
os.close(master)
|
||||||
|
if slave is not None:
|
||||||
|
os.close(slave)
|
||||||
|
return b""
|
||||||
|
|
||||||
|
|
||||||
|
def run_private(args, cancel, timeout, meter=None):
|
||||||
|
# Neither SSH errors nor SCP output may disclose paths, clipboard/file data,
|
||||||
|
# or credentials. Authentication never reads from the interactive terminal.
|
||||||
|
if meter is not None:
|
||||||
|
return run_metered(args, cancel, timeout, meter)
|
||||||
|
with subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
|
||||||
|
stderr=subprocess.DEVNULL, start_new_session=True) as process:
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
while True:
|
||||||
|
if cancel.is_set() or time.monotonic() > deadline:
|
||||||
|
os.killpg(process.pid, signal.SIGKILL)
|
||||||
|
process.communicate()
|
||||||
|
raise PasteError("Upload cancelled." if cancel.is_set() else "Upload timed out; paste was not sent.")
|
||||||
|
try:
|
||||||
|
stdout, _ = process.communicate(timeout=0.1)
|
||||||
|
if process.returncode:
|
||||||
|
raise PasteError("Upload failed; check the UU mapping and SSH access. Paste was not sent.")
|
||||||
|
return stdout
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class Uploader:
|
||||||
|
def __init__(self, config, host):
|
||||||
|
common = ["-F", str(config)] if config else []
|
||||||
|
common += ["-o", "BatchMode=yes", "-o", "ConnectTimeout=15"]
|
||||||
|
self.ssh = ["/usr/bin/ssh", *common, host]
|
||||||
|
self.scp = ["/usr/bin/scp", "-q", *common]
|
||||||
|
self.host = host
|
||||||
|
|
||||||
|
def upload(self, paths, cancel, progress=None):
|
||||||
|
sizes = [os.stat(path).st_size for path in paths] if progress else []
|
||||||
|
if progress:
|
||||||
|
progress("connecting", 0, sum(sizes), 0)
|
||||||
|
script = ('umask 077; d="$HOME/.local/share/uuremote/uploads"; '
|
||||||
|
'mkdir -p "$d" && mktemp -d "$d/paste.XXXXXXXX"')
|
||||||
|
try:
|
||||||
|
directory = run_private([*self.ssh, script], cancel, 30).decode("utf-8").strip()
|
||||||
|
except UnicodeError:
|
||||||
|
raise PasteError("Invalid upload destination; paste was not sent.") from None
|
||||||
|
if (not directory.startswith("/") or len(directory) > 4096 or
|
||||||
|
any(ord(c) < 32 or ord(c) == 127 for c in directory) or
|
||||||
|
not re.fullmatch(r"paste\.[A-Za-z0-9]+", directory.rsplit("/", 1)[-1])):
|
||||||
|
raise PasteError("Invalid upload destination; paste was not sent.")
|
||||||
|
try:
|
||||||
|
# Use modern SCP's SFTP mode, never legacy SCP (-O). Unique batch
|
||||||
|
# directories prevent overwrites; all local paths are absolute.
|
||||||
|
if progress:
|
||||||
|
progress("uploading", 0, sum(sizes), 0)
|
||||||
|
scp = self.scp[:1] + self.scp[2:] # Remove only our own -q.
|
||||||
|
run_private([*scp, *paths, f"{self.host}:{directory}/"], cancel, 300,
|
||||||
|
SCPMeter(sizes, progress))
|
||||||
|
progress("finishing", sum(sizes), sum(sizes), 0)
|
||||||
|
else:
|
||||||
|
run_private([*self.scp, *paths, f"{self.host}:{directory}/"], cancel, 300)
|
||||||
|
except (PasteError, OSError):
|
||||||
|
# Clean only this batch, with quoted remote shell syntax. Cancellation
|
||||||
|
# of one upload must not stop another SSH/UU session.
|
||||||
|
try:
|
||||||
|
run_private([*self.ssh, "rm -rf -- " + shlex.quote(directory)], threading.Event(), 10)
|
||||||
|
except (PasteError, OSError):
|
||||||
|
pass
|
||||||
|
raise
|
||||||
|
return " ".join(shlex.quote(directory + "/" + Path(p).name) for p in paths).encode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def write_all(fd, data):
|
||||||
|
view = memoryview(data)
|
||||||
|
while view:
|
||||||
|
view = view[os.write(fd, view):]
|
||||||
|
|
||||||
|
|
||||||
|
def display_size(size):
|
||||||
|
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
|
||||||
|
if size < 1024 or unit == "TiB":
|
||||||
|
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
|
||||||
|
size /= 1024
|
||||||
|
|
||||||
|
|
||||||
|
class UploadDisplay:
|
||||||
|
"""Session-local title and OSC 9;4 progress; terminal cells stay untouched."""
|
||||||
|
|
||||||
|
# https://ghostty.org/docs/vt/osc/conemu: states 0=clear, 1=percent, 3=busy.
|
||||||
|
|
||||||
|
def __init__(self, emit):
|
||||||
|
self.emit, self.active = emit, False
|
||||||
|
self.title, self.pending = b"UU SSH", b""
|
||||||
|
self.state = ("connecting", 0, 0, 0)
|
||||||
|
self.started = self.rendered = 0
|
||||||
|
|
||||||
|
def observe(self, data):
|
||||||
|
self.pending = (self.pending + data)[-8192:]
|
||||||
|
for match in re.finditer(rb"\x1b\][02];([^\x07\x1b]*)(?:\x07|\x1b\\)", self.pending):
|
||||||
|
self.title = match[1]
|
||||||
|
# Retain only an incomplete OSC title across output reads.
|
||||||
|
index = self.pending.rfind(b"\x1b]")
|
||||||
|
if index < 0:
|
||||||
|
self.pending = b"\x1b" if self.pending.endswith(b"\x1b") else b""
|
||||||
|
else:
|
||||||
|
tail = self.pending[index:]
|
||||||
|
self.pending = tail if b"\x07" not in tail and b"\x1b\\" not in tail else b""
|
||||||
|
|
||||||
|
def start(self, total):
|
||||||
|
self.active = True
|
||||||
|
self.started = time.monotonic()
|
||||||
|
self.state = ("connecting", 0, total, 0)
|
||||||
|
self.render(force=True)
|
||||||
|
|
||||||
|
def update(self, stage, done, total, speed):
|
||||||
|
self.state = stage, done, total, speed
|
||||||
|
|
||||||
|
def render(self, force=False):
|
||||||
|
now = time.monotonic()
|
||||||
|
if not self.active or (not force and now - self.rendered < 0.2):
|
||||||
|
return
|
||||||
|
self.rendered = now
|
||||||
|
stage, done, total, speed = self.state
|
||||||
|
elapsed = int(now - self.started)
|
||||||
|
if stage in ("connecting", "cancelling"):
|
||||||
|
label = "Connecting" if stage == "connecting" else "Cancelling"
|
||||||
|
text = f"UU upload: {label} | {display_size(total)} | {elapsed}s"
|
||||||
|
indicator = b"\x1b]9;4;3\x1b\\"
|
||||||
|
else:
|
||||||
|
percent = min(100, int(done * 100 / total)) if total else 100
|
||||||
|
label = "Finishing" if stage == "finishing" else "Uploading"
|
||||||
|
text = (f"UU upload: {label} {percent}% | {display_size(done)}/{display_size(total)}"
|
||||||
|
f" | {display_size(speed)}/s | {elapsed}s")
|
||||||
|
indicator = f"\x1b]9;4;1;{percent}\x1b\\".encode()
|
||||||
|
self.emit(b"\x1b]2;" + text.encode() + b"\x1b\\" + indicator)
|
||||||
|
|
||||||
|
def finish(self):
|
||||||
|
if self.active:
|
||||||
|
self.active = False
|
||||||
|
self.emit(b"\x1b]9;4;0\x1b\\\x1b]2;" + self.title + b"\x1b\\")
|
||||||
|
|
||||||
|
|
||||||
|
def relay(command, read_clipboard, uploader):
|
||||||
|
original = termios.tcgetattr(0)
|
||||||
|
master, slave = pty.openpty()
|
||||||
|
|
||||||
|
def resize(*_):
|
||||||
|
try:
|
||||||
|
size = fcntl.ioctl(0, termios.TIOCGWINSZ, bytes(8))
|
||||||
|
fcntl.ioctl(master, termios.TIOCSWINSZ, size)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
resize()
|
||||||
|
|
||||||
|
def child_tty():
|
||||||
|
os.setsid()
|
||||||
|
fcntl.ioctl(0, termios.TIOCSCTTY, 0)
|
||||||
|
|
||||||
|
child = subprocess.Popen(command, stdin=slave, stdout=slave, stderr=slave, preexec_fn=child_tty)
|
||||||
|
os.close(slave)
|
||||||
|
previous_resize = signal.signal(signal.SIGWINCH, resize)
|
||||||
|
|
||||||
|
def shutdown(signum, _frame):
|
||||||
|
raise SystemExit(128 + signum)
|
||||||
|
|
||||||
|
previous_signals = {sig: signal.signal(sig, shutdown)
|
||||||
|
for sig in (signal.SIGHUP, signal.SIGTERM, signal.SIGINT)}
|
||||||
|
frames, modes = InputFrames(), OutputModes()
|
||||||
|
events, completed = collections.deque(), queue.Queue()
|
||||||
|
updates = queue.Queue()
|
||||||
|
display = UploadDisplay(lambda data: write_all(1, data))
|
||||||
|
cancel, uploading, interrupted = threading.Event(), False, False
|
||||||
|
worker = None
|
||||||
|
last_input = time.monotonic()
|
||||||
|
|
||||||
|
def upload_worker(paths):
|
||||||
|
try:
|
||||||
|
completed.put((uploader.upload(paths, cancel, lambda *args: updates.put(args)), None))
|
||||||
|
except (OSError, PasteError):
|
||||||
|
completed.put((None, "Upload failed or cancelled; paste was not sent."))
|
||||||
|
|
||||||
|
def notice(message):
|
||||||
|
write_all(2, ("\r\n[UU paste] " + message + "\r\n").encode())
|
||||||
|
|
||||||
|
def interrupt_upload():
|
||||||
|
nonlocal interrupted, frames
|
||||||
|
if not uploading:
|
||||||
|
return
|
||||||
|
pending = list(events)
|
||||||
|
positions = [(i, payload.rfind(b"\x03")) for i, (kind, payload) in enumerate(pending)
|
||||||
|
if kind == "data" and b"\x03" in payload]
|
||||||
|
if positions:
|
||||||
|
index, offset = positions[-1]
|
||||||
|
cancel.set()
|
||||||
|
interrupted = True
|
||||||
|
_, done, total, _ = display.state
|
||||||
|
display.update("cancelling", done, total, 0)
|
||||||
|
display.render(force=True)
|
||||||
|
frames = InputFrames()
|
||||||
|
events.clear()
|
||||||
|
events.extend(frames.feed(pending[index][1][offset + 1:]))
|
||||||
|
events.extend(pending[index + 1:])
|
||||||
|
write_all(master, b"\x03")
|
||||||
|
|
||||||
|
try:
|
||||||
|
tty.setraw(0)
|
||||||
|
write_all(1, ENABLE)
|
||||||
|
while True:
|
||||||
|
interrupt_upload()
|
||||||
|
while not updates.empty():
|
||||||
|
update = updates.get_nowait()
|
||||||
|
if not interrupted:
|
||||||
|
display.update(*update)
|
||||||
|
if uploading:
|
||||||
|
display.render()
|
||||||
|
try:
|
||||||
|
data, error = completed.get_nowait()
|
||||||
|
except queue.Empty:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
uploading = False
|
||||||
|
display.finish()
|
||||||
|
if error:
|
||||||
|
notice(error)
|
||||||
|
elif not interrupted:
|
||||||
|
write_all(master, paste_bytes(data, modes.bracketed))
|
||||||
|
while events and not uploading:
|
||||||
|
kind, data = events.popleft()
|
||||||
|
if kind == "error":
|
||||||
|
notice("Paste exceeds 8 MiB; paste was not sent.")
|
||||||
|
continue
|
||||||
|
if kind == "data":
|
||||||
|
write_all(master, data)
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
files = copied_files(data, read_clipboard)
|
||||||
|
except PasteError as error:
|
||||||
|
notice(str(error))
|
||||||
|
continue
|
||||||
|
if files is None:
|
||||||
|
write_all(master, paste_bytes(data, modes.bracketed))
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
total = sum(os.stat(path).st_size for path in files)
|
||||||
|
except OSError:
|
||||||
|
notice("A copied file is no longer readable; paste was not sent.")
|
||||||
|
continue
|
||||||
|
cancel.clear()
|
||||||
|
uploading, interrupted = True, False
|
||||||
|
display.start(total)
|
||||||
|
worker = threading.Thread(target=upload_worker, args=(files,), daemon=True)
|
||||||
|
worker.start()
|
||||||
|
interrupt_upload()
|
||||||
|
readable, _, _ = select.select([0, master], [], [], 0.025)
|
||||||
|
if master in readable:
|
||||||
|
try:
|
||||||
|
data = os.read(master, 65536)
|
||||||
|
except OSError as error:
|
||||||
|
if error.errno != errno.EIO:
|
||||||
|
raise
|
||||||
|
data = b""
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
display.observe(data)
|
||||||
|
write_all(1, modes.feed(data))
|
||||||
|
if 0 in readable:
|
||||||
|
data = os.read(0, 65536)
|
||||||
|
if not data:
|
||||||
|
break
|
||||||
|
last_input = time.monotonic()
|
||||||
|
events.extend(frames.feed(data))
|
||||||
|
if sum(len(payload) for _, payload in events) > MAX_PASTE:
|
||||||
|
events.clear()
|
||||||
|
notice("Input queue is full; queued input was discarded.")
|
||||||
|
elif time.monotonic() - last_input > 0.025:
|
||||||
|
data = frames.flush_key()
|
||||||
|
if data:
|
||||||
|
events.append(("data", data))
|
||||||
|
if modes.buffer:
|
||||||
|
write_all(1, modes.buffer)
|
||||||
|
finally:
|
||||||
|
cancel.set()
|
||||||
|
signal.signal(signal.SIGWINCH, previous_resize)
|
||||||
|
for sig, previous in previous_signals.items():
|
||||||
|
signal.signal(sig, previous)
|
||||||
|
termios.tcsetattr(0, termios.TCSADRAIN, original)
|
||||||
|
display.finish()
|
||||||
|
write_all(1, DISABLE)
|
||||||
|
os.close(master)
|
||||||
|
if child.poll() is None:
|
||||||
|
try:
|
||||||
|
child.wait(timeout=2)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
os.killpg(child.pid, signal.SIGTERM)
|
||||||
|
try:
|
||||||
|
child.wait(timeout=2)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
os.killpg(child.pid, signal.SIGKILL)
|
||||||
|
status = child.wait()
|
||||||
|
if worker is not None:
|
||||||
|
worker.join(timeout=12)
|
||||||
|
return status if status >= 0 else 128 - status
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser(description=__doc__)
|
||||||
|
parser.add_argument("-F", "--ssh-config", type=Path)
|
||||||
|
parser.add_argument("host", help="SSH alias for an existing UU loopback port mapping")
|
||||||
|
parser.add_argument("command", nargs=argparse.REMAINDER)
|
||||||
|
args = parser.parse_args()
|
||||||
|
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.@-]*", args.host):
|
||||||
|
parser.error("use an SSH host alias, without options or a port")
|
||||||
|
common = ["-F", str(args.ssh_config)] if args.ssh_config else []
|
||||||
|
command = ["/usr/bin/ssh", *common]
|
||||||
|
if not (os.isatty(0) and os.isatty(1)):
|
||||||
|
os.execv(command[0], [*command, args.host, *args.command])
|
||||||
|
helper = Path(__file__).resolve().with_name("clipboard-files")
|
||||||
|
if not helper.is_file():
|
||||||
|
parser.error("run contrib/macos-ssh/install.sh on your Mac first")
|
||||||
|
return relay([*command, "-tt", args.host, *args.command],
|
||||||
|
lambda: clipboard_paths(helper), Uploader(args.ssh_config, args.host))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
try:
|
||||||
|
sys.exit(main())
|
||||||
|
except (OSError, PasteError):
|
||||||
|
print("UU SSH companion failed; check the UU mapping and SSH configuration.", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Unofficial UU Remote Linux host in a container, for NAS boxes (Synology DSM, etc.) without a desktop.
|
||||||
|
# Headless mode: file transfer, terminal and port mapping; no remote desktop. Uses the published release binary.
|
||||||
|
FROM ubuntu:24.04
|
||||||
|
ARG VERSION=v0.2.9
|
||||||
|
LABEL org.opencontainers.image.source="https://github.com/VallierDev/uu-remote-linux" \
|
||||||
|
org.opencontainers.image.description="Unofficial UU Remote Linux host, headless (file transfer, terminal, port mapping)" \
|
||||||
|
org.opencontainers.image.licenses="GPL-3.0"
|
||||||
|
RUN apt-get update \
|
||||||
|
&& DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
|
||||||
|
ca-certificates curl bash libx11-6 libxext6 libxtst6 libxfixes3 libgtk-3-0 \
|
||||||
|
&& cd /tmp \
|
||||||
|
&& base="https://github.com/VallierDev/uu-remote-linux/releases/download/${VERSION}/uu-remote-linux-${VERSION}-x86_64-linux.tar.gz" \
|
||||||
|
&& curl -fsSLO "$base" && curl -fsSLO "$base.sha256" && sha256sum -c "uu-remote-linux-${VERSION}-x86_64-linux.tar.gz.sha256" \
|
||||||
|
&& tar xzf "uu-remote-linux-${VERSION}-x86_64-linux.tar.gz" \
|
||||||
|
&& install -m755 "$(find /tmp -name uuremote-server -type f | head -1)" /usr/local/bin/uuremote-server \
|
||||||
|
&& rm -rf /tmp/* /var/lib/apt/lists/*
|
||||||
|
# Credentials live in /config (keep it private); /data is what file transfer and the terminal see as home.
|
||||||
|
ENV UU_CONFIG=/config/config.json UU_DESKTOP_BACKEND=none UU_LOGIN_WINDOW=0 UU_AUDIO=0 RUST_LOG=info HOME=/data
|
||||||
|
VOLUME ["/config", "/data"]
|
||||||
|
WORKDIR /data
|
||||||
|
ENTRYPOINT ["uuremote-server"]
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Docker(群晖 / NAS,无桌面)
|
||||||
|
|
||||||
|
本目录是 [`ghcr.io/vallierdev/uu-remote-linux`](https://github.com/VallierDev/uu-remote-linux/pkgs/container/uu-remote-linux) 镜像的构建文件。
|
||||||
|
**部署和使用步骤见 [docs/deploy-nas-docker.md](../docs/deploy-nas-docker.md)。**
|
||||||
|
|
||||||
|
This directory builds the `ghcr.io/vallierdev/uu-remote-linux` image; see
|
||||||
|
[docs/deploy-nas-docker.md](../docs/deploy-nas-docker.md#english) for deployment.
|
||||||
|
|
||||||
|
自行构建 / build locally: `docker compose build`(`Dockerfile` 从 GitHub 发布包安装 `uuremote-server`,可用 `--build-arg VERSION=vX.Y.Z` 指定版本)。
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
# docker compose up -d (first run: log in once, see README.md in this directory)
|
||||||
|
services:
|
||||||
|
uu-remote:
|
||||||
|
image: ghcr.io/vallierdev/uu-remote-linux:latest
|
||||||
|
build: .
|
||||||
|
container_name: uu-remote
|
||||||
|
# Host networking gives WebRTC direct UDP paths; bridge mode also works but falls back to relays more often.
|
||||||
|
network_mode: host
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./config:/config
|
||||||
|
# Folder offered to file transfer and the terminal (change to your share, e.g. /volume1/homes/you).
|
||||||
|
- ./data:/data
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# 群晖 / NAS 部署指南(Docker,无桌面)
|
||||||
|
|
||||||
|
**简体中文** | [English](#english)
|
||||||
|
|
||||||
|
镜像:[`ghcr.io/vallierdev/uu-remote-linux`](https://github.com/VallierDev/uu-remote-linux/pkgs/container/uu-remote-linux)
|
||||||
|
(标签 `latest` 或具体版本如 `v0.2.8`)
|
||||||
|
|
||||||
|
把本项目主机跑在没有桌面的 NAS 上之后,就能在外面用官方 UU 远程客户端(手机 / Mac / Windows):
|
||||||
|
|
||||||
|
| 功能 | 说明 |
|
||||||
|
|---|---|
|
||||||
|
| 文件传输 | 收发 NAS 上的文件(只开放你挂进容器的文件夹) |
|
||||||
|
| 终端 | 打开容器里的命令行(bash) |
|
||||||
|
| 端口映射 | 经 UU 访问家里局域网的服务:NAS 管理页、路由器、其他电脑的 SSH / 远程桌面等 |
|
||||||
|
|
||||||
|
**不提供远程桌面**(NAS 没有图形界面,点「远程桌面」会一直显示正在连接,属正常)。
|
||||||
|
|
||||||
|
## 准备
|
||||||
|
|
||||||
|
- x86_64 的 NAS(群晖 DSM 7.2 及以上已安装「Container Manager」,或任意装了 Docker 的 Linux NAS)。ARM 机型暂不支持。
|
||||||
|
- 能 SSH 登录 NAS(群晖:控制面板 → 终端机和 SNMP → 启用 SSH),并有管理员权限(`sudo`)。
|
||||||
|
- 手机上的 UU 远程 App,用于扫码登录。
|
||||||
|
|
||||||
|
## 第一步:建目录和配置
|
||||||
|
|
||||||
|
SSH 登录 NAS,新建一个目录(下面以 `/volume1/docker/uu-remote` 为例):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo mkdir -p /volume1/docker/uu-remote/config
|
||||||
|
sudo chmod 700 /volume1/docker/uu-remote/config
|
||||||
|
cd /volume1/docker/uu-remote
|
||||||
|
```
|
||||||
|
|
||||||
|
新建 `compose.yaml`,内容如下。把 `/volume1/共享文件夹` 改成你想远程访问的文件夹(可以写多行挂多个):
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
services:
|
||||||
|
uu-remote:
|
||||||
|
image: ghcr.io/vallierdev/uu-remote-linux:latest
|
||||||
|
container_name: uu-remote
|
||||||
|
network_mode: host # 让远程连接尽量走直连,速度更快
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- ./config:/config # 登录信息,请勿外传
|
||||||
|
- /volume1/共享文件夹:/data # 文件传输和终端看到的目录
|
||||||
|
```
|
||||||
|
|
||||||
|
## 第二步:扫码登录(只需一次)
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo docker compose pull
|
||||||
|
sudo docker compose run --rm uu-remote login --no-gui
|
||||||
|
```
|
||||||
|
|
||||||
|
终端里会显示一个二维码:用手机 UU 远程扫码并确认。看到登录成功的提示后,按 `Ctrl+C` 退出(如果没有自动退出)。
|
||||||
|
|
||||||
|
> 二维码等同于你的登录凭据,**不要截图或发给别人**。登录信息保存在 `config/config.json`。
|
||||||
|
> 一定要用上面的 `docker compose run`(主机网络),这样设备在列表里显示的是 NAS 的名字;
|
||||||
|
> 若用普通 `docker run` 登录,设备名会是一串随机字符。
|
||||||
|
|
||||||
|
## 第三步:启动
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo docker compose up -d
|
||||||
|
sudo docker compose logs -f
|
||||||
|
```
|
||||||
|
|
||||||
|
日志里出现 `availability=Some("ready")` 就说明上线了,按 `Ctrl+C` 退出日志查看(容器继续在后台运行)。
|
||||||
|
之后 NAS 开机会自动启动它。
|
||||||
|
|
||||||
|
**用群晖界面管理**:Container Manager → 项目 → 新增,路径选 `/volume1/docker/uu-remote`,会自动读取 `compose.yaml`。
|
||||||
|
首次登录仍需在 SSH 里执行第二步。
|
||||||
|
|
||||||
|
## 使用
|
||||||
|
|
||||||
|
打开官方 UU 远程客户端,在「我的设备」里找到你的 NAS(显示为 Windows 设备,这是正常的):
|
||||||
|
|
||||||
|
- **文件传输**:浏览、上传、下载 `/data` 里的文件。
|
||||||
|
- **终端**:进入容器的命令行,当前目录是 `/data`。注意这是容器而不是 NAS 系统本身。
|
||||||
|
- **端口映射**:例如目标填 `127.0.0.1`、端口 `5000`,就能在本地浏览器打开 NAS 的 DSM 管理页;
|
||||||
|
填局域网里其他设备的地址和端口(如 `192.168.1.10:22`)即可访问那台设备的服务。
|
||||||
|
|
||||||
|
## 更新
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd /volume1/docker/uu-remote
|
||||||
|
sudo docker compose pull && sudo docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
`config` 目录保留即可,不用重新登录。
|
||||||
|
|
||||||
|
## 停用与移除
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo docker compose down # 停止并删除容器
|
||||||
|
```
|
||||||
|
|
||||||
|
再在官方客户端的设备列表里删除这台设备;如需彻底清除登录信息,删除 `config` 目录。
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
- **设备名是一串随机字符**:登录时没有用主机网络。删除 `config/config.json`,按第二步用 `docker compose run` 重新登录。
|
||||||
|
- **一直不上线**:`sudo docker compose logs --tail 100` 查看日志;确认 NAS 能访问外网。
|
||||||
|
- **连接慢、经常卡**:确认 `network_mode: host` 没有被去掉。
|
||||||
|
- **想要远程桌面**:NAS 上不支持;请在有桌面的 Linux 电脑上安装主机端(见主 README)。
|
||||||
|
|
||||||
|
安全提示:只挂需要远程访问的文件夹;端口映射可以访问 NAS 所在局域网,请保管好 UU 账号。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
Image: [`ghcr.io/vallierdev/uu-remote-linux`](https://github.com/VallierDev/uu-remote-linux/pkgs/container/uu-remote-linux)
|
||||||
|
|
||||||
|
Runs this project's host headless on a desktop-less NAS (x86_64, e.g. Synology DSM 7.2+ with Container Manager) for the
|
||||||
|
official UU Remote clients: **file transfer** (folders you mount at `/data`), **terminal** (bash inside the container) and
|
||||||
|
**port mapping** into your LAN. No remote desktop.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo mkdir -p /volume1/docker/uu-remote/config && sudo chmod 700 /volume1/docker/uu-remote/config
|
||||||
|
cd /volume1/docker/uu-remote
|
||||||
|
# compose.yaml: image ghcr.io/vallierdev/uu-remote-linux:latest, network_mode: host,
|
||||||
|
# volumes ./config:/config and /volume1/your-share:/data (see the Chinese section above)
|
||||||
|
sudo docker compose pull
|
||||||
|
sudo docker compose run --rm uu-remote login --no-gui # scan the QR with the UU mobile app; the QR is a credential
|
||||||
|
sudo docker compose up -d
|
||||||
|
sudo docker compose logs -f # wait for availability=Some("ready")
|
||||||
|
```
|
||||||
|
|
||||||
|
Update with `docker compose pull && docker compose up -d` (keep `config/`). Remove with `docker compose down`, then delete
|
||||||
|
the device in the official client.
|
||||||
|
|
||||||
|
**Unofficial project, not affiliated with NetEase.**
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 51 KiB After Width: | Height: | Size: 161 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 255 KiB |
@@ -0,0 +1,22 @@
|
|||||||
|
控制端:修复 FFmpeg 9 下没有画面;新增「删除设备」。/ Viewer: fix no video with FFmpeg 9; add device removal.
|
||||||
|
|
||||||
|
### 控制端修复 / Viewer — fixed
|
||||||
|
- **FFmpeg 9 下桌面没有画面**(v0.2.2、v0.2.3 的回归):为兼容 FFmpeg 4.4 改用的 `-vsync 0` 已被 FFmpeg 9 删除,解码进程一启动就退出,
|
||||||
|
所有帧都解码失败。现在启动时探测当前 ffmpeg 支持的参数:新版本用 `-fps_mode passthrough`,旧版本(如 Ubuntu 22.04 的 4.4)用 `-vsync 0`。
|
||||||
|
已在 FFmpeg 9.0.2 上连接官方 Mac 被控端实测:0 解码错误。
|
||||||
|
Fixed: with FFmpeg 9 every frame failed to decode (`-vsync` was removed). Verified against the official Mac host on FFmpeg 9.0.2.
|
||||||
|
|
||||||
|
### 控制端新增 / Viewer — added
|
||||||
|
- **删除设备**:启动窗口「更多工具 → 删除设备」(带确认),或命令行 `uuremote-viewer unbind DEVICE`,把设备从账号中移除,
|
||||||
|
与官方客户端的「删除设备」相同。命令行方式已对一台测试设备实测删除成功;⚠️ 启动窗口里的按钮尚未实机点击验收;
|
||||||
|
分享给你的设备(`--shared`)只有字符串依据,未实测。
|
||||||
|
Remove a device from the account (CLI verified live on a test device; launcher button and `--shared` not yet verified).
|
||||||
|
|
||||||
|
### 已知问题 / Known issues
|
||||||
|
- 剪贴板只在控制端窗口获得焦点时同步;控制端 → 官方 Windows 被控端的剪贴板仍在排查。
|
||||||
|
- Clipboard syncs only while the viewer window is focused; viewer → official Windows host clipboard is still unresolved.
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.4-x86_64-linux.tar.gz`:主机 `uuremote-server`(X11 版)与控制端 `uuremote-viewer`(x86_64,glibc ≥ 2.35;控制端需 SDL2、GTK3、ffmpeg),附带 `contrib/`。主机端与 v0.2.3 相同。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
窗口颜色修复;控制端可接收官方 Mac 被控端的剪贴板。/ Window colors fixed; viewer receives the official Mac host's clipboard.
|
||||||
|
|
||||||
|
### 修复 / Fixed
|
||||||
|
- **深色系统主题下窗口文字看不见**(#43):协助窗口、控制端启动窗口和工具窗口使用固定浅色背景,但部分文字跟随系统深色主题变成了白色。
|
||||||
|
现在这些窗口固定使用浅色主题。已在虚拟机中设置深色偏好后截图确认。
|
||||||
|
GTK windows now stay on the light theme, so text is readable under dark system themes.
|
||||||
|
- **控制端 ↔ 官方 Mac 被控端剪贴板**:Mac 被控端以 `public.utf8-plain-text`(UTF-8)提供文本,而不是 Windows 的 `CF_UNICODETEXT`,
|
||||||
|
之前控制端不会请求,剪贴板始终不同步。现在两种格式都支持;主机端发给官方客户端的格式不变。
|
||||||
|
Mac → 控制端已实机验证;⚠️ 控制端 → Mac 尚未验证。
|
||||||
|
The viewer now handles the Mac host's UTF-8 text format (Mac → viewer verified live; viewer → Mac not yet verified).
|
||||||
|
|
||||||
|
### 已验证 / Verified with the official Mac host(FFmpeg 9.0.2)
|
||||||
|
- 画面 0 解码错误,键盘输入正确,文件上传/下载/列目录 sha256 一致。
|
||||||
|
|
||||||
|
### 已知问题 / Known issues
|
||||||
|
- 剪贴板只在控制端窗口获得焦点时同步;控制端 → 官方 Windows 被控端的剪贴板仍在排查。
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.5-x86_64-linux.tar.gz`:主机 `uuremote-server`(X11 版)与控制端 `uuremote-viewer`(x86_64,glibc ≥ 2.35;控制端需 SDL2、GTK3、ffmpeg),附带 `contrib/`。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
控制端可打开官方 Mac 被控端的终端;输入问题诊断日志。/ Viewer terminal works with the official Mac host; input diagnostics.
|
||||||
|
|
||||||
|
### 控制端修复 / Viewer — fixed
|
||||||
|
- **连接官方 Mac 被控端的终端**:之前一连上就断开(「Terminal channel closed」)。Mac 被控端把终端的应答发在终端通道上,
|
||||||
|
控制端现在能识别。已实机验证:可打开终端并正常回显。Mac 被控端的端口映射也已实测可用。
|
||||||
|
Terminal sessions with the official Mac host now open (verified live); port mapping with it was verified too.
|
||||||
|
|
||||||
|
### 主机端诊断 / Host diagnostics(#46)
|
||||||
|
- 收到不认识的输入事件时记一条日志(只有动作名和字段名,**不含输入内容**),用于排查手机输入法打字无反应。
|
||||||
|
- 小键盘按键记录被控端当前的 NumLock 状态(只记开/关,不记按键),用于排查小键盘不出数字。
|
||||||
|
- Logs unsupported input actions (names only, never typed text) and the server's NumLock state for numpad keys.
|
||||||
|
|
||||||
|
### 其他 / Other
|
||||||
|
- README 标题与开头加入控制端介绍并放上截图(#44)。
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.6-x86_64-linux.tar.gz`:主机 `uuremote-server`(X11 版)与控制端 `uuremote-viewer`(x86_64,glibc ≥ 2.35;控制端需 SDL2、GTK3、ffmpeg),附带 `contrib/`。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
手机输入法打字(实验);控制端 → 官方 Windows 被控端剪贴板修复。/ Mobile input-method text (experimental); viewer → Windows host clipboard fixed.
|
||||||
|
|
||||||
|
### 主机端 / Host
|
||||||
|
- **手机自带输入法打字**(#13、#46):官方 Windows 被控端用 `text_input` 动作接收手机输入法的文字。本版主机端支持这个动作,
|
||||||
|
在 X11 上把文字(含中文)直接输入到当前窗口;不论它从哪个数据通道到达都会处理。
|
||||||
|
已用手机 UU 远程实测:手机自带键盘输入的英文正确打出(手机在 CONTROL 通道发送 `text_input`);中文注入已在 X11 上
|
||||||
|
单独实测正确,但尚未用手机中文输入法实测。Wayland / 门户后端暂不支持,会记录一次警告。
|
||||||
|
诊断:非 CONTROL 通道收到的输入动作会记录动作名(不含内容)。
|
||||||
|
- Mobile input-method text via the official `text_input {content}` action, typed on X11. Verified with the UU mobile app
|
||||||
|
(English); Chinese injection verified on X11 separately, not yet with a phone IME.
|
||||||
|
|
||||||
|
### 控制端修复 / Viewer — fixed
|
||||||
|
- **控制端 → 官方 Windows 被控端剪贴板**:之前被控端确认收到,但粘贴为空。原因是控制端同时发送的「富剪贴板格式通告」
|
||||||
|
会覆盖刚写入的文本,而 Windows 被控端之后从不请求数据。现在按被控端平台发送:Windows 及本项目主机只发文本变更,
|
||||||
|
Mac 只发格式通告,平台未知时两者都发。已实测:Windows 被控端「运行」框可粘贴,官方 Mac 被控端正常。
|
||||||
|
Viewer → official Windows host clipboard now works (verified live); Mac unchanged and verified.
|
||||||
|
|
||||||
|
### 社区贡献 / Community
|
||||||
|
- **Mac SSH 粘贴助手**(#45,感谢 @jo32):`contrib/macos-ssh/`,在 Ghostty 里经 UU 端口映射用 SSH 时粘贴 Finder 文件会先上传再插入路径。
|
||||||
|
可选工具,维护者尚未实机验收。Optional contrib tool, not verified by the maintainer.
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.7-x86_64-linux.tar.gz`:主机 `uuremote-server`(X11 版)与控制端 `uuremote-viewer`(x86_64,glibc ≥ 2.35;控制端需 SDL2、GTK3、ffmpeg),附带 `contrib/`。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
群晖 / NAS 容器镜像。/ Docker image for Synology and other NAS boxes.
|
||||||
|
|
||||||
|
### 新增 / Added
|
||||||
|
- **群晖 / NAS(Docker,无桌面)**:`ghcr.io/vallierdev/uu-remote-linux`,在没有图形界面的 NAS 上运行本项目主机,
|
||||||
|
供官方客户端使用文件传输、终端(容器内 bash)和端口映射(经 UU 访问家里局域网的服务)。不提供远程桌面。
|
||||||
|
已在群晖 DSM 7.3.2(x86_64)上实测:文件上传下载 sha256 一致、终端回显正常、端口映射访问 DSM 管理页返回 200。
|
||||||
|
安装与首次扫码登录见 [docker/README.md](https://github.com/VallierDev/uu-remote-linux/blob/main/docker/README.md)。
|
||||||
|
- Headless NAS container image (file transfer, terminal, port mapping), verified on Synology DSM 7.3.2 (x86_64).
|
||||||
|
|
||||||
|
主机端与控制端程序与 v0.2.7 相同。/ Host and viewer binaries are unchanged from v0.2.7.
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.8-x86_64-linux.tar.gz`(主机 `uuremote-server` + 控制端 `uuremote-viewer`,附带 `contrib/`),或 `docker pull ghcr.io/vallierdev/uu-remote-linux:v0.2.8`。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
修复 H.265 + VAAPI 时手机卡在「正在传输」;VAAPI 可选加大编码缓冲。/ Fix H.265 + VAAPI stalling at "transferring"; optional VAAPI VBV buffer.
|
||||||
|
|
||||||
|
### 修复 / Fixed
|
||||||
|
- **H.265 用 VAAPI 硬件编码时没有画面**(#48,感谢 @NuoFang6):`hevc_vaapi` 只在关键帧处写帧分隔符,主机按分隔符切帧,
|
||||||
|
把整组画面当成一帧后全部被拦下,被控端几乎不发画面,手机停在「正在传输」。现在按图像边界切分 H.265 访问单元,
|
||||||
|
不再依赖帧分隔符;维护者补充了后缀 SEI 等尾随单元的处理。
|
||||||
|
已实测:作者在 Intel 核显 + 官方安卓客户端上(2560×1440,约 58 fps);维护者在 RTX 3090 上用固定输入探针验证
|
||||||
|
`hevc_nvenc` 与 `libx265` 均 90/90 帧可解码、首帧为关键帧。
|
||||||
|
- H.265 access units are now split on picture boundaries (RFC 7798), fixing hevc_vaapi sessions that sent almost nothing.
|
||||||
|
|
||||||
|
### 新增 / Added
|
||||||
|
- **`UU_VAAPI_BUFFER_MS`**(#47,感谢 @NuoFang6,源自 #42):可选加大 VAAPI 的编码缓冲(10–1000 ms),缓解高分辨率下
|
||||||
|
关键帧被压糊、画面周期性模糊。默认不启用。⚠️ 仅在一台机器上实测,代价是关键帧变大,建议从 250 ms 试起。
|
||||||
|
- Optional VAAPI VBV buffer `UU_VAAPI_BUFFER_MS` (off by default; verified on one machine only).
|
||||||
|
|
||||||
|
### 下载 / Download
|
||||||
|
`uu-remote-linux-v0.2.9-x86_64-linux.tar.gz`(主机 `uuremote-server` + 控制端 `uuremote-viewer`,附带 `contrib/`),或 `docker pull ghcr.io/vallierdev/uu-remote-linux:v0.2.9`。
|
||||||
|
|
||||||
|
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||||
+73
-12
@@ -5,11 +5,37 @@ use crate::protocol::{decode_wire,WireValue};
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
const UNICODE_TEXT:u64=13;
|
const UNICODE_TEXT:u64=13;
|
||||||
|
/// The official Mac host offers its pasteboard text as format id 0 named `public.utf8-plain-text` (observed live).
|
||||||
|
const MAC_TEXT:&str="public.utf8-plain-text";
|
||||||
|
#[derive(Clone,Copy,PartialEq,Eq,Debug)]
|
||||||
|
enum TextFormat {Windows,Mac}
|
||||||
|
impl TextFormat {
|
||||||
|
fn of(format:&[u8])->Option<Self>{
|
||||||
|
if number(format,1)==Ok(UNICODE_TEXT){return Some(Self::Windows)}
|
||||||
|
let named=|n|text_field(format,n).is_ok_and(|s|s==MAC_TEXT);
|
||||||
|
(named(2)||named(3)).then_some(Self::Mac)
|
||||||
|
}
|
||||||
|
fn id(self)->u64{match self{Self::Windows=>UNICODE_TEXT,Self::Mac=>0}}
|
||||||
|
fn name(self)->&'static str{match self{Self::Windows=>"CF_UNICODETEXT",Self::Mac=>MAC_TEXT}}
|
||||||
|
fn encode(self,text:&str)->Vec<u8>{match self{Self::Windows=>encode_windows(text),Self::Mac=>text.as_bytes().to_vec()}}
|
||||||
|
fn decode(self,data:&[u8])->Result<String,&'static str>{
|
||||||
|
match self{
|
||||||
|
Self::Windows=>decode_windows(data),
|
||||||
|
Self::Mac=>{
|
||||||
|
let data=data.strip_suffix(&[0]).unwrap_or(data);
|
||||||
|
if data.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}
|
||||||
|
let text=std::str::from_utf8(data).map_err(|_|"invalid UTF-8 clipboard text")?;
|
||||||
|
if text.contains('\0'){return Err("embedded NUL in clipboard text");}
|
||||||
|
Ok(text.to_owned())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
const BLOCK_BYTES:usize=0x20000;
|
const BLOCK_BYTES:usize=0x20000;
|
||||||
const MAX_BYTES:usize=MAX_TEXT*2+2;
|
const MAX_BYTES:usize=MAX_TEXT*2+2;
|
||||||
pub struct ResultMessages {pub messages:Vec<(u32,Vec<u8>)>,pub text:Option<String>}
|
pub struct ResultMessages {pub messages:Vec<(u32,Vec<u8>)>,pub text:Option<String>}
|
||||||
impl Default for ResultMessages {fn default()->Self{Self{messages:Vec::new(),text:None}}}
|
impl Default for ResultMessages {fn default()->Self{Self{messages:Vec::new(),text:None}}}
|
||||||
struct Pending {key:String, count:Option<usize>, blocks:BTreeMap<usize,Vec<u8>>}
|
struct Pending {key:String, format:TextFormat, count:Option<usize>, blocks:BTreeMap<usize,Vec<u8>>}
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct State {local:Option<String>, pending:Option<Pending>}
|
pub struct State {local:Option<String>, pending:Option<Pending>}
|
||||||
pub fn format_ids(rpc:&[u8])->Vec<u64>{
|
pub fn format_ids(rpc:&[u8])->Vec<u64>{
|
||||||
@@ -62,12 +88,15 @@ fn decode_windows(data:&[u8])->Result<String,&'static str>{
|
|||||||
if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}Ok(text)
|
if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}Ok(text)
|
||||||
}
|
}
|
||||||
impl State{
|
impl State{
|
||||||
pub fn offer(&mut self,id:u64,text:String)->Result<Vec<u8>,&'static str>{
|
pub fn offer(&mut self,id:u64,text:String)->Result<Vec<u8>,&'static str>{self.offer_formats(id,text,&[TextFormat::Windows])}
|
||||||
|
/// Viewer offers: Windows hosts pick CF_UNICODETEXT, the official Mac host its UTF-8 type.
|
||||||
|
pub fn offer_any_host(&mut self,id:u64,text:String)->Result<Vec<u8>,&'static str>{self.offer_formats(id,text,&[TextFormat::Windows,TextFormat::Mac])}
|
||||||
|
fn offer_formats(&mut self,id:u64,text:String,formats:&[TextFormat])->Result<Vec<u8>,&'static str>{
|
||||||
if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}
|
if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}
|
||||||
if text.contains('\0')||encode_windows(&text).len()>MAX_BYTES{return Err("clipboard encoded text exceeds limit");}
|
if text.contains('\0')||encode_windows(&text).len()>MAX_BYTES{return Err("clipboard encoded text exceeds limit");}
|
||||||
self.local=Some(text);
|
self.local=Some(text);
|
||||||
let mut format=Vec::new();int(1,UNICODE_TEXT,&mut format);string(2,"CF_UNICODETEXT",&mut format);
|
let mut list=Vec::new();
|
||||||
let mut list=Vec::new();nested(1,&format,&mut list);
|
for kind in formats {let mut format=Vec::new();int(1,kind.id(),&mut format);string(2,kind.name(),&mut format);nested(1,&format,&mut list);}
|
||||||
Ok(request(id,1,&list))
|
Ok(request(id,1,&list))
|
||||||
}
|
}
|
||||||
pub fn request(&mut self,rpc:&[u8],next:&mut impl FnMut()->u64)->Result<ResultMessages,&'static str>{
|
pub fn request(&mut self,rpc:&[u8],next:&mut impl FnMut()->u64)->Result<ResultMessages,&'static str>{
|
||||||
@@ -78,22 +107,30 @@ impl State{
|
|||||||
if let Some(list)=bytes(clip,1)?{
|
if let Some(list)=bytes(clip,1)?{
|
||||||
out.messages.push((22,response(h,1,&[])));
|
out.messages.push((22,response(h,1,&[])));
|
||||||
let fields=decode_wire(list).map_err(|_|"invalid clipboard format list")?;
|
let fields=decode_wire(list).map_err(|_|"invalid clipboard format list")?;
|
||||||
let supports_text=fields.iter().filter(|f|f.number==1).any(|f|match f.value{WireValue::Bytes(format)=>number(format,1)==Ok(UNICODE_TEXT),_=>false});
|
let offered:Vec<TextFormat>=fields.iter().filter(|f|f.number==1).filter_map(|f|match f.value{WireValue::Bytes(format)=>TextFormat::of(format),_=>None}).collect();
|
||||||
|
let chosen=if offered.contains(&TextFormat::Windows){Some(TextFormat::Windows)}else{offered.first().copied()};
|
||||||
|
let supports_text=chosen.is_some();
|
||||||
self.pending=None;
|
self.pending=None;
|
||||||
if supports_text{
|
if !supports_text{
|
||||||
|
// Format ids/names only (never data), to learn non-Windows peers' text formats.
|
||||||
|
let formats:Vec<(u64,String)>=fields.iter().filter(|f|f.number==1).filter_map(|f|match f.value{WireValue::Bytes(format)=>Some(format),_=>None})
|
||||||
|
.take(8).map(|format|(number(format,1).unwrap_or(u64::MAX),decode_wire(format).ok().and_then(|x|x.into_iter().find_map(|y|match (y.number,y.value){(n,WireValue::Bytes(s)) if n!=1=>std::str::from_utf8(s).ok().map(|s|s.chars().take(48).collect()),_=>None})).unwrap_or_default())).collect();
|
||||||
|
log::info!("Clipboard offer without a supported text format: formats={formats:?}");
|
||||||
|
}
|
||||||
|
if let Some(format)=chosen{
|
||||||
let id=next();
|
let id=next();
|
||||||
let epoch=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs() as u32;
|
let epoch=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs() as u32;
|
||||||
let key=format!("{epoch:08x}-0000-4000-8000-{:012x}",id & 0xffffffffffff);
|
let key=format!("{epoch:08x}-0000-4000-8000-{:012x}",id & 0xffffffffffff);
|
||||||
let mut ask=Vec::new();int(1,UNICODE_TEXT,&mut ask);string(2,&key,&mut ask);string(3,"CF_UNICODETEXT",&mut ask);
|
let mut ask=Vec::new();int(1,format.id(),&mut ask);string(2,&key,&mut ask);string(3,format.name(),&mut ask);
|
||||||
self.pending=Some(Pending{key,count:None,blocks:BTreeMap::new()});
|
self.pending=Some(Pending{key,format,count:None,blocks:BTreeMap::new()});
|
||||||
out.messages.push((21,request(id,2,&ask)));
|
out.messages.push((21,request(id,2,&ask)));
|
||||||
}
|
}
|
||||||
}else if let Some(ask)=bytes(clip,2)?{
|
}else if let Some(ask)=bytes(clip,2)?{
|
||||||
let key=text_field(ask,2)?;
|
let key=text_field(ask,2)?;
|
||||||
if key.len()>256||key.is_empty(){return Err("invalid clipboard block key");}
|
if key.len()>256||key.is_empty(){return Err("invalid clipboard block key");}
|
||||||
let available=number(ask,1)?==UNICODE_TEXT&&self.local.is_some();
|
let format=if number(ask,1)?==UNICODE_TEXT{Some(TextFormat::Windows)}else if text_field(ask,3).is_ok_and(|s|s==MAC_TEXT){Some(TextFormat::Mac)}else{None};
|
||||||
let mut confirm=Vec::new();int(1,if available{1}else{2},&mut confirm);string(2,key,&mut confirm);
|
let data=format.zip(self.local.as_ref()).map(|(format,text)|format.encode(text));
|
||||||
let data=if available{Some(encode_windows(self.local.as_ref().unwrap()))}else{None};
|
let mut confirm=Vec::new();int(1,if data.is_some(){1}else{2},&mut confirm);string(2,key,&mut confirm);
|
||||||
if let Some(data)=&data{int(3,data.chunks(BLOCK_BYTES).len() as u64,&mut confirm);}
|
if let Some(data)=&data{int(3,data.chunks(BLOCK_BYTES).len() as u64,&mut confirm);}
|
||||||
out.messages.push((22,response(h,2,&confirm)));
|
out.messages.push((22,response(h,2,&confirm)));
|
||||||
if let Some(data)=data{
|
if let Some(data)=data{
|
||||||
@@ -144,13 +181,37 @@ impl State{
|
|||||||
else if (1..=count).all(|i|pending.blocks.contains_key(&i)){1}
|
else if (1..=count).all(|i|pending.blocks.contains_key(&i)){1}
|
||||||
else{return Ok(None);};
|
else{return Ok(None);};
|
||||||
let data:Vec<u8>=(first..first+count).flat_map(|i|pending.blocks[&i].iter().copied()).collect();
|
let data:Vec<u8>=(first..first+count).flat_map(|i|pending.blocks[&i].iter().copied()).collect();
|
||||||
self.pending=None;decode_windows(&data).map(Some)
|
let format=pending.format;self.pending=None;format.decode(&data).map(Some)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests{
|
mod tests{
|
||||||
use super::*;
|
use super::*;
|
||||||
|
#[test] fn mac_utf8_text_round_trips_both_directions(){
|
||||||
|
// Mac host offer: format list {1 id 0, 2 "public.utf8-plain-text"} (observed live).
|
||||||
|
let mut mac=Vec::new();int(1,0,&mut mac);string(2,MAC_TEXT,&mut mac);
|
||||||
|
let mut list=Vec::new();nested(1,&mac,&mut list);
|
||||||
|
let mut viewer=State::default();let mut id=200;let mut next=||{id+=1;id};
|
||||||
|
let asked=viewer.request(&request(7,1,&list),&mut next).unwrap();
|
||||||
|
assert_eq!(asked.messages.len(),2);
|
||||||
|
let ask_rpc=&asked.messages[1].1;let clip=bytes(ask_rpc,9).unwrap().unwrap();let ask=bytes(clip,2).unwrap().unwrap();
|
||||||
|
assert_eq!(number(ask,1),Ok(0));assert_eq!(text_field(ask,3),Ok(MAC_TEXT));
|
||||||
|
let key=text_field(ask,2).unwrap().to_owned();
|
||||||
|
let mut confirm=Vec::new();int(1,1,&mut confirm);string(2,&key,&mut confirm);int(3,1,&mut confirm);
|
||||||
|
assert_eq!(viewer.response(&response(header(ask_rpc).unwrap(),2,&confirm)).unwrap(),None);
|
||||||
|
let mut block=Vec::new();string(1,&key,&mut block);int(2,0,&mut block);nested(3,"中文 text\n".as_bytes(),&mut block);
|
||||||
|
assert_eq!(viewer.request(&request(8,3,&block),&mut next).unwrap().text.as_deref(),Some("中文 text\n"));
|
||||||
|
// Viewer offer lists both formats; a Mac-style ask gets UTF-8 bytes back.
|
||||||
|
let offer=viewer.offer_any_host(9,"hi".into()).unwrap();
|
||||||
|
assert_eq!(format_ids(&offer),vec![13,0]);
|
||||||
|
let mut ask=Vec::new();int(1,0,&mut ask);string(2,"k",&mut ask);string(3,MAC_TEXT,&mut ask);
|
||||||
|
let out=viewer.request(&request(10,2,&ask),&mut next).unwrap();
|
||||||
|
let data=bytes(bytes(bytes(&out.messages[1].1,9).unwrap().unwrap(),3).unwrap().unwrap(),3).unwrap().unwrap();
|
||||||
|
assert_eq!(data,b"hi");
|
||||||
|
// Host-side offers are unchanged: CF_UNICODETEXT only.
|
||||||
|
assert_eq!(format_ids(&State::default().offer(1,"hi".into()).unwrap()),vec![13]);
|
||||||
|
}
|
||||||
#[test]
|
#[test]
|
||||||
fn desktop_clipboard_negotiates_and_buffers_unicode_until_confirmation(){
|
fn desktop_clipboard_negotiates_and_buffers_unicode_until_confirmation(){
|
||||||
let text="UU-test-中文🙂\n".repeat(900);
|
let text="UU-test-中文🙂\n".repeat(900);
|
||||||
|
|||||||
@@ -15,6 +15,9 @@ pub enum ControlInput {
|
|||||||
MouseAbsolute { x: f64, y: f64 },
|
MouseAbsolute { x: f64, y: f64 },
|
||||||
MouseRelative { dx: i32, dy: i32 },
|
MouseRelative { dx: i32, dy: i32 },
|
||||||
MouseScroll { dx: i32, dy: i32 },
|
MouseScroll { dx: i32, dy: i32 },
|
||||||
|
/// Official Windows host `text_input {content}` (KeyboardMouseRunner::execTextInput): text typed by the
|
||||||
|
/// mobile clients' own input method. Never logged.
|
||||||
|
TextInput { text: String },
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
@@ -58,6 +61,11 @@ pub fn decode_control(data: &[u8]) -> Result<ControlMessage, String> {
|
|||||||
"mouse_move_relative" => ControlInput::MouseRelative {
|
"mouse_move_relative" => ControlInput::MouseRelative {
|
||||||
dx: integer(&v, "delta_x")?, dy: integer(&v, "delta_y")?,
|
dx: integer(&v, "delta_x")?, dy: integer(&v, "delta_y")?,
|
||||||
},
|
},
|
||||||
|
"text_input" => {
|
||||||
|
let text = v.get("content").and_then(Value::as_str).ok_or("CONTROL field content must be a string")?;
|
||||||
|
if text.len() > 16 * 1024 { return Err("text_input content exceeds 16 KiB".into()); }
|
||||||
|
ControlInput::TextInput { text: text.to_owned() }
|
||||||
|
}
|
||||||
"mouse_scroll" => ControlInput::MouseScroll {
|
"mouse_scroll" => ControlInput::MouseScroll {
|
||||||
dx: integer(&v, "delta_x")?, dy: integer(&v, "delta_y")?,
|
dx: integer(&v, "delta_x")?, dy: integer(&v, "delta_y")?,
|
||||||
},
|
},
|
||||||
@@ -137,6 +145,9 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn does_not_invent_actions_for_unknown_json() {
|
fn does_not_invent_actions_for_unknown_json() {
|
||||||
assert!(matches!(decode_control(br#"{"action":"unverified"}"#).unwrap(), ControlMessage::Unsupported(_)));
|
assert!(matches!(decode_control(br#"{"action":"unverified"}"#).unwrap(), ControlMessage::Unsupported(_)));
|
||||||
|
assert_eq!(decode_control("{\"action\":\"text_input\",\"content\":\"你好 a\"}".as_bytes()).unwrap(),
|
||||||
|
ControlMessage::Input(ControlInput::TextInput { text: "你好 a".into() }));
|
||||||
|
assert!(decode_control(br#"{"action":"text_input"}"#).is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,9 +10,12 @@ extern "C" {
|
|||||||
fn x11_key_event(keycode: libc::c_int, is_press: libc::c_int) -> libc::c_int;
|
fn x11_key_event(keycode: libc::c_int, is_press: libc::c_int) -> libc::c_int;
|
||||||
fn x11_release_all() -> libc::c_int;
|
fn x11_release_all() -> libc::c_int;
|
||||||
fn x11_terminal_shortcut_state() -> libc::c_int;
|
fn x11_terminal_shortcut_state() -> libc::c_int;
|
||||||
|
fn x11_type_utf8(text: *const libc::c_char) -> libc::c_int;
|
||||||
}
|
}
|
||||||
#[cfg(not(target_os = "linux"))]
|
#[cfg(not(target_os = "linux"))]
|
||||||
unsafe fn x11_terminal_shortcut_state() -> libc::c_int { 0 }
|
unsafe fn x11_terminal_shortcut_state() -> libc::c_int { 0 }
|
||||||
|
#[cfg(not(target_os = "linux"))]
|
||||||
|
unsafe fn x11_type_utf8(_: *const libc::c_char) -> libc::c_int { 0 }
|
||||||
|
|
||||||
#[cfg(not(target_os = "linux"))]
|
#[cfg(not(target_os = "linux"))]
|
||||||
unsafe fn x11_mouse_move(_: libc::c_int, _: libc::c_int) -> libc::c_int { 0 }
|
unsafe fn x11_mouse_move(_: libc::c_int, _: libc::c_int) -> libc::c_int { 0 }
|
||||||
@@ -248,6 +251,14 @@ impl InputInjector {
|
|||||||
if AUDIT.fetch_add(1,std::sync::atomic::Ordering::Relaxed) < 8 {
|
if AUDIT.fetch_add(1,std::sync::atomic::Ordering::Relaxed) < 8 {
|
||||||
log::info!("Desktop keyboard injection outcome: result={result}");
|
log::info!("Desktop keyboard injection outcome: result={result}");
|
||||||
}
|
}
|
||||||
|
// KP_0..KP_9 type digits only with NumLock on (#46); record the server's NumLock state, not the key.
|
||||||
|
static NUMPAD: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||||
|
if (0x60..=0x6f).contains(&key) && is_press && self.backend==crate::desktop_backend::DesktopBackend::X11
|
||||||
|
&& NUMPAD.fetch_add(1,std::sync::atomic::Ordering::Relaxed) < 4 {
|
||||||
|
let (mut x,mut y,mut mask)=(0,0,0u32);
|
||||||
|
let state=unsafe { x11_pointer_state(&mut x,&mut y,&mut mask) };
|
||||||
|
log::info!("Desktop numpad key: result={result} numlock={}", state==0 && mask & 0x10 != 0);
|
||||||
|
}
|
||||||
if result == 0 {
|
if result == 0 {
|
||||||
let mut held=self.held.lock().unwrap();
|
let mut held=self.held.lock().unwrap();
|
||||||
if is_press {held.keys.insert(symbol);} else {held.keys.remove(&symbol);}
|
if is_press {held.keys.insert(symbol);} else {held.keys.remove(&symbol);}
|
||||||
@@ -349,6 +360,20 @@ impl InputInjector {
|
|||||||
if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::key(symbol,pressed) }
|
if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::key(symbol,pressed) }
|
||||||
else { unsafe { x11_key_symbol(symbol as libc::c_ulong,i32::from(pressed)) } }
|
else { unsafe { x11_key_symbol(symbol as libc::c_ulong,i32::from(pressed)) } }
|
||||||
}
|
}
|
||||||
|
/// Mobile input-method text (`text_input`). X11 only for now; other backends log once.
|
||||||
|
pub fn text_input(&self, text: &str) {
|
||||||
|
let _serial=self.serial.lock().unwrap();
|
||||||
|
let Ok(c_text)=std::ffi::CString::new(text.replace('\0',"")) else { return };
|
||||||
|
if self.backend==crate::desktop_backend::DesktopBackend::X11 {
|
||||||
|
let typed=unsafe { x11_type_utf8(c_text.as_ptr()) };
|
||||||
|
log::info!("Desktop text input: chars={} result={}", text.chars().count(), typed);
|
||||||
|
} else {
|
||||||
|
static WARNED:std::sync::atomic::AtomicBool=std::sync::atomic::AtomicBool::new(false);
|
||||||
|
if !WARNED.swap(true,std::sync::atomic::Ordering::Relaxed) {
|
||||||
|
log::warn!("Mobile text input is not supported on the {:?} backend yet", self.backend);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
pub fn key_event(&self, keycode: i32, is_press: bool) {
|
pub fn key_event(&self, keycode: i32, is_press: bool) {
|
||||||
let _serial=self.serial.lock().unwrap();
|
let _serial=self.serial.lock().unwrap();
|
||||||
if self.backend!=crate::desktop_backend::DesktopBackend::X11 { return; }
|
if self.backend!=crate::desktop_backend::DesktopBackend::X11 { return; }
|
||||||
|
|||||||
+126
-17
@@ -94,16 +94,57 @@ fn nal_offsets_for(bytes: &[u8], kind: u8, codec: VideoCodec) -> Vec<usize> {
|
|||||||
let matches = match codec {
|
let matches = match codec {
|
||||||
VideoCodec::H264 => header < bytes.len() && bytes[header] & 31 == kind,
|
VideoCodec::H264 => header < bytes.len() && bytes[header] & 31 == kind,
|
||||||
// HEVC has a two-byte header: forbidden_zero_bit=0, temporal_id_plus1 != 0.
|
// HEVC has a two-byte header: forbidden_zero_bit=0, temporal_id_plus1 != 0.
|
||||||
VideoCodec::H265 => header + 1 < bytes.len() && bytes[header] & 128 == 0
|
VideoCodec::H265 => hevc_nal_kind(bytes, header) == Some(kind),
|
||||||
&& bytes[header + 1] & 7 != 0 && (bytes[header] >> 1) & 63 == kind,
|
|
||||||
};
|
};
|
||||||
if matches { result.push(i); }
|
if matches { result.push(i); }
|
||||||
i += prefix;
|
i += prefix;
|
||||||
}
|
}
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
fn aud_offsets_for(bytes: &[u8], codec: VideoCodec) -> Vec<usize> {
|
|
||||||
nal_offsets_for(bytes, if codec == VideoCodec::H265 { 35 } else { 9 }, codec)
|
/// Validated HEVC NAL unit type from the two-byte header (`None` when it is incomplete or the
|
||||||
|
/// forbidden bit is set or temporal_id_plus1 is zero).
|
||||||
|
fn hevc_nal_kind(bytes: &[u8], header: usize) -> Option<u8> {
|
||||||
|
(header + 1 < bytes.len() && bytes[header] & 128 == 0 && bytes[header + 1] & 7 != 0)
|
||||||
|
.then(|| (bytes[header] >> 1) & 63)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Access-unit starts for H.265, independent of where the encoder puts its AUDs. VAAPI writes an
|
||||||
|
/// AUD only at IRAPs, so splitting on AUD alone groups a whole GOP into one "frame" (and that
|
||||||
|
/// frame then fails the IRAP gate, so nothing is sent). RFC 7798 §3.1 puts the boundary at the
|
||||||
|
/// first NAL after a VCL NAL that is either non-VCL (AUD/VPS/SPS/PPS/SEI) or starts a picture
|
||||||
|
/// (first_slice_segment_in_pic_flag), which also keeps multi-slice pictures in one unit.
|
||||||
|
fn hevc_au_offsets(bytes: &[u8]) -> Vec<usize> {
|
||||||
|
let mut result = Vec::new();
|
||||||
|
let mut previous_vcl = false;
|
||||||
|
let mut first = true;
|
||||||
|
let mut i = 0;
|
||||||
|
while i + 3 < bytes.len() {
|
||||||
|
let prefix = if bytes[i..].starts_with(&[0, 0, 0, 1]) { 4 }
|
||||||
|
else if bytes[i..].starts_with(&[0, 0, 1]) { 3 } else { i += 1; continue };
|
||||||
|
let header = i + prefix;
|
||||||
|
if let Some(kind) = hevc_nal_kind(bytes, header) {
|
||||||
|
let vcl = kind < 32;
|
||||||
|
let starts_picture = vcl && bytes.get(header + 2).is_some_and(|byte| byte & 0x80 != 0);
|
||||||
|
// RFC 7798 / H.265 7.4.2.4.4: only these non-VCL types may open the next access unit.
|
||||||
|
// Suffix SEI (40), filler (38) and end of sequence/bitstream (36, 37) stay with the
|
||||||
|
// picture they follow.
|
||||||
|
let opens_unit = matches!(kind, 32..=35 | 39 | 41..=44 | 48..=55);
|
||||||
|
if first || (previous_vcl && (opens_unit || starts_picture)) { result.push(i); }
|
||||||
|
// Trailing NALs (suffix SEI, filler, end markers) do not end "after a VCL NAL".
|
||||||
|
if vcl || opens_unit { previous_vcl = vcl; }
|
||||||
|
first = false;
|
||||||
|
}
|
||||||
|
i += prefix;
|
||||||
|
}
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
fn au_offsets_for(bytes: &[u8], codec: VideoCodec) -> Vec<usize> {
|
||||||
|
match codec {
|
||||||
|
VideoCodec::H264 => nal_offsets_for(bytes, 9, codec),
|
||||||
|
VideoCodec::H265 => hevc_au_offsets(bytes),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
fn is_independent_frame_for(bytes: &[u8], codec: VideoCodec) -> bool {
|
fn is_independent_frame_for(bytes: &[u8], codec: VideoCodec) -> bool {
|
||||||
match codec {
|
match codec {
|
||||||
@@ -114,7 +155,7 @@ fn is_independent_frame_for(bytes: &[u8], codec: VideoCodec) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
fn aud_offsets(bytes: &[u8]) -> Vec<usize> { aud_offsets_for(bytes, VideoCodec::H264) }
|
fn aud_offsets(bytes: &[u8]) -> Vec<usize> { au_offsets_for(bytes, VideoCodec::H264) }
|
||||||
fn is_independent_frame(bytes: &[u8]) -> bool { is_independent_frame_for(bytes, VideoCodec::H264) }
|
fn is_independent_frame(bytes: &[u8]) -> bool { is_independent_frame_for(bytes, VideoCodec::H264) }
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -178,10 +219,17 @@ fn vaapi_options(settings: &VideoSettings, gop: &str) -> Vec<String> {
|
|||||||
let (maxrate, buffer) = rate_args(settings, Encoder::Vaapi);
|
let (maxrate, buffer) = rate_args(settings, Encoder::Vaapi);
|
||||||
// QVBR is not uniformly available on Intel/AMD drivers. VBR + qmin sets a quality
|
// QVBR is not uniformly available on Intel/AMD drivers. VBR + qmin sets a quality
|
||||||
// floor while retaining the viewer's bitrate cap; unsupported drivers fall back to CPU.
|
// floor while retaining the viewer's bitrate cap; unsupported drivers fall back to CPU.
|
||||||
["-c:v", Encoder::Vaapi.name_for(settings.codec), "-profile:v", profile_for(settings.codec, true), "-g", gop, "-bf", "0",
|
let mut options: Vec<String> = ["-c:v", Encoder::Vaapi.name_for(settings.codec), "-profile:v", profile_for(settings.codec, true),
|
||||||
"-rc_mode", "VBR", "-b:v", &settings.max_kbps().map_or("16M".into(), |k| format!("{}k",k*3/4)),
|
"-g", gop, "-bf", "0", "-rc_mode", "VBR", "-b:v", &settings.max_kbps().map_or("16M".into(), |k| format!("{}k",k*3/4)),
|
||||||
"-maxrate", &maxrate, "-bufsize", &buffer, "-qmin", &settings.cq().to_string(), "-async_depth", "1", "-aud", "1"]
|
"-maxrate", &maxrate, "-bufsize", &buffer, "-qmin", &settings.cq().to_string(), "-async_depth", "1"]
|
||||||
.into_iter().map(str::to_owned).collect()
|
.into_iter().map(str::to_owned).collect();
|
||||||
|
// h264_vaapi writes an AUD per picture and the reader splits access units on it. hevc_vaapi
|
||||||
|
// does not: with `-aud 1` it writes an AUD only at IRAPs and drops every other picture from
|
||||||
|
// the bitstream (a 90-frame clip encoded to 3 IDRs and no P-frames), so HEVC leaves AUD off
|
||||||
|
// and hevc_au_offsets() splits pictures by their own boundaries. Parameter sets are still
|
||||||
|
// repeated in-band ahead of every IDR.
|
||||||
|
if settings.codec == VideoCodec::H264 { options.extend(["-aud".into(), "1".into()]); }
|
||||||
|
options
|
||||||
}
|
}
|
||||||
|
|
||||||
fn profile_for(codec: VideoCodec, vaapi: bool) -> &'static str {
|
fn profile_for(codec: VideoCodec, vaapi: bool) -> &'static str {
|
||||||
@@ -480,7 +528,21 @@ async fn read_inprocess(
|
|||||||
/// whole IDR frame, otherwise large desktops get near-grey keyframes that sharpen over the GOP (#8).
|
/// whole IDR frame, otherwise large desktops get near-grey keyframes that sharpen over the GOP (#8).
|
||||||
/// Half a second of bitrate still starved repeated 0.5 s-GOP keyframes at 3296x2036/2M; one second did not.
|
/// Half a second of bitrate still starved repeated 0.5 s-GOP keyframes at 3296x2036/2M; one second did not.
|
||||||
fn buffer_kbits(max_kbps: u32, encoder: Encoder) -> u32 {
|
fn buffer_kbits(max_kbps: u32, encoder: Encoder) -> u32 {
|
||||||
if encoder == Encoder::Cpu { max_kbps.clamp(500, 8000) } else { (max_kbps / 8).clamp(100, 500) }
|
if encoder == Encoder::Cpu { max_kbps.clamp(500, 8000) }
|
||||||
|
else if encoder == Encoder::Vaapi {
|
||||||
|
let requested = std::env::var("UU_VAAPI_BUFFER_MS").ok();
|
||||||
|
vaapi_buffer_kbits(max_kbps, requested.as_deref()).unwrap_or((max_kbps / 8).clamp(100, 500))
|
||||||
|
}
|
||||||
|
else { (max_kbps / 8).clamp(100, 500) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opt-in VAAPI VBV buffer: `码率上限 × 毫秒 / 1000` for `UU_VAAPI_BUFFER_MS` in 10-1000 ms.
|
||||||
|
/// The 100-500 kbit default is sized for NVENC; VAAPI quantizes a whole desktop keyframe when
|
||||||
|
/// the buffer is that small, which reads as a blur that sharpens over each GOP (#42).
|
||||||
|
/// Unset, out of range or unparsable values keep the default buffer.
|
||||||
|
fn vaapi_buffer_kbits(max_kbps: u32, value: Option<&str>) -> Option<u32> {
|
||||||
|
let ms = value?.trim().parse::<u32>().ok().filter(|ms| (10..=1000).contains(ms))?;
|
||||||
|
Some((max_kbps.saturating_mul(ms) / 1000).max(1))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn buffer_for(settings: &VideoSettings, encoder: Encoder) -> u32 {
|
fn buffer_for(settings: &VideoSettings, encoder: Encoder) -> u32 {
|
||||||
@@ -651,7 +713,7 @@ async fn read_encoder_with(
|
|||||||
pending.extend_from_slice(&chunk[..count]);
|
pending.extend_from_slice(&chunk[..count]);
|
||||||
// A chunk can include the next AUD, so split before enforcing the bound.
|
// A chunk can include the next AUD, so split before enforcing the bound.
|
||||||
loop {
|
loop {
|
||||||
let aud = aud_offsets_for(&pending, settings.codec);
|
let aud = au_offsets_for(&pending, settings.codec);
|
||||||
if aud.len() < 2 { break; }
|
if aud.len() < 2 { break; }
|
||||||
let next = aud[1];
|
let next = aud[1];
|
||||||
if next > MAX_ACCESS_UNIT { return Err("Encoder access unit exceeds limit".into()); }
|
if next > MAX_ACCESS_UNIT { return Err("Encoder access unit exceeds limit".into()); }
|
||||||
@@ -686,7 +748,16 @@ fn probe_settings() -> Result<VideoSettings,String> {
|
|||||||
None=>crate::capture_setting::QUALITY_AUTO,
|
None=>crate::capture_setting::QUALITY_AUTO,
|
||||||
Some(v)=>v.parse::<u64>().ok().filter(|q|(1..=5).contains(q)).ok_or("UU_PROBE_QUALITY must be 1-5")?,
|
Some(v)=>v.parse::<u64>().ok().filter(|q|(1..=5).contains(q)).ok_or("UU_PROBE_QUALITY must be 1-5")?,
|
||||||
};
|
};
|
||||||
Ok(VideoSettings {fps,quality,..VideoSettings::default()})
|
Ok(VideoSettings {fps,quality,codec:probe_codec(),..VideoSettings::default()})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The probe follows `UU_VIDEO_CODEC` so the HEVC path can be measured at all (H.264 otherwise),
|
||||||
|
/// and its first access unit is then checked against that codec instead of always H.264.
|
||||||
|
fn probe_codec() -> VideoCodec {
|
||||||
|
match std::env::var("UU_VIDEO_CODEC").ok().as_deref().map(str::to_ascii_lowercase).as_deref() {
|
||||||
|
Some("h265") | Some("hevc") => VideoCodec::H265,
|
||||||
|
_ => VideoCodec::H264,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn probe_input_command(spec:&FfmpegSpec,input:&std::ffi::OsStr,loop_input:bool,settings:&VideoSettings,
|
fn probe_input_command(spec:&FfmpegSpec,input:&std::ffi::OsStr,loop_input:bool,settings:&VideoSettings,
|
||||||
@@ -700,7 +771,7 @@ fn probe_input_command(spec:&FfmpegSpec,input:&std::ffi::OsStr,loop_input:bool,s
|
|||||||
command.args(scale_options(settings,encoder));
|
command.args(scale_options(settings,encoder));
|
||||||
command.args(encoder_options(settings,encoder,&gop_frames(settings.fps,false).to_string(),None));
|
command.args(encoder_options(settings,encoder,&gop_frames(settings.fps,false).to_string(),None));
|
||||||
command.args(timing_args(timing,settings.fps));
|
command.args(timing_args(timing,settings.fps));
|
||||||
command.args(["-frames:v",&wanted.to_string(),"-f","h264","pipe:1"]);
|
command.args(["-frames:v",&wanted.to_string(),"-f",if settings.codec==VideoCodec::H265 {"hevc"} else {"h264"},"pipe:1"]);
|
||||||
command
|
command
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -749,10 +820,10 @@ pub async fn probe_input(input:OsString,path:Option<String>)->Result<(),String>
|
|||||||
let n=stdout.read(&mut chunk).await.map_err(|e|format!("Encoder read: {e}"))?;
|
let n=stdout.read(&mut chunk).await.map_err(|e|format!("Encoder read: {e}"))?;
|
||||||
pending.extend_from_slice(&chunk[..n]);
|
pending.extend_from_slice(&chunk[..n]);
|
||||||
loop {
|
loop {
|
||||||
let aud=aud_offsets_for(&pending,settings.codec);
|
let aud=au_offsets_for(&pending,settings.codec);
|
||||||
let end=if aud.len()>1 { aud[1] } else if n==0 && !pending.is_empty() { pending.len() } else { break; };
|
let end=if aud.len()>1 { aud[1] } else if n==0 && !pending.is_empty() { pending.len() } else { break; };
|
||||||
if end>MAX_ACCESS_UNIT { return Err("Encoder access unit exceeds limit".into()); }
|
if end>MAX_ACCESS_UNIT { return Err("Encoder access unit exceeds limit".into()); }
|
||||||
if count==0 && !is_independent_frame(&pending[..end]) { return Err("Video probe did not begin with IDR".into()); }
|
if count==0 && !is_independent_frame_for(&pending[..end], settings.codec) { return Err("Video probe did not begin with IDR".into()); }
|
||||||
if let Some(file)=file.as_mut() { file.write_all(&pending[..end]).map_err(|e|e.to_string())?; }
|
if let Some(file)=file.as_mut() { file.write_all(&pending[..end]).map_err(|e|e.to_string())?; }
|
||||||
bytes+=end; count+=1;
|
bytes+=end; count+=1;
|
||||||
pending.drain(..end);
|
pending.drain(..end);
|
||||||
@@ -787,7 +858,7 @@ pub async fn probe(size:(u32,u32),display:String,portal:Option<Arc<crate::portal
|
|||||||
tokio::time::timeout(Duration::from_secs(15+wanted/30),async {
|
tokio::time::timeout(Duration::from_secs(15+wanted/30),async {
|
||||||
while count<wanted {
|
while count<wanted {
|
||||||
let frame=rx.recv().await.ok_or("Video probe encoder ended")?;
|
let frame=rx.recv().await.ok_or("Video probe encoder ended")?;
|
||||||
if count==0 && !is_independent_frame(&frame.data) { return Err("Video probe did not begin with IDR".to_owned()); }
|
if count==0 && !is_independent_frame_for(&frame.data, settings.codec) { return Err("Video probe did not begin with IDR".to_owned()); }
|
||||||
if let Some(file)=file.as_mut() { file.write_all(&frame.data).map_err(|e|e.to_string())?; }
|
if let Some(file)=file.as_mut() { file.write_all(&frame.data).map_err(|e|e.to_string())?; }
|
||||||
bytes+=frame.data.len(); count+=1;
|
bytes+=frame.data.len(); count+=1;
|
||||||
}
|
}
|
||||||
@@ -1066,6 +1137,20 @@ mod tests {
|
|||||||
assert_eq!(buffer_kbits(30_000, Encoder::Cpu), 8000);
|
assert_eq!(buffer_kbits(30_000, Encoder::Cpu), 8000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vaapi_buffer_env_is_opt_in_and_bounded() {
|
||||||
|
assert_eq!(vaapi_buffer_kbits(30_000, None), None);
|
||||||
|
assert_eq!(vaapi_buffer_kbits(30_000, Some("250")), Some(7500));
|
||||||
|
assert_eq!(vaapi_buffer_kbits(30_000, Some(" 10 ")), Some(300));
|
||||||
|
assert_eq!(vaapi_buffer_kbits(30_000, Some("1000")), Some(30_000));
|
||||||
|
// Out of the documented range, empty or unparsable keeps the default buffer.
|
||||||
|
for value in ["", "9", "1001", "0", "abc", "-250", "250ms"] {
|
||||||
|
assert_eq!(vaapi_buffer_kbits(30_000, Some(value)), None, "{value}");
|
||||||
|
}
|
||||||
|
// A tiny cap must not produce a zero-sized buffer.
|
||||||
|
assert_eq!(vaapi_buffer_kbits(1, Some("10")), Some(1));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn vaapi_is_explicit_and_upload_follows_scale() {
|
fn vaapi_is_explicit_and_upload_follows_scale() {
|
||||||
assert_eq!(Encoder::from_setting(None, true), Encoder::Nvenc);
|
assert_eq!(Encoder::from_setting(None, true), Encoder::Nvenc);
|
||||||
@@ -1207,7 +1292,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn hevc_annex_b_boundaries_and_irap_use_two_byte_headers() {
|
fn hevc_annex_b_boundaries_and_irap_use_two_byte_headers() {
|
||||||
let bytes = [0,0,0,1,70,1,80,0,0,1,64,1,42,0,0,1,38,1,42,0,0,1,70,1,80];
|
let bytes = [0,0,0,1,70,1,80,0,0,1,64,1,42,0,0,1,38,1,42,0,0,1,70,1,80];
|
||||||
assert_eq!(aud_offsets_for(&bytes, VideoCodec::H265), vec![0,19]);
|
assert_eq!(au_offsets_for(&bytes, VideoCodec::H265), vec![0,19]);
|
||||||
assert!(is_independent_frame_for(&bytes[..19], VideoCodec::H265));
|
assert!(is_independent_frame_for(&bytes[..19], VideoCodec::H265));
|
||||||
for kind in 16..=21 {
|
for kind in 16..=21 {
|
||||||
assert!(is_independent_frame_for(&[0,0,1,kind << 1,1,42], VideoCodec::H265));
|
assert!(is_independent_frame_for(&[0,0,1,kind << 1,1,42], VideoCodec::H265));
|
||||||
@@ -1218,6 +1303,27 @@ mod tests {
|
|||||||
assert!(!is_independent_frame_for(&[0,0,1,166,1,42], VideoCodec::H265));
|
assert!(!is_independent_frame_for(&[0,0,1,166,1,42], VideoCodec::H265));
|
||||||
assert!(!is_independent_frame_for(&[0,0,1,38,1,42,0,0,1,2,1,42], VideoCodec::H265));
|
assert!(!is_independent_frame_for(&[0,0,1,38,1,42,0,0,1,2,1,42], VideoCodec::H265));
|
||||||
}
|
}
|
||||||
|
#[test]
|
||||||
|
fn hevc_access_units_do_not_depend_on_aud_placement() {
|
||||||
|
// VAAPI writes an AUD only at IRAPs: AUD VPS SPS PPS IDR, then one P per picture.
|
||||||
|
let vaapi = [0,0,0,1,70,1,0x80, 0,0,0,1,64,1,0x42, 0,0,0,1,66,1,0x42,
|
||||||
|
0,0,0,1,68,1,0x42, 0,0,0,1,38,1,0x80, 0,0,0,1,2,1,0x80, 0,0,0,1,2,1,0x80];
|
||||||
|
assert_eq!(hevc_au_offsets(&vaapi), vec![0, 35, 42]);
|
||||||
|
// x265/nvenc style: an AUD in front of every picture.
|
||||||
|
let with_aud = [0,0,0,1,70,1,0x80, 0,0,0,1,64,1,0x42, 0,0,0,1,38,1,0x80,
|
||||||
|
0,0,0,1,70,1,0x80, 0,0,0,1,2,1,0x80, 0,0,0,1,70,1,0x80, 0,0,0,1,2,1,0x80];
|
||||||
|
assert_eq!(hevc_au_offsets(&with_aud), vec![0, 21, 35]);
|
||||||
|
// A picture split over several slices stays one access unit.
|
||||||
|
let multi_slice = [0,0,0,1,38,1,0x80, 0,0,0,1,38,1,0x00, 0,0,0,1,2,1,0x80];
|
||||||
|
assert_eq!(hevc_au_offsets(&multi_slice), vec![0, 14]);
|
||||||
|
// Truncated/invalid NALs must not invent boundaries. An invalid header is skipped, and
|
||||||
|
// the first valid NAL after it still opens the first unit.
|
||||||
|
assert_eq!(hevc_au_offsets(&[0,0,1,70]), Vec::<usize>::new());
|
||||||
|
assert_eq!(hevc_au_offsets(&[0,0,1,128,1,0x80]), Vec::<usize>::new());
|
||||||
|
assert_eq!(hevc_au_offsets(&[0,0,1,128,1,0x80, 0,0,1,2,1,0x80]), vec![6]);
|
||||||
|
// A suffix SEI (40) after a picture stays in that picture's unit; the next slice opens the next one.
|
||||||
|
assert_eq!(hevc_au_offsets(&[0,0,1,0x26,1,0x80, 0,0,1,0x50,1,0x05, 0,0,1,0x02,1,0x80]), vec![0, 12]);
|
||||||
|
}
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn hevc_dependency_gate_recovers_only_at_irap_after_overflow() {
|
async fn hevc_dependency_gate_recovers_only_at_irap_after_overflow() {
|
||||||
let (tx, mut rx) = mpsc::channel(1);
|
let (tx, mut rx) = mpsc::channel(1);
|
||||||
@@ -1250,6 +1356,8 @@ mod tests {
|
|||||||
for pair in [["-c:v", "hevc_vaapi"], ["-profile:v", "main"], ["-bf", "0"], ["-bufsize", "500k"]] {
|
for pair in [["-c:v", "hevc_vaapi"], ["-profile:v", "main"], ["-bf", "0"], ["-bufsize", "500k"]] {
|
||||||
assert!(vaapi.windows(2).any(|window| window == pair));
|
assert!(vaapi.windows(2).any(|window| window == pair));
|
||||||
}
|
}
|
||||||
|
// hevc_vaapi with -aud drops every non-IRAP picture, so H.265 must not ask for AUDs.
|
||||||
|
assert!(!vaapi.iter().any(|option| option == "-aud"));
|
||||||
assert_eq!(Encoder::Nvenc.name_for(VideoCodec::H265), "hevc_nvenc");
|
assert_eq!(Encoder::Nvenc.name_for(VideoCodec::H265), "hevc_nvenc");
|
||||||
assert_eq!(Encoder::Cpu.name_for(VideoCodec::H264), "libx264");
|
assert_eq!(Encoder::Cpu.name_for(VideoCodec::H264), "libx264");
|
||||||
}
|
}
|
||||||
@@ -1261,3 +1369,4 @@ mod tests {
|
|||||||
assert!(!is_independent_frame(&[0,0,0,1,9,48,0,0,1,1,154]));
|
assert!(!is_independent_frame(&[0,0,0,1,9,48,0,0,1,1,154]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
+31
-4
@@ -42,6 +42,18 @@ impl std::fmt::Display for Error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Mirrors Windows 0x140b77cd0 / 0x140b7a6d0, not host RoomData.
|
// Mirrors Windows 0x140b77cd0 / 0x140b7a6d0, not host RoomData.
|
||||||
|
/// Treat the caller's device string as one opaque path segment, never a URL/query.
|
||||||
|
fn path_segment(device: &str) -> Result<String, Error> {
|
||||||
|
if device.is_empty() || device=="." || device==".." { return Err(Error::InvalidDevice); }
|
||||||
|
Ok(device.bytes().map(|b|if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {(b as char).to_string()}else{format!("%{b:02X}")}).collect())
|
||||||
|
}
|
||||||
|
fn parse_ack(status: u16, body: Value) -> Result<(), Error> {
|
||||||
|
let code = body.get("code").and_then(Value::as_i64).unwrap_or(-1);
|
||||||
|
if code == 1120 { return Err(Error::AuthenticationExpired); }
|
||||||
|
if status == 200 && code == 0 { return Ok(()); }
|
||||||
|
let msg = body.get("msg").and_then(Value::as_str).unwrap_or("").chars().take(120).collect();
|
||||||
|
Err(Error::Api(i32::try_from(code).unwrap_or(-1), msg))
|
||||||
|
}
|
||||||
pub fn parse_join(status: u16, value: Value) -> Result<JoinData, Error> {
|
pub fn parse_join(status: u16, value: Value) -> Result<JoinData, Error> {
|
||||||
let code = value.get("code").and_then(Value::as_i64).and_then(|v| i32::try_from(v).ok()).ok_or(Error::InvalidResponse)?;
|
let code = value.get("code").and_then(Value::as_i64).and_then(|v| i32::try_from(v).ok()).ok_or(Error::InvalidResponse)?;
|
||||||
let msg = value.get("msg").and_then(Value::as_str).ok_or(Error::InvalidResponse)?.chars().take(120).collect::<String>();
|
let msg = value.get("msg").and_then(Value::as_str).ok_or(Error::InvalidResponse)?.chars().take(120).collect::<String>();
|
||||||
@@ -110,10 +122,7 @@ impl Api {
|
|||||||
Ok((status, response.json().await.map_err(|_| Error::InvalidResponse)?))
|
Ok((status, response.json().await.map_err(|_| Error::InvalidResponse)?))
|
||||||
}
|
}
|
||||||
pub async fn join(&self, device: &str, force_join: bool, retry: bool) -> Result<JoinData, Error> {
|
pub async fn join(&self, device: &str, force_join: bool, retry: bool) -> Result<JoinData, Error> {
|
||||||
// Treat the caller's device string as one opaque path segment, never a URL/query.
|
let path = format!("/api/v1/room/join/by_device/{}", path_segment(device)?);
|
||||||
if device.is_empty() || device=="." || device==".." { return Err(Error::InvalidDevice); }
|
|
||||||
let encoded=device.bytes().map(|b|if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {(b as char).to_string()}else{format!("%{b:02X}")}).collect::<String>();
|
|
||||||
let path = format!("/api/v1/room/join/by_device/{encoded}");
|
|
||||||
let mut retries = 0;
|
let mut retries = 0;
|
||||||
loop {
|
loop {
|
||||||
let result = match self.request(reqwest::Method::POST, &path, Some(json!({"force_join":force_join}))).await {
|
let result = match self.request(reqwest::Method::POST, &path, Some(json!({"force_join":force_join}))).await {
|
||||||
@@ -143,6 +152,15 @@ impl Api {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
/// Remove a device from the account (official 「删除设备」). Paths from the Windows host strings
|
||||||
|
/// `/api/v1/device/%s/unbind` and `/api/v1/device/share/%s/unbind` (own vs. shared-with-me device).
|
||||||
|
/// POST verified live against an own device; the shared-device path is from strings only.
|
||||||
|
pub async fn unbind(&self, device: &str, shared: bool) -> Result<(), Error> {
|
||||||
|
let segment = path_segment(device)?;
|
||||||
|
let path = if shared { format!("/api/v1/device/share/{segment}/unbind") } else { format!("/api/v1/device/{segment}/unbind") };
|
||||||
|
let (status, body) = self.request(reqwest::Method::POST, &path, None).await?;
|
||||||
|
parse_ack(status, body)
|
||||||
|
}
|
||||||
/// Structure-only probe of the device list (status, JSON keys/types/lengths, never values).
|
/// Structure-only probe of the device list (status, JSON keys/types/lengths, never values).
|
||||||
pub async fn devices_shape(&self, method: reqwest::Method) -> Result<String, Error> {
|
pub async fn devices_shape(&self, method: reqwest::Method) -> Result<String, Error> {
|
||||||
let path = "/api/v1/device/list";
|
let path = "/api/v1/device/list";
|
||||||
@@ -188,6 +206,15 @@ impl Api {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
#[test] fn unbind_ack_and_device_segment(){
|
||||||
|
use super::*;
|
||||||
|
assert_eq!(parse_ack(200,json!({"code":0,"msg":"ok"})),Ok(()));
|
||||||
|
assert_eq!(parse_ack(422,json!({"code":1120})),Err(Error::AuthenticationExpired));
|
||||||
|
assert_eq!(parse_ack(200,json!({"code":5003,"msg":"no such device"})),Err(Error::Api(5003,"no such device".into())));
|
||||||
|
assert_eq!(parse_ack(404,json!({})),Err(Error::Api(-1,String::new())));
|
||||||
|
assert_eq!(path_segment("a/b?c").unwrap(),"a%2Fb%3Fc");
|
||||||
|
for bad in ["",".",".."]{assert_eq!(path_segment(bad),Err(Error::InvalidDevice));}
|
||||||
|
}
|
||||||
use super::*;
|
use super::*;
|
||||||
#[test]
|
#[test]
|
||||||
fn target_platform_matches_only_the_selected_device(){
|
fn target_platform_matches_only_the_selected_device(){
|
||||||
|
|||||||
+23
-8
@@ -95,7 +95,8 @@ impl CommandBackend {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct SyncState {last:Option<String>,assembly:text::Assembly,rich:rich::State,seq:u64}
|
// target_mac: Some(true) official Mac host, Some(false) Windows-type host (official or this project), None unknown.
|
||||||
|
struct SyncState {last:Option<String>,assembly:text::Assembly,rich:rich::State,seq:u64,target_mac:Option<bool>}
|
||||||
impl SyncState {
|
impl SyncState {
|
||||||
async fn apply(&mut self,backend:&Backend,value:String)->Result<(),()>{
|
async fn apply(&mut self,backend:&Backend,value:String)->Result<(),()>{
|
||||||
if backend.write(&value).await? {
|
if backend.write(&value).await? {
|
||||||
@@ -111,10 +112,13 @@ impl SyncState {
|
|||||||
/// ignores the other form.
|
/// ignores the other form.
|
||||||
fn local(&mut self,value:String)->Result<Option<Vec<Vec<u8>>>,&'static str>{
|
fn local(&mut self,value:String)->Result<Option<Vec<Vec<u8>>>,&'static str>{
|
||||||
if self.last.as_ref()==Some(&value){return Ok(None)}
|
if self.last.as_ref()==Some(&value){return Ok(None)}
|
||||||
let id=self.next();let payload=self.rich.offer(id,value.clone())?;
|
let id=self.next();let payload=self.rich.offer_any_host(id,value.clone())?;
|
||||||
let rich=wire::envelope(self.next(),21,&payload);
|
let rich=wire::envelope(self.next(),21,&payload);
|
||||||
let text=wire::envelope(self.next(),21,&crate::clipboard_protocol::text_request(self.next(),&value));
|
let text=wire::envelope(self.next(),21,&crate::clipboard_protocol::text_request(self.next(),&value));
|
||||||
self.last=Some(value);Ok(Some(vec![rich,text]))
|
self.last=Some(value);
|
||||||
|
// Live-verified: the official Windows host writes case-10 text, then a rich format list replaces it with a
|
||||||
|
// placeholder it never asks us to render (paste is empty). The Mac host only takes the rich offer.
|
||||||
|
Ok(Some(match self.target_mac {Some(true)=>vec![rich],Some(false)=>vec![text],None=>vec![rich,text]}))
|
||||||
}
|
}
|
||||||
fn receive(&mut self,data:&[u8])->Result<(Vec<Vec<u8>>,Option<String>),&'static str>{
|
fn receive(&mut self,data:&[u8])->Result<(Vec<Vec<u8>>,Option<String>),&'static str>{
|
||||||
if data.len()>MAX_TEXT*2+1024{return Err("clipboard message exceeds limit")}
|
if data.len()>MAX_TEXT*2+1024{return Err("clipboard message exceeds limit")}
|
||||||
@@ -151,23 +155,24 @@ impl SyncState {
|
|||||||
async fn send(channel:&RTCDataChannel,message:Vec<u8>)->Result<(),()>{
|
async fn send(channel:&RTCDataChannel,message:Vec<u8>)->Result<(),()>{
|
||||||
tokio::time::timeout(Duration::from_secs(2),channel.send(&bytes::Bytes::from(message))).await.map_err(|_|())?.map_err(|_|())?;Ok(())
|
tokio::time::timeout(Duration::from_secs(2),channel.send(&bytes::Bytes::from(message))).await.map_err(|_|())?.map_err(|_|())?;Ok(())
|
||||||
}
|
}
|
||||||
pub struct Bridge {backend:Option<Backend>,pub enabled:bool,tx:Option<mpsc::Sender<Vec<u8>>>,task:Option<tokio::task::JoinHandle<()>>}
|
pub struct Bridge {backend:Option<Backend>,pub enabled:bool,tx:Option<mpsc::Sender<Vec<u8>>>,task:Option<tokio::task::JoinHandle<()>>,target_mac:Option<bool>}
|
||||||
impl Bridge {
|
impl Bridge {
|
||||||
pub fn new(desktop:bool)->Self{
|
pub fn new(desktop:bool)->Self{
|
||||||
let backend=if desktop{Backend::detect()}else{None};let enabled=backend.is_some();
|
let backend=if desktop{Backend::detect()}else{None};let enabled=backend.is_some();
|
||||||
Self{backend,enabled,tx:None,task:None}
|
Self{backend,enabled,tx:None,task:None,target_mac:None}
|
||||||
}
|
}
|
||||||
#[cfg(feature="viewer-sdl")]
|
#[cfg(feature="viewer-sdl")]
|
||||||
pub fn sdl(tx:mpsc::Sender<ClipboardRequest>)->Self{
|
pub fn sdl(tx:mpsc::Sender<ClipboardRequest>)->Self{
|
||||||
let backend=(std::env::var("UU_VIEWER_CLIPBOARD").as_deref()!=Ok("0")).then_some(Backend::Sdl(tx));
|
let backend=(std::env::var("UU_VIEWER_CLIPBOARD").as_deref()!=Ok("0")).then_some(Backend::Sdl(tx));
|
||||||
Self{enabled:backend.is_some(),backend,tx:None,task:None}
|
Self{enabled:backend.is_some(),backend,tx:None,task:None,target_mac:None}
|
||||||
}
|
}
|
||||||
|
pub fn set_target_mac(&mut self,mac:Option<bool>){self.target_mac=mac;}
|
||||||
pub fn start(&mut self,channel:&Arc<RTCDataChannel>,control:&Arc<RTCDataChannel>,observed:Arc<Observed>){
|
pub fn start(&mut self,channel:&Arc<RTCDataChannel>,control:&Arc<RTCDataChannel>,observed:Arc<Observed>){
|
||||||
let Some(backend)=self.backend.take() else{return};
|
let Some(backend)=self.backend.take() else{return};let target_mac=self.target_mac;
|
||||||
let (tx,mut rx)=mpsc::channel::<Vec<u8>>(16);self.tx=Some(tx);
|
let (tx,mut rx)=mpsc::channel::<Vec<u8>>(16);self.tx=Some(tx);
|
||||||
let channel=Arc::downgrade(channel);let control=Arc::downgrade(control);
|
let channel=Arc::downgrade(channel);let control=Arc::downgrade(control);
|
||||||
self.task=Some(tokio::spawn(async move{
|
self.task=Some(tokio::spawn(async move{
|
||||||
let mut state=SyncState::default();let mut tick=tokio::time::interval(POLL);
|
let mut state=SyncState{target_mac,..SyncState::default()};let mut tick=tokio::time::interval(POLL);
|
||||||
let mut retries=0;let mut last_probe=std::time::Instant::now();
|
let mut retries=0;let mut last_probe=std::time::Instant::now();
|
||||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||||
loop {
|
loop {
|
||||||
@@ -325,6 +330,16 @@ impl Drop for Bridge{fn drop(&mut self){self.stop();}}
|
|||||||
if reverse && received.is_some(){viewer.last=Some(value.clone());assert!(viewer.local(value).unwrap().is_none());}
|
if reverse && received.is_some(){viewer.last=Some(value.clone());assert!(viewer.local(value).unwrap().is_none());}
|
||||||
(received,unavailable)
|
(received,unavailable)
|
||||||
}
|
}
|
||||||
|
#[test] fn local_change_follows_target_platform(){
|
||||||
|
for (mac,kinds) in [(Some(true),vec![9]),(Some(false),vec![10]),(None,vec![9,10])]{
|
||||||
|
let mut viewer=SyncState{target_mac:mac,..SyncState::default()};
|
||||||
|
let cases:Vec<u32>=viewer.local("text".into()).unwrap().unwrap().iter().map(|m|{
|
||||||
|
let rpc=decode_wire(m).unwrap().into_iter().find_map(|f|match (f.number,f.value){(21,WireValue::Bytes(b))=>Some(b.to_vec()),_=>None}).unwrap();
|
||||||
|
decode_wire(&rpc).unwrap().iter().map(|f|f.number).find(|n|*n!=1).unwrap()
|
||||||
|
}).collect();
|
||||||
|
assert_eq!(cases,kinds,"{mac:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
#[test] fn local_change_also_sends_windows_text_change_request(){
|
#[test] fn local_change_also_sends_windows_text_change_request(){
|
||||||
let mut viewer=SyncState::default();
|
let mut viewer=SyncState::default();
|
||||||
let messages=viewer.local("windows 中文".into()).unwrap().unwrap();assert_eq!(messages.len(),2);
|
let messages=viewer.local("windows 中文".into()).unwrap().unwrap();assert_eq!(messages.len(),2);
|
||||||
|
|||||||
@@ -21,14 +21,14 @@ impl Cli {
|
|||||||
fn with_codec(codec:Codec,width:u32,height:u32)->Result<Self,String> {
|
fn with_codec(codec:Codec,width:u32,height:u32)->Result<Self,String> {
|
||||||
let ffmpeg=std::env::var("UU_VIEWER_FFMPEG").unwrap_or_else(|_|"ffmpeg".into());
|
let ffmpeg=std::env::var("UU_VIEWER_FFMPEG").unwrap_or_else(|_|"ffmpeg".into());
|
||||||
let filter=format!("scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2");
|
let filter=format!("scale={width}:{height}:force_original_aspect_ratio=decrease,pad={width}:{height}:(ow-iw)/2:(oh-ih)/2");
|
||||||
let mut child=Command::new(ffmpeg)
|
let passthrough=passthrough_args(&ffmpeg);
|
||||||
|
let mut child=Command::new(&ffmpeg)
|
||||||
.args(["-hide_banner","-loglevel","error","-nostdin","-threads","1","-probesize","32","-analyzeduration","0",
|
.args(["-hide_banner","-loglevel","error","-nostdin","-threads","1","-probesize","32","-analyzeduration","0",
|
||||||
"-fflags","nobuffer","-flags","low_delay","-f",codec.demuxer(),"-i","pipe:0","-an","-vf",&filter,
|
"-fflags","nobuffer","-flags","low_delay","-f",codec.demuxer(),"-i","pipe:0","-an","-vf",&filter,
|
||||||
"-pix_fmt","rgb24",
|
"-pix_fmt","rgb24",
|
||||||
// Raw H.264/H.265 carries no timestamps; constant-rate output dropped almost every frame of
|
// Raw H.264/H.265 carries no timestamps; constant-rate output dropped almost every frame of
|
||||||
// the official Mac host's stream (270 → 2). Pass frames through unchanged.
|
// the official Mac host's stream (270 → 2). Pass frames through unchanged.
|
||||||
// -vsync 0 also supports Ubuntu 22.04's FFmpeg 4.4, which lacks -fps_mode.
|
passthrough.0,passthrough.1,"-f","rawvideo","pipe:1"])
|
||||||
"-vsync","0","-f","rawvideo","pipe:1"])
|
|
||||||
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
|
.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null())
|
||||||
.spawn().map_err(|e|format!("Start ffmpeg decoder: {e}"))?;
|
.spawn().map_err(|e|format!("Start ffmpeg decoder: {e}"))?;
|
||||||
let input=child.stdin.take().ok_or("ffmpeg stdin missing")?;
|
let input=child.stdin.take().ok_or("ffmpeg stdin missing")?;
|
||||||
@@ -47,6 +47,23 @@ impl Cli {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// FFmpeg ≥ 5.1 has `-fps_mode`; FFmpeg 8+ removed `-vsync`, and Ubuntu 22.04's 4.4 lacks `-fps_mode`.
|
||||||
|
/// Probe once per binary with a one-frame null run instead of parsing version strings.
|
||||||
|
fn passthrough_args(ffmpeg:&str)->(&'static str,&'static str) {
|
||||||
|
static CACHE:std::sync::Mutex<Vec<(String,bool)>>=std::sync::Mutex::new(Vec::new());
|
||||||
|
let mut cache=CACHE.lock().unwrap_or_else(|e|e.into_inner());
|
||||||
|
let fps_mode=match cache.iter().find(|(name,_)|name==ffmpeg) {
|
||||||
|
Some(&(_,known))=>known,
|
||||||
|
None=>{
|
||||||
|
let ok=Command::new(ffmpeg).args(["-hide_banner","-loglevel","quiet","-nostdin","-f","lavfi","-i","color=s=16x16:d=0.04",
|
||||||
|
"-fps_mode","passthrough","-f","null","-"]).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())
|
||||||
|
.status().is_ok_and(|s|s.success());
|
||||||
|
cache.push((ffmpeg.into(),ok));ok
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if fps_mode {("-fps_mode","passthrough")} else {("-vsync","0")}
|
||||||
|
}
|
||||||
|
|
||||||
impl Decoder for Cli {
|
impl Decoder for Cli {
|
||||||
fn set_codec(&mut self,codec:Codec)->Result<(),String>{
|
fn set_codec(&mut self,codec:Codec)->Result<(),String>{
|
||||||
if self.codec!=codec {*self=Self::with_codec(codec,self.width,self.height)?;}Ok(())
|
if self.codec!=codec {*self=Self::with_codec(codec,self.width,self.height)?;}Ok(())
|
||||||
@@ -72,6 +89,16 @@ impl Drop for Cli { fn drop(&mut self) { let _=self.child.kill(); let _=self.chi
|
|||||||
#[cfg(test)] mod tests {
|
#[cfg(test)] mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
// Six synthetic red IDRs per fixture; no captured desktop or external encoder dependency.
|
// Six synthetic red IDRs per fixture; no captured desktop or external encoder dependency.
|
||||||
|
#[cfg(unix)] #[test] fn passthrough_follows_ffmpeg_option_support(){
|
||||||
|
use std::os::unix::fs::PermissionsExt;
|
||||||
|
let dir=std::env::temp_dir().join(format!("uu-ffprobe-{}",std::process::id()));std::fs::create_dir_all(&dir).unwrap();
|
||||||
|
for (name,script,expected) in [("new","exit 0",("-fps_mode","passthrough")),("old","case \"$*\" in *-fps_mode*) exit 1;; esac",("-vsync","0"))]{
|
||||||
|
let path=dir.join(name);std::fs::write(&path,format!("#!/bin/sh\n{script}\n")).unwrap();
|
||||||
|
std::fs::set_permissions(&path,std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||||
|
assert_eq!(super::passthrough_args(path.to_str().unwrap()),expected);
|
||||||
|
}
|
||||||
|
std::fs::remove_dir_all(dir).unwrap();
|
||||||
|
}
|
||||||
#[test] fn ffmpeg_decodes_h264_and_hevc_420_and_444_to_rgb24(){
|
#[test] fn ffmpeg_decodes_h264_and_hevc_420_and_444_to_rgb24(){
|
||||||
match Command::new("ffmpeg").arg("-version").stdout(Stdio::null()).stderr(Stdio::null()).status(){
|
match Command::new("ffmpeg").arg("-version").stdout(Stdio::null()).stderr(Stdio::null()).status(){
|
||||||
Err(e) if e.kind()==std::io::ErrorKind::NotFound=>{eprintln!("skip: ffmpeg is not on PATH");return},
|
Err(e) if e.kind()==std::io::ErrorKind::NotFound=>{eprintln!("skip: ffmpeg is not on PATH");return},
|
||||||
|
|||||||
+2
-1
@@ -195,7 +195,8 @@ impl Peer {
|
|||||||
if state.chroma.swap(chroma,Ordering::AcqRel)!=chroma {log::info!("Viewer capture sync: chroma={chroma}");}
|
if state.chroma.swap(chroma,Ordering::AcqRel)!=chroma {log::info!("Viewer capture sync: chroma={chroma}");}
|
||||||
}
|
}
|
||||||
let count=state.control_messages.fetch_add(1,Ordering::Relaxed);
|
let count=state.control_messages.fetch_add(1,Ordering::Relaxed);
|
||||||
if wire::echo_matches(&message.data,1) {state.clipboard_supported.store(wire::echo_clipboard_supported(&message.data),Ordering::Release);state.echo_received.store(true,Ordering::Release);}
|
if wire::echo_matches(&message.data,1) {let supported=wire::echo_clipboard_supported(&message.data);
|
||||||
|
if state.clipboard_supported.swap(supported,Ordering::AcqRel)!=supported || !state.echo_received.load(Ordering::Acquire) {log::info!("Viewer echo: clipboard_supported={supported}");}state.echo_received.store(true,Ordering::Release);}
|
||||||
if let Some(request)=wire::echo_request_seq(&message.data) {
|
if let Some(request)=wire::echo_request_seq(&message.data) {
|
||||||
if let Some(control)=control_for_echo.upgrade() {let _=control.send(&bytes::Bytes::from(wire::echo_response_with_clipboard(1_000_000+request,request,clipboard_enabled))).await;}
|
if let Some(control)=control_for_echo.upgrade() {let _=control.send(&bytes::Bytes::from(wire::echo_response_with_clipboard(1_000_000+request,request,clipboard_enabled))).await;}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ impl Window {
|
|||||||
use super::clipboard::ClipboardRequest;
|
use super::clipboard::ClipboardRequest;
|
||||||
match request {
|
match request {
|
||||||
ClipboardRequest::Read(reply)=>{
|
ClipboardRequest::Read(reply)=>{
|
||||||
|
if self.clipboard_dirty {log::debug!("Viewer clipboard read: focused={} has_text={}",self.focused,self.clipboard.has_clipboard_text());}
|
||||||
let result=if self.focused && std::mem::take(&mut self.clipboard_dirty) && self.clipboard.has_clipboard_text(){read_clipboard()}else{Ok(None)};
|
let result=if self.focused && std::mem::take(&mut self.clipboard_dirty) && self.clipboard.has_clipboard_text(){read_clipboard()}else{Ok(None)};
|
||||||
let _=reply.send(result);
|
let _=reply.send(result);
|
||||||
},
|
},
|
||||||
@@ -162,6 +163,8 @@ pub async fn run(session:&mut Session,window:&mut Window,decoder:&mut dyn super:
|
|||||||
|
|
||||||
#[cfg(test)] mod tests {
|
#[cfg(test)] mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
// macOS: SDL video must start on the main thread, which the test harness does not use; CI runs it on Linux.
|
||||||
|
#[cfg_attr(target_os="macos",ignore)]
|
||||||
#[tokio::test] async fn clipboard_requests_use_existing_window(){
|
#[tokio::test] async fn clipboard_requests_use_existing_window(){
|
||||||
if std::env::var_os("UU_VIEWER_CLIPBOARD_TEST_CHILD").is_none(){
|
if std::env::var_os("UU_VIEWER_CLIPBOARD_TEST_CHILD").is_none(){
|
||||||
let output=std::process::Command::new(std::env::current_exe().unwrap())
|
let output=std::process::Command::new(std::env::current_exe().unwrap())
|
||||||
|
|||||||
@@ -40,7 +40,9 @@ impl Terminal {
|
|||||||
let worker=tokio::spawn(async move {
|
let worker=tokio::spawn(async move {
|
||||||
let mut decoder=Decoder::default();
|
let mut decoder=Decoder::default();
|
||||||
while let Some((channel,data))=rx.recv().await {
|
while let Some((channel,data))=rx.recv().await {
|
||||||
if channel==CONTROL {
|
// Terminal RPC answers (check_env) come on CONTROL or, from the official Mac host, on BINARY
|
||||||
|
// next to TERM frames (as this project's host does).
|
||||||
|
if channel==CONTROL || (channel==BINARY && !data.starts_with(b"TERM")) {
|
||||||
if let Some(r)=blob(&data,22) {if let (Some(h),Some(body))=(blob(r,1),blob(r,24)) {
|
if let Some(r)=blob(&data,22) {if let (Some(h),Some(body))=(blob(r,1),blob(r,24)) {
|
||||||
if let Some(t)=p.lock().unwrap().remove(&(24,uint(h,1))) {let _=t.send(Ok(body.to_vec()));}
|
if let Some(t)=p.lock().unwrap().remove(&(24,uint(h,1))) {let _=t.send(Ok(body.to_vec()));}
|
||||||
}}continue
|
}}continue
|
||||||
@@ -85,7 +87,12 @@ impl Terminal {
|
|||||||
// "not implemented", not "unavailable"; go on and let OPEN report availability.
|
// "not implemented", not "unavailable"; go on and let OPEN report availability.
|
||||||
match tokio::time::timeout(std::time::Duration::from_secs(3),self.request((24,id),CONTROL,wire::envelope(id,21,&r))).await{
|
match tokio::time::timeout(std::time::Duration::from_secs(3),self.request((24,id),CONTROL,wire::envelope(id,21,&r))).await{
|
||||||
Err(_)=>Ok(()),
|
Err(_)=>Ok(()),
|
||||||
Ok(b)=>{let b=b?;if uint(&b,1)!=0 {return Err("Terminal environment unavailable".into())}Ok(())}
|
Ok(b)=>{let b=b?;let code=uint(&b,1);
|
||||||
|
if code!=0 {
|
||||||
|
let message=blob(&b,2).map(|m|String::from_utf8_lossy(m).chars().take(80).collect::<String>()).unwrap_or_default();
|
||||||
|
log::info!("Terminal check_env: code={code} message={message:?}");
|
||||||
|
return Err("Terminal environment unavailable".into())
|
||||||
|
}Ok(())}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
pub async fn list_sessions(&self)->Result<Vec<Value>,String>{
|
pub async fn list_sessions(&self)->Result<Vec<Value>,String>{
|
||||||
|
|||||||
@@ -195,6 +195,15 @@ pub async fn run(credentials: impl Fn() -> Result<crate::auth::Credentials, Stri
|
|||||||
Err(_) => toast("电源指令失败:无法启动会话进程"),
|
Err(_) => toast("电源指令失败:无法启动会话进程"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
["connect", id, "unbind"] => {
|
||||||
|
if let Some(s)=sessions.remove(*id){s.stop().await;}
|
||||||
|
let result=match credentials(){
|
||||||
|
Ok(creds)=>super::api::Api::new(crate::auth::UUAuthClient::new(creds),crate::auth::BASE_URL).unbind(id,false).await.map_err(|e|e.to_string()),
|
||||||
|
Err(e)=>Err(e),
|
||||||
|
};
|
||||||
|
match result {Ok(())=>toast("设备已从账号删除"),Err(e)=>toast(&format!("删除设备失败:{e}"))}
|
||||||
|
next_refresh=Instant::now();
|
||||||
|
}
|
||||||
["connect", _, kind] => log::info!("Viewer UI: {kind} is not supported yet"),
|
["connect", _, kind] => log::info!("Viewer UI: {kind} is not supported yet"),
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-7
@@ -13,7 +13,7 @@ use viewer::clipboard;
|
|||||||
#[cfg(test)] #[path="initialization.rs"] mod initialization;
|
#[cfg(test)] #[path="initialization.rs"] mod initialization;
|
||||||
use viewer::{api::Api,rtc::ReadyPolicy,session::{Options,Session},wire::Shape};
|
use viewer::{api::Api,rtc::ReadyPolicy,session::{Options,Session},wire::Shape};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
const HELP:&str="Experimental native viewer.\n uuremote-viewer ui (GTK window: sign-in, devices, sessions) Desktop UI requires viewer-sdl (decodes with the ffmpeg CLI, or FFmpeg 6.x libraries with viewer-ffmpeg).\n uuremote-viewer power DEVICE reboot|shutdown\n uuremote-viewer terminal DEVICE [SESSION]\n uuremote-viewer files DEVICE ls PATH | get REMOTE LOCAL | put LOCAL REMOTE\n uuremote-viewer portmap DEVICE LOCAL_PORT HOST PORT\n uuremote-viewer files-ui|portmap-ui|terminal-ui DEVICE NAME (GTK tool windows)\n uuremote-viewer login [--no-gui]\n uuremote-viewer devices METHOD ARRAY_POINTER ID_POINTER NAME_POINTER\n uuremote-viewer assist CONNECT_ID (验证码从 stdin 读取一行)\n uuremote-viewer connect DEVICE true|false SHAPE_JSON echo|manual raw|legacy [--view-only]\nVideo: UU_VIEWER_CODEC=h264 forces H.264; UU_VIEWER_CHROMA=444 requests true color (default 4:2:0).\nAudio: UU_VIEWER_AUDIO=0 disables playback. UU_VIEWER_VIEW_ONLY=1 disables desktop input.\nDevice-list method/JSON pointers and compatibility shape require verified operator configuration.\nQR login reuses the sibling uuremote-server login command. Never run login in a captured log.\nEcho readiness is transport observation only; no sendVideoTrack RPC is emitted.";
|
const HELP:&str="Experimental native viewer.\n uuremote-viewer ui (GTK window: sign-in, devices, sessions) Desktop UI requires viewer-sdl (decodes with the ffmpeg CLI, or FFmpeg 6.x libraries with viewer-ffmpeg).\n uuremote-viewer power DEVICE reboot|shutdown\n uuremote-viewer unbind DEVICE [--shared] (从账号删除设备 / remove a device from the account)\n uuremote-viewer terminal DEVICE [SESSION]\n uuremote-viewer files DEVICE ls PATH | get REMOTE LOCAL | put LOCAL REMOTE\n uuremote-viewer portmap DEVICE LOCAL_PORT HOST PORT\n uuremote-viewer files-ui|portmap-ui|terminal-ui DEVICE NAME (GTK tool windows)\n uuremote-viewer login [--no-gui]\n uuremote-viewer devices METHOD ARRAY_POINTER ID_POINTER NAME_POINTER\n uuremote-viewer assist CONNECT_ID (验证码从 stdin 读取一行)\n uuremote-viewer connect DEVICE true|false SHAPE_JSON echo|manual raw|legacy [--view-only]\nVideo: UU_VIEWER_CODEC=h264 forces H.264; UU_VIEWER_CHROMA=444 requests true color (default 4:2:0).\nAudio: UU_VIEWER_AUDIO=0 disables playback. UU_VIEWER_VIEW_ONLY=1 disables desktop input.\nDevice-list method/JSON pointers and compatibility shape require verified operator configuration.\nQR login reuses the sibling uuremote-server login command. Never run login in a captured log.\nEcho readiness is transport observation only; no sendVideoTrack RPC is emitted.";
|
||||||
const DEFAULT_SHAPE:&str=r#"{"capture_type":1,"platform":3,"client_version":"4.42.0","width":1920,"height":1080,"fps":60,"chroma":1,
|
const DEFAULT_SHAPE:&str=r#"{"capture_type":1,"platform":3,"client_version":"4.42.0","width":1920,"height":1080,"fps":60,"chroma":1,
|
||||||
"decoders":[{"fps":60,"codec":1,"width":3840,"height":2160,"chroma":1}],"display_modes":[[1920,1080,60]],
|
"decoders":[{"fps":60,"codec":1,"width":3840,"height":2160,"chroma":1}],"display_modes":[[1920,1080,60]],
|
||||||
"displays":[{"id":1,"fps":60,"type":0,"hdr":0}],
|
"displays":[{"id":1,"fps":60,"type":0,"hdr":0}],
|
||||||
@@ -55,6 +55,10 @@ async fn run(args:&[String])->Result<(),String> {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Some("unbind") if (args.len()==2 || (args.len()==3 && args[2]=="--shared")) && !args[1].is_empty() => {
|
||||||
|
api()?.unbind(&args[1],args.len()==3).await.map_err(|e|format!("删除设备失败:{e}"))?;
|
||||||
|
println!("已从账号删除设备");Ok(())
|
||||||
|
}
|
||||||
Some("power")=>power_command(args).await,
|
Some("power")=>power_command(args).await,
|
||||||
Some("terminal-local") if args.len()==2 || args.len()==3=>{
|
Some("terminal-local") if args.len()==2 || args.len()==3=>{
|
||||||
let session=if args.len()==3{Some(args[2].parse::<u32>().ok().filter(|n|*n!=0).ok_or("Invalid terminal session id")?)}else{None};
|
let session=if args.len()==3{Some(args[2].parse::<u32>().ok().filter(|n|*n!=0).ok_or("Invalid terminal session id")?)}else{None};
|
||||||
@@ -89,21 +93,21 @@ async fn desktop_command(args:&[String],code:Option<String>)->Result<(),String>
|
|||||||
}else{None};
|
}else{None};
|
||||||
let creds=credentials()?;
|
let creds=credentials()?;
|
||||||
let api=Api::new(auth::UUAuthClient::new(creds.clone()),auth::BASE_URL);
|
let api=Api::new(auth::UUAuthClient::new(creds.clone()),auth::BASE_URL);
|
||||||
#[cfg(feature="viewer-sdl")]
|
|
||||||
let account_connection=code.is_none();
|
let account_connection=code.is_none();
|
||||||
let room=match code {
|
let room=match code {
|
||||||
Some(code)=>api.join_share(&args[1],&code).await,
|
Some(code)=>api.join_share(&args[1],&code).await,
|
||||||
None=>api.join(&args[1],force,true).await,
|
None=>api.join(&args[1],force,true).await,
|
||||||
}.map_err(|e|e.to_string())?;
|
}.map_err(|e|e.to_string())?;
|
||||||
|
let target_mac=if shape.capture_type==1 {api.target_is_mac(&room,account_connection.then_some(args[1].as_str())).await} else {Err(viewer::api::Error::UnknownKeyboardPlatform)};
|
||||||
#[cfg(feature="viewer-sdl")]
|
#[cfg(feature="viewer-sdl")]
|
||||||
if let Some((window,_))=desktop.as_mut().filter(|_|!view_only){
|
if let Some((window,_))=desktop.as_mut().filter(|_|!view_only){
|
||||||
let device=account_connection.then_some(args[1].as_str());
|
window.set_mac(*target_mac.as_ref().map_err(|e|e.to_string())?);
|
||||||
window.set_mac(api.target_is_mac(&room,device).await.map_err(|e|e.to_string())?);
|
|
||||||
}
|
}
|
||||||
#[cfg(feature="viewer-sdl")]
|
#[cfg(feature="viewer-sdl")]
|
||||||
let clipboard=desktop.as_ref().map(|(window,_)|window.clipboard_bridge()).unwrap_or_else(||clipboard::Bridge::new(false));
|
let mut clipboard=desktop.as_ref().map(|(window,_)|window.clipboard_bridge()).unwrap_or_else(||clipboard::Bridge::new(false));
|
||||||
#[cfg(not(feature="viewer-sdl"))]
|
#[cfg(not(feature="viewer-sdl"))]
|
||||||
let clipboard=clipboard::Bridge::new(shape.capture_type==1);
|
let mut clipboard=clipboard::Bridge::new(shape.capture_type==1);
|
||||||
|
clipboard.set_target_mac(target_mac.ok());
|
||||||
let options=Options{timeout:Duration::from_secs(12),legacy_prefix:legacy,ready_policy:policy,clipboard};
|
let options=Options{timeout:Duration::from_secs(12),legacy_prefix:legacy,ready_policy:policy,clipboard};
|
||||||
let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?;
|
let mut session=Session::open(&room,&shape,&creds.device_id,&creds.client_id,options,Default::default()).await?;
|
||||||
#[cfg(feature="viewer-sdl")]
|
#[cfg(feature="viewer-sdl")]
|
||||||
@@ -124,7 +128,7 @@ mod cli_tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn invalid_commands_never_fall_through_to_login_or_host_service() {
|
async fn invalid_commands_never_fall_through_to_login_or_host_service() {
|
||||||
for args in [vec!["invalid"],vec!["power"],vec!["power","device","logout"],vec!["power","device","reboot","extra"],vec!["login","--invalid"],vec!["connect"],vec!["assist"],vec!["assist","id","forbidden-code-argument"],vec!["terminal"],vec!["terminal","device","extra"],vec!["terminal","device","0"],vec!["terminal","device","4294967296"],vec!["terminal-ui","device"],vec!["files","device","bad","path"],vec!["portmap","device","bad","host","80"],vec!["portmap","device","8000","host","0"],vec!["devices","DELETE","/data","/id","/name"]] {
|
for args in [vec!["invalid"],vec!["power"],vec!["power","device","logout"],vec!["power","device","reboot","extra"],vec!["login","--invalid"],vec!["connect"],vec!["assist"],vec!["assist","id","forbidden-code-argument"],vec!["terminal"],vec!["terminal","device","extra"],vec!["terminal","device","0"],vec!["terminal","device","4294967296"],vec!["terminal-ui","device"],vec!["files","device","bad","path"],vec!["portmap","device","bad","host","80"],vec!["portmap","device","8000","host","0"],vec!["devices","DELETE","/data","/id","/name"],vec!["unbind"],vec!["unbind",""],vec!["unbind","device","--other"],vec!["unbind","device","--shared","extra"]] {
|
||||||
assert!(run(&args.into_iter().map(str::to_owned).collect::<Vec<_>>()).await.is_err());
|
assert!(run(&args.into_iter().map(str::to_owned).collect::<Vec<_>>()).await.is_err());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-1
@@ -1041,6 +1041,21 @@ impl WebRtcSession {
|
|||||||
if let Ok(txt) = std::str::from_utf8(&msg.data) {
|
if let Ok(txt) = std::str::from_utf8(&msg.data) {
|
||||||
log::debug!("DataChannel [{}] received UTF-8 data: {} bytes", channel_name, txt.len());
|
log::debug!("DataChannel [{}] received UTF-8 data: {} bytes", channel_name, txt.len());
|
||||||
if let Ok(val) = serde_json::from_str::<serde_json::Value>(txt) {
|
if let Ok(val) = serde_json::from_str::<serde_json::Value>(txt) {
|
||||||
|
if !channel_name.contains("CONTROL") {
|
||||||
|
// Input JSON on another channel (mobile input-method text was missing from CONTROL, #13/#46):
|
||||||
|
// record action names only, once per name, and accept text_input wherever it arrives.
|
||||||
|
if let Some(action) = val.get("action").and_then(serde_json::Value::as_str) {
|
||||||
|
static SEEN: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
|
||||||
|
let mut seen = SEEN.lock().unwrap();
|
||||||
|
if seen.len() < 32 && action.len() <= 40 && action.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') && !seen.iter().any(|s| s == action) {
|
||||||
|
seen.push(action.to_owned());
|
||||||
|
log::info!("JSON action on {} channel: action={}", if channel_name.contains("STREAMER") {"STREAMER"} else if channel_name.contains("TEXT") {"TEXT"} else {"other"}, action);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(crate::control_protocol::ControlMessage::Input(crate::control_protocol::ControlInput::TextInput {text})) = crate::control_protocol::decode_control(&msg.data) {
|
||||||
|
if let Some(session)=message_input_session.as_ref() { session.with_input(|| input_worker.text_input(&text)); }
|
||||||
|
}
|
||||||
|
}
|
||||||
if channel_name.contains("CONTROL") {
|
if channel_name.contains("CONTROL") {
|
||||||
match crate::control_protocol::decode_control(&msg.data) {
|
match crate::control_protocol::decode_control(&msg.data) {
|
||||||
Ok(crate::control_protocol::ControlMessage::Input(event)) => {
|
Ok(crate::control_protocol::ControlMessage::Input(event)) => {
|
||||||
@@ -1051,7 +1066,7 @@ impl WebRtcSession {
|
|||||||
static RECEIPTS: [std::sync::atomic::AtomicUsize; 3] = [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
|
static RECEIPTS: [std::sync::atomic::AtomicUsize; 3] = [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
|
||||||
let (slot, kind) = match &event {
|
let (slot, kind) = match &event {
|
||||||
ControlInput::MouseButton {..} | ControlInput::MouseClick {..} => (0, "button"),
|
ControlInput::MouseButton {..} | ControlInput::MouseClick {..} => (0, "button"),
|
||||||
ControlInput::Keyboard {..} | ControlInput::KeyboardClick {..} => (1, "keyboard"),
|
ControlInput::Keyboard {..} | ControlInput::KeyboardClick {..} | ControlInput::TextInput {..} => (1, "keyboard"),
|
||||||
_ => (2, "motion"),
|
_ => (2, "motion"),
|
||||||
};
|
};
|
||||||
if RECEIPTS[slot].fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 {
|
if RECEIPTS[slot].fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 {
|
||||||
@@ -1063,6 +1078,7 @@ impl WebRtcSession {
|
|||||||
ControlInput::MouseRelative {dx,dy} => input_worker.mouse_relative(*dx,*dy),
|
ControlInput::MouseRelative {dx,dy} => input_worker.mouse_relative(*dx,*dy),
|
||||||
ControlInput::MouseScroll {dx,dy} => input_worker.mouse_scroll(*dx,*dy),
|
ControlInput::MouseScroll {dx,dy} => input_worker.mouse_scroll(*dx,*dy),
|
||||||
ControlInput::Keyboard {key, pressed} => input_worker.windows_key_event(*key, *pressed),
|
ControlInput::Keyboard {key, pressed} => input_worker.windows_key_event(*key, *pressed),
|
||||||
|
ControlInput::TextInput {text} => input_worker.text_input(text),
|
||||||
ControlInput::KeyboardClick {key} => {input_worker.windows_key_event(*key, true);input_worker.windows_key_event(*key, false);},
|
ControlInput::KeyboardClick {key} => {input_worker.windows_key_event(*key, true);input_worker.windows_key_event(*key, false);},
|
||||||
ControlInput::MouseButton {button,pressed} => input_worker.wire_mouse_button(*button,*pressed),
|
ControlInput::MouseButton {button,pressed} => input_worker.wire_mouse_button(*button,*pressed),
|
||||||
ControlInput::MouseClick {button} => {input_worker.wire_mouse_button(*button,true);input_worker.wire_mouse_button(*button,false);},
|
ControlInput::MouseClick {button} => {input_worker.wire_mouse_button(*button,true);input_worker.wire_mouse_button(*button,false);},
|
||||||
@@ -1071,6 +1087,16 @@ impl WebRtcSession {
|
|||||||
});}
|
});}
|
||||||
|
|
||||||
},
|
},
|
||||||
|
Ok(crate::control_protocol::ControlMessage::Unsupported(v)) => {
|
||||||
|
// Action name and key names only, never values (an IME text event would carry typed text).
|
||||||
|
static UNSUPPORTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||||
|
if UNSUPPORTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 16 {
|
||||||
|
let action = v.get("action").and_then(serde_json::Value::as_str)
|
||||||
|
.filter(|a| a.len() <= 40 && a.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')).unwrap_or("?");
|
||||||
|
let keys: Vec<&str> = v.as_object().map(|o| o.keys().map(String::as_str).take(12).collect()).unwrap_or_default();
|
||||||
|
log::info!("Unsupported CONTROL input: action={action} keys={keys:?}");
|
||||||
|
}
|
||||||
|
},
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
} else if channel_name.contains("STREAMER") {
|
} else if channel_name.contains("STREAMER") {
|
||||||
|
|||||||
Reference in new issue
Block a user