mirror of
https://github.com/VallierDev/uu-remote-linux.git
synced 2026-11-16 08:50:40 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab137a1b20 | ||
|
|
092ea713f8 | ||
|
|
53d5f0e144 | ||
|
|
6b5216df35 | ||
|
|
d66937a01c | ||
|
|
825f964f7d | ||
|
|
3f2da6f587 | ||
|
|
027abba44d | ||
|
|
ef86019b39 | ||
|
|
003da254a6 |
No files matched your search
@@ -133,7 +133,7 @@ viewer does not reconnect them automatically.
|
||||
| `UU_LOGIN_WINDOW=0` | don't auto-open the login window |
|
||||
| `UU_ENGINE_DIR` | directory holding `libuu-wayland.so` / `libuu-portal.so` (`--features engine-plugins`, used by release packages: engines are dlopen'ed only on Wayland sessions; also searched next to the binary, `../lib/uu-remote-linux`, `~/.local/lib/uu-remote-linux`, `/usr/lib/uu-remote-linux`) |
|
||||
| `UU_WOL_HELPER=1` | experimental: report LAN info (`api-ipv4…/api/v1/device/wake_on_lan/info` {mac, ip, subnet_mask}) after sign-in and answer `wake_on_lan` pushes (`target_device` {mac, ip, subnet_mask}) with a magic packet, like the official Windows host (field names from its log strings; not verified end to end). `wake_on_lan` push key names are always logged |
|
||||
| `UU_USE_PROXY=1` | honor HTTP/SOCKS proxy env vars; cloud API clients bypass env proxies by default |
|
||||
| `UU_USE_PROXY=1` | honor HTTP/HTTPS proxy env vars for REST and WebSocket signaling (not ICE/media); clients bypass env proxies by default |
|
||||
| `UU_REMOTE_ASSIST=0`, `UU_ASSIST_ALLOW=1`, `UU_ASSIST_UI=tty`, `UU_ASSIST_DEBUG=1` | disable assistance / allow at start / terminal UI for `assist` / include the server's short error message in assist errors |
|
||||
|
||||
Token has no expiry field; API code 1120 (HTTP 422) means invalid/expired → re-login. `config.json` is parsed once
|
||||
|
||||
Generated
+3
-1
@@ -2741,7 +2741,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "uu-remote-linux"
|
||||
version = "0.2.34"
|
||||
version = "0.2.36"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.22.1",
|
||||
@@ -2758,12 +2758,14 @@ dependencies = [
|
||||
"nix 0.29.0",
|
||||
"qrcode",
|
||||
"rand 0.8.8",
|
||||
"rcgen",
|
||||
"reqwest",
|
||||
"sdl2",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tokio-tungstenite",
|
||||
"webrtc",
|
||||
"x11rb",
|
||||
|
||||
+6
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "uu-remote-linux"
|
||||
version = "0.2.34"
|
||||
version = "0.2.36"
|
||||
edition = "2021"
|
||||
default-run = "uuremote-server"
|
||||
authors = ["uu-remote-linux contributors"]
|
||||
@@ -60,6 +60,11 @@ x11rb = { version = "0.13", features = ["damage", "shm", "allow-unsafe-code"], o
|
||||
|
||||
sdl2 = { version = "0.37", optional = true, features = ["use-pkgconfig"] }
|
||||
|
||||
[dev-dependencies]
|
||||
# Synthetic loopback WSS certificates only; both crates already occur in Cargo.lock.
|
||||
rcgen = "0.11.3"
|
||||
tokio-rustls = { version = "0.26.6", default-features = false, features = ["ring", "tls12"] }
|
||||
|
||||
[build-dependencies]
|
||||
cc = "1.0"
|
||||
|
||||
|
||||
+13
-2
@@ -45,7 +45,7 @@
|
||||
| Mouse / keyboard | Absolute and relative motion, clicks, wheel, keys; no spurious key repeat on high-latency links; optional uinput virtual devices on Wayland (layout independent, see below) |
|
||||
| Mac shortcuts | **Recommended**: turn off 「使用 macOS 快捷键」 (use macOS shortcuts) in the Mac viewer's remote-window menu; then Cmd+C/V/A/F/X/Z work as on a Mac (Cmd+C/V become Ctrl+Shift+C/V in terminals) and Ctrl+C always interrupts. With the option on, the viewer sends Cmd as Ctrl: in a terminal Ctrl+V / Cmd+V paste, Ctrl+C interrupts, copy is Cmd+Shift+C (X11) |
|
||||
| Pointer shape | Remote cursor shape is mirrored to the viewer (X11) |
|
||||
| Clipboard | Two-way text sync |
|
||||
| Clipboard | Two-way text sync; Wayland mobile IME text inputs use clipboard paste fallback (see below) |
|
||||
| Quality / frame rate / resolution | Auto, Original 20M, Ultra 8M, HD 2M, custom; 30/60/90/144 fps; on X11 a resolution choice changes the desktop resolution itself like the official Windows host (xrandr, adding the mode when missing; restored for "original" or on disconnect), `UU_DESKTOP_RESIZE=0` scales in the encoder instead; Wayland scales in the encoder |
|
||||
| Sound | System audio captured from PulseAudio / PipeWire and sent as Opus |
|
||||
| File transfer | Upload, download (including folders), create folder, rename, delete |
|
||||
@@ -84,6 +84,8 @@ plugins, permissions and encoders only, no account data, tokens or addresses) an
|
||||
Wayland limits: captures one screen by default; Hyprland can enable monitor switching as described below. Resolution is fixed. The native Hyprland backend now pipelines two shm screencopy buffers and passes the viewer's requested fps to both capture pacing and the encoder. Actual fps remains limited by the compositor, rendering and readback (the old serial path measured about 16–22 fps at 2560x1600; the pipeline is VM-measured only, not a hardware guarantee). The portal backend does not support dynamic resolution; see below for GNOME wake and lock recovery; the clipboard syncs while the viewer's remote window has focus. On the first connection the desktop asks for "Remote Desktop / Screen Sharing"
|
||||
permission; the permission is remembered once granted.
|
||||
|
||||
**Mobile IME typing and clipboard on Wayland**: Mobile IME text (`text_input`) on Wayland is typed through spare keycodes on wlroots compositors. On Portal (GNOME / KDE) or compositors where keycodes are exhausted, it automatically falls back to typing via "system clipboard write + `Shift+Insert` (or `UU_WAYLAND_PASTE_KEY=ctrl_v`)". **Note**: This fallback replaces the host's existing clipboard contents and may echo back to the viewer's clipboard via two-way sync; set `UU_WAYLAND_TEXT=0` to completely disable Wayland mobile text input and clipboard paste fallback.
|
||||
|
||||
Scaled GNOME desktops using native Portal input use EIS on the same authorized session when `ConnectToEIS` and a screen `mapping_id` are available. Each axis is mapped using the matched region and actual frame dimensions, with no fixed resolution or scale factor. This avoids scaled-coordinate rejection by `NotifyPointerMotionAbsolute`. Portal builds require libei >= 1.1. Missing EIS support retains the legacy input path and its existing scaling limitations; other initialization failures are reported and trigger session recovery. After a successful EIS connection, all input uses EIS. Capture alone and uinput do not initialize EIS; missing optional logical dimensions do not block capture. Keyboard input uses the existing Windows VK to evdev mapping. Recovery keeps the encoder frame dimensions fixed but accepts logical-size changes after scaling. On GNOME, a display-change notification enables earlier recovery when previously streaming Portal capture remains paused without a valid format for a 200 ms grace after both conditions are present. Healthy renegotiation cancels the early check; repeated notifications do not postpone the same interruption. The five-second fallback remains without a related notification. Static video and valid-format pauses do not trigger recovery. Tested while connected on Ubuntu 26.04, GNOME Wayland, one 3840x2160 display: 200% -> 166.67% -> 200%, with continuously updating video and full-screen pointer control after recovery. Switching briefly freezes and goes black before recovering; five seconds is the fallback threshold, not total recovery time. See [#35](../../pull/35) for timing measurements and validation limits. Lock recovery still needs hardware acceptance testing; multi-monitor support, live resolution changes, and rotation/reflection transforms are outside this fix's scope. Capture settings remain at protocol version 4: advertised resolutions use pixel coordinates and DPR 1; Portal logical dimensions are used only for local input mapping.
|
||||
|
||||
GNOME Portal CONTROL no longer waits for a consent dialog or the first video frame. It announces the selected desktop before reporting secure-desktop state and receiving the official viewer's “auto unlock host” request. The official Android viewer requires this desktop selection before entering its auto-unlock flow, so the notification must precede capture readiness; actual screen dimensions, codec information and capture permissions still follow their real readiness state. Enable auto unlock in the viewer and use the current Linux user's login password. The host verifies it with PAM, unlocks the existing GNOME session, requests display wake, and restores capture, input and clipboard through the shared Portal session. Initial consent or revoked permissions still require local approval. Reconnect if physical or logical dimensions change.
|
||||
@@ -210,6 +212,10 @@ Run inside your graphical session:
|
||||
Scan the code with the **NetEase UU Remote mobile app** and confirm. Credentials are stored only on this
|
||||
machine, in `~/.config/uuremote/config.json` (mode 0600).
|
||||
|
||||
A failed status query or the 60-second request timeout does not prove that the QR expired or that the phone confirmed login. The official-client refresh policy is unchanged: after a query error, click Refresh QR (Enter in a terminal; refresh after 60 seconds with neither a window nor a terminal). QR request diagnostics contain only the request phase, error category, elapsed time, HTTP/API status and last known scan state—not tickets, URLs or response content. A `connect` category alone does not identify a DNS, TLS or proxy cause.
|
||||
|
||||
The same file holds this machine's device identity (`device_id`, `client_id`, `system_id`), which reinstalls and new QR logins keep. **Do not copy `config.json` between machines or clone a second host from a snapshot/disk that includes the home directory**: two host instances with one identity, on the same or different machines, kick each other out of the room. The log then shows `Cloud room leave without peer identifier` every few seconds with reconnects, and viewers disconnect right after connecting. On a cloned or copied machine, stop the service, remove those three keys plus `token`, `csrf` and `user_id`, and run `uuremote-server login` to register a new device. A leftover instance on the same machine (for example an old `~/.local/bin/uuremote-server` started by hand) has the same effect; `uuremote-server doctor` warns when more than one host instance is running.
|
||||
|
||||
### 4. Run as a user service
|
||||
|
||||
`~/.config/systemd/user/uuremote-native.service`:
|
||||
@@ -356,7 +362,12 @@ Common environment variables:
|
||||
| `UU_LOGIN_WINDOW=0` | Do not open the login window automatically when credentials are missing |
|
||||
| `UU_PORT_MAPPING=0` | Disable port mapping (the official host's controlled-side switch) |
|
||||
| `UU_WOL_HELPER=1` | Experimental: act as a remote-boot helper like the official Windows host — report this host's LAN info after sign-in and send a magic packet to the LAN when the cloud asks to wake a PC (not verified end to end) |
|
||||
| `UU_USE_PROXY=1` | Honor HTTP/SOCKS proxy environment variables; by default proxies are ignored and NetEase servers are reached directly |
|
||||
| `UU_USE_PROXY=1` | Share environment HTTP/HTTPS proxy policy between REST and host/viewer WebSocket signaling; proxies are ignored by default |
|
||||
|
||||
|
||||
`UU_USE_PROXY=1` uses only proxy settings already available to the current process. `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` (and lowercase forms) and `NO_PROXY` follow reqwest's standard selection, with uppercase taking precedence. Signaling rejects invalid/unsupported values in the selected variables (HTTP/HTTPS only, not SOCKS), proxy URLs with paths/queries/fragments, and CGI environments that would ignore proxies; this validation is intentionally stricter than silently ignoring bad values. No matching proxy or a `NO_PROXY` match still means direct access; a selected proxy failing does not trigger direct fallback. Certificate verification remains enabled and redirects are not followed, so room authentication is not forwarded to a redirect target.
|
||||
|
||||
**This covers HTTP/WebSocket compatibility only: it does not proxy ICE/WebRTC media, add TURN TCP/TLS, or create network access.** Login, signaling and media each need an allowed network path. Connector errors expose only fixed categories/HTTP status; do not enable dependency TRACE logs that may record URLs or authentication information.
|
||||
|
||||
Host settings such as "lock after remote session" and "mute host" are stored in
|
||||
`~/.config/uuremote/host_settings.json`. The same file stores `video_encoder`
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
| 鼠标 / 键盘 | 绝对/相对移动、点击、滚轮、按键;修复了网络延迟导致的按键连发;Wayland 下可用 uinput 虚拟键鼠(不依赖键盘布局,见下文) |
|
||||
| Mac 快捷键 | **推荐**:在 Mac 远控窗口菜单里关闭「使用 macOS 快捷键」,之后和在 Mac 上一样:Cmd+C/V/A/F/X/Z 是复制、粘贴、全选、查找、剪切、撤销(终端里 Cmd+C/V 自动变成 Ctrl+Shift+C/V),Ctrl+C 在终端里始终是中断。保持开启时,客户端会把 Cmd 和 Ctrl 都当成 Ctrl 发送:终端里 Ctrl+V / Cmd+V 自动转成粘贴,Ctrl+C 是中断,复制用 Cmd+Shift+C(X11) |
|
||||
| 鼠标指针样式 | 远端指针形状实时同步(X11) |
|
||||
| 剪贴板 | 双向文本同步 |
|
||||
| 剪贴板 | 双向文本同步;Wayland 手机输入法输入通过剪贴板兜底粘贴,见下文 |
|
||||
| 画质 / 帧率 / 分辨率 | 自动、原画 20M、超清 8M、高清 2M、自定义;30/60/90/144 帧;X11 下切换分辨率会像官方 Windows 被控端一样真正修改桌面分辨率(xrandr,缺少该模式时自动添加;选「原始」或断开后恢复),`UU_DESKTOP_RESIZE=0` 改为仅由编码器缩放;Wayland 仍由编码器缩放 |
|
||||
| 声音 | 采集系统声音(PulseAudio / PipeWire),Opus 编码传到控制端 |
|
||||
| 文件传输 | 上传、下载(含文件夹)、新建文件夹、重命名、删除 |
|
||||
@@ -75,6 +75,8 @@ GNOME Wayland 的 Portal/EIS 路径已在 Ubuntu 26.04、GNOME 50、单屏 4K/20
|
||||
|
||||
Wayland 下的限制:默认采集单屏,Hyprland 可按上文启用切屏;分辨率固定;Hyprland 原生后端默认使用双缓冲流水线 shm screencopy,控制端帧率设置会同步到采集节拍和编码器,但实际帧率仍受合成器、渲染和读回速度限制(旧串行路径在 2560x1600 曾测得约 16~22 帧;流水线只在虚拟机里测量过,不代表实机保证);portal 后端暂不支持动态分辨率;GNOME 的屏幕唤醒与锁屏恢复见下;剪贴板只在控制端的远控窗口处于前台时同步。
|
||||
|
||||
**Wayland 手机输入法打字与剪贴板**:Wayland 下手机端输入法提交的文字(`text_input`)优先通过虚拟键盘空闲键码上屏;在 Portal(GNOME / KDE)或键码耗尽的环境下,自动通过「写系统剪贴板 + 触发 `Shift+Insert`(或 `UU_WAYLAND_PASTE_KEY=ctrl_v`)」兜底粘贴。**注意**:此兜底过程会覆盖被控端原有的剪贴板内容,且会被双向同步回传到控制端剪贴板;设置 `UU_WAYLAND_TEXT=0` 可完全关闭 Wayland 文字输入及该粘贴兜底。
|
||||
|
||||
GNOME 缩放桌面在使用 Portal 原生键鼠时,若支持 `ConnectToEIS` 和屏幕 `mapping_id`,通过同一授权会话的 EIS 接口注入输入,按匹配的区域与实际帧尺寸分别映射横纵坐标,没有固定分辨率或缩放倍率,可避免 `NotifyPointerMotionAbsolute` 在缩放时拒绝坐标。Portal 构建需要 libei ≥ 1.1。缺少 EIS 支持时保留旧输入路径及其既有缩放限制;其他初始化错误会明确报告并触发会话恢复。EIS 连接成功后全部输入统一使用 EIS。只采集画面或使用 uinput 时不会初始化 EIS;缺少可选的逻辑尺寸也不阻断采集。键盘沿用项目现有的 Windows VK → evdev 映射。恢复时保持编码器的采集帧尺寸不变,允许缩放后的逻辑尺寸变化。GNOME 显示配置变化后,已推流的 Portal 采集若持续「暂停且无有效格式」,会在关联通知后的 200 毫秒宽限结束后提前进入现有恢复流程;正常重协商恢复会取消提前判定,连续通知不会推迟同次异常的判定。未收到相关通知时保留五秒兜底;静态画面或有效格式下的暂停不会触发恢复。Ubuntu 26.04、GNOME Wayland 单屏 3840×2160 已实测保持连接切换 200%→166.67%→200%,恢复后画面持续更新且鼠标可控制全屏;切换期间会短暂停顿、黑屏后恢复,五秒是兜底判定阈值,并非总恢复时间。提前恢复的测量结果和验证范围见 [#35](../../pull/35)。此路径仍需实机验证锁屏恢复;多屏、连接中改变分辨率及旋转/镜像变换不属于本次修复范围。 捕获设置协议仍为版本 4:对客户端上报的分辨率统一使用像素坐标、DPR 为 1;Portal 逻辑尺寸仅用于本地输入映射。
|
||||
|
||||
GNOME Portal 的控制通道不再等待授权窗口或第一帧画面:先通知客户端当前选择桌面,再上报锁屏状态、接收官方客户端的「自动解锁被控端」请求。官方 Android 客户端需要桌面目标通知才会进入自动解锁流程,因此该通知不能等待采集就绪;真实屏幕尺寸、编码信息及采集权限仍按实际就绪状态上报。请在客户端启用自动解锁,使用当前 Linux 用户的登录密码;主机通过 PAM 验证后解锁当前 GNOME 会话、请求点亮屏幕,并恢复同一 Portal 会话中的画面、键鼠和剪贴板。首次授权或权限被撤销时仍需本机确认。物理或逻辑分辨率变化后需要重连。
|
||||
@@ -193,6 +195,10 @@ cargo build --release --features wayland,portal # + GNOME/KDE Wayland
|
||||
用手机上的 **网易 UU 远程 App** 扫码并确认即可。登录信息只保存在本机的
|
||||
`~/.config/uuremote/config.json`(权限 0600)里。
|
||||
|
||||
登录状态查询失败或达到 60 秒请求超时不代表二维码已过期,也不代表手机已经确认。程序保留官方客户端的刷新策略:查询出错后点击「刷新二维码」(终端按回车;无窗口且无终端时 60 秒后刷新)。二维码请求诊断只包含请求阶段、错误类别、耗时、HTTP/API 状态及最后已知扫码状态,不输出票据、URL 或响应内容;`connect` 类别本身不能确定是 DNS、TLS 还是代理问题。
|
||||
|
||||
这个文件里还有本机的设备身份(`device_id`、`client_id`、`system_id`),重装软件和重新扫码登录都会沿用它。**不要在机器之间拷贝 `config.json`,也不要从带着家目录的快照/数据盘克隆出第二台主机**:同一身份的两个主机实例(不论在同一台还是不同机器上)会互相把对方踢出房间,日志表现为每隔几秒出现 `Cloud room leave without peer identifier` 并反复重连,控制端一连就断。克隆或拷贝出来的机器先停掉服务,删掉配置里这三个键和 `token`、`csrf`、`user_id`,再运行 `uuremote-server login` 注册为新设备。同一台机器上残留的旧实例(例如以前手动启动的 `~/.local/bin/uuremote-server`)也会这样,`uuremote-server doctor` 发现多个主机实例时会提示。
|
||||
|
||||
### 4. 作为用户服务常驻
|
||||
|
||||
`~/.config/systemd/user/uuremote-native.service`:
|
||||
@@ -324,7 +330,12 @@ systemctl --user restart uuremote-native.service
|
||||
| `UU_ASSIST_ALLOW=1` | 启动时就允许他人远程协助(覆盖窗口里保存的开关状态) |
|
||||
| `UU_PORT_MAPPING=0` | 关闭端口映射(对应官方被控端的开关) |
|
||||
| `UU_WOL_HELPER=1` | 实验性:让这台主机像官方 Windows 被控端一样充当「远程开机」辅助设备——登录后向网易上报本机局域网信息,收到云端唤醒请求时向同一局域网发送唤醒包(未经端到端验证) |
|
||||
| `UU_USE_PROXY=1` | 使用环境变量里的 HTTP/SOCKS 代理;默认忽略代理、直连网易服务器 |
|
||||
| `UU_USE_PROXY=1` | REST API 与 host/viewer WebSocket 信令共用环境 HTTP/HTTPS 代理策略;默认忽略代理、直连 |
|
||||
|
||||
|
||||
`UU_USE_PROXY=1` 仅使用当前进程已有的代理配置;`HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY`(及小写形式)和 `NO_PROXY` 按 reqwest 的标准规则选择,大写优先。信令拒绝选定变量中的无效/不支持的代理 URL(仅 HTTP/HTTPS;不支持 SOCKS)、带路径/查询/片段的代理 URL,以及会忽略代理的 CGI 环境;此校验比 reqwest 默默忽略坏值更严格。未配置匹配代理或命中 `NO_PROXY` 时仍正常直连,选中代理后连接失败不会改为直连。信令保留 TLS 证书校验,不跟随重定向,也不转发认证头到重定向目标。
|
||||
|
||||
**这只解决 HTTP 与 WebSocket 的代理兼容性,不代理 ICE/WebRTC 媒体,也不提供 TURN TCP/TLS 或任何新的网络出口。** 登录、信令和媒体必须分别有允许使用的网络路径。连接器只返回固定错误类别/HTTP 状态;不要为诊断开启会记录 URL/认证信息的依赖库 TRACE 日志。
|
||||
|
||||
「远程结束后自动锁屏」「静音运行」等设置保存在 `~/.config/uuremote/host_settings.json`。同一文件里的 `video_encoder`(`auto`/`cpu`/`vaapi`/`nvenc`)和 `video_codec`(`auto`/`h264`/`h265`)用 `uuremote-server set-encoder`、`uuremote-server set-codec` 写入(非法参数退出码 2)。非 `auto` 的值优先于 `UU_VIDEO_ENCODER` / `UU_VIDEO_CODEC`;`auto` 或留空则落到环境变量,再落到 auto(有 NVIDIA 时 NVENC 优先,失败再 CPU;没有 NVIDIA 时就是 CPU,不探测;codec 仍是硬件优先 H.265、CPU 用 H.264)。探测在启动时后台进行,不挡住第一路出图。成功结果缓存到进程退出,但 NVIDIA 是否存在(`/proc/driver/nvidia/version` 或 `/dev/nvidia0`)与报告不一致时,下一次桌面连接会在后台再探测一次(`warm_auto_probe`),这一路仍用缓存的编码器,直到新结果写入。NVENC 失败只缓存 10 分钟,到期后的桌面连接同样在后台再探测一次,这一路仍用当前结果。`set-encoder` 和 `set-codec` 写完后若 `host.pid` 指向正在运行的本程序,都会发 `SIGUSR2`:编码器变化时进行中的桌面流立刻换编码器(不断开,沿用本会话已协商的 codec;新编码器起不来时按进程内 → FFmpeg 进程 → CPU 回退)。手改文件后可 `kill -USR2 $(cat ~/.config/uuremote/host.pid)`。`SIGUSR2` 不重新探测。codec 偏好仍在下次建立桌面连接时生效(运行中的 host 只记日志,不重开编码)。显式 `vaapi` 请求真彩时仍用 VAAPI、编码 4:2:0,并在 CaptureSettingSync 的 field 3 回报 4:2:0。所选编码器在本机不可用时,建流回退 CPU 并记 warning。VAAPI 进入 auto 要等 #33。
|
||||
|
||||
|
||||
+17
-2
@@ -56,6 +56,15 @@ static void track_injected_key(int keycode, int is_press) {
|
||||
}
|
||||
}
|
||||
|
||||
/* XShmAttach fails asynchronously (BadAccess when the X server cannot reach our segment, e.g. a
|
||||
* server in another container); Xlib's default handler would exit the process before the XGetImage fallback. */
|
||||
static volatile int g_shm_attach_failed = 0;
|
||||
static int shm_attach_error(Display *display, XErrorEvent *event) {
|
||||
(void)display; (void)event;
|
||||
g_shm_attach_failed = 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void shm_open_image(void) {
|
||||
g_use_shm = 0;
|
||||
if (!XShmQueryExtension(g_display)) return;
|
||||
@@ -66,9 +75,15 @@ static void shm_open_image(void) {
|
||||
if (g_shminfo.shmid == -1) return;
|
||||
g_shminfo.shmaddr = g_shm_image->data = (char *)shmat(g_shminfo.shmid, 0, 0);
|
||||
g_shminfo.readOnly = False;
|
||||
if (g_shminfo.shmaddr != (char *)-1 && XShmAttach(g_display, &g_shminfo)) {
|
||||
if (g_shminfo.shmaddr != (char *)-1) {
|
||||
XSync(g_display, False);
|
||||
g_use_shm = 1;
|
||||
g_shm_attach_failed = 0;
|
||||
int (*previous)(Display *, XErrorEvent *) = XSetErrorHandler(shm_attach_error);
|
||||
Status attached = XShmAttach(g_display, &g_shminfo);
|
||||
XSync(g_display, False);
|
||||
XSetErrorHandler(previous);
|
||||
if (attached && !g_shm_attach_failed) g_use_shm = 1;
|
||||
else fprintf(stderr, "X11 shared-memory capture unavailable; using XGetImage\n");
|
||||
}
|
||||
shmctl(g_shminfo.shmid, IPC_RMID, 0); // 标记删除,进程退出时自动回收;失败时也不遗留段
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
信令可走 HTTP 代理、二维码登录错误分类、重复主机实例诊断,以及 Wayland 手机端文字输入兜底。/ Signaling through an opt-in HTTP proxy, clearer QR login errors, duplicate-host diagnostics, and a Wayland fallback for mobile text input.
|
||||
|
||||
### 新增 / Added
|
||||
- **信令遵循 `UU_USE_PROXY=1`(#123)**:主机和 Linux 控制端的 WebSocket 信令改用与 REST 接口相同的 HTTP 客户端,开启 `UU_USE_PROXY=1` 后也走环境里的 HTTP/HTTPS 代理(不支持 SOCKS;选中的代理失败不会改为直连;不跟随重定向)。不代理 ICE/WebRTC 媒体。默认(不开代理)行为不变。
|
||||
Host and viewer signaling now use the same HTTP client as the REST API, so `UU_USE_PROXY=1` applies to signaling too (HTTP/HTTPS proxies only, no direct fallback, no redirects). Media is not proxied; the default is unchanged.
|
||||
- **Wayland/Portal 手机端文字输入兜底(#119,感谢 @shofukantkts)**:没有空闲键码的合成器和 Portal 后端上,手机端输入的文字经剪贴板 + Shift+Insert 粘贴;`UU_WAYLAND_TEXT=0` 可关闭。
|
||||
Mobile text input on Portal and compositors without spare keycodes is pasted via the clipboard and Shift+Insert; `UU_WAYLAND_TEXT=0` disables it.
|
||||
|
||||
### 修复 / Fixed
|
||||
- **二维码登录错误分类(#121)**:状态查询失败不再一律提示「网络超时」,区分超时、连接失败、响应异常与二维码过期;诊断只含阶段、类别、耗时和状态码,不输出票据、URL 或服务器内容。
|
||||
QR polling failures are no longer all reported as a network timeout; timeouts, connection failures, bad responses and expiry are distinguished, with diagnostics that never include tickets, URLs or server content.
|
||||
- **重复主机实例(#122)**:同一身份的两个主机实例(拷贝了 `config.json`,或残留的旧手动实例)会互相把对方踢出房间,表现为控制端一连就断。`doctor` 现在能数到重新执行后进程名为 `exe` 的实例并给出提示;README 说明不要在机器之间拷贝 `config.json`;日志会记录无 peer id 的 leave 事件结构(仅键名/类型/长度)。
|
||||
Two host instances sharing one identity kick each other out of the room. `doctor` now counts re-executed instances and warns about extras, the README explains not to copy `config.json` between machines, and leave events without a peer id log their shape (keys/types/lengths only).
|
||||
|
||||
### 验证范围 / Validation
|
||||
单元测试与 CI。#123 在真实 Linux X11 主机上实测不开代理时信令与 iPhone 桌面连接正常;经真实代理的信令尚未实测。#122 的修复在报告环境实机验证。
|
||||
|
||||
### 下载 / Download
|
||||
`uu-remote-linux_0.2.35_<amd64|arm64>.deb`,或 `uu-remote-linux-v0.2.35-<x86_64|aarch64>-linux.tar.gz`(解压后运行 `./install.sh`),或 `docker pull ghcr.io/vallierdev/uu-remote-linux:v0.2.35`(x86_64)。
|
||||
|
||||
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||
@@ -0,0 +1,15 @@
|
||||
修复 X11 共享内存被拒时主机直接退出,以及 Linux 控制端加入已有会话时可能永久黑屏。/ Fixes the host exiting when X11 refuses shared memory, and a possible black screen when the Linux viewer joins a host that already streams to another session.
|
||||
|
||||
### 修复 / Fixed
|
||||
- **X11 MIT-SHM 被拒时直接退出**:X 服务器无法访问本程序的共享内存段时(例如 X 服务器在另一个容器里),`XShmAttach` 返回 BadAccess,Xlib 默认错误处理直接结束了进程,原有的 `XGetImage` 退路没有机会执行。现在捕获该错误并改用 `XGetImage` 抓屏。
|
||||
When `XShmAttach` is refused (BadAccess, e.g. an X server in another container), the host now falls back to `XGetImage` instead of being terminated by Xlib's default error handler.
|
||||
- **控制端加入已有会话时黑屏(#124,感谢 @shao-zhijie)**:Linux 控制端过去只在丢包或解码出错时请求关键帧;加入一条已在推流的干净 H.264 流时永远等不到 IDR。现在首帧显示前每 30 个访问单元请求一次关键帧(PLI),300 个仍无画面时日志给出提示。
|
||||
The Linux viewer now requests key frames (PLI) every 30 access units until the first frame is shown, and logs a warning after 300.
|
||||
|
||||
### 验证范围 / Validation
|
||||
单元测试与 CI。共享内存退路尚待在报告环境实机确认;#124 中官方 Mac 主机是否响应 PLI 尚未实测。
|
||||
|
||||
### 下载 / Download
|
||||
`uu-remote-linux_0.2.36_<amd64|arm64>.deb`,或 `uu-remote-linux-v0.2.36-<x86_64|aarch64>-linux.tar.gz`(解压后运行 `./install.sh`),或 `docker pull ghcr.io/vallierdev/uu-remote-linux:v0.2.36`(x86_64)。
|
||||
|
||||
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||
+109
-9
@@ -91,6 +91,48 @@ pub struct UUAuthClient {
|
||||
guest_id: Option<String>,
|
||||
}
|
||||
|
||||
/// QR failures are safe to display: never retain a URL, source error or response body.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum QrRequestErrorKind { Timeout, Connect, Decode, Body, Request }
|
||||
impl QrRequestErrorKind {
|
||||
fn from_reqwest(error: &reqwest::Error) -> Self {
|
||||
if error.is_timeout() { Self::Timeout }
|
||||
else if error.is_connect() { Self::Connect }
|
||||
else if error.is_decode() { Self::Decode }
|
||||
else if error.is_body() { Self::Body }
|
||||
else { Self::Request }
|
||||
}
|
||||
fn label(self) -> &'static str {
|
||||
match self { Self::Timeout => "timeout", Self::Connect => "connect", Self::Decode => "decode",
|
||||
Self::Body => "body", Self::Request => "request" }
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct QrRequestError {
|
||||
pub kind: QrRequestErrorKind,
|
||||
phase: &'static str,
|
||||
elapsed_ms: u128,
|
||||
http_status: Option<u16>,
|
||||
}
|
||||
impl std::fmt::Display for QrRequestError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "phase={} kind={} elapsed_ms={} http_status={:?}",
|
||||
self.phase, self.kind.label(), self.elapsed_ms, self.http_status)
|
||||
}
|
||||
}
|
||||
impl QrRequestError {
|
||||
pub fn response_received(&self) -> bool { self.http_status.is_some() }
|
||||
fn new(kind: QrRequestErrorKind, phase: &'static str, started: std::time::Instant, http_status: Option<u16>) -> Self {
|
||||
Self { kind, phase, elapsed_ms: started.elapsed().as_millis(), http_status }
|
||||
}
|
||||
}
|
||||
async fn send_qr_request(request: reqwest::RequestBuilder, started: std::time::Instant) -> Result<(u16, serde_json::Value), QrRequestError> {
|
||||
let resp = request.send().await.map_err(|e| QrRequestError::new(QrRequestErrorKind::from_reqwest(&e), "send", started, None))?;
|
||||
let status = resp.status().as_u16();
|
||||
let value = resp.json().await.map_err(|e| QrRequestError::new(QrRequestErrorKind::from_reqwest(&e), "response", started, Some(status)))?;
|
||||
Ok((status, value))
|
||||
}
|
||||
|
||||
/// Transport failures name only the outer request; the cause (certificate, proxy, DNS,
|
||||
/// timeout) lives in the source chain. URL user-info (proxy credentials) and query
|
||||
/// strings are removed before the chain is shown.
|
||||
@@ -121,17 +163,20 @@ fn redact_urls(text: &str) -> String {
|
||||
out
|
||||
}
|
||||
|
||||
/// Cloud API clients ignore ambient HTTP/SOCKS proxy settings by default: a local
|
||||
/// Cloud API and signaling clients ignore ambient HTTP/HTTPS proxy settings by default: a local
|
||||
/// proxy that intercepts TLS breaks login and signaling. `UU_USE_PROXY=1` opts back
|
||||
/// into reqwest's standard proxy environment handling.
|
||||
pub fn http_client_builder() -> reqwest::ClientBuilder {
|
||||
let builder = reqwest::Client::builder();
|
||||
if std::env::var("UU_USE_PROXY").ok().as_deref().is_some_and(proxy_requested) {
|
||||
if proxy_enabled() {
|
||||
builder
|
||||
} else {
|
||||
builder.no_proxy()
|
||||
}
|
||||
}
|
||||
pub(crate) fn proxy_enabled() -> bool {
|
||||
std::env::var("UU_USE_PROXY").ok().as_deref().is_some_and(proxy_requested)
|
||||
}
|
||||
fn proxy_requested(value: &str) -> bool {
|
||||
matches!(value.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")
|
||||
}
|
||||
@@ -253,13 +298,13 @@ impl UUAuthClient {
|
||||
|
||||
/// Signed POST with an optional JSON body (None = empty body, like Moya `requestPlain`) and an
|
||||
/// explicit timeout. The official clients long-poll the QR status with a 60 s request timeout.
|
||||
pub async fn post_with_timeout(&self, path: &str, body: Option<&serde_json::Value>, timeout: std::time::Duration) -> Result<(u16, serde_json::Value), String> {
|
||||
let body_str = body.map(serde_json::to_string).transpose().map_err(|e| e.to_string())?.unwrap_or_default();
|
||||
let resp = self.http.post(format!("{}{}", BASE_URL, path)).timeout(timeout)
|
||||
.headers(self.build_headers("POST", path, &body_str)).body(body_str)
|
||||
.send().await.map_err(|e| format!("HTTP post {path} failed: {}", transport_error(&e)))?;
|
||||
let status = resp.status().as_u16();
|
||||
Ok((status, resp.json().await.unwrap_or(serde_json::Value::Null)))
|
||||
pub async fn post_with_timeout(&self, path: &str, body: Option<&serde_json::Value>, timeout: std::time::Duration) -> Result<(u16, serde_json::Value), QrRequestError> {
|
||||
let started = std::time::Instant::now();
|
||||
let body_str = body.map(serde_json::to_string).transpose()
|
||||
.map_err(|_| QrRequestError::new(QrRequestErrorKind::Request, "encode", started, None))?.unwrap_or_default();
|
||||
let request = self.http.post(format!("{}{}", BASE_URL, path)).timeout(timeout)
|
||||
.headers(self.build_headers("POST", path, &body_str)).body(body_str);
|
||||
send_qr_request(request, started).await
|
||||
}
|
||||
|
||||
/// Signed JSON POST to another API host (the signature covers the path only).
|
||||
@@ -389,3 +434,58 @@ mod guest_tests {
|
||||
for value in ["", "0", "false", "no", "off", "2"] { assert!(!super::proxy_requested(value)); }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod qr_request_tests {
|
||||
use super::*;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
// Synthetic, loopback-only responses: no account, device, proxy or live login API.
|
||||
async fn response(reply: &'static [u8], stall: bool) -> QrRequestError {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let mut request = [0u8; 4096];
|
||||
let _ = socket.read(&mut request).await.unwrap();
|
||||
socket.write_all(reply).await.unwrap();
|
||||
if stall { std::future::pending::<()>().await; }
|
||||
});
|
||||
let request = reqwest::Client::builder().no_proxy().build().unwrap()
|
||||
.post(format!("http://fixture-user:fixture-password@{addr}/fixture-path?token=fixture-ticket"))
|
||||
.timeout(Duration::from_secs(2));
|
||||
let error = send_qr_request(request, Instant::now()).await.unwrap_err();
|
||||
server.abort();
|
||||
let output = format!("{error} {error:?}");
|
||||
for secret in ["fixture-user", "fixture-password", "fixture-path", "fixture-ticket", "fixture-body", "127.0.0.1", "http://"] {
|
||||
assert!(!output.contains(secret));
|
||||
}
|
||||
error
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn qr_request_distinguishes_send_timeout_body_timeout_and_bad_json_without_secrets() {
|
||||
let error = response(b"", true).await;
|
||||
assert_eq!((error.kind, error.phase, error.http_status), (QrRequestErrorKind::Timeout, "send", None));
|
||||
assert!(!error.response_received());
|
||||
let error = response(b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n", true).await;
|
||||
assert_eq!((error.kind, error.phase, error.http_status), (QrRequestErrorKind::Timeout, "response", Some(200)));
|
||||
assert!(error.response_received());
|
||||
let error = response(b"HTTP/1.1 502 Bad Gateway\r\nContent-Length: 12\r\n\r\nfixture-body", false).await;
|
||||
assert_eq!((error.kind, error.phase, error.http_status), (QrRequestErrorKind::Decode, "response", Some(502)));
|
||||
assert!(error.response_received());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn qr_connection_failure_is_not_a_timeout() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
drop(listener);
|
||||
let request = reqwest::Client::builder().no_proxy().build().unwrap()
|
||||
.post(format!("http://{addr}/fixture-ticket")).timeout(Duration::from_secs(2));
|
||||
let error = send_qr_request(request, Instant::now()).await.unwrap_err();
|
||||
assert_eq!((error.kind, error.phase, error.http_status), (QrRequestErrorKind::Connect, "send", None));
|
||||
assert!(!format!("{error} {error:?}").contains("fixture-ticket"));
|
||||
}
|
||||
}
|
||||
+50
-2
@@ -147,11 +147,39 @@ pub async fn run() -> Result<(), String> {
|
||||
Err(_) => line("config mode", "missing (run `uuremote-server login`)"),
|
||||
}
|
||||
line("service", command_output("systemctl", &["--user", "is-active", "uuremote-native.service"]).await.unwrap_or_else(|| "systemctl unavailable".into()));
|
||||
let running = command_output("pgrep", &["-c", "-x", "uuremote-server"]).await.filter(|n| !n.is_empty()).unwrap_or_else(|| "unknown".into());
|
||||
line("uuremote-server procs", format!("{running} (including this one; more than 2 means duplicates)"));
|
||||
let running = host_processes();
|
||||
line("uuremote-server procs", format!("{} (including this one; more than 2 means duplicates)", running.map_or_else(|| "unknown".into(), |n| n.to_string())));
|
||||
if running.is_some_and(|n| n > 2) {
|
||||
println!(" ! another host instance is running (check `pgrep -af uuremote`); stop the extra one, e.g. an old copy started by hand");
|
||||
println!(" instances sharing one identity, on this or another machine, kick each other out of the room: never copy config.json between machines");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Hosts re-exec through /proc/self/exe (comm "exe"), so match the executable's file name, not the process name.
|
||||
/// Helpers a host spawns (Wayland capture, login window) are its children and are not separate instances.
|
||||
fn host_processes() -> Option<usize> {
|
||||
let hosts: Vec<(u32, u32)> = std::fs::read_dir("/proc").ok()?.flatten()
|
||||
.filter_map(|entry| Some((entry.file_name().to_str()?.parse::<u32>().ok()?, entry.path())))
|
||||
.filter(|(_, dir)| std::fs::read_link(dir.join("exe")).is_ok_and(|exe| is_host_executable(&exe)))
|
||||
.filter_map(|(pid, dir)| Some((pid, parent_pid(&std::fs::read_to_string(dir.join("stat")).ok()?)?)))
|
||||
.collect();
|
||||
Some(top_level(&hosts))
|
||||
}
|
||||
|
||||
/// Field 4 of /proc/<pid>/stat; the command name in field 2 may contain spaces and parentheses.
|
||||
fn parent_pid(stat: &str) -> Option<u32> {
|
||||
stat.rsplit_once(')')?.1.split_whitespace().nth(1)?.parse().ok()
|
||||
}
|
||||
|
||||
fn top_level(hosts: &[(u32, u32)]) -> usize {
|
||||
hosts.iter().filter(|(_, parent)| !hosts.iter().any(|(pid, _)| pid == parent)).count()
|
||||
}
|
||||
|
||||
fn is_host_executable(exe: &std::path::Path) -> bool {
|
||||
exe.file_name().and_then(|name| name.to_str()).is_some_and(|name| name.trim_end_matches(" (deleted)") == "uuremote-server")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
@@ -174,4 +202,24 @@ mod tests {
|
||||
assert!(!super::missing_display(DesktopBackend::Wayland, false, None, None));
|
||||
assert!(!super::missing_display(DesktopBackend::X11, true, None, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_processes_match_the_executable_even_after_reexec() {
|
||||
use std::path::Path;
|
||||
for exe in ["/usr/bin/uuremote-server", "/home/u/.local/bin/uuremote-server", "/usr/bin/uuremote-server (deleted)"] {
|
||||
assert!(super::is_host_executable(Path::new(exe)));
|
||||
}
|
||||
for exe in ["/usr/bin/uuremote-viewer", "/usr/bin/bash", "/usr/bin/uuremote-server-old"] {
|
||||
assert!(!super::is_host_executable(Path::new(exe)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_helpers_are_not_counted_as_instances() {
|
||||
assert_eq!(super::parent_pid("8943 (exe) S 1699 8943 1699 0 -1"), Some(1699));
|
||||
assert_eq!(super::parent_pid("12 (a) b (c) R 7 12"), Some(7));
|
||||
// service 10 with a login window 11, a stale copy 20, doctor 30
|
||||
assert_eq!(super::top_level(&[(10, 1), (11, 10), (20, 5), (30, 9)]), 3);
|
||||
assert_eq!(super::top_level(&[(10, 1), (11, 10), (30, 9)]), 2);
|
||||
}
|
||||
}
|
||||
+134
-4
@@ -372,8 +372,93 @@ impl InputInjector {
|
||||
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)) } }
|
||||
}
|
||||
/// Set clipboard content for text injection on Wayland / Portal.
|
||||
/// Tries Portal RemoteDesktop.SetSelection first, then wl-copy as fallback.
|
||||
fn set_clipboard_text(&self, text: &str) -> bool {
|
||||
if text.is_empty() || text.len() > crate::clipboard::MAX_TEXT {
|
||||
return false;
|
||||
}
|
||||
// In unit tests, never invoke external clipboard binaries (wl-copy)
|
||||
// or alter the system clipboard to prevent side effects on developer desktops.
|
||||
#[cfg(test)]
|
||||
{
|
||||
let _ = text;
|
||||
false
|
||||
}
|
||||
#[cfg(not(test))]
|
||||
{
|
||||
// 1. Try Portal clipboard if session is bound and active
|
||||
if let Some(portal) = self.portal.lock().unwrap().as_ref() {
|
||||
if portal.clipboard_set(text).is_ok() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
// 2. Try wl-copy in Wayland session
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
|
||||
if let Ok(mut child) = std::process::Command::new("wl-copy")
|
||||
.args(["--type", "text/plain;charset=utf-8"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.spawn()
|
||||
{
|
||||
if let Some(mut stdin) = child.stdin.take() {
|
||||
use std::io::Write;
|
||||
let _ = stdin.write_all(text.as_bytes());
|
||||
}
|
||||
if let Ok(status) = child.wait() {
|
||||
if status.success() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Injects text by copying it to the clipboard and simulating a paste shortcut.
|
||||
/// Uses Shift+Insert by default (broadest Linux compatibility across GUI apps and terminals),
|
||||
/// or Ctrl+V if configured via UU_WAYLAND_PASTE_KEY=ctrl_v.
|
||||
fn paste_text_via_clipboard(&self, text: &str) -> bool {
|
||||
if !self.set_clipboard_text(text) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Give the clipboard daemon / compositor a brief moment to register the selection.
|
||||
std::thread::sleep(std::time::Duration::from_millis(25));
|
||||
|
||||
let use_ctrl_v = std::env::var("UU_WAYLAND_PASTE_KEY")
|
||||
.is_ok_and(|v| v.eq_ignore_ascii_case("ctrl_v") || v.eq_ignore_ascii_case("ctrl+v"));
|
||||
|
||||
if use_ctrl_v {
|
||||
// Control_L (0xffe3) + 'v' (0x76)
|
||||
self.inject_key(0xffe3, true);
|
||||
std::thread::sleep(std::time::Duration::from_millis(15));
|
||||
self.inject_key(0x76, true);
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
self.inject_key(0x76, false);
|
||||
std::thread::sleep(std::time::Duration::from_millis(15));
|
||||
self.inject_key(0xffe3, false);
|
||||
} else {
|
||||
// Shift_L (0xffe1) + Insert (0xff63)
|
||||
self.inject_key(0xffe1, true);
|
||||
std::thread::sleep(std::time::Duration::from_millis(15));
|
||||
self.inject_key(0xff63, true);
|
||||
std::thread::sleep(std::time::Duration::from_millis(20));
|
||||
self.inject_key(0xff63, false);
|
||||
std::thread::sleep(std::time::Duration::from_millis(15));
|
||||
self.inject_key(0xffe1, false);
|
||||
}
|
||||
|
||||
// Brief delay allowing the target application to consume the paste event
|
||||
std::thread::sleep(std::time::Duration::from_millis(25));
|
||||
true
|
||||
}
|
||||
|
||||
/// Mobile input-method text (`text_input`). X11 types it directly; Wayland re-maps a spare
|
||||
/// keycode in the virtual keyboard's keymap. Other backends log once.
|
||||
/// keycode in the virtual keyboard's keymap. Portal and other Wayland environments inject
|
||||
/// via clipboard paste (Shift+Insert). Set UU_WAYLAND_TEXT=0 to disable Wayland text injection.
|
||||
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 };
|
||||
@@ -381,17 +466,31 @@ impl InputInjector {
|
||||
let typed=unsafe { x11_type_utf8(c_text.as_ptr()) };
|
||||
log::info!("Desktop text input: chars={} result={}", text.chars().count(), typed);
|
||||
} else if self.backend==crate::desktop_backend::DesktopBackend::Wayland {
|
||||
// Escape hatch: keep the old behaviour without rebuilding.
|
||||
// Escape hatch: disable Wayland text typing/pasting entirely without rebuilding.
|
||||
if std::env::var("UU_WAYLAND_TEXT").is_ok_and(|v|v=="0") { return; }
|
||||
let typed=crate::wayland::type_utf8(text);
|
||||
if typed>=0 {
|
||||
log::info!("Desktop text input: chars={} result={}", text.chars().count(), typed);
|
||||
return;
|
||||
}
|
||||
// A keymap whose keycodes are all mapped cannot carry text; report it once.
|
||||
// Fallback to clipboard paste if keymap has no spare keycodes or native typing failed
|
||||
if self.paste_text_via_clipboard(text) {
|
||||
log::info!("Desktop text input (Wayland clipboard paste fallback): chars={} result=ok", text.chars().count());
|
||||
return;
|
||||
}
|
||||
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 unavailable on the Wayland backend (no spare keycode in this keymap)");
|
||||
log::warn!("Mobile text input unavailable on the Wayland backend (native and clipboard fallback failed)");
|
||||
}
|
||||
} else if self.backend==crate::desktop_backend::DesktopBackend::Portal {
|
||||
if std::env::var("UU_WAYLAND_TEXT").is_ok_and(|v|v=="0") { return; }
|
||||
if self.paste_text_via_clipboard(text) {
|
||||
log::info!("Desktop text input (Portal clipboard paste): chars={} result=ok", text.chars().count());
|
||||
return;
|
||||
}
|
||||
static WARNED:std::sync::atomic::AtomicBool=std::sync::atomic::AtomicBool::new(false);
|
||||
if !WARNED.swap(true,std::sync::atomic::Ordering::Relaxed) {
|
||||
log::warn!("Portal clipboard text paste failed: ensure clipboard permission or wl-copy is available");
|
||||
}
|
||||
} else {
|
||||
static WARNED:std::sync::atomic::AtomicBool=std::sync::atomic::AtomicBool::new(false);
|
||||
@@ -728,3 +827,34 @@ mod x11_monitor_pointer_tests {
|
||||
crate::wayland::select(0).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod clipboard_paste_text_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn rejects_empty_and_oversized_text() {
|
||||
let input = InputInjector::new();
|
||||
assert!(!input.set_clipboard_text(""));
|
||||
let oversized = "a".repeat(crate::clipboard::MAX_TEXT + 1);
|
||||
assert!(!input.set_clipboard_text(&oversized));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_input_handles_portal_backend_safely_without_side_effects() {
|
||||
let mut input = InputInjector::new();
|
||||
input.backend = crate::desktop_backend::DesktopBackend::Portal;
|
||||
// In unit tests, set_clipboard_text avoids external commands so this
|
||||
// will not mutate the host's actual clipboard.
|
||||
input.text_input("测试输入法文字");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_input_respects_disable_env() {
|
||||
let mut input = InputInjector::new();
|
||||
input.backend = crate::desktop_backend::DesktopBackend::Portal;
|
||||
std::env::set_var("UU_WAYLAND_TEXT", "0");
|
||||
input.text_input("测试输入法文字");
|
||||
std::env::remove_var("UU_WAYLAND_TEXT");
|
||||
}
|
||||
}
|
||||
+108
-19
@@ -8,7 +8,7 @@
|
||||
//! (analysis/tools-fix-20261013/viewer-fieldmd.json). Results are written to the private
|
||||
//! config file (chmod 600). Tokens and tickets are never printed or logged.
|
||||
|
||||
use crate::auth::{Credentials, UUAuthClient};
|
||||
use crate::auth::{Credentials, QrRequestErrorKind, UUAuthClient};
|
||||
use crate::login_ui::{LoginUi, Tone};
|
||||
use serde_json::{json, Value};
|
||||
use std::time::Duration;
|
||||
@@ -127,6 +127,35 @@ fn render_qr(content: &str) -> Result<String, String> {
|
||||
/// API code for an expired login QR code.
|
||||
const QR_EXPIRED: i64 = 1190;
|
||||
|
||||
/// QR API errors must not echo server messages/validation fields: they may contain credentials.
|
||||
fn qr_data<'a>(stage: &str, status: u16, body: &'a Value) -> Result<&'a Value, String> {
|
||||
let code = body.get("code").and_then(Value::as_i64);
|
||||
if status == 200 && code == Some(0) { return Ok(body.get("data").unwrap_or(&Value::Null)); }
|
||||
Err(format!("{stage}: http_status={status} api_code={code:?}"))
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum QrPollAction { Wait(i64), Scanned, Confirmed, Refresh(Duration), Failed(&'static str) }
|
||||
|
||||
/// Preserve the official refresh policy; a failed query says nothing about QR expiry.
|
||||
fn qr_poll_action(last_status: i64, http_status: u16, body: &Value) -> QrPollAction {
|
||||
if body.get("code").and_then(Value::as_i64) == Some(QR_EXPIRED) {
|
||||
return QrPollAction::Failed("二维码已失效");
|
||||
}
|
||||
let Ok(data) = qr_data("qrcode status", http_status, body) else {
|
||||
return QrPollAction::Failed("二维码状态查询失败");
|
||||
};
|
||||
match data.get("status").and_then(Value::as_i64) {
|
||||
Some(1) => QrPollAction::Wait(1),
|
||||
Some(2) if last_status != 2 => QrPollAction::Scanned,
|
||||
Some(2) => QrPollAction::Wait(2),
|
||||
Some(0) => QrPollAction::Refresh(Duration::from_millis(350)),
|
||||
Some(3) => QrPollAction::Refresh(Duration::ZERO),
|
||||
Some(4) => QrPollAction::Confirmed,
|
||||
_ => QrPollAction::Failed("二维码状态响应异常"),
|
||||
}
|
||||
}
|
||||
|
||||
/// QR modules as RGBA pixels: `scale` pixels per module, `quiet` light modules around the code.
|
||||
fn qr_rgba(content: &str, scale: usize, quiet: usize) -> Result<(Vec<u8>, usize), String> {
|
||||
let code = qrcode::QrCode::new(content.as_bytes()).map_err(|e| format!("QR encode failed: {e}"))?;
|
||||
@@ -276,8 +305,16 @@ pub(crate) async fn flow(ui: &LoginUi) -> Result<String, String> {
|
||||
// every QR within seconds (#68).
|
||||
let timeout = Duration::from_secs(60);
|
||||
loop {
|
||||
let (status, resp) = client.post_with_timeout("/api/v1/qrcode/gen/login", None, timeout).await?;
|
||||
let d = match data("qrcode gen", status, &resp) {
|
||||
let (status, resp) = match client.post_with_timeout("/api/v1/qrcode/gen/login", None, timeout).await {
|
||||
Ok(r) => r,
|
||||
Err(e) if e.response_received() => {
|
||||
eprintln!("QR generation response failed: {e}");
|
||||
wait_for_refresh(ui, "二维码加载失败").await;
|
||||
continue;
|
||||
}
|
||||
Err(e) => return Err(format!("QR generation failed: {e}")),
|
||||
};
|
||||
let d = match qr_data("qrcode gen", status, &resp) {
|
||||
Ok(d) => d.clone(),
|
||||
Err(e) => { println!("QR code could not be loaded ({e})"); wait_for_refresh(ui, "二维码加载失败").await; continue; }
|
||||
};
|
||||
@@ -303,24 +340,42 @@ pub(crate) async fn flow(ui: &LoginUi) -> Result<String, String> {
|
||||
let query = json!({"token": ticket, "qrcode_jump_url": url, "login_status": login_status});
|
||||
let (status, resp) = match client.post_with_timeout("/api/v1/qrcode/login/status", Some(&query), timeout).await {
|
||||
Ok(r) => r,
|
||||
Err(_) => break "网络超时,二维码已停止刷新",
|
||||
Err(e) => {
|
||||
eprintln!("QR status query failed: {e}; last_status={login_status}");
|
||||
break match e.kind {
|
||||
QrRequestErrorKind::Timeout => "二维码状态查询超时(不代表二维码已失效)",
|
||||
_ => "二维码状态查询失败(不代表二维码已失效)",
|
||||
};
|
||||
}
|
||||
};
|
||||
let code = resp.get("code").and_then(|c| c.as_i64());
|
||||
if code == Some(QR_EXPIRED) { break "二维码已失效"; }
|
||||
let Ok(d) = data("qrcode status", status, &resp) else { break "二维码状态查询失败"; };
|
||||
let st = d.get("status").and_then(|v| v.as_i64()).unwrap_or(login_status);
|
||||
match st {
|
||||
1 => {}
|
||||
2 => if login_status != 2 {
|
||||
match qr_poll_action(login_status, status, &resp) {
|
||||
QrPollAction::Wait(st) => {
|
||||
if st == 1 && login_status != 1 { ui.status("等待扫码…", Tone::Info); }
|
||||
login_status = st;
|
||||
}
|
||||
QrPollAction::Scanned => {
|
||||
login_status = 2;
|
||||
println!("已扫码,请在手机上确认 (scanned, confirm on the phone)");
|
||||
ui.status("已扫码,请在手机上确认登录", Tone::Ok);
|
||||
},
|
||||
3 => { println!("QR code expired; generating a new one"); break ""; }
|
||||
0 => { tokio::time::sleep(Duration::from_millis(350)).await; break ""; }
|
||||
4 => {
|
||||
}
|
||||
QrPollAction::Refresh(delay) => {
|
||||
if delay.is_zero() { println!("QR code expired; generating a new one"); }
|
||||
else { tokio::time::sleep(delay).await; }
|
||||
break "";
|
||||
}
|
||||
QrPollAction::Confirmed => {
|
||||
println!("已确认,正在完成登录 (confirmed, completing login)");
|
||||
ui.status("已确认,正在完成登录…", Tone::Info);
|
||||
let body = json!({"token": ticket, "qrcode_jump_url": url});
|
||||
let (status, resp) = client.post_with_timeout("/api/v1/login/by_qrcode", Some(&body), timeout).await?;
|
||||
let d = match data("qrcode login", status, &resp) {
|
||||
let (status, resp) = match client.post_with_timeout("/api/v1/login/by_qrcode", Some(&body), timeout).await {
|
||||
Ok(r) => r,
|
||||
Err(e) if e.response_received() => {
|
||||
eprintln!("QR login exchange response failed: {e}");
|
||||
break "登录失败";
|
||||
}
|
||||
Err(e) => return Err(format!("QR login exchange failed: {e}")),
|
||||
};
|
||||
let d = match qr_data("qrcode login", status, &resp) {
|
||||
Ok(d) => d,
|
||||
Err(e) => { println!("QR login not granted ({e})"); break "登录失败"; }
|
||||
};
|
||||
@@ -339,9 +394,12 @@ pub(crate) async fn flow(ui: &LoginUi) -> Result<String, String> {
|
||||
println!("Logged in as {} ({}); saved to {}", nickname, user, path.display());
|
||||
return Ok(if nickname.is_empty() { user.to_string() } else { nickname.to_string() });
|
||||
}
|
||||
other => { println!("QR status: {other}"); break "二维码已失效"; }
|
||||
QrPollAction::Failed(reason) => {
|
||||
eprintln!("QR status query stopped: http_status={status} api_code={:?} status={:?} last_status={login_status}",
|
||||
resp.get("code").and_then(Value::as_i64), resp.get("data").and_then(|d| d.get("status")).and_then(Value::as_i64));
|
||||
break reason;
|
||||
}
|
||||
}
|
||||
login_status = st;
|
||||
};
|
||||
if !failure.is_empty() { wait_for_refresh(ui, failure).await; }
|
||||
}
|
||||
@@ -376,6 +434,37 @@ async fn wait_for_refresh(ui: &LoginUi, reason: &str) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn qr_poll_keeps_waiting_scanned_and_confirmed_distinct() {
|
||||
let reply = |status| json!({"code": 0, "data": {"status": status}});
|
||||
assert_eq!(qr_poll_action(1, 200, &reply(1)), QrPollAction::Wait(1));
|
||||
assert_eq!(qr_poll_action(1, 200, &reply(2)), QrPollAction::Scanned);
|
||||
assert_eq!(qr_poll_action(2, 200, &reply(2)), QrPollAction::Wait(2));
|
||||
assert_eq!(qr_poll_action(2, 200, &reply(4)), QrPollAction::Confirmed);
|
||||
assert_eq!(qr_poll_action(1, 200, &reply(0)), QrPollAction::Refresh(Duration::from_millis(350)));
|
||||
assert_eq!(qr_poll_action(2, 200, &reply(3)), QrPollAction::Refresh(Duration::ZERO));
|
||||
assert_eq!(qr_poll_action(2, 400, &json!({"code": 1190})), QrPollAction::Failed("二维码已失效"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qr_poll_failures_do_not_imply_expiry_or_confirmation() {
|
||||
for last in [1, 2] {
|
||||
for body in [json!(null), json!({"code": 1}), json!({"code": 0, "data": {"status": 4}})] {
|
||||
assert_eq!(qr_poll_action(last, 503, &body), QrPollAction::Failed("二维码状态查询失败"));
|
||||
}
|
||||
assert_eq!(qr_poll_action(last, 200, &json!({"code": 1})), QrPollAction::Failed("二维码状态查询失败"));
|
||||
for data in [json!(null), json!({}), json!({"status": "4"}), json!({"status": 99}), json!({"status": -1})] {
|
||||
assert_eq!(qr_poll_action(last, 200, &json!({"code": 0, "data": data})), QrPollAction::Failed("二维码状态响应异常"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qr_api_errors_do_not_echo_server_content() {
|
||||
let body = json!({"code": 1001, "msg": "fixture-token", "data": [{"loc": "fixture-ticket"}]});
|
||||
assert_eq!(qr_data("qrcode gen", 400, &body).unwrap_err(), "qrcode gen: http_status=400 api_code=Some(1001)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_ticket_prefers_status_query_ticket() {
|
||||
assert_eq!(qr_ticket(&json!({"token": "old", "status_query_ticket": "new"})), Some("new"));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! UU Remote Pure Native Linux Server (Rust Edition)
|
||||
//! Zero-Wine, Zero-Python, Single-Binary, 5 Native Tools Integrated
|
||||
|
||||
mod ws_transport;
|
||||
mod engine_plugin;
|
||||
mod doctor;
|
||||
mod wol;
|
||||
|
||||
+3
-9
@@ -7,7 +7,6 @@ use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio_tungstenite::connect_async;
|
||||
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
@@ -231,14 +230,8 @@ mod refresh_tests {
|
||||
async fn open_socket(
|
||||
req: tokio_tungstenite::tungstenite::handshake::client::Request,
|
||||
limit: Duration,
|
||||
) -> Result<tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>, String> {
|
||||
match tokio::time::timeout(limit, connect_async(req)).await {
|
||||
Ok(result) => result.map(|(ws, _)| ws).map_err(|e| format!("WS connect failed: {}", e)),
|
||||
Err(_) => {
|
||||
log::warn!("Signaling connect timed out after {}s", limit.as_secs());
|
||||
Err("WS connect timed out".into())
|
||||
}
|
||||
}
|
||||
) -> Result<crate::ws_transport::Socket, String> {
|
||||
crate::ws_transport::connect(req, limit).await
|
||||
}
|
||||
|
||||
impl SignalingClient {
|
||||
@@ -469,6 +462,7 @@ impl SignalingClient {
|
||||
log::info!("Cloud peer event: generation={} event={} age_s={} pings={} last_ping_gap_s={} ice_id_present={}",generation,event_name,started.elapsed().as_secs(),pings,last_ping.elapsed().as_secs(),data.get("ice_id").is_some());
|
||||
let ice_id = data.get("ice_id").and_then(|v| v.as_str()).unwrap_or("");
|
||||
if ice_id.is_empty() {
|
||||
log::info!("Cloud room leave shape: {}", crate::protocol::json_shape(data, 3));
|
||||
log::warn!("Cloud room leave without peer identifier; renewing signaling (expiry cause unknown)");
|
||||
if !send_event(&event_sender, SignalingEvent::Disconnected).await { break; }
|
||||
} else {
|
||||
|
||||
+11
-1
@@ -11,8 +11,14 @@ pub trait Decoder { fn set_codec(&mut self,codec:super::media::Codec)->Result<()
|
||||
pub trait FrameSink { fn present(&mut self,frame:&Frame)->Result<(),String>; }
|
||||
/// Counts only (access units, presented frames, decode errors) for the periodic stats line.
|
||||
pub static STATS:[std::sync::atomic::AtomicU64;3]=[std::sync::atomic::AtomicU64::new(0),std::sync::atomic::AtomicU64::new(0),std::sync::atomic::AtomicU64::new(0)];
|
||||
fn wants_key_frame(units:u64,presented:u64)->bool {presented==0 && units%30==0}
|
||||
pub fn display(decoder:&mut dyn Decoder,sink:&mut dyn FrameSink,au:&[u8],codec:super::media::Codec,pli:&AtomicBool)->Result<(),String> {
|
||||
STATS[0].fetch_add(1,Ordering::Relaxed);
|
||||
let units=STATS[0].fetch_add(1,Ordering::Relaxed)+1;
|
||||
// A later session can join a clean stream with no IDR in flight (#124): keep asking until a frame shows.
|
||||
if wants_key_frame(units,STATS[1].load(Ordering::Relaxed)) {
|
||||
pli.store(true,Ordering::Release);
|
||||
if units==300 { log::warn!("Viewer desktop: no decodable frame after {units} access units; requesting key frames (another session may hold the host)"); }
|
||||
}
|
||||
// Local diagnostic: UU_VIEWER_DUMP_H264=path appends the first 300 access units (owner's own stream).
|
||||
if codec==super::media::Codec::H264 && STATS[0].load(Ordering::Relaxed)<=300 { if let Some(path)=std::env::var_os("UU_VIEWER_DUMP_H264") {
|
||||
use std::io::Write; if let Ok(mut f)=std::fs::OpenOptions::new().create(true).append(true).open(path){let _=f.write_all(au);}
|
||||
@@ -32,5 +38,9 @@ pub fn display(decoder:&mut dyn Decoder,sink:&mut dyn FrameSink,au:&[u8],codec:s
|
||||
use super::*;
|
||||
struct Mock(bool);impl Decoder for Mock {fn set_codec(&mut self,_:crate::viewer::media::Codec)->Result<(),String>{Ok(())} fn decode(&mut self,_:&[u8])->Result<Vec<Frame>,String>{if self.0{Err("synthetic".into())}else{Ok(vec![Frame{width:1,height:1,rgb:vec![0;3],content:None}])}} fn reset(&mut self){self.0=false;}}
|
||||
struct Sink(usize);impl FrameSink for Sink{fn present(&mut self,f:&Frame)->Result<(),String>{assert_eq!(f.rgb.len(),3);self.0+=1;Ok(())}}
|
||||
#[test] fn requests_key_frames_until_the_first_frame(){
|
||||
assert_eq!((1..=90).filter(|&n|wants_key_frame(n,0)).count(),3);
|
||||
assert!(!(1..=90).any(|n|wants_key_frame(n,1)));
|
||||
}
|
||||
#[test] fn decode_error_requests_pli_and_recovers(){let mut d=Mock(true);let mut s=Sink(0);let p=AtomicBool::new(false);display(&mut d,&mut s,&[],crate::viewer::media::Codec::H264,&p).unwrap();assert!(p.load(Ordering::Acquire));display(&mut d,&mut s,&[],crate::viewer::media::Codec::H264,&p).unwrap();assert_eq!(s.0,1);}
|
||||
}
|
||||
@@ -3,13 +3,11 @@
|
||||
use base64::Engine as _;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::Value;
|
||||
use tokio::net::TcpStream;
|
||||
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};
|
||||
use tokio_tungstenite::tungstenite::{client::IntoClientRequest, Message};
|
||||
use std::{collections::VecDeque,time::Duration};
|
||||
|
||||
pub struct Signal {
|
||||
ws: WebSocketStream<MaybeTlsStream<TcpStream>>,
|
||||
ws: crate::ws_transport::Socket,
|
||||
next_ack:u64,
|
||||
pending:VecDeque<Value>,
|
||||
legacy_prefix:bool,
|
||||
@@ -17,14 +15,14 @@ pub struct Signal {
|
||||
impl Signal {
|
||||
pub async fn connect(urls:&[String], token:&str, timeout:Duration, legacy_prefix:bool)->Result<Self,String> {
|
||||
for url in urls {
|
||||
if let Ok(Ok(signal))=tokio::time::timeout(timeout,Self::one(url,token,legacy_prefix)).await {return Ok(signal)}
|
||||
if let Ok(Ok(signal))=tokio::time::timeout(timeout,Self::one(url,token,legacy_prefix,timeout)).await {return Ok(signal)}
|
||||
}
|
||||
Err("Signaling connection failed (details omitted)".into())
|
||||
}
|
||||
async fn one(url:&str,token:&str,legacy_prefix:bool)->Result<Self,String> {
|
||||
async fn one(url:&str,token:&str,legacy_prefix:bool,timeout:Duration)->Result<Self,String> {
|
||||
let mut request=format!("{}/socket.io/?transport=websocket&EIO=4",url.trim_end_matches('/')).into_client_request().map_err(|_|"Invalid signaling endpoint")?;
|
||||
request.headers_mut().insert("X-NRD-AUTH",token.parse().map_err(|_|"Invalid room authentication header")?);
|
||||
let (ws,_)=connect_async(request).await.map_err(|_|"Signaling transport failed")?;
|
||||
let ws=crate::ws_transport::connect(request,timeout).await?;
|
||||
let mut s=Self{ws,next_ack:10,pending:VecDeque::new(),legacy_prefix};
|
||||
let mut opened=false;
|
||||
loop {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#[path = "auth.rs"] mod auth;
|
||||
#[path = "config.rs"] mod config;
|
||||
#[path = "protocol.rs"] mod protocol;
|
||||
mod ws_transport;
|
||||
mod viewer;
|
||||
#[cfg(test)] #[path="hevc.rs"] mod hevc;
|
||||
use viewer::clipboard;
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Socket.IO's WebSocket transport uses the same opt-in proxy policy as the REST client.
|
||||
//! No proxy addresses, room headers, response text or underlying errors are displayed.
|
||||
use std::time::Duration;
|
||||
use reqwest::header::{HeaderMap, CONNECTION, UPGRADE, SEC_WEBSOCKET_ACCEPT, SEC_WEBSOCKET_KEY,
|
||||
SEC_WEBSOCKET_EXTENSIONS, SEC_WEBSOCKET_PROTOCOL};
|
||||
use tokio_tungstenite::{WebSocketStream, tungstenite::{handshake::{client::Request, derive_accept_key}, protocol::Role}};
|
||||
|
||||
pub type Socket = WebSocketStream<reqwest::Upgraded>;
|
||||
|
||||
/// Validate configuration rather than let reqwest silently ignore an unsupported proxy URL.
|
||||
/// Selection/NO_PROXY matching still belongs to reqwest, not a second proxy implementation.
|
||||
fn validate_proxy_url(value: &str) -> Result<(), &'static str> {
|
||||
if value.is_empty() { return Ok(()); }
|
||||
// Match reqwest's system-proxy parser before URL normalization (which would accept
|
||||
// whitespace/Unicode that http::Uri rejects and the connector would silently ignore).
|
||||
let uri: tokio_tungstenite::tungstenite::http::Uri = value.parse().map_err(|_| "Invalid signaling proxy configuration")?;
|
||||
if uri.authority().is_none() { return Err("Invalid signaling proxy configuration"); }
|
||||
let url = if value.contains("://") { reqwest::Url::parse(value) }
|
||||
else { reqwest::Url::parse(&format!("http://{value}")) }
|
||||
.map_err(|_| "Invalid signaling proxy configuration")?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none()
|
||||
|| url.port_or_known_default().is_none() || url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
|
||||
return Err("Unsupported signaling proxy configuration (HTTP/HTTPS only)");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn client() -> Result<reqwest::Client, String> {
|
||||
if crate::auth::proxy_enabled() {
|
||||
let mut configured = false;
|
||||
for names in [["HTTP_PROXY", "http_proxy"], ["HTTPS_PROXY", "https_proxy"], ["ALL_PROXY", "all_proxy"]] {
|
||||
if let Some(value) = names.iter().find_map(std::env::var_os) {
|
||||
let value = value.to_str().ok_or("Invalid signaling proxy configuration")?;
|
||||
validate_proxy_url(value)?;
|
||||
configured |= !value.is_empty();
|
||||
}
|
||||
}
|
||||
// reqwest disables environment proxies in CGI contexts; don't silently ignore an opt-in.
|
||||
if configured && std::env::var_os("REQUEST_METHOD").is_some() {
|
||||
return Err("Signaling environment proxies are disabled in CGI contexts".into());
|
||||
}
|
||||
}
|
||||
crate::auth::http_client_builder().http1_only().redirect(reqwest::redirect::Policy::none())
|
||||
.retry(reqwest::retry::never()).build().map_err(|_| "Signaling HTTP client setup failed".into())
|
||||
}
|
||||
|
||||
pub async fn connect(request: Request, timeout: Duration) -> Result<Socket, String> {
|
||||
let client = client()?;
|
||||
match tokio::time::timeout(timeout, connect_with_client(&client, request)).await {
|
||||
Ok(result) => result,
|
||||
Err(_) => Err("WS connect failed: timeout".into()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_with_client(client: &reqwest::Client, request: Request) -> Result<Socket, String> {
|
||||
let (mut parts, _) = request.into_parts();
|
||||
if parts.method != reqwest::Method::GET || parts.headers.contains_key(SEC_WEBSOCKET_EXTENSIONS)
|
||||
|| parts.headers.contains_key(SEC_WEBSOCKET_PROTOCOL) || parts.headers.contains_key("proxy-authorization") {
|
||||
return Err("Unsupported signaling WebSocket request".into());
|
||||
}
|
||||
let mut url = reqwest::Url::parse(&parts.uri.to_string()).map_err(|_| "Invalid signaling endpoint")?;
|
||||
if !url.username().is_empty() || url.password().is_some() || url.fragment().is_some() {
|
||||
return Err("Invalid signaling endpoint".into());
|
||||
}
|
||||
let scheme = match url.scheme() { "ws" => "http", "wss" => "https", _ => return Err("Unsupported signaling endpoint scheme".into()) };
|
||||
url.set_scheme(scheme).map_err(|_| "Invalid signaling endpoint")?;
|
||||
let key = parts.headers.get(SEC_WEBSOCKET_KEY).ok_or("Missing WebSocket handshake key")?;
|
||||
let accept = derive_accept_key(key.as_bytes());
|
||||
for name in ["x-nrd-auth", "authorization", "cookie"] {
|
||||
if let Some(value) = parts.headers.get_mut(name) { value.set_sensitive(true); }
|
||||
}
|
||||
// reqwest owns DNS/TCP/proxy CONNECT/TLS. No custom relay, direct fallback or redirect.
|
||||
let response = client.get(url).version(reqwest::Version::HTTP_11).headers(parts.headers).send().await
|
||||
.map_err(|e| if e.is_timeout() { "WS connect failed: timeout" } else if e.is_connect() { "WS connect failed: connection" } else { "WS connect failed: request" })?;
|
||||
if response.status() != reqwest::StatusCode::SWITCHING_PROTOCOLS {
|
||||
return Err(format!("WS upgrade refused: http_status={}", response.status().as_u16()));
|
||||
}
|
||||
verify_upgrade(response.version(), response.headers(), &accept)?;
|
||||
let stream = response.upgrade().await.map_err(|_| "WS upgrade failed")?;
|
||||
Ok(WebSocketStream::from_raw_socket(stream, Role::Client, None).await)
|
||||
}
|
||||
|
||||
/// RFC 6455 §4.1: validate before handing upgraded bytes to the frame codec. Socket.IO
|
||||
/// requests no extensions/subprotocols. Unlike a generic HTTP client we never follow redirects.
|
||||
fn verify_upgrade(version: reqwest::Version, headers: &HeaderMap, accept: &str) -> Result<(), &'static str> {
|
||||
let single = |name: reqwest::header::HeaderName| {
|
||||
let mut values = headers.get_all(name).iter();
|
||||
let value = values.next()?.to_str().ok()?;
|
||||
values.next().is_none().then_some(value)
|
||||
};
|
||||
let connection_upgrade = headers.get_all(CONNECTION).iter().all(|value| value.to_str().is_ok())
|
||||
&& headers.get_all(CONNECTION).iter().any(|value|
|
||||
value.to_str().is_ok_and(|value| value.split(',').any(|token| token.trim().eq_ignore_ascii_case("upgrade"))));
|
||||
if version != reqwest::Version::HTTP_11 || !connection_upgrade
|
||||
|| !single(UPGRADE).is_some_and(|v| v.eq_ignore_ascii_case("websocket"))
|
||||
|| single(SEC_WEBSOCKET_ACCEPT) != Some(accept)
|
||||
|| headers.contains_key(SEC_WEBSOCKET_EXTENSIONS) || headers.contains_key(SEC_WEBSOCKET_PROTOCOL) {
|
||||
return Err("Invalid signaling WebSocket upgrade response");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "ws_transport_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,245 @@
|
||||
use super::*;
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use tokio::{io::{AsyncRead, AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}};
|
||||
use tokio_tungstenite::tungstenite::{client::IntoClientRequest, Message};
|
||||
|
||||
fn request(url: &str) -> Request {
|
||||
let mut request = url.into_client_request().unwrap();
|
||||
request.headers_mut().insert("x-nrd-auth", "fixture-room-secret".parse().unwrap());
|
||||
request
|
||||
}
|
||||
|
||||
fn test_client() -> reqwest::ClientBuilder {
|
||||
reqwest::Client::builder().no_proxy().http1_only()
|
||||
.redirect(reqwest::redirect::Policy::none()).retry(reqwest::retry::never())
|
||||
}
|
||||
|
||||
async fn read_headers<S: AsyncRead + Unpin>(socket: &mut S) -> String {
|
||||
let mut bytes = Vec::new();
|
||||
while !bytes.ends_with(b"\r\n\r\n") {
|
||||
let mut byte = [0];
|
||||
socket.read_exact(&mut byte).await.unwrap();
|
||||
bytes.push(byte[0]);
|
||||
assert!(bytes.len() < 16384);
|
||||
}
|
||||
String::from_utf8(bytes).unwrap()
|
||||
}
|
||||
|
||||
fn header<'a>(request: &'a str, name: &str) -> Option<&'a str> {
|
||||
request.lines().filter_map(|line| line.split_once(':'))
|
||||
.find(|(key, _)| key.eq_ignore_ascii_case(name)).map(|(_, value)| value.trim())
|
||||
}
|
||||
|
||||
async fn accept_upgrade(listener: TcpListener, proxy: bool) -> TcpStream {
|
||||
let (mut socket, _) = listener.accept().await.unwrap();
|
||||
let received = read_headers(&mut socket).await;
|
||||
assert!(received.starts_with(if proxy { "GET http://" } else { "GET /" }));
|
||||
assert!(header(&received, "x-nrd-auth") == Some("fixture-room-secret"));
|
||||
if !proxy { assert!(header(&received, "proxy-authorization").is_none()); }
|
||||
let accept = derive_accept_key(header(&received, "sec-websocket-key").unwrap().as_bytes());
|
||||
let mut response = format!("HTTP/1.1 101 Switching Protocols\r\nConnection: keep-alive, Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept: {accept}\r\n\r\n").into_bytes();
|
||||
// The first Engine.IO frame shares a single write with the HTTP response.
|
||||
response.extend_from_slice(&[0x81, 3, b'0', b'{', b'}']);
|
||||
socket.write_all(&response).await.unwrap();
|
||||
socket
|
||||
}
|
||||
|
||||
async fn no_connection(listener: &TcpListener) {
|
||||
assert!(tokio::time::timeout(Duration::from_millis(150), listener.accept()).await.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_upgrade_validation_accepts_tokens_and_rejects_unsolicited_or_ambiguous_headers() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(CONNECTION, "keep-alive, Upgrade".parse().unwrap());
|
||||
headers.insert(UPGRADE, "WebSocket".parse().unwrap());
|
||||
headers.insert(SEC_WEBSOCKET_ACCEPT, "fixture-accept".parse().unwrap());
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_11, &headers, "fixture-accept").is_ok());
|
||||
headers.append(CONNECTION, "keep-alive".parse().unwrap());
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_11, &headers, "fixture-accept").is_ok());
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_2, &headers, "fixture-accept").is_err());
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_11, &headers, "wrong").is_err());
|
||||
for name in [CONNECTION, UPGRADE, SEC_WEBSOCKET_ACCEPT] {
|
||||
let mut missing = headers.clone(); missing.remove(name);
|
||||
assert!(verify_upgrade(reqwest::Version::HTTP_11, &missing, "fixture-accept").is_err());
|
||||
}
|
||||
for name in [UPGRADE, SEC_WEBSOCKET_ACCEPT, SEC_WEBSOCKET_EXTENSIONS, SEC_WEBSOCKET_PROTOCOL] {
|
||||
let mut invalid = headers.clone(); invalid.append(name, "fixture-server-secret".parse().unwrap());
|
||||
let error = verify_upgrade(reqwest::Version::HTTP_11, &invalid, "fixture-accept").unwrap_err();
|
||||
assert!(!error.contains("fixture"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_configuration_errors_never_echo_proxy_values() {
|
||||
for proxy in ["", "127.0.0.1:3128", "http://127.0.0.1:3128", "https://fixture-user:[email protected]:3128"] {
|
||||
assert!(validate_proxy_url(proxy).is_ok());
|
||||
}
|
||||
for proxy in ["socks5://fixture-user:[email protected]:3128", "http://127.0.0.1:3128/?fixture-token", "http://127.0.0.1:3128/#fixture-token", "http://127.0.0.1:3128/fixture-secret", "http://[fixture-invalid", " http://127.0.0.1:3128", "http://127.0.0.1:3128 ", "http://例子.invalid:3128"] {
|
||||
let error = validate_proxy_url(proxy).unwrap_err();
|
||||
assert!(!error.contains("fixture"));
|
||||
assert!(!error.contains("127.0.0.1"));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn upgrade_keeps_prefetched_frame_and_does_not_limit_socket_lifetime() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/socket.io/?fixture-query-secret", listener.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let socket = accept_upgrade(listener, false).await;
|
||||
let mut socket = WebSocketStream::from_raw_socket(socket, Role::Server, None).await;
|
||||
tokio::time::sleep(Duration::from_millis(1200)).await;
|
||||
assert!(matches!(socket.next().await, Some(Ok(Message::Text(value))) if value == "fixture-client-frame"));
|
||||
socket.send(Message::Text("fixture-late-frame".into())).await.unwrap();
|
||||
});
|
||||
let http = test_client().build().unwrap();
|
||||
let mut socket = tokio::time::timeout(Duration::from_secs(1), connect_with_client(&http, request(&url))).await.unwrap().unwrap();
|
||||
assert!(matches!(socket.next().await, Some(Ok(Message::Text(value))) if value == "0{}"));
|
||||
// A one-second establishment deadline must not remain attached to the upgraded stream.
|
||||
tokio::time::sleep(Duration::from_millis(1300)).await;
|
||||
socket.send(Message::Text("fixture-client-frame".into())).await.unwrap();
|
||||
let message = tokio::time::timeout(Duration::from_secs(3), socket.next()).await.unwrap();
|
||||
assert!(matches!(message, Some(Ok(Message::Text(value))) if value == "fixture-late-frame"));
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn proxy_refusal_never_falls_back_to_origin_or_echoes_server_content() {
|
||||
let origin = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy_url = format!("http://{}", proxy.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = proxy.accept().await.unwrap();
|
||||
let received = read_headers(&mut socket).await;
|
||||
assert!(received.starts_with("GET http://"));
|
||||
assert!(header(&received, "proxy-authorization").is_some());
|
||||
socket.write_all(b"HTTP/1.1 407 Proxy Authentication Required\r\nContent-Length: 19\r\n\r\nfixture-body-secret").await.unwrap();
|
||||
});
|
||||
let proxy = reqwest::Proxy::all(proxy_url).unwrap().basic_auth("fixture-user", "fixture-proxy-secret");
|
||||
let http = test_client().proxy(proxy).build().unwrap();
|
||||
let result = tokio::time::timeout(Duration::from_secs(5),
|
||||
connect_with_client(&http, request(&format!("ws://{}/fixture-path-secret", origin.local_addr().unwrap()))))
|
||||
.await.expect("proxy refusal must not wait on a fallback origin");
|
||||
let error = result.err().expect("proxy refusal must fail");
|
||||
assert!(error.contains("407")); assert!(!error.contains("fixture"));
|
||||
no_connection(&origin).await;
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn redirects_are_not_followed_with_room_credentials() {
|
||||
let origin = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let destination = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/socket.io/", origin.local_addr().unwrap());
|
||||
let location = format!("http://{}/fixture-redirect-secret", destination.local_addr().unwrap());
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = origin.accept().await.unwrap();
|
||||
let _ = read_headers(&mut socket).await;
|
||||
socket.write_all(format!("HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\n\r\n").as_bytes()).await.unwrap();
|
||||
});
|
||||
let result = tokio::time::timeout(Duration::from_secs(5),
|
||||
connect_with_client(&test_client().build().unwrap(), request(&url)))
|
||||
.await.expect("redirect must not wait on its destination");
|
||||
let error = result.err().expect("redirect must fail");
|
||||
assert!(error.contains("302")); assert!(!error.contains("fixture"));
|
||||
no_connection(&destination).await;
|
||||
server.await.unwrap();
|
||||
}
|
||||
|
||||
// No global environment mutation: the subprocess has only synthetic loopback configuration.
|
||||
#[test]
|
||||
fn environment_policy_probe() {
|
||||
let Ok(url) = std::env::var("UU_WS_TEST_ENDPOINT") else { return; };
|
||||
assert!(url.starts_with("ws://127.0.0.1:"));
|
||||
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
|
||||
runtime.block_on(async {
|
||||
let mut socket = connect(request(&url), Duration::from_secs(5)).await.expect("fixture connection failed");
|
||||
let message = tokio::time::timeout(Duration::from_secs(3), socket.next()).await.unwrap();
|
||||
assert!(matches!(message, Some(Ok(Message::Text(value))) if value == "0{}"));
|
||||
});
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn environment_proxy_opt_in_and_no_proxy_match_rest_policy() {
|
||||
for (opt_in, bypass, via_proxy) in [(false, false, false), (true, false, true), (true, true, false)] {
|
||||
let origin = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let url = format!("ws://{}/socket.io/", origin.local_addr().unwrap());
|
||||
let proxy_url = format!("http://fixture-user:fixture-proxy-secret@{}", proxy.local_addr().unwrap());
|
||||
let (selected, unused) = if via_proxy { (proxy, origin) } else { (origin, proxy) };
|
||||
let server = tokio::spawn(async move { let _socket = accept_upgrade(selected, via_proxy).await; });
|
||||
let mut child = tokio::process::Command::new(std::env::current_exe().unwrap());
|
||||
child.args(["--exact", "ws_transport::tests::environment_policy_probe", "--nocapture"])
|
||||
.env_clear().env("UU_WS_TEST_ENDPOINT", url).env("HTTP_PROXY", proxy_url);
|
||||
if opt_in { child.env("UU_USE_PROXY", "1"); }
|
||||
if bypass { child.env("NO_PROXY", "127.0.0.1"); }
|
||||
let output = tokio::time::timeout(Duration::from_secs(10), child.output()).await.unwrap().unwrap();
|
||||
assert!(output.status.success(), "isolated proxy-policy subprocess failed");
|
||||
assert!(!output.stdout.windows(b"fixture-room-secret".len()).any(|s| s == b"fixture-room-secret"));
|
||||
assert!(!output.stderr.windows(b"fixture-proxy-secret".len()).any(|s| s == b"fixture-proxy-secret"));
|
||||
no_connection(&unused).await;
|
||||
server.await.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wss_connect_keeps_origin_auth_inside_tls_and_requires_trusted_certificate() {
|
||||
use std::sync::Arc;
|
||||
use tokio_rustls::{rustls, TlsAcceptor};
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||
// A fresh test certificate/key, kept only in memory. The mock does not relay anywhere:
|
||||
// it accepts CONNECT and then speaks TLS + WebSocket on that same loopback socket.
|
||||
let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
|
||||
let cert_der = cert.serialize_der().unwrap();
|
||||
let root = reqwest::Certificate::from_der(&cert_der).unwrap();
|
||||
let config = rustls::ServerConfig::builder_with_provider(Arc::new(rustls::crypto::ring::default_provider()))
|
||||
.with_safe_default_protocol_versions().unwrap().with_no_client_auth()
|
||||
.with_single_cert(vec![CertificateDer::from(cert_der)],
|
||||
PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(cert.serialize_private_key_der()))).unwrap();
|
||||
let acceptor = TlsAcceptor::from(Arc::new(config));
|
||||
for trusted in [false, true] {
|
||||
let origin = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let proxy = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let port = origin.local_addr().unwrap().port();
|
||||
let proxy_url = format!("http://{}", proxy.local_addr().unwrap());
|
||||
let acceptor = acceptor.clone();
|
||||
let server = tokio::spawn(async move {
|
||||
let (mut socket, _) = proxy.accept().await.unwrap();
|
||||
let received = read_headers(&mut socket).await;
|
||||
assert!(received.starts_with(&format!("CONNECT localhost:{port} HTTP/1.1\r\n")));
|
||||
assert!(header(&received, "x-nrd-auth").is_none());
|
||||
assert!(header(&received, "proxy-authorization").is_some());
|
||||
assert!(!received.contains("fixture-room-secret"));
|
||||
socket.write_all(b"HTTP/1.1 200 Connection Established\r\n\r\n").await.unwrap();
|
||||
let tls = acceptor.accept(socket).await;
|
||||
if !trusted { assert!(tls.is_err()); return; }
|
||||
let mut tls = tls.expect("fixture TLS handshake failed");
|
||||
let received = read_headers(&mut tls).await;
|
||||
assert!(received.starts_with("GET /socket.io/"));
|
||||
assert!(header(&received, "x-nrd-auth") == Some("fixture-room-secret"));
|
||||
assert!(header(&received, "proxy-authorization").is_none());
|
||||
assert!(!received.contains("fixture-proxy-secret"));
|
||||
let accept = derive_accept_key(header(&received, "sec-websocket-key").unwrap().as_bytes());
|
||||
let mut response = format!("HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Accept: {accept}\r\n\r\n").into_bytes();
|
||||
response.extend_from_slice(&[0x81, 3, b'0', b'{', b'}']);
|
||||
tls.write_all(&response).await.unwrap();
|
||||
});
|
||||
let proxy = reqwest::Proxy::all(proxy_url).unwrap().basic_auth("fixture-user", "fixture-proxy-secret");
|
||||
let mut builder = test_client().proxy(proxy);
|
||||
if trusted { builder = builder.add_root_certificate(root.clone()); }
|
||||
let client = builder.build().unwrap();
|
||||
let result = tokio::time::timeout(Duration::from_secs(5),
|
||||
connect_with_client(&client, request(&format!("wss://localhost:{port}/socket.io/?fixture-query-secret")))).await.unwrap();
|
||||
if trusted {
|
||||
let mut socket = result.expect("trusted fixture WebSocket failed");
|
||||
let message = tokio::time::timeout(Duration::from_secs(3), socket.next()).await.unwrap();
|
||||
assert!(matches!(message, Some(Ok(Message::Text(value))) if value == "0{}"));
|
||||
} else {
|
||||
let error = result.err().expect("untrusted fixture certificate must fail");
|
||||
assert!(!error.contains("fixture")); assert!(!error.contains("localhost"));
|
||||
}
|
||||
no_connection(&origin).await;
|
||||
tokio::time::timeout(Duration::from_secs(5), server).await.unwrap().unwrap();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user