Bring PS5 GTA6 to 120FPS with DLSS 5. An advanced Windows video player and capture enhancement tool featuring real-time preview for videos, images, and capture card sources. Combine AI-powered Super Resolution, DLSS5 image enhancement, and Frame Generation to deliver a next-generation visual experience.
C++
feat(moonlight): protocol layer for Moonlight / Sunshine hosts (S0-S1)
Veyra Goal Agent9d9de895faca
diff --git a/AGENTS.md b/AGENTS.mdindex ff2ec0ae..9d44c0dd 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -1,5 +1,7 @@# Veyra 项目 Agent 执行规则+> **2026-10-01 Moonlight(PC 串流)接入授权(用户:“不用,我有用户有双机,你就先干Moonlight吧,开工”;并同意下载官方源码、按阶段在新分支提交)**:在 `E:/项目/Veyra/worktrees/moonlight-20261001` 的新分支 `codex/moonlight-20261001`(从 `main` `09392c4` 开出)按 `docs/STREAMING_PLAN_MOONLIGHT_XBOX_2026-10-01.md` 与 `docs/MOONLIGHT_EXECUTION_2026-10-01.md` 实现串流核心:新增 `src/moonlight`、`include/veyra/moonlight`、`cmake/VeyraMoonlight.cmake`、`scripts/moonlight`、`tests/moonlight`,以及接入所必需的来源类、引擎/桥接/QML 接点;只接入串流核心,效果器沿用现有同一条处理链,不为串流另设预设或开关。PS5、采集卡等既有来源路径不改行为。已按用户授权从 GitHub 下载并固定两个官方源码到 `E:/项目/Veyra/deps/moonlight/`:moonlight-common-c `f900dd4767759c7b9d0e93bcea666b55c69ea62f`(含 enet `aca87840…`、nanors `b1e3c22c…`)与 moonlight-qt 浅克隆 `8369d1a0e11b999d4d1598f62ca5f6dea49602fb`(仅作移植参考,不编译)。**不下载、不安装、不连接 Sunshine 或任何主机**(用户明确“不用”,真机互通由用户的双机测试者验证);Xbox 仍只做调研。可在该分支按阶段 commit;不合并 main、不 push、不 Release、不碰桌面原目录。真机互通、4K60 实测与运动画面未验前,不得称 Moonlight 已通过。+> **2026-10-01 2.0.0 合并 main 授权(用户:“基本上2.0.0已经没啥问题了,剩下一些小bug和功能我后面再和你对,现在分支有点多……先合并一手,存档一下,更新更新文档,对齐目前进度”)**:整理 2.0.0 各分支并合并到**本地** `main`;先存档到 `E:/项目/Veyra/archives/merge-2.0.0-20261001/`(全引用 git bundle、合并前两处未提交状态、SHA256),打 `checkpoint/pre-merge-2.0.0-main-20261001`、`checkpoint/2.0.0-branch-tip-20261001`、`checkpoint/merged-2.0.0-20261001` 标签,合并后更新文档。授权范围:commit、打标签、本地 `--no-ff` 合并、删除已并入 `main` 且指向同一提交的重复分支名。**不含** push、GitHub Release、Runtime Pack 上传、删除旧 Win32 界面、删除 worktree 或用户文件、改动桌面原目录;这些仍需另行授权。此后 2.0.0 的新工作从 `main` 另开分支;本文件此前条目中的 `codex/*-2026092x/30` 阶段分支名均已并入 `main`,见 `docs/BRANCH_MAP_2026-10-01.md`。> **2026-09-30 真人反馈修复授权**:先存档,再将 RTX40 NR 改为 SF-v2、RTX50 保留 Lecram,NR 节点提供双版本选择,淘汰新候选中的旧40运行库;随后按用户指定 `FIX_PLAN_1.4.4_FIELD_ISSUES_2026-09-30.md` 排查修复。仅在 E 盘 `p0-p1-r53-20260927`、新分支 `codex/field-issues-20260930`;保留当前 FSR/XeSS 和全部既有改动。必要的 NR 选择/配置迁移、GPU 故障、呈现、采集协商、HDR/比例/运动输入、分辨率/导出反馈修复接点获本轮授权,覆盖这些接点的历史冻结;无关改造仍冻结。范围、存档和验收见 `docs/FIELD_ISSUES_EXECUTION_2026-09-30.md`。原桌面 checkout、main、原 beta/历史发布/下载原件保留;不 commit/tag/merge/push/Release,不派子 Agent。新候选可原样使用已批准 Lecram/SF-v2,不 patch、不入源码 Git。diff --git a/CMakeLists.txt b/CMakeLists.txtindex ae97972b..00a35c33 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -48,6 +48,7 @@ set(VEYRA_CLIP_TOOLS_ROOT "" CACHE PATH "vcpkg-installed x64-windows root with ooption(VEYRA_ENABLE_EXPERIMENTAL_DLSSNR"Enable local-only experimental Feature 18 adapter" OFF)option(VEYRA_ENABLE_REMOTEPLAY "Build PS5 Remote Play with pinned Chiaki source" OFF)+option(VEYRA_ENABLE_MOONLIGHT "Build the Moonlight / Sunshine streaming core (pinned moonlight-common-c)" OFF)option(VEYRA_ENABLE_DLSS_SR "Enable public DLSS SR backend" OFF)option(VEYRA_ENABLE_DLSS_FG "Enable public DLSSG backend" OFF)option(VEYRA_ENABLE_NVOF "Enable NVIDIA Optical Flow guidance" OFF)@@ -60,6 +61,17 @@ list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")include(VeyraWarnings)include(VeyraShaders)+if(VEYRA_ENABLE_MOONLIGHT)+ set(VEYRA_ROOT "${CMAKE_CURRENT_SOURCE_DIR}")+ include(VeyraMoonlight)+ veyra_apply_warnings(veyra_moonlight_protocol)+ add_executable(veyra_moonlight_protocol_tests tests/moonlight/ProtocolTests.cpp)+ target_compile_features(veyra_moonlight_protocol_tests PRIVATE cxx_std_20)+ target_compile_definitions(veyra_moonlight_protocol_tests PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+ target_link_libraries(veyra_moonlight_protocol_tests PRIVATE veyra_moonlight_protocol)+ veyra_apply_warnings(veyra_moonlight_protocol_tests)+endif()+# NVIDIA's static NGX core shim (nvsdk_ngx_s*.lib) is built against the# static CRT (MT/MTd); match it for the diagnostic tools that link it.set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.mdindex b667278e..60f046fe 100644--- a/THIRD_PARTY_NOTICES.md+++ b/THIRD_PARTY_NOTICES.md@@ -573,3 +573,25 @@ ingress. DXGI duplication is a Veyra addition. Screen capture is video-only.## dav1d (1.3.0 AV1 playback)FFmpeg dynamically links dav1d 1.5.4 from the pinned local vcpkg build. The portable package includes its complete aggregated copyright/license text in `licenses/DAV1D-COPYRIGHT.txt` and provenance in `licenses/DAV1D-SPDX.json`. The FFmpeg corresponding-source ZIP includes dav1d source and its vcpkg port. Upstream: https://code.videolan.org/videolan/dav1d . License set recorded by the build: Apache-2.0, BSD-2-Clause, ISC and MIT; retain all notices supplied with the source.++## Moonlight / GameStream streaming core (2026-10-01)++The optional `VEYRA_ENABLE_MOONLIGHT` build compiles **moonlight-common-c** (GPL-3.0,+https://github.com/moonlight-stream/moonlight-common-c) at commit+`f900dd4767759c7b9d0e93bcea666b55c69ea62f` (2026-09-26) together with its two pinned submodules:+ENet (MIT, https://github.com/cgutman/enet, `aca87840b57f045a1f7f9299e4b1b9b8e2a5e2f1`) and+nanors (MIT, https://github.com/sleepybishop/nanors, `b1e3c22ca0cdc0bb83e3cd6ed1a2fc77869ed99a`).+The build refuses any other checkout (`scripts/moonlight/verify-moonlight-stage.py`, pins in+`scripts/moonlight/dependency-lock.json`). No Moonlight or Sunshine binary is committed or bundled.++The host HTTP(S) client, the pairing handshake and the serverinfo / applist / launch handling in+`src/moonlight/` and `include/veyra/moonlight/` are a port of **moonlight-qt** (GPL-3.0,+https://github.com/moonlight-stream/moonlight-qt, commit `8369d1a0e11b999d4d1598f62ca5f6dea49602fb`):+`app/backend/nvhttp.cpp`, `nvpairingmanager.cpp`, `identitymanager.cpp`, `nvcomputer.cpp` and the default+bitrate table of `app/streaming/session.cpp`, with the Qt types replaced by standard C++, OpenSSL and Winsock.+Nothing from the moonlight-qt tree is compiled. The OpenSSL (Apache-2.0) and Opus (BSD-3-Clause) libraries come+from the same vcpkg tree as the PS5 build. Veyra is GPL-3.0, which is compatible with all of the above.+License texts: `licenses/moonlight/ENET_MIT.txt`, `licenses/moonlight/NANORS_MIT.txt`; the GPL-3.0 text is Veyra's own `LICENSE`.++The streamed machine runs **Sunshine** (GPL-3.0, https://github.com/LizardByte/Sunshine), which users install+themselves; Veyra neither ships nor downloads it.diff --git a/cmake/VeyraMoonlight.cmake b/cmake/VeyraMoonlight.cmakenew file mode 100644index 00000000..dcb3a95f--- /dev/null+++ b/cmake/VeyraMoonlight.cmake@@ -0,0 +1,58 @@+include_guard(GLOBAL)+# Moonlight / GameStream streaming core.+#+# veyra_moonlight_common_c moonlight-common-c (GPL-3.0) + its pinned ENet and nanors, built from+# the exact checkout named in scripts/moonlight/dependency-lock.json+# veyra_moonlight_protocol host HTTP(S) client, pairing, identity (Qt-free, OpenSSL + Winsock)+#+# Nothing is downloaded by the build: VEYRA_MOONLIGHT_SOURCE_DIR must point at a checkout that passes+# scripts/moonlight/verify-moonlight-stage.py. Sunshine, the host, is never part of this build.+set(VEYRA_MOONLIGHT_SOURCE_DIR "" CACHE PATH "Pinned moonlight-common-c checkout (with submodules)")+if(NOT EXISTS "${VEYRA_MOONLIGHT_SOURCE_DIR}/src/Limelight.h")+ message(FATAL_ERROR "VEYRA_ENABLE_MOONLIGHT needs VEYRA_MOONLIGHT_SOURCE_DIR to be the pinned moonlight-common-c checkout")+endif()+find_package(Python3 REQUIRED COMPONENTS Interpreter)+execute_process(+ COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/moonlight/verify-moonlight-stage.py"+ --source "${VEYRA_MOONLIGHT_SOURCE_DIR}" --lock "${CMAKE_CURRENT_SOURCE_DIR}/scripts/moonlight/dependency-lock.json"+ RESULT_VARIABLE MOONLIGHT_VERIFY_RESULT OUTPUT_VARIABLE MOONLIGHT_VERIFY_OUTPUT ERROR_VARIABLE MOONLIGHT_VERIFY_ERROR)+if(NOT MOONLIGHT_VERIFY_RESULT EQUAL 0)+ message(FATAL_ERROR "moonlight-common-c verification failed: ${MOONLIGHT_VERIFY_OUTPUT} ${MOONLIGHT_VERIFY_ERROR}")+endif()+string(STRIP "${MOONLIGHT_VERIFY_OUTPUT}" MOONLIGHT_VERIFY_OUTPUT)+message(STATUS "${MOONLIGHT_VERIFY_OUTPUT}")++find_package(OpenSSL REQUIRED)++# ENet as shipped with moonlight-common-c (a fork with IPv6 and retransmission changes).+set(ENET_NO_INSTALL ON CACHE BOOL "" FORCE)+add_subdirectory("${VEYRA_MOONLIGHT_SOURCE_DIR}/enet" "${CMAKE_CURRENT_BINARY_DIR}/moonlight-enet" EXCLUDE_FROM_ALL)++file(GLOB VEYRA_MOONLIGHT_C_SOURCES "${VEYRA_MOONLIGHT_SOURCE_DIR}/src/*.c")+list(APPEND VEYRA_MOONLIGHT_C_SOURCES+ "${VEYRA_MOONLIGHT_SOURCE_DIR}/nanors/rs.c"+ "${VEYRA_MOONLIGHT_SOURCE_DIR}/nanors/deps/obl/oblas_common.c"+ "${VEYRA_MOONLIGHT_SOURCE_DIR}/nanors/deps/obl/oblas_lite.c")+add_library(veyra_moonlight_common_c STATIC ${VEYRA_MOONLIGHT_C_SOURCES})+set_target_properties(veyra_moonlight_common_c PROPERTIES C_STANDARD 11 C_EXTENSIONS OFF)+target_include_directories(veyra_moonlight_common_c SYSTEM PUBLIC "${VEYRA_MOONLIGHT_SOURCE_DIR}/src")+target_include_directories(veyra_moonlight_common_c SYSTEM PRIVATE+ "${VEYRA_MOONLIGHT_SOURCE_DIR}/nanors"+ "${VEYRA_MOONLIGHT_SOURCE_DIR}/nanors/deps"+ "${VEYRA_MOONLIGHT_SOURCE_DIR}/nanors/deps/obl")+target_compile_definitions(veyra_moonlight_common_c PRIVATE HAS_SOCKLEN_T NDEBUG)+target_compile_options(veyra_moonlight_common_c PRIVATE /W3 /wd4100 /wd4232 /wd5105)+target_link_libraries(veyra_moonlight_common_c PRIVATE enet OpenSSL::Crypto ws2_32 winmm)++add_library(veyra_moonlight_protocol STATIC+ "${VEYRA_ROOT}/src/moonlight/Xml.cpp"+ "${VEYRA_ROOT}/src/moonlight/Crypto.cpp"+ "${VEYRA_ROOT}/src/moonlight/Http.cpp"+ "${VEYRA_ROOT}/src/moonlight/Client.cpp"+ "${VEYRA_ROOT}/src/moonlight/Pairing.cpp"+ "${VEYRA_ROOT}/src/moonlight/IdentityStore.cpp")+target_compile_features(veyra_moonlight_protocol PUBLIC cxx_std_20)+set_target_properties(veyra_moonlight_protocol PROPERTIES CXX_EXTENSIONS OFF)+target_compile_definitions(veyra_moonlight_protocol PRIVATE NOMINMAX WIN32_LEAN_AND_MEAN)+target_include_directories(veyra_moonlight_protocol PUBLIC "${VEYRA_ROOT}/include")+target_link_libraries(veyra_moonlight_protocol PUBLIC OpenSSL::SSL OpenSSL::Crypto PRIVATE ws2_32 crypt32 shell32 ole32 advapi32 user32)diff --git a/docs/MOONLIGHT_EXECUTION_2026-10-01.md b/docs/MOONLIGHT_EXECUTION_2026-10-01.mdnew file mode 100644index 00000000..5c75f6eb--- /dev/null+++ b/docs/MOONLIGHT_EXECUTION_2026-10-01.md@@ -0,0 +1,46 @@+# Moonlight(PC 串流)接入执行记录++方案:`docs/STREAMING_PLAN_MOONLIGHT_XBOX_2026-10-01.md`。分支 `codex/moonlight-20261001`(从 `main` `09392c4` 开出)。范围与授权见 `AGENTS.md` 2026-10-01 条。++**边界(用户 2026-10-01 明确)**:接入的只是串流核心(协议、解码、音频、输入、主机与游戏选择界面)。NR / SR / 补帧 / 调色沿用现有同一条处理链,开关与默认值(补帧本来默认关)不为串流另设。Moonlight 协议本身支持 4K60,实际上限看主机编码器、网络与本机解码。++**验证边界**:我不安装、不连接 Sunshine 或任何主机。下面的"通过"只指离线测试(模拟主机、固件、已知答案测试);与真实 Sunshine 的互通、4K60、延迟、运动画面、手柄键鼠都要由有双机的测试者验证,未验前不得称通过。++## 阶段++| 阶段 | 内容 | 状态 |+|---|---|---|+| S0 | 依赖固定(`scripts/moonlight/dependency-lock.json` + 校验脚本)、CMake 开关、许可记录 | 完成 |+| S1 | 协议层(Qt 无关):XML、加密、HTTP(S)、主机请求、配对、身份存储 | 完成,离线测试 69 项通过 |+| S2 | 会话来源:`LiStartConnection`、视频解码、音频、遥测、引擎接入 | 未开始 |+| S3 | 输入:手柄、键鼠捕获、保留键 | 未开始 |+| S4 | 前端:首页卡片、PC 串流页、配对对话框、设置、串流中 UI | 未开始 |+| S5 | 质量:HDR、AV1、丢包与重连、稳定性 | 未开始 |++## S0/S1 记录++**依赖**(均按 GPL-3.0 移植/使用,记录在 `THIRD_PARTY_NOTICES.md`)+- moonlight-common-c `f900dd47…`,含 enet `aca87840…`、nanors `b1e3c22c…`;构建前由 `verify-moonlight-stage.py` 校验,提交号或未记录的改动都会拒绝构建。+- moonlight-qt `8369d1a0…`:仅作移植参考。其自带的 common-c 子模块指针 `478e79b9…` 在上游已取不到(`not our ref`),但 moonlight-qt 代码已使用我们固定版本的新接口(`MODIFIER_EXTENDED`、`LI_CTYPE_STEAM`、`LiSendControllerTouchEvent2`),二者配套。+- 构建依赖来自已有的 vcpkg 静态树:OpenSSL 3.6.4、Opus;没有新增第三方二进制。++**设计决定**+1. 协议层不用 Qt、不用 curl:现有 curl 是 Chiaki 自带的(系统 TLS,不支持客户端证书)。直接用 OpenSSL 写很小的 HTTP(S) 客户端(Winsock 非阻塞 + 截止时间 + 取消标志),可离线单测,引擎库保持 Qt 无关。+2. 证书固定:握手后、发出任何请求前,比较服务器证书与配对时保存的证书,不符即拒绝(`TransportError::Kind::Tls`);没有固定证书时拒绝发 HTTPS。+3. `serverinfo` 逻辑照搬 moonlight-qt:有固定证书先走 HTTPS,遇 401 或 TLS 失败回落 HTTP;未配对只走 HTTP 并取 HTTPS 端口。+4. 配对五步按 moonlight-qt 的 `NvPairingManager` 移植(盐 + PIN → AES-128 密钥,代数 7 起 SHA-256,之前 SHA-1);失败路径都会通知主机 `unpair`;取消不会留下半完成的配对。+5. 客户端身份(RSA-2048 自签证书 + 私钥 + 唯一 id)用 DPAPI 加密存于 `%LOCALAPPDATA%\Veyra\moonlight\`,原子写入;私钥不进日志。+6. 设备名用 `Veyra`(moonlight-qt 用历史遗留的 `roth`),这样 Sunshine 的已配对客户端列表里能认出。**这是与上游不同之处,真机互通时要留意**;若有主机拒绝,改回常量 `kDeviceName`。+7. 解析器是只读小型 XML 读取器,限制 1 MB 与 32 层嵌套,只支持五个预定义实体和数字字符引用。++**验证(离线)**+- `veyra_moonlight_protocol_tests`:69 项通过,连续运行 10 次无失败。覆盖:XML 解析与畸形输入、实体与空标题、状态码(含 GFE 特例);AES-128 已知答案(FIPS-197)、SHA-256/SHA-1 已知答案、签名校验;身份创建与 DPAPI 存取(文件内无明文私钥、损坏文件被拒);一个模拟主机(实现主机一侧的五步配对、TLS 双向证书、三种 HTTP 分帧):配对成功、错 PIN、主机忙、等待 PIN 时取消、主机遗忘配对后的回落、服务器证书与固定证书不符被拒、启动请求参数(mode、rikey、rikeyid 的大端 int32、HDR、GFE 的 fps 特例)、盒装图、连接被拒。+- 变异验证:故意改坏配对第 4 步的签名,测试立即报 4 项失败;恢复后全过。+- 构建:`veyra_moonlight_protocol`(`/W4 /WX`)与 `veyra_moonlight_common_c`(含 ENet、nanors)均编译通过。+- **模拟主机与客户端出自同一份协议理解**,所以它证明客户端自洽且对坏数据安全,不证明与真实 Sunshine 互通。++**发现的测试自身问题**:Windows 上回环口被拒绝的连接有时要约 2 秒才报错,可能与 2 秒超时撞车而报成 Timeout;相应测试已同时接受 Connect 与 Timeout。++## 下一步++S2:`MoonlightSessionSource`(拉取模式 `LiWaitForNextVideoFrame`、每帧立即解码、丢帧放在解码后且不标不连续)、Opus 多声道、遥测与延迟分解;先做离线可测的部分(解码单元拼接、HDR 元数据、时间戳换算)。diff --git a/docs/STREAMING_PLAN_MOONLIGHT_XBOX_2026-10-01.md b/docs/STREAMING_PLAN_MOONLIGHT_XBOX_2026-10-01.mdnew file mode 100644index 00000000..e8d38fae--- /dev/null+++ b/docs/STREAMING_PLAN_MOONLIGHT_XBOX_2026-10-01.md@@ -0,0 +1,295 @@+# Moonlight 与 Xbox 串流接入方案(调研 + 设计,2026-10-01)++> 状态:**只是调研和方案,没有写任何代码,没有连接过任何主机、主机账号或主机设备。** 信息来自公开仓库与网页(文末来源)。凡是第三方博客里的数字都标了"第三方说法",不是本机实测。+> 读者决定三件事:先做哪个、怎么排页面、Xbox 的账号风险要不要担。见第 9 节。++## 0. 结论++| | Moonlight(PC 串流) | Xbox 串流 |+|---|---|---|+| 能不能接入 | **能,而且顺**。协议成熟,核心库是 C、GPLv3,与软件同许可 | **能做,但风险高、不稳**。官方没有开放协议,全靠社区逆向 |+| 主机端 | 用户的电脑装 Sunshine(开源,GPLv3) | Xbox 主机本身,无需装东西,但要开远程功能 |+| 延迟 | 局域网第三方说法 5–15 ms;软件这边能做到"解码完直接进处理链" | 走 WebRTC,延迟取决于实现方式,没有可靠数据 |+| 视频编码 | H.264 / HEVC / AV1,含 10-bit HDR | 目前开源实现只处理 H.264(High 档优先) |+| 登录 | 局域网 PIN 配对,不碰任何账号 | 要登录微软账号,官方没给第三方的登录通道 |+| 建议 | **先做**,约一条完整的垂直功能 | **Moonlight 做完后再评估**,先做一个小型可行性验证 |++最重要的一条产品判断:大多数人玩主机用的是采集卡,采集卡路径已经做到内部延迟 1 ms 左右。Xbox 串流的价值是"不用采集卡",不是"更低延迟"。Moonlight 的价值更实在:电脑游戏(含 4K60)串到另一台电脑上,画面进入软件现有的处理链,和采集卡、PS5 串流一样使用同一套效果器。++**范围说明(2026-10-01 按用户纠正):接入的只是"串流核心"(协议、解码、音频、输入、主机与游戏选择界面)。NR / SR / 补帧 / 调色是软件现有的同一条处理链,开关、默认值(补帧本来就默认关)、预设、延迟提示全部沿用现有界面,不为串流另设预设或开关。**++## 1. Moonlight / Sunshine 调研++### 1.1 它是什么++- **Moonlight** 是 NVIDIA GameStream 协议的开源客户端;GameStream 停止后,社区做了开源主机端 **Sunshine**,说同一套协议,支持 NVIDIA / AMD / Intel 编码器。+- 核心库 **moonlight-common-c**:GameStream 协议的 C 实现,**GPL-3.0**;自带 ENet 分支(可靠 UDP 控制通道)和 nanors(FEC 纠错)。README 特别警告不能链接系统的其它 ENet,否则连新版主机会崩。+- 官方客户端 **moonlight-qt**:C++/Qt,**GPL-3.0**。和软件同为 Qt,目录里 `app/backend` 有配对、发现、主机列表的全部逻辑(`nvhttp.cpp` 19.5 KB、`nvpairingmanager.cpp` 13.6 KB、`computermanager.cpp` 36.5 KB 等),`app/streaming` 是会话、音视频、输入。+- Sunshine 2026-05 出了新版(Vulkan 编码等),另有社区分支(如 foundation-sunshine)加强了 HDR 与 AMD 编码。兼容性按"说同一协议"估计,实现前要逐个验证。++### 1.2 库的接口(读自 `Limelight.h`)++- 启动:`LiStartConnection(服务器信息, 串流配置, 连接回调, 视频回调, 音频回调, …)`,同步执行、非线程安全;可用 `LiInterruptConnection` 中断。+- 视频回调 `submitDecodeUnit` 给的是 **Annex-B 码流**(SPS/PPS/VPS/图像数据缓冲链)。每个单元带:帧号、帧类型(IDR/P)、`frameHostProcessingLatency`(主机处理延迟,0.1 ms 单位)、`receiveTimeUs`、`enqueueTimeUs`、`presentationTimeUs`、RTP 时间戳、HDR 标志与色彩空间。解码不了就返回 `DR_NEED_IDR` 请求关键帧。+- 有 **拉取模式**(`CAPABILITY_PULL_RENDERER`:`LiWaitForNextVideoFrame` / `LiCompleteVideoFrame`):渲染线程自己取最新帧,不需要库里再排一层队列。另有 `CAPABILITY_DIRECT_SUBMIT`(在接收线程直接提交,要求回调不阻塞)。+- 编码格式位:H.264、H.264 4:4:4、HEVC Main / Main10 / 4:4:4、AV1 Main8 / Main10 / 4:4:4。+- 串流配置:宽高帧率、码率、包大小、是否远程、音频声道、`supportedVideoFormats`、色彩空间与范围、加密开关。+- 输入:鼠标相对/绝对、键盘、最多 16 个手柄(Sunshine 15)、手柄到达事件(带类型与能力位)、陀螺仪/加速度、触控、手写笔;震动、扳机、LED、自适应扳机通过连接回调回传。+- 统计:`LiGetEstimatedRttInfo`(往返时间)、`LiGetRTPVideoStats` / `LiGetRTPAudioStats`(丢包与纠错计数)、HDR 元数据。+- **库不做的事**:配对、主机发现、`/serverinfo` `/launch` `/resume` `/cancel` 这些 HTTP(S) 调用。这些在 moonlight-qt 的 backend 里,需要 OpenSSL(证书、RSA、AES)。++### 1.3 延迟++- 第三方说法:局域网 5–15 ms(主机采集 + 编码 + 网络 + 解码),对比 Parsec 10–20 ms、Steam 远程畅玩 10–25 ms;硬件解码能把解码从约 8 ms 压到约 2 ms。**这些不是本机实测。**+- 主机端编码(NVENC/AMF/QSV)约几毫秒,网络(有线)约 1–2 ms,这两块软件管不了。软件能管的是:接收后的排队、解码、上传、处理链、呈现。++### 1.4 与软件的契合点++1. **解码可直接复用**:`CaptureCompressedDecoder` 已经用 D3D12VA 解 H.264 / HEVC / AV1 / VP9,失败回落软件;输入正是 Annex-B。解码后的 GPU 表面直接进处理链,没有 CPU 拷贝。+2. **会话结构有现成模板**:PS5 的 `RemotePlaySessionSource`(后台线程、遥测、音频 WASAPI、断线恢复),新的来源类照着写。+3. **构建有现成模板**:`VEYRA_ENABLE_REMOTEPLAY` + `cmake/VeyraRemotePlay.cmake`(固定版本第三方源码 + 来源校验脚本)。PS5 那套已经带了 OpenSSL 和 Opus,Moonlight 要的加密和音频解码都在。+4. **手柄层有现成模板**:`ControllerInput`(SDL3)。目前语义按 PS 按键,要加一层通用映射。+5. **许可**:GPLv3 对 GPLv3,可以直接移植,义务同以前:逐项记录来源仓库、固定提交、改动,写进 `THIRD_PARTY_NOTICES.md`。++## 2. Xbox 调研++### 2.1 官方与开源现状++- 微软没有开放 Xbox 远程游玩协议。现有第三方客户端都是**逆向**出来的,同一套叫 xHome(家庭串流)/ xCloud(云游戏)。+- 主要开源项目:+ - **Greenlight**(unknownskl,MIT,TypeScript,Electron 类桌面程序):包装 `xbox-xcloud-player`。+ - **xbox-xcloud-player**(同作者,`package.json` 写 MIT,但 GitHub 没识别出 LICENSE 文件;**复制代码前要向作者确认**):WebRTC 客户端库,依赖浏览器的 `RTCPeerConnection`。+ - **Kite**(Rust + Tauri,MIT):Windows 客户端,WebRTC 仍在 WebView 里,用 Insertable Streams 把已编码视频取出来交给 Rust 做录像。其自带技术文档和 README 互相矛盾(文档说没做输入,README 说做了),只能当线索。+ - **XStreaming**(移动端)、**blacklight**(Tauri + Svelte)、**GreenOvercast** 等。+- 这些项目**没有一个是原生(非浏览器)的 WebRTC 实现**,都借用浏览器引擎的 WebRTC。++### 2.2 协议要点(来自上述项目)++1. 登录链:微软 OAuth → Xbox Live 令牌 → XSTS 令牌(`gssv` 受众)→ 请求头 `XBL3.0 x=用户哈希;令牌`。+2. 信令走**微软的服务器**(即使在同一局域网):`GET /v2/login/user` 列主机;`POST /v5/sessions/home/{serverId}/play` 建会话,返回 SDP offer;`/sdp` 回 answer;`/ice` 交换候选。+3. 媒体走 WebRTC(ICE 点对点或中继):一路视频、一路音频,外加 **4 条数据通道**:`input`(手柄/键盘)、`control`、`message`、`chat`。+4. 视频编码:`xbox-xcloud-player` 的编码偏好只处理 H.264(High 优先,其次 Baseline)加 VP8/VP9,**没见 HEVC/AV1 处理**。这只是这个库的偏好,不等于主机不支持别的。+5. 分辨率帧率:通用说明是家庭串流最高 1080p60(不是这些项目的实测)。+6. 主机要求:设置里开启远程功能;睡眠模式选"即开"才能被唤醒;从外网用要上行约 15 Mbps、NAT 最好是开放。++### 2.3 三个必须正视的问题++- **登录没有合规通道**。Kite 要求**每个用户自己在 Azure 注册应用**(设备码登录),项目不带共享的客户端 ID;其说明里没有提账号风险。另一类做法是冒用微软自家 App 的客户端 ID(Greenlight 这一类的做法,我没核实)。两种都不理想:前者用户门槛高,后者有账号/条款风险。**这是 Xbox 能不能做的第一道关。**+- **协议随时会变**,而且完全不受我们控制。微软一改,功能就坏,且没有官方渠道通知。+- **条款**:各项目只写了"不隶属于微软,仅限自己的账号和主机、遵守微软服务协议",没做法律评估,我也不做。产品里只能标"实验功能 / 非官方",并由你承担是否发布的判断。++## 3. 方案取舍++### 3.1 先 Moonlight,后 Xbox++理由:Moonlight 风险低、收益明确、可本机闭环验证;Xbox 的"登录 + 协议稳定性"两个问题不先解决,做多少都可能白做。Xbox 只做一个小型可行性验证(第 8 节 X0),通过再立项。++### 3.2 不要一次性重构 PS5 的串流代码++PS5 路径已经稳定,串流类型绑在 `RemotePlayConnectDesc` 上。新协议**另写一个并列的会话来源**,先复制这套模式,等 Moonlight 稳定后,再评估抽出公共的"串流会话"接口。避免为了整洁去动已验证的 PS5。++## 4. Moonlight 技术设计++### 4.1 模块++```+src/moonlight/+ MoonlightHttp HTTP(S) 调用:serverinfo / pair / applist / launch / resume / cancel+ MoonlightPairing PIN 配对、客户端证书(移植自 moonlight-qt 的 nvhttp/nvpairingmanager)+ MoonlightDiscovery mDNS(_nvstream._tcp)+ 手填 IP+ MoonlightSession 封装 LiStartConnection、回调、统计+ MoonlightSource 实现 IFrameSource(像 RemotePlaySessionSource)+ MoonlightInput 手柄/键鼠 → Li* 输入函数+third_party/moonlight-common-c(固定提交 + ENet + nanors,带来源校验脚本)+cmake/VeyraMoonlight.cmake,选项 VEYRA_ENABLE_MOONLIGHT+```++### 4.2 数据流与线程++```+Sunshine ──UDP──▶ moonlight-common-c ──Annex-B──▶ 接收线程(不阻塞)+ ▲ │ 最新帧邮箱(容量 1)+ │ 输入(ENet) ▼+MoonlightInput ◀── 输入线程(≥250 Hz) 解码线程:D3D12VA(已有解码器)+ │ GPU 表面,0 次 CPU 拷贝+ ▼+ EnhanceGraph(NR/SR/补帧,可全关)──▶ 呈现+音频:Opus 多声道解码 ──▶ WASAPI(10 ms 缓冲,沿用采集路径的经验)+```++### 4.3 低延迟设计(沿用这几轮的经验)++1. **每一帧都立刻解码,丢帧放在"解码之后"**。解码后的表面丢掉很便宜;在码流层丢 P 帧会打断参考链,逼主机重发关键帧(`DR_NEED_IDR`),一次丢帧变成一次画质冲击。+2. **丢帧不标"不连续"**。这几轮查出来的教训:把丢帧标成时间线断点,会让 NR/补帧的历史被整个重置。只有真实的解码错误或码流缺口才算断点。+3. **优先用拉取模式**(`LiWaitForNextVideoFrame`),引擎线程自己拿最新帧,库里不再多排一层。+4. **"解码完成"的 GPU 围栏直接唤醒引擎线程**(这次采集路径已经这样做,目前只对物理采集生效,要扩到串流)。+5. **效果器不属于串流接入**:串流只是一个新来源,解码后的画面以和采集卡、PS5 相同的方式进入处理链。处理链的开关、默认值(补帧本来就默认关)、预设、延迟提示都沿用现有界面,不为串流另设。接入要保证的只是:来源不额外增加排队,处理链的延迟行为和采集卡路径一致。+6. **延迟分解面板**:主机处理(库给的 `frameHostProcessingLatency`)+ 网络 + 接收排队 + 解码 + 软件处理 + 呈现。这也是验收依据。++### 4.3.1 验收基准++同一主机、同一分辨率帧率编码,对比官方 moonlight-qt:**软件"接收到呈现"的中位数不高于它 + 1 ms(处理链全关时)**。这个数字要在 S2 实测后再确认合理性。++### 4.4 HDR 与编码++- HEVC Main10 / AV1 10-bit PQ 走硬件解码的 P010 表面,进现有的 HDR 合同(PS5 的 `H265Hdr` 已有先例)。**软件解码路径目前只输出 8-bit NV12**,所以 HDR 要求硬解,硬解失败必须明确提示,不静默降成 SDR 假装正常。+- 主机 HDR 状态走 `setHdrMode` 回调和 `LiGetHdrMetadata`;要核对与 Windows HDR 开关的关系。+- 先做 H.264 / HEVC,AV1 与 HDR 放到 S5。+- **4K60**:`STREAM_CONFIGURATION` 直接传宽高帧率,协议没有固定上限,官方 Moonlight 提供 4K 与 60/120 fps 选项。实际能否跑满取决于主机编码器、网络带宽和本机解码;本机 4K60 HEVC/AV1 硬解的耗时没测过,S2 里实测。4K 画面进处理链的开销与 4K 采集卡相同,不是串流特有的问题。++### 4.5 输入++- **手柄**:SDL3 读取,**独立输入线程**(现有 `ControllerInput` 的 SDL 调用在界面线程,串流要更高频、更稳);`LiSendControllerArrivalEvent` 声明能力,震动/扳机由连接回调回到手柄。陀螺仪要主机明确要求才发。+- **键鼠**:捕获模式下用 Raw Input 读相对鼠标;QML 窗口里视频窗口是穿透的,输入在主窗口侧拿。捕获期间软件自己的快捷键会和游戏冲突,所以约定:捕获时只保留一组带修饰键的保留键(沿用 Moonlight 习惯:Ctrl+Alt+Shift+Z 释放鼠标,Ctrl+Alt+Shift+Q 退出串流),F11、Home、Alt 等全部交给游戏;释放捕获后恢复。+- 全屏"Home 快速调节面板"在串流里同样可用(释放捕获时),这是软件的独有优势:边玩边调 NR/SR。++### 4.6 安全与存储++- 配对产生的客户端证书和私钥、主机密钥:DPAPI 加密保存在 `%LOCALAPPDATA%\Veyra\moonlight`,与 PS5 凭据同一原则;日志不得出现密钥、PIN、证书。+- 只在局域网自动发现;手填地址时校验格式(沿用 PS5 的 `validHost` 思路)。+- 远程(外网)串流先不做;库有 `streamingRemotely` 开关,留到 S6。++### 4.7 引擎接入点++- `IFrameSource` 直接实现;`SourceReadStatus::Waiting` 用于"暂时没有新帧"。+- `EngineController::run(..., remoteRequest)` 现有的 `isRemote` 分支按 PS5 写,要么扩成"串流来源",要么加一条并列分支;**评估后决定,不在方案阶段拍板**。+- 引擎里和采集相关的几项延迟优化(围栏唤醒、背压)当前部分只对物理采集生效,要逐项检查哪些应该对串流生效。++## 5. Xbox 技术设计(仅在 X0 通过后)++### 5.1 三种做法++| | A 内嵌网页引擎 + 取编码帧 | B 原生 libdatachannel | C 原生 libwebrtc |+|---|---|---|---|+| 做法 | 用 WebView2 / QtWebEngine 跑现成的 JS 协议库,用 Insertable Streams 读出已编码的视频帧,丢给软件自己的硬解,不让浏览器解码 | 用 C++17 的轻量 WebRTC 库自己收 RTP、自己做抖动缓冲和关键帧请求 | 用谷歌的完整 WebRTC 栈,注入自己的解码器 |+| 优点 | 最快出原型;协议细节都在现成 JS 里 | 延迟最可控,包小,最贴合处理链 | 抖动缓冲、带宽估计、丢包恢复都现成 |+| 缺点 | 多一层浏览器运行时和跨进程传输;JS 里的一跳增加不可控延迟 | 缺带宽估计和抖动缓冲,要自己写;和微软服务器互通性未知;**许可 MPL-2.0(我凭记忆写,使用前要核对)** | Windows 上体积和构建都很重 |+| 判断 | 用来做 X0 的可行性验证 | **量产首选,前提是 X0 证明互通** | B 不通时的后备 |++- 现成数据点(第三方):另一个开源桌面串流项目用浏览器解码约占 33 ms(总约 50 ms),其路线图里的原生客户端就是为了压这一段。说明浏览器解码确实是延迟大头,做法 A 必须绕开浏览器解码。+- 解码之后(硬解 → 处理链)与 Moonlight 完全相同,共用同一套实现。++### 5.2 X0 可行性验证要回答的问题(不写产品代码)++1. 登录:有没有一条不冒用微软第一方客户端 ID、又不要普通用户自己注册 Azure 应用的办法?(没有就停。)+2. 互通:B 方案(libdatachannel)能否与微软的信令与 WebRTC 端点完成 SDP/ICE/DTLS/SCTP 握手,并收到视频。+3. 编码:实际协商出的是什么编码、分辨率、码率。+4. 延迟:收到 RTP 到出画的耗时,与做法 A 对比。+5. 稳定:关键帧请求、断线重连、主机唤醒。++**X0 需要你本人在场**:用你自己的微软账号和 Xbox 主机,由你授权并操作登录;我不会代为登录、不会碰账号令牌。++### 5.3 输入与账号存储++- 手柄包格式从 `xbox-xcloud-player` 的输入通道代码读取(MIT,先确认许可);同样走独立输入线程。+- 令牌用 DPAPI 加密存盘,日志脱敏;提供"退出登录并清除"。++## 6. 前端方案++### 6.1 总体原则++- 沿用软件现有的设计语言:`VPage`、`VCard`、`DLayer` 对话框、`VRow`/`VSelect`/`VSeg`/`VSwitch` 设置行、`PerfOrbs`;**不新造控件**,除非必须(主机卡片、游戏卡片是新的两个组件)。+- 串流前的"设置"和串流中的"观看"分开:设置在页面/对话框里做;一旦连上,立刻进入现有的播放页(极简 / 专业 / 节点都能用),不另造播放界面。+- 上面的线框图是**版式示意**,不是最终配色和尺寸。++### 6.2 页面与流程++**① 首页**(`HomePage.qml`)+- 来源卡片现在是 4 张(打开视频、采集卡、PS5 串流、屏幕捕获),一排 164 px 宽。加两张变 6 张,共约 1044 px,在 1280 窗口内放得下,窄窗口换成两行。+- 新卡片:**PC 串流**(副标题显示"已保存 N 台主机"或"Sunshine 主机");**Xbox 串流**(标"实验",仅在设置里打开"实验功能"后显示)。+- 另一种做法:合成一张"游戏串流"卡,点开后选 PS5 / PC / Xbox。好处是首页干净,坏处是改变 PS5 现有入口。**默认建议加卡片、不动 PS5**,见第 9 节。+- "继续上次"那一行已经有 `lastSource`,新增 `moonlight` 类型,点一下直接重连上次的主机与游戏。++**② PC 串流页**(新页面,三栏,对应线框图 2)+- **左栏 主机列表**:自动发现 + 手填 IP。每台主机一张卡:名称、地址、状态点(在线 / 未配对 / 忙 / 离线)。操作:配对、删除、刷新。+- **配对对话框**:软件生成 4 位 PIN 显示出来,提示"到主机的 Sunshine 网页(本机 47990 端口)的配对页输入这个 PIN";配对成功自动关闭,失败给出可操作的原因。+- **中栏 游戏网格**:选中主机后拉取游戏列表,显示封面(复用现有的缩略图服务);正在运行的游戏带"运行中"标记,操作有"继续"和"退出游戏"。首项常是"桌面"。+- **右栏 串流设置**:只放串流核心参数——分辨率与帧率(列出档位,含 4K 60)、码率(默认自动,可手调)、编码(自动 / H.264 / HEVC / AV1)、HDR、音频声道(立体声 / 5.1 / 7.1)、手柄(按键映射、仅观看)。效果器不在这里,连上后用软件现有的页面调。底部一个主按钮"开始串流"。+- 设置按主机分别保存。+- 首次使用、没有主机时,主区域显示"怎么装 Sunshine"的三步引导,带官网链接;软件不捆绑 Sunshine。++**③ 串流中**(复用播放页,对应线框图 3)+- **顶部胶囊**(`TopDock`)在串流时多一个延迟小胶囊:往返时间、丢包率、鼠标捕获状态和释放键。+- **专业 / 列表模式**的耗时区多一块"串流延迟分解":主机 / 网络 / 接收 / 解码 / 软件处理,一条彩色分段条加各项毫秒(线框里的数值只是示意)。+- **控制条**(`CineBar`)新增:断开、退出主机上的游戏、释放鼠标。断开和退出是两个不同动作,文案要写清"断开后游戏继续运行"。+- 全屏 Home 快速调节面板照常可用。++**④ 设置页新增"串流"分组**+默认预设、统计显示默认开关、保留键、清除所有配对和证书。++**⑤ Xbox 对话框**(X0 之后)+登录状态 → 主机列表(含电源状态、唤醒按钮)→ 分辨率 / 码率 / 手柄 → 连接。顶部固定一条"非官方实验功能,仅限自己的账号和主机"的提示。++### 6.3 桥接接口(沿用 `ps5*` 的写法)++```+veyra.moonlight 状态对象:hosts、active、busy、status、stats+moonlightScan() / moonlightAddHost(addr)+moonlightPair(hostId) → PIN 文本 / 结果信号+moonlightApps(hostId) → 游戏列表+moonlightConnect(hostId, appId, options) / moonlightDisconnect(quitApp)+moonlightSet(key, value) 设置按主机保存+moonlightForget(hostId)+```++### 6.4 测试++- QML 组件测试(与现有 `tst_components.qml` 同路):主机卡状态、配对对话框流程、游戏网格"运行中"、设置行。+- 用录制的 `serverinfo` / `applist` XML 固件做协议解析与配对的无网络单元测试。+- 真实截图检查(和这几轮一样,按页面逐屏对照线框)。++## 7. 风险与未知++| 风险 | 影响 | 处理 |+|---|---|---|+| Sunshine 各分支对协议的扩展不一致 | 个别主机连不上或缺功能 | 以官方 Sunshine 为基线,其它分支单独列兼容清单 |+| 输入捕获与软件快捷键冲突 | 误触发或按不了 | 保留键方案 + 释放捕获时才响应软件快捷键 |+| HDR 路径依赖硬解 | 部分显卡无法 HDR 串流 | 明确提示,不静默降级 |+| D3D12VA 对 HEVC/AV1 的支持因显卡而异 | 部分显卡只能 H.264 | 按能力选择并告知 |+| Xbox 登录方式 | 可能整个停摆 | X0 先验证,不通就不做 |+| Xbox 协议被微软改动 | 功能随时失效 | 标实验功能,版本里写明 |+| 本机只有一张 RTX 5070 | 其它显卡(解码、HDR)未验 | 如实标"未验",由持卡用户验收 |+| 我无法在没有用户在场时完成的验证 | 实际串流、Xbox 登录 | 明确列为需用户在场的项 |++## 8. 分阶段计划++工作量用相对大小(S 小、M 中、L 大)表示,不写具体周数,因为取决于验证中遇到的问题。++### Moonlight++| 阶段 | 内容 | 交付与验收 | 需要用户 |+|---|---|---|---|+| **S0** 准备 | 定范围;固定 moonlight-common-c 与 moonlight-qt 的提交;核对各依赖许可;写入 NOTICES 草稿;准备一台 Sunshine 主机(可以是你的电脑本机回环) | 决策清单确认;来源校验脚本 | **同意下载并安装 Sunshine**(下载须你授权) |+| **S1** 协议层 (M) | 移植 HTTP/配对/发现;固件单测 | 无网络单测全过;与本机 Sunshine 成功配对、列游戏 | 在 Sunshine 网页输入 PIN |+| **S2** 会话与画面 (L) | 会话来源、解码、音频、遥测、引擎接入 | 处理链全关时,延迟对比 moonlight-qt(第 4.3.1);延迟分解日志 | 无(本机回环即可) |+| **S3** 输入 (M) | 手柄、键鼠捕获、保留键、震动 | 本机回环下手柄/键鼠能控制;输入线程频率实测 | 你在场操作输入 |+| **S4** 前端 (M–L) | 首页卡、PC 串流页、配对对话框、设置、串流中 UI | QML 测试通过;逐屏截图与线框对照 | 你确认版式 |+| **S5** 质量 (M) | HDR、AV1、4K60 实测、丢包与重连、睡眠恢复、1 小时稳定性 | 各项实测记录;未验项如实列出 | 有第二台电脑或不同显卡更好 |+| **S6** 可选 | 外网串流 | — | — |++### Xbox++| 阶段 | 内容 | 判定 |+|---|---|---|+| **X0** 可行性验证 (S–M) | 第 5.2 的五个问题;一个一次性的验证程序,不进产品 | 登录方案和 libdatachannel 互通两项任一不通,则停止并如实汇报 |+| **X1+** | 原生会话、输入、前端(按 X0 结论定,前端对应第 6.2 ⑤) | 另行立项 |++## 9. 需要你决定的事++1. **顺序**:是否同意先做 Moonlight,Xbox 只做 X0 验证?+2. **首页**:加卡片(6 张、不动 PS5),还是合成一张"游戏串流"卡?我默认建议加卡片。+3. **Sunshine**:S0 要下载安装 Sunshine 做本机回环测试,你是否同意我下载?(我不会自己去下载。)+4. **Xbox 风险**:你是否接受"非官方、依赖逆向协议、登录方式未定"作为立项前提?以及 X0 需要你本人用自己的账号和主机在场操作,是否接受?+5. **许可**:`xbox-xcloud-player` 缺 LICENSE 文件,使用其代码前是否由你联系作者确认?(仅在 X0 通过后才需要。)++## 10. 来源++- moonlight-common-c:https://github.com/moonlight-stream/moonlight-common-c ;接口头文件 `Limelight.h`(读取于 2026-10-01)+- moonlight-qt 源码结构:https://github.com/moonlight-stream/moonlight-qt+- Sunshine(LizardByte):https://app.lizardbyte.dev/Sunshine/ ;社区分支 foundation-sunshine:https://github.com/AlkaidLab/foundation-sunshine+- Greenlight:https://github.com/unknownskl/greenlight ;xbox-xcloud-player:https://github.com/unknownskl/xbox-xcloud-player+- Kite:https://github.com/DRHATL95/kite(含 AZURE_SETUP.md、TECHNICAL_DETAILS.md)+- Xbox 远程游玩通用说明(第三方):https://www.digitalcitizen.life/how-xbox-remote-play-works-and-why-it-feels-different-from-cloud-gaming/+- libdatachannel 与 libWebRTC 对比:https://tensorworks.com.au/blog/a-brief-comparison-of-libdatachannel-and-libwebrtc/+- 原生串流项目的延迟拆分(第三方):https://github.com/jrf63/desktop-streaming+- 软件内的参照实现:`src/source/RemotePlaySessionSource.cpp`、`src/remoteplay/ControllerInput.cpp`、`cmake/VeyraRemotePlay.cmake`、`qml/Veyra/HomePage.qml`、`qml/Veyra/DialogHost.qml`(PS5 对话框)diff --git a/include/veyra/moonlight/Client.h b/include/veyra/moonlight/Client.hnew file mode 100644index 00000000..9075933e--- /dev/null+++ b/include/veyra/moonlight/Client.h@@ -0,0 +1,80 @@+// SPDX-License-Identifier: GPL-3.0-only+// Requests to one GameStream host: serverinfo, applist, launch/resume/cancel,+// box art and unpair, plus the parsing of their answers. Ported from+// moonlight-qt's NvHTTP; the pairing handshake is in Pairing.h.+#pragma once+#include <array>+#include <atomic>+#include <string>+#include <vector>++#include "veyra/moonlight/Crypto.h"+#include "veyra/moonlight/Http.h"+#include "veyra/moonlight/Types.h"+#include "veyra/moonlight/Xml.h"++namespace veyra::moonlight {++struct LaunchRequest {+ int appId = 0;+ int width = 1920, height = 1080, fps = 60;+ std::array<uint8_t, 16> remoteInputKey{}; // AES key of the input stream+ std::array<uint8_t, 4> remoteInputKeyId{}; // first 4 bytes of the input IV, big endian+ bool hdr = false; // a 10-bit video format was requested+ bool sops = false; // let the host change its own resolution+ bool localAudio = false; // keep playing audio on the host too+ int surroundAudioInfo = 0; // SURROUNDAUDIOINFO_FROM_AUDIO_CONFIGURATION+ int gamepadMask = 0;+ bool persistGamepads = false;+ std::string extraQuery; // LiGetLaunchUrlQueryParameters(), already "&k=v..."+};++class ServerClient {+public:+ ServerClient(const Identity& identity, HostAddress address, std::string pinnedServerCertPem,+ uint16_t httpsPort, bool useTrueUniqueId);+ // The HTTP client points at this object's own identity, so a copy rebinds it.+ ServerClient(const ServerClient& other);+ ServerClient& operator=(const ServerClient&) = delete;++ void setCancel(const std::atomic<bool>* cancel) { cancel_ = cancel; }+ const HostAddress& address() const { return address_; }+ uint16_t httpsPort() const { return httpsPort_; }+ const std::string& pinnedServerCertificate() const { return http_.pinnedServerCertificate(); }+ void setPinnedServerCertificate(std::string pem) { http_.setPinnedServerCertificate(std::move(pem)); }+ void setHttpsPort(uint16_t port) { httpsPort_ = port; }+ void setUseTrueUniqueId(bool value) { useTrueUniqueId_ = value; }++ // HTTPS first once a server certificate is pinned (it reports the real pairing+ // state); HTTP otherwise, or when the TLS side refuses us (not paired / new+ // certificate). Throws StatusError or TransportError.+ ServerInfo serverInfo(bool fastFail = false);+ std::vector<AppEntry> appList();++ // `verb` is "launch" for a fresh app or "resume" for the running one.+ // Returns the RTSP session URL the stream connects to.+ std::string launch(const char* verb, const LaunchRequest& request, bool nvidiaServerSoftware);+ void quit();+ void unpair();+ std::string boxArt(int appId);++ // One request with the standard uniqueid/uuid prefix; the raw answer body.+ std::string request(bool tls, const std::string& command, const std::string& arguments, int timeoutMs);++ static ServerInfo parseServerInfo(const xml::Node& root);+ static std::vector<AppEntry> parseAppList(const xml::Node& root);+ // Throws StatusError unless the root element reports status_code 200.+ static xml::Node checkedRoot(const std::string& body);++private:+ HttpResponse fetch(bool tls, const std::string& command, const std::string& arguments, int timeoutMs);++ Identity identity_;+ HostAddress address_;+ uint16_t httpsPort_;+ bool useTrueUniqueId_;+ HttpClient http_;+ const std::atomic<bool>* cancel_ = nullptr;+};++} // namespace veyra::moonlightdiff --git a/include/veyra/moonlight/Crypto.h b/include/veyra/moonlight/Crypto.hnew file mode 100644index 00000000..7319b57f--- /dev/null+++ b/include/veyra/moonlight/Crypto.h@@ -0,0 +1,47 @@+// SPDX-License-Identifier: GPL-3.0-only+// Client identity and the small set of OpenSSL operations the GameStream+// pairing handshake needs (ported from moonlight-qt identitymanager/nvpairingmanager).+#pragma once+#include <string>+#include <string_view>++namespace veyra::moonlight {++// The client's long-lived identity: a self-signed RSA-2048 certificate (CN+// "NVIDIA GameStream Client", 20 years) and its key, both PEM, plus the+// unique id that the host knows this client by.+struct Identity {+ std::string certPem;+ std::string keyPem; // secret: never logged, stored with DPAPI+ std::string uniqueId; // 16 lowercase hex characters++ // Both PEMs parse, belong together, and the id is 16 hex characters.+ bool valid() const;+};++Identity createIdentity();++namespace crypto {++std::string randomBytes(size_t count);++// Raw digest: SHA-256 for GameStream generation 7 and later, SHA-1 before.+std::string digest(std::string_view data, bool sha256);++// AES-128-ECB without padding; input length must be a multiple of 16, else empty.+std::string aesEcbEncrypt(std::string_view plain, std::string_view key);+std::string aesEcbDecrypt(std::string_view cipher, std::string_view key);++// RSA-SHA256 signature of `message` with the identity's key.+std::string sign(const Identity& identity, std::string_view message);+// Verifies an RSA-SHA256 signature against the public key in `certPem`.+bool verify(std::string_view message, std::string_view signature, std::string_view certPem);++// The certificate's own signature bits (what the pairing hashes mix in).+std::string certificateSignature(std::string_view certPem);++// DER form, used to pin a server certificate; empty when the PEM does not parse.+std::string certificateDer(std::string_view certPem);++} // namespace crypto+} // namespace veyra::moonlightdiff --git a/include/veyra/moonlight/Http.h b/include/veyra/moonlight/Http.hnew file mode 100644index 00000000..b50a6d6d--- /dev/null+++ b/include/veyra/moonlight/Http.h@@ -0,0 +1,51 @@+// SPDX-License-Identifier: GPL-3.0-only+// The GameStream host speaks plain HTTP on one port and HTTPS (mutual TLS, with+// the client certificate from pairing and a self-signed server certificate that+// is pinned at pairing time) on another. This is the small client for both:+// Winsock + OpenSSL, blocking with a deadline and a cancel flag, one request per+// connection (the host does not cope with persistent connections).+#pragma once+#include <atomic>+#include <string>++#include "veyra/moonlight/Crypto.h"+#include "veyra/moonlight/Types.h"++namespace veyra::moonlight {++struct HttpTarget {+ std::string host;+ uint16_t port = 0;+ bool tls = false;+};++struct HttpOptions {+ int timeoutMs = 5000; // 0: no deadline, only `cancel` ends the wait+ const std::atomic<bool>* cancel = nullptr;+ size_t maxBodyBytes = size_t(8) << 20;+};++struct HttpResponse {+ int status = 0;+ std::string body;+};++class HttpClient {+public:+ // `identity` supplies the TLS client certificate; `pinnedServerCertPem` is the+ // only server certificate accepted over TLS. HTTPS without both is refused.+ HttpClient(const Identity* identity, std::string pinnedServerCertPem);++ // GET path?query. Throws TransportError. A TLS failure (handshake, pinned+ // certificate mismatch, rejected client certificate) has Kind::Tls.+ HttpResponse get(const HttpTarget& target, const std::string& pathAndQuery, const HttpOptions& options) const;++ void setPinnedServerCertificate(std::string pem) { pinned_ = std::move(pem); }+ const std::string& pinnedServerCertificate() const { return pinned_; }++private:+ const Identity* identity_;+ std::string pinned_;+};++} // namespace veyra::moonlightdiff --git a/include/veyra/moonlight/IdentityStore.h b/include/veyra/moonlight/IdentityStore.hnew file mode 100644index 00000000..17da0f15--- /dev/null+++ b/include/veyra/moonlight/IdentityStore.h@@ -0,0 +1,25 @@+// SPDX-License-Identifier: GPL-3.0-only+// Where the client identity lives on disk: one DPAPI-protected file in+// %LOCALAPPDATA%\Veyra\moonlight, written atomically (temp file + replace),+// the same approach as the PS5 pairing profiles. The private key never leaves+// this file and is never logged.+#pragma once+#include <filesystem>+#include <optional>++#include "veyra/moonlight/Crypto.h"++namespace veyra::moonlight {++std::filesystem::path dataDirectory();++// nullopt when the file is missing, unreadable (another Windows user, damaged)+// or holds an identity that does not validate.+std::optional<Identity> loadIdentity(const std::filesystem::path& file);+bool saveIdentity(const std::filesystem::path& file, const Identity& identity);++// The saved identity, or a freshly created one that is saved first. `created`+// (optional) reports which. Throws std::runtime_error if a new identity cannot be saved.+Identity loadOrCreateIdentity(const std::filesystem::path& file, bool* created = nullptr);++} // namespace veyra::moonlightdiff --git a/include/veyra/moonlight/Pairing.h b/include/veyra/moonlight/Pairing.hnew file mode 100644index 00000000..4882f00b--- /dev/null+++ b/include/veyra/moonlight/Pairing.h@@ -0,0 +1,39 @@+// SPDX-License-Identifier: GPL-3.0-only+// The GameStream pairing handshake (ported from moonlight-qt's NvPairingManager).+//+// The client shows a four digit PIN that the user types into the host (for+// Sunshine: its web UI). Both sides derive an AES key from the salted PIN,+// exchange and verify challenges, and swap certificates; the client keeps the+// host's certificate and pins it for every later HTTPS request.+#pragma once+#include <atomic>+#include <string>++#include "veyra/moonlight/Client.h"++namespace veyra::moonlight {++enum class PairResult {+ Paired,+ Failed,+ PinWrong,+ AlreadyInProgress, // the host is busy pairing another client+ Cancelled,+};++struct PairOutcome {+ PairResult result = PairResult::Failed;+ std::string serverCertPem; // valid only when Paired+ std::string detail; // which step failed, for diagnostics (no secrets)+};++// Four digits, zero padded, from the system random source.+std::string generatePin();++// `client` must already know the host's HTTPS port (call serverInfo() first) and+// is not modified: the handshake works on a copy. Blocks until the user has+// entered the PIN on the host (or `cancel` is set).+PairOutcome pairWithHost(const ServerClient& client, const Identity& identity, const ServerInfo& host,+ const std::string& pin, const std::atomic<bool>* cancel);++} // namespace veyra::moonlightdiff --git a/include/veyra/moonlight/Types.h b/include/veyra/moonlight/Types.hnew file mode 100644index 00000000..597b83da--- /dev/null+++ b/include/veyra/moonlight/Types.h@@ -0,0 +1,75 @@+// SPDX-License-Identifier: GPL-3.0-only+// Moonlight / GameStream host protocol: shared types.+//+// The pairing, serverinfo and launch logic under src/moonlight is a port of+// moonlight-qt's app/backend (GPL-3.0, https://github.com/moonlight-stream/moonlight-qt,+// commit pinned in scripts/moonlight/dependency-lock.json) with the Qt types+// replaced. See THIRD_PARTY_NOTICES.md.+#pragma once+#include <cstdint>+#include <stdexcept>+#include <string>+#include <vector>++namespace veyra::moonlight {++constexpr uint16_t kDefaultHttpPort = 47989;+constexpr uint16_t kDefaultHttpsPort = 47984;++// Server codec support bits of the serverinfo ServerCodecModeSupport field.+// Values are the SCM_* constants of moonlight-common-c's Limelight.h; they are+// repeated here so the protocol library and its tests do not need that header.+constexpr int kServerH264 = 0x00000001;+constexpr int kServerHevc = 0x00000100;+constexpr int kServerHevcMain10 = 0x00000200;+constexpr int kServerAv1Main8 = 0x00010000;+constexpr int kServerAv1Main10 = 0x00020000;++struct HostAddress {+ std::string host; // IPv4/IPv6 literal or DNS name, no brackets+ uint16_t httpPort = kDefaultHttpPort;+ bool empty() const { return host.empty(); }+ bool operator==(const HostAddress&) const = default;+};++struct DisplayMode {+ int width = 0, height = 0, refreshRate = 0;+};++struct ServerInfo {+ std::string hostname, uniqueId, mac, localIp, externalIp;+ std::string appVersion, gfeVersion, gpuModel, state;+ uint16_t httpsPort = kDefaultHttpsPort;+ uint16_t externalPort = 0;+ int serverCodecModeSupport = kServerH264;+ int maxLumaPixelsHevc = 0;+ int currentGame = 0; // 0 unless the host is busy streaming+ bool paired = false;+ bool nvidiaServerSoftware = false; // GFE / RTX Experience report "MJOLNIR"+ std::vector<DisplayMode> displayModes;++ // First component of appversion (the "server generation"): 7+ pairs with SHA-256.+ int appVersionMajor() const;+};++struct AppEntry {+ std::string name;+ int id = 0;+ bool hdrSupported = false;+ bool isAppCollectorGame = false;+};++// A well-formed response whose status_code is not 200.+struct StatusError : std::runtime_error {+ int status;+ StatusError(int code, const std::string& message) : std::runtime_error(message), status(code) {}+};++// The request itself failed (connect, timeout, TLS, malformed HTTP).+struct TransportError : std::runtime_error {+ enum class Kind { Connect, Timeout, Tls, Protocol, Cancelled };+ Kind kind;+ TransportError(Kind k, const std::string& message) : std::runtime_error(message), kind(k) {}+};++} // namespace veyra::moonlightdiff --git a/include/veyra/moonlight/Xml.h b/include/veyra/moonlight/Xml.hnew file mode 100644index 00000000..696d6a4f--- /dev/null+++ b/include/veyra/moonlight/Xml.h@@ -0,0 +1,41 @@+// SPDX-License-Identifier: GPL-3.0-only+// A very small XML reader for the host's answers (serverinfo, applist, pair,+// launch). They are a few kilobytes of plain elements; this is deliberately not+// a general XML parser: no DTD, no namespaces, the five predefined entities and+// numeric character references only, bounded size and depth.+#pragma once+#include <map>+#include <optional>+#include <string>+#include <string_view>+#include <vector>++namespace veyra::moonlight::xml {++struct Node {+ std::string name;+ std::map<std::string, std::string> attributes;+ std::string text; // concatenated character data (not trimmed)+ std::vector<Node> children;++ // Pre-order, first match among the descendants (like scanning start elements).+ const Node* find(std::string_view elementName) const;+ std::vector<const Node*> findAll(std::string_view elementName) const;+};++constexpr size_t kMaxDocumentBytes = size_t(1) << 20;+constexpr int kMaxDepth = 32;++// The root element, or nothing when the document is malformed or too large.+std::optional<Node> parse(std::string_view document);++std::string decodeEntities(std::string_view text);++// Text of the first element called `tag`, empty when it is absent.+std::string textOf(const Node& root, std::string_view tag);++// Hex <-> bytes (lower/upper case accepted when decoding; invalid input gives nothing).+std::string toHex(const std::string& bytes);+std::optional<std::string> fromHex(std::string_view hex);++} // namespace veyra::moonlight::xmldiff --git a/licenses/moonlight/ENET_MIT.txt b/licenses/moonlight/ENET_MIT.txtnew file mode 100644index 00000000..6906f8eb--- /dev/null+++ b/licenses/moonlight/ENET_MIT.txt@@ -0,0 +1,7 @@+Copyright (c) 2002-2020 Lee Salzman++Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.diff --git a/licenses/moonlight/NANORS_MIT.txt b/licenses/moonlight/NANORS_MIT.txtnew file mode 100644index 00000000..89a77e62--- /dev/null+++ b/licenses/moonlight/NANORS_MIT.txt@@ -0,0 +1,21 @@+MIT License++Copyright (c) 2021 Joseph Calderon++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.diff --git a/scripts/moonlight/dependency-lock.json b/scripts/moonlight/dependency-lock.jsonnew file mode 100644index 00000000..4e7ee994--- /dev/null+++ b/scripts/moonlight/dependency-lock.json@@ -0,0 +1,44 @@+{+ "moonlight_common_c": {+ "repository": "https://github.com/moonlight-stream/moonlight-common-c.git",+ "commit": "f900dd4767759c7b9d0e93bcea666b55c69ea62f",+ "commit_date": "2026-09-26",+ "license": "GPL-3.0",+ "submodules": {+ "enet": {+ "repository": "https://github.com/cgutman/enet.git",+ "commit": "aca87840b57f045a1f7f9299e4b1b9b8e2a5e2f1",+ "license": "MIT"+ },+ "nanors": {+ "repository": "https://github.com/sleepybishop/nanors.git",+ "commit": "b1e3c22ca0cdc0bb83e3cd6ed1a2fc77869ed99a",+ "license": "MIT"+ }+ },+ "local_path": "E:/项目/Veyra/deps/moonlight/moonlight-common-c",+ "patches": []+ },+ "moonlight_qt_reference": {+ "repository": "https://github.com/moonlight-stream/moonlight-qt.git",+ "commit": "8369d1a0e11b999d4d1598f62ca5f6dea49602fb",+ "commit_date": "2026-09-27",+ "license": "GPL-3.0",+ "note": "Reference only: pairing, launch and serverinfo logic in src/moonlight/ is a port of app/backend/{nvhttp,nvpairingmanager,identitymanager,nvcomputer}.cpp with the Qt types replaced; nothing from this tree is compiled.",+ "local_path": "E:/项目/Veyra/deps/moonlight/moonlight-qt",+ "ported_files": [+ "app/backend/nvhttp.cpp",+ "app/backend/nvpairingmanager.cpp",+ "app/backend/identitymanager.cpp",+ "app/backend/nvcomputer.cpp",+ "app/streaming/session.cpp (stream configuration, default bitrate table)"+ ]+ },+ "native_dependencies": [+ "OpenSSL (crypto + ssl, static, from the existing remoteplay vcpkg tree)",+ "Opus (audio decode, same tree)",+ "ENet and nanors (bundled with moonlight-common-c as pinned submodules)"+ ],+ "no_runtime_dlls_or_vendor_sdks_in_this_package": true,+ "sunshine_host": "Not bundled and not downloaded. Users install Sunshine (GPL-3.0, LizardByte) on the machine being streamed."+}diff --git a/scripts/moonlight/verify-moonlight-stage.py b/scripts/moonlight/verify-moonlight-stage.pynew file mode 100644index 00000000..f49030b9--- /dev/null+++ b/scripts/moonlight/verify-moonlight-stage.py@@ -0,0 +1,55 @@+#!/usr/bin/env python3+"""Verify that the moonlight-common-c checkout is exactly the pinned one.++Used by cmake/VeyraMoonlight.cmake before anything is compiled: the commit of+the library and of both bundled submodules must match dependency-lock.json and+the tree must have no local modifications, so a build can never silently use a+different protocol implementation.+"""+import argparse+import json+import subprocess+import sys+from pathlib import Path+++def git(directory: Path, *args: str) -> str:+ result = subprocess.run(['git', '-C', str(directory), *args], capture_output=True, text=True, encoding='utf-8')+ if result.returncode != 0:+ raise RuntimeError(f'git {" ".join(args)} failed in {directory}: {result.stderr.strip()}')+ return result.stdout.strip()+++def main() -> int:+ parser = argparse.ArgumentParser()+ parser.add_argument('--source', required=True, help='moonlight-common-c checkout')+ parser.add_argument('--lock', required=True, help='dependency-lock.json')+ args = parser.parse_args()+ lock = json.loads(Path(args.lock).read_text(encoding='utf-8'))['moonlight_common_c']+ source = Path(args.source)+ problems = []+ if not (source / 'src' / 'Limelight.h').is_file():+ print(f'MOONLIGHT_STAGE FAIL: {source} is not a moonlight-common-c checkout', file=sys.stderr)+ return 2+ head = git(source, 'rev-parse', 'HEAD')+ if head != lock['commit']:+ problems.append(f'library commit {head} != pinned {lock["commit"]}')+ if lock['patches'] == [] and git(source, 'status', '--porcelain', '--untracked-files=no'):+ problems.append('tracked files are modified but the lock lists no patches')+ for name, pin in lock['submodules'].items():+ sub = source / name+ if not (sub / 'LICENSE').is_file() and not (sub / 'LICENSE.txt').is_file():+ problems.append(f'submodule {name} is not checked out')+ continue+ commit = git(sub, 'rev-parse', 'HEAD')+ if commit != pin['commit']:+ problems.append(f'submodule {name} commit {commit} != pinned {pin["commit"]}')+ if problems:+ print('MOONLIGHT_STAGE FAIL: ' + '; '.join(problems), file=sys.stderr)+ return 1+ print(f'MOONLIGHT_STAGE PASS {head}')+ return 0+++if __name__ == '__main__':+ sys.exit(main())diff --git a/src/moonlight/Client.cpp b/src/moonlight/Client.cppnew file mode 100644index 00000000..c1c3b1d2--- /dev/null+++ b/src/moonlight/Client.cpp@@ -0,0 +1,200 @@+// SPDX-License-Identifier: GPL-3.0-only+#include "veyra/moonlight/Client.h"++#include <algorithm>+#include <cstdlib>++namespace veyra::moonlight {++namespace {++constexpr int kFastFailTimeoutMs = 2000;+constexpr int kRequestTimeoutMs = 5000;+constexpr int kLaunchTimeoutMs = 120000;+constexpr int kQuitTimeoutMs = 30000;+// GFE lets a client quit another client's game when everybody uses this id.+constexpr const char* kSharedUniqueId = "0123456789ABCDEF";++int toInt(const std::string& text, int fallback = 0) {+ if (text.empty()) return fallback;+ char* end = nullptr;+ const long value = std::strtol(text.c_str(), &end, 10);+ return end == text.c_str() ? fallback : int(value);+}++uint16_t toPort(const std::string& text) {+ const long value = std::strtol(text.c_str(), nullptr, 10);+ return (value > 0 && value <= 65535) ? uint16_t(value) : uint16_t(0);+}++} // namespace++int ServerInfo::appVersionMajor() const {+ return std::atoi(appVersion.c_str());+}++ServerClient::ServerClient(const Identity& identity, HostAddress address, std::string pinnedServerCertPem,+ uint16_t httpsPort, bool useTrueUniqueId)+ : identity_(identity), address_(std::move(address)), httpsPort_(httpsPort), useTrueUniqueId_(useTrueUniqueId),+ http_(&identity_, std::move(pinnedServerCertPem)) {}++ServerClient::ServerClient(const ServerClient& other)+ : identity_(other.identity_), address_(other.address_), httpsPort_(other.httpsPort_),+ useTrueUniqueId_(other.useTrueUniqueId_), http_(&identity_, other.http_.pinnedServerCertificate()), cancel_(other.cancel_) {}++HttpResponse ServerClient::fetch(bool tls, const std::string& command, const std::string& arguments, int timeoutMs) {+ const std::string uuid = xml::toHex(crypto::randomBytes(16));+ std::string path = "/" + command + "?uniqueid=" + (useTrueUniqueId_ ? identity_.uniqueId : std::string(kSharedUniqueId)) + "&uuid=" + uuid;+ if (!arguments.empty()) path += "&" + arguments;+ HttpTarget target;+ target.host = address_.host;+ target.port = tls ? httpsPort_ : address_.httpPort;+ target.tls = tls;+ HttpOptions options;+ options.timeoutMs = timeoutMs;+ options.cancel = cancel_;+ return http_.get(target, path, options);+}++std::string ServerClient::request(bool tls, const std::string& command, const std::string& arguments, int timeoutMs) {+ return fetch(tls, command, arguments, timeoutMs).body;+}++xml::Node ServerClient::checkedRoot(const std::string& body) {+ auto root = xml::parse(body);+ if (!root || root->name != "root") throw StatusError(-1, "Malformed XML (missing root element)");+ const auto code = root->attributes.find("status_code");+ // The status can be 0xFFFFFFFF in rare cases, so read it unsigned and cast.+ const int status = code == root->attributes.end() ? -1 : int(uint32_t(std::strtoul(code->second.c_str(), nullptr, 10)));+ if (status == 200) return std::move(*root);+ std::string message;+ if (const auto it = root->attributes.find("status_message"); it != root->attributes.end()) message = it->second;+ int reported = status;+ // GFE's unhelpful answer to a missing audio capture device.+ if (status == -1 && message == "Invalid") {+ reported = 418;+ message = "Missing audio capture device";+ }+ throw StatusError(reported, message);+}++ServerInfo ServerClient::parseServerInfo(const xml::Node& root) {+ ServerInfo info;+ info.hostname = xml::textOf(root, "hostname");+ if (info.hostname.empty()) info.hostname = "UNKNOWN";+ info.uniqueId = xml::textOf(root, "uniqueid");+ info.mac = xml::textOf(root, "mac");+ const std::string codecSupport = xml::textOf(root, "ServerCodecModeSupport");+ info.serverCodecModeSupport = codecSupport.empty() ? kServerH264 : toInt(codecSupport, kServerH264);+ info.maxLumaPixelsHevc = toInt(xml::textOf(root, "MaxLumaPixelsHEVC"));+ info.localIp = xml::textOf(root, "LocalIP");+ const uint16_t https = toPort(xml::textOf(root, "HttpsPort"));+ info.httpsPort = https ? https : kDefaultHttpsPort;+ info.externalPort = toPort(xml::textOf(root, "ExternalPort"));+ info.externalIp = xml::textOf(root, "ExternalIP");+ info.state = xml::textOf(root, "state");+ info.nvidiaServerSoftware = info.state.find("MJOLNIR") != std::string::npos;+ info.paired = xml::textOf(root, "PairStatus") == "1";+ info.appVersion = xml::textOf(root, "appversion");+ info.gfeVersion = xml::textOf(root, "GfeVersion");+ info.gpuModel = xml::textOf(root, "gputype");+ // GFE 2.8+ keeps currentgame set to the last game played, so it only counts+ // while the server reports itself busy.+ const auto endsWith = [](const std::string& s, const std::string& suffix) {+ return s.size() >= suffix.size() && s.compare(s.size() - suffix.size(), suffix.size(), suffix) == 0;+ };+ info.currentGame = endsWith(info.state, "_SERVER_BUSY") ? toInt(xml::textOf(root, "currentgame")) : 0;+ for (const xml::Node* mode : root.findAll("DisplayMode")) {+ DisplayMode parsed;+ parsed.width = toInt(xml::textOf(*mode, "Width"));+ parsed.height = toInt(xml::textOf(*mode, "Height"));+ parsed.refreshRate = toInt(xml::textOf(*mode, "RefreshRate"));+ info.displayModes.push_back(parsed);+ }+ std::stable_sort(info.displayModes.begin(), info.displayModes.end(), [](const DisplayMode& a, const DisplayMode& b) {+ return uint64_t(a.width) * uint64_t(a.height) * uint64_t(a.refreshRate) < uint64_t(b.width) * uint64_t(b.height) * uint64_t(b.refreshRate);+ });+ return info;+}++std::vector<AppEntry> ServerClient::parseAppList(const xml::Node& root) {+ std::vector<AppEntry> apps;+ for (const xml::Node* app : root.findAll("App")) {+ // An app needs at least a title element (an empty one is allowed) and an id.+ if (!app->find("AppTitle") || !app->find("ID")) throw StatusError(-1, "Invalid applist XML");+ AppEntry entry;+ entry.name = xml::textOf(*app, "AppTitle");+ entry.id = toInt(xml::textOf(*app, "ID"));+ entry.hdrSupported = xml::textOf(*app, "IsHdrSupported") == "1";+ entry.isAppCollectorGame = xml::textOf(*app, "IsAppCollectorGame") == "1";+ apps.push_back(std::move(entry));+ }+ return apps;+}++ServerInfo ServerClient::serverInfo(bool fastFail) {+ const int timeout = fastFail ? kFastFailTimeoutMs : kRequestTimeoutMs;+ for (;;) {+ const bool httpsPossible = !http_.pinnedServerCertificate().empty() && httpsPort_ != 0;+ if (httpsPossible) {+ // Always try HTTPS first, since it properly reports the pairing status.+ try {+ return parseServerInfo(checkedRoot(request(true, "serverinfo", "", timeout)));+ } catch (const StatusError& e) {+ if (e.status != 401) throw;+ } catch (const TransportError& e) {+ // Certificate mismatch or a client certificate the host does not know: fall back to HTTP.+ if (e.kind != TransportError::Kind::Tls) throw;+ }+ return parseServerInfo(checkedRoot(request(false, "serverinfo", "", timeout)));+ }+ // Before pairing only HTTP is used. It also tells us the HTTPS port.+ const ServerInfo info = parseServerInfo(checkedRoot(request(false, "serverinfo", "", timeout)));+ httpsPort_ = info.httpsPort;+ if (!http_.pinnedServerCertificate().empty()) continue; // now the HTTPS port is known+ return info;+ }+}++std::vector<AppEntry> ServerClient::appList() {+ return parseAppList(checkedRoot(request(true, "applist", "", kRequestTimeoutMs)));+}++std::string ServerClient::launch(const char* verb, const LaunchRequest& r, bool nvidiaServerSoftware) {+ // A frame rate above 60 makes GFE's SOPS fall back to 720p60; asking for 0 keeps+ // the requested resolution. Sunshine does not need the workaround.+ const int fps = (r.fps > 60 && nvidiaServerSoftware) ? 0 : r.fps;+ const int32_t keyId = int32_t((uint32_t(r.remoteInputKeyId[0]) << 24) | (uint32_t(r.remoteInputKeyId[1]) << 16) |+ (uint32_t(r.remoteInputKeyId[2]) << 8) | uint32_t(r.remoteInputKeyId[3]));+ std::string key(reinterpret_cast<const char*>(r.remoteInputKey.data()), r.remoteInputKey.size());+ std::string arguments = "appid=" + std::to_string(r.appId) ++ "&mode=" + std::to_string(r.width) + "x" + std::to_string(r.height) + "x" + std::to_string(fps) ++ "&additionalStates=1&sops=" + (r.sops ? "1" : "0") ++ "&rikey=" + xml::toHex(key) + "&rikeyid=" + std::to_string(keyId) ++ (r.hdr ? "&hdrMode=1&clientHdrCapVersion=0&clientHdrCapSupportedFlagsInUint32=0&clientHdrCapMetaDataId=NV_STATIC_METADATA_TYPE_1&clientHdrCapDisplayData=0x0x0x0x0x0x0x0x0x0x0" : "") ++ "&localAudioPlayMode=" + (r.localAudio ? "1" : "0") ++ "&surroundAudioInfo=" + std::to_string(r.surroundAudioInfo) ++ "&remoteControllersBitmap=" + std::to_string(r.gamepadMask) ++ "&gcmap=" + std::to_string(r.gamepadMask) ++ "&gcpersist=" + (r.persistGamepads ? "1" : "0") + r.extraQuery;+ const xml::Node root = checkedRoot(request(true, verb, arguments, kLaunchTimeoutMs));+ return xml::textOf(root, "sessionUrl0");+}++void ServerClient::quit() {+ checkedRoot(request(true, "cancel", "", kQuitTimeoutMs));+ // Newer GFE answers success even when quitting another client's game fails.+ if (serverInfo().currentGame != 0) throw StatusError(599, "");+}++void ServerClient::unpair() {+ request(false, "unpair", "", kRequestTimeoutMs);+}++std::string ServerClient::boxArt(int appId) {+ const HttpResponse response = fetch(true, "appasset", "appid=" + std::to_string(appId) + "&AssetType=2&AssetIdx=0", kRequestTimeoutMs);+ if (response.status != 200) throw StatusError(response.status, "box art not available");+ return response.body;+}++} // namespace veyra::moonlightdiff --git a/src/moonlight/Crypto.cpp b/src/moonlight/Crypto.cppnew file mode 100644index 00000000..608a99b4--- /dev/null+++ b/src/moonlight/Crypto.cpp@@ -0,0 +1,178 @@+// SPDX-License-Identifier: GPL-3.0-only+#include "veyra/moonlight/Crypto.h"++#include <openssl/bio.h>+#include <openssl/evp.h>+#include <openssl/pem.h>+#include <openssl/rand.h>+#include <openssl/x509.h>++#include <cctype>+#include <memory>+#include <new>+#include <stdexcept>++namespace veyra::moonlight {++namespace {++struct BioFree { void operator()(BIO* p) const { BIO_free_all(p); } };+struct X509Free { void operator()(X509* p) const { X509_free(p); } };+struct PkeyFree { void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); } };+struct CtxFree { void operator()(EVP_CIPHER_CTX* p) const { EVP_CIPHER_CTX_free(p); } };+struct MdFree { void operator()(EVP_MD_CTX* p) const { EVP_MD_CTX_free(p); } };++using BioPtr = std::unique_ptr<BIO, BioFree>;+using X509Ptr = std::unique_ptr<X509, X509Free>;+using PkeyPtr = std::unique_ptr<EVP_PKEY, PkeyFree>;++X509Ptr readCertificate(std::string_view pem) {+ if (pem.empty() || pem.size() > (1u << 16)) return nullptr;+ BioPtr bio(BIO_new_mem_buf(pem.data(), int(pem.size())));+ if (!bio) return nullptr;+ return X509Ptr(PEM_read_bio_X509(bio.get(), nullptr, nullptr, nullptr));+}++PkeyPtr readPrivateKey(std::string_view pem) {+ if (pem.empty() || pem.size() > (1u << 16)) return nullptr;+ BioPtr bio(BIO_new_mem_buf(pem.data(), int(pem.size())));+ if (!bio) return nullptr;+ return PkeyPtr(PEM_read_bio_PrivateKey(bio.get(), nullptr, nullptr, nullptr));+}++std::string memoryContents(BIO* bio) {+ BUF_MEM* mem = nullptr;+ BIO_get_mem_ptr(bio, &mem);+ return mem ? std::string(mem->data, mem->length) : std::string();+}++bool isLowerHex16(const std::string& id) {+ if (id.size() != 16) return false;+ for (char c : id) if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false;+ return true;+}++std::string aesEcb(std::string_view input, std::string_view key, bool encrypt) {+ if (input.empty() || input.size() % 16 || key.size() < 16) return {};+ std::unique_ptr<EVP_CIPHER_CTX, CtxFree> ctx(EVP_CIPHER_CTX_new());+ if (!ctx) throw std::bad_alloc();+ if (EVP_CipherInit_ex(ctx.get(), EVP_aes_128_ecb(), nullptr, reinterpret_cast<const unsigned char*>(key.data()), nullptr, encrypt ? 1 : 0) != 1) return {};+ EVP_CIPHER_CTX_set_padding(ctx.get(), 0);+ std::string out(input.size(), '\0');+ int produced = 0;+ if (EVP_CipherUpdate(ctx.get(), reinterpret_cast<unsigned char*>(out.data()), &produced,+ reinterpret_cast<const unsigned char*>(input.data()), int(input.size())) != 1 || size_t(produced) != input.size()) return {};+ return out;+}++} // namespace++bool Identity::valid() const {+ if (!isLowerHex16(uniqueId)) return false;+ auto cert = readCertificate(certPem);+ auto key = readPrivateKey(keyPem);+ if (!cert || !key) return false;+ // The key must be the one the certificate was issued for.+ return X509_check_private_key(cert.get(), key.get()) == 1;+}++Identity createIdentity() {+ PkeyPtr key(EVP_RSA_gen(2048));+ if (!key) throw std::runtime_error("RSA key generation failed");+ X509Ptr cert(X509_new());+ if (!cert) throw std::bad_alloc();+ X509_set_version(cert.get(), 2);+ ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), 0);+ X509_gmtime_adj(X509_getm_notBefore(cert.get()), 0);+ X509_gmtime_adj(X509_getm_notAfter(cert.get()), 60L * 60 * 24 * 365 * 20);+ X509_set_pubkey(cert.get(), key.get());+ X509_NAME* name = X509_NAME_new();+ if (!name) throw std::bad_alloc();+ X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC,+ reinterpret_cast<const unsigned char*>("NVIDIA GameStream Client"), -1, -1, 0);+ X509_set_subject_name(cert.get(), name);+ X509_set_issuer_name(cert.get(), name);+ X509_NAME_free(name);+ if (X509_sign(cert.get(), key.get(), EVP_sha256()) <= 0) throw std::runtime_error("certificate signing failed");++ BioPtr keyBio(BIO_new(BIO_s_mem())), certBio(BIO_new(BIO_s_mem()));+ if (!keyBio || !certBio) throw std::bad_alloc();+ PEM_write_bio_PrivateKey(keyBio.get(), key.get(), nullptr, nullptr, 0, nullptr, nullptr);+ PEM_write_bio_X509(certBio.get(), cert.get());++ Identity identity;+ identity.keyPem = memoryContents(keyBio.get());+ identity.certPem = memoryContents(certBio.get());+ static constexpr char digits[] = "0123456789abcdef";+ for (unsigned char c : crypto::randomBytes(8)) { identity.uniqueId.push_back(digits[c >> 4]); identity.uniqueId.push_back(digits[c & 15]); }+ if (!identity.valid()) throw std::runtime_error("newly generated identity is unreadable");+ return identity;+}++namespace crypto {++std::string randomBytes(size_t count) {+ std::string out(count, '\0');+ if (count && RAND_bytes(reinterpret_cast<unsigned char*>(out.data()), int(count)) != 1) throw std::runtime_error("RAND_bytes failed");+ return out;+}++std::string digest(std::string_view data, bool sha256) {+ unsigned char buffer[EVP_MAX_MD_SIZE];+ unsigned int length = 0;+ if (EVP_Digest(data.data(), data.size(), buffer, &length, sha256 ? EVP_sha256() : EVP_sha1(), nullptr) != 1) return {};+ return std::string(reinterpret_cast<char*>(buffer), length);+}++std::string aesEcbEncrypt(std::string_view plain, std::string_view key) { return aesEcb(plain, key, true); }+std::string aesEcbDecrypt(std::string_view cipher, std::string_view key) { return aesEcb(cipher, key, false); }++std::string sign(const Identity& identity, std::string_view message) {+ auto key = readPrivateKey(identity.keyPem);+ if (!key) return {};+ std::unique_ptr<EVP_MD_CTX, MdFree> ctx(EVP_MD_CTX_new());+ if (!ctx) throw std::bad_alloc();+ if (EVP_DigestSignInit(ctx.get(), nullptr, EVP_sha256(), nullptr, key.get()) != 1) return {};+ if (EVP_DigestSignUpdate(ctx.get(), message.data(), message.size()) != 1) return {};+ size_t length = 0;+ if (EVP_DigestSignFinal(ctx.get(), nullptr, &length) != 1) return {};+ std::string signature(length, '\0');+ if (EVP_DigestSignFinal(ctx.get(), reinterpret_cast<unsigned char*>(signature.data()), &length) != 1) return {};+ signature.resize(length);+ return signature;+}++bool verify(std::string_view message, std::string_view signature, std::string_view certPem) {+ auto cert = readCertificate(certPem);+ if (!cert) return false;+ PkeyPtr key(X509_get_pubkey(cert.get()));+ if (!key) return false;+ std::unique_ptr<EVP_MD_CTX, MdFree> ctx(EVP_MD_CTX_new());+ if (!ctx) throw std::bad_alloc();+ if (EVP_DigestVerifyInit(ctx.get(), nullptr, EVP_sha256(), nullptr, key.get()) != 1) return false;+ if (EVP_DigestVerifyUpdate(ctx.get(), message.data(), message.size()) != 1) return false;+ return EVP_DigestVerifyFinal(ctx.get(), reinterpret_cast<const unsigned char*>(signature.data()), signature.size()) == 1;+}++std::string certificateSignature(std::string_view certPem) {+ auto cert = readCertificate(certPem);+ if (!cert) return {};+ const ASN1_BIT_STRING* signature = nullptr;+ X509_get0_signature(&signature, nullptr, cert.get());+ if (!signature) return {};+ return std::string(reinterpret_cast<const char*>(ASN1_STRING_get0_data(signature)), size_t(ASN1_STRING_length(signature)));+}++std::string certificateDer(std::string_view certPem) {+ auto cert = readCertificate(certPem);+ if (!cert) return {};+ unsigned char* der = nullptr;+ const int length = i2d_X509(cert.get(), &der);+ if (length <= 0 || !der) return {};+ std::string out(reinterpret_cast<char*>(der), size_t(length));+ OPENSSL_free(der);+ return out;+}++} // namespace crypto+} // namespace veyra::moonlightdiff --git a/src/moonlight/Http.cpp b/src/moonlight/Http.cppnew file mode 100644index 00000000..f6012d7c--- /dev/null+++ b/src/moonlight/Http.cpp@@ -0,0 +1,341 @@+// SPDX-License-Identifier: GPL-3.0-only+#include "veyra/moonlight/Http.h"++#include <winsock2.h>+#include <ws2tcpip.h>++#include <openssl/bio.h>+#include <openssl/err.h>+#include <openssl/pem.h>+#include <openssl/ssl.h>+#include <openssl/x509.h>++#include <algorithm>+#include <cctype>+#include <chrono>+#include <cstdlib>+#include <cstring>+#include <memory>+#include <string_view>+#include <new>++namespace veyra::moonlight {++namespace {++using Clock = std::chrono::steady_clock;++struct WsaInit {+ WsaInit() { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }+ ~WsaInit() { WSACleanup(); }+};+void ensureWinsock() { static WsaInit init; }++struct Wait {+ Clock::time_point deadline;+ bool infinite = false;+ const std::atomic<bool>* cancel = nullptr;+};++void check(const Wait& w) {+ if (w.cancel && w.cancel->load(std::memory_order_relaxed)) throw TransportError(TransportError::Kind::Cancelled, "cancelled");+ if (!w.infinite && Clock::now() >= w.deadline) throw TransportError(TransportError::Kind::Timeout, "request timed out");+}++// Waits until the socket is ready (or has failed: a refused non-blocking connect+// is reported through the except set on Windows). Slices of 50 ms keep the+// cancel flag and the deadline responsive.+void waitSocket(SOCKET s, bool forRead, bool forWrite, const Wait& w) {+ for (;;) {+ check(w);+ fd_set readSet, writeSet, errorSet;+ FD_ZERO(&readSet); FD_ZERO(&writeSet); FD_ZERO(&errorSet);+ if (forRead) FD_SET(s, &readSet);+ if (forWrite) FD_SET(s, &writeSet);+ FD_SET(s, &errorSet);+ timeval slice{0, 50 * 1000};+ const int ready = select(0, &readSet, &writeSet, &errorSet, &slice);+ if (ready > 0) return;+ if (ready == SOCKET_ERROR) throw TransportError(TransportError::Kind::Connect, "select failed");+ }+}++struct Socket {+ SOCKET handle = INVALID_SOCKET;+ Socket() = default;+ explicit Socket(SOCKET s) : handle(s) {}+ Socket(const Socket&) = delete;+ Socket& operator=(const Socket&) = delete;+ ~Socket() { if (handle != INVALID_SOCKET) closesocket(handle); }+};++struct AddrInfoFree { void operator()(addrinfo* p) const { freeaddrinfo(p); } };++SOCKET connectSocket(const std::string& host, uint16_t port, const Wait& overall) {+ addrinfo hints{};+ hints.ai_family = AF_UNSPEC;+ hints.ai_socktype = SOCK_STREAM;+ hints.ai_protocol = IPPROTO_TCP;+ addrinfo* raw = nullptr;+ const std::string portText = std::to_string(port);+ if (getaddrinfo(host.c_str(), portText.c_str(), &hints, &raw) != 0 || !raw)+ throw TransportError(TransportError::Kind::Connect, "cannot resolve the host address");+ std::unique_ptr<addrinfo, AddrInfoFree> list(raw);+ size_t candidates = 0;+ for (addrinfo* ai = raw; ai; ai = ai->ai_next) ++candidates;+ for (addrinfo* ai = raw; ai; ai = ai->ai_next) {+ SOCKET s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);+ if (s == INVALID_SOCKET) continue;+ u_long nonBlocking = 1;+ ioctlsocket(s, FIONBIO, &nonBlocking);+ // With several candidate addresses one unreachable family must not eat the whole budget.+ Wait attempt = overall;+ if (candidates > 1) {+ const auto cap = Clock::now() + std::chrono::seconds(3);+ if (attempt.infinite || cap < attempt.deadline) { attempt.deadline = cap; attempt.infinite = false; }+ }+ const int result = connect(s, ai->ai_addr, int(ai->ai_addrlen));+ if (result == SOCKET_ERROR) {+ if (WSAGetLastError() != WSAEWOULDBLOCK) { closesocket(s); continue; }+ try {+ waitSocket(s, false, true, attempt);+ } catch (const TransportError& e) {+ closesocket(s);+ if (e.kind == TransportError::Kind::Timeout && candidates > 1 && Clock::now() < overall.deadline) continue;+ throw;+ }+ int error = 0;+ int length = sizeof(error);+ getsockopt(s, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&error), &length);+ if (error != 0) { closesocket(s); continue; }+ }+ BOOL noDelay = TRUE;+ setsockopt(s, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<const char*>(&noDelay), sizeof(noDelay));+ return s;+ }+ throw TransportError(TransportError::Kind::Connect, "the host did not accept the connection");+}++struct CtxFree { void operator()(SSL_CTX* p) const { SSL_CTX_free(p); } };+struct SslFree { void operator()(SSL* p) const { SSL_free(p); } };+struct BioFree { void operator()(BIO* p) const { BIO_free_all(p); } };+struct X509Free { void operator()(X509* p) const { X509_free(p); } };+struct PkeyFree { void operator()(EVP_PKEY* p) const { EVP_PKEY_free(p); } };++std::unique_ptr<SSL_CTX, CtxFree> makeContext(const Identity& identity) {+ std::unique_ptr<SSL_CTX, CtxFree> ctx(SSL_CTX_new(TLS_client_method()));+ if (!ctx) throw std::bad_alloc();+ SSL_CTX_set_min_proto_version(ctx.get(), TLS1_2_VERSION);+ // The host's certificate is self-signed: trust comes from the pinned copy,+ // compared right after the handshake and before anything is sent.+ SSL_CTX_set_verify(ctx.get(), SSL_VERIFY_NONE, nullptr);+ std::unique_ptr<BIO, BioFree> certBio(BIO_new_mem_buf(identity.certPem.data(), int(identity.certPem.size())));+ std::unique_ptr<BIO, BioFree> keyBio(BIO_new_mem_buf(identity.keyPem.data(), int(identity.keyPem.size())));+ std::unique_ptr<X509, X509Free> cert(certBio ? PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr) : nullptr);+ std::unique_ptr<EVP_PKEY, PkeyFree> key(keyBio ? PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr) : nullptr);+ if (!cert || !key || SSL_CTX_use_certificate(ctx.get(), cert.get()) != 1 || SSL_CTX_use_PrivateKey(ctx.get(), key.get()) != 1)+ throw TransportError(TransportError::Kind::Tls, "the client identity could not be loaded");+ return ctx;+}++// One connection, plain or TLS, read and written under the same deadline.+class Connection {+public:+ Connection(SOCKET socket, SSL* ssl, const Wait& wait) : socket_(socket), ssl_(ssl), wait_(wait) {}++ void writeAll(std::string_view data) {+ size_t sent = 0;+ while (sent < data.size()) {+ check(wait_);+ const int chunk = int(std::min<size_t>(data.size() - sent, 1 << 16));+ if (ssl_) {+ const int n = SSL_write(ssl_, data.data() + sent, chunk);+ if (n > 0) { sent += size_t(n); continue; }+ const int error = SSL_get_error(ssl_, n);+ if (error == SSL_ERROR_WANT_READ) waitSocket(socket_, true, false, wait_);+ else if (error == SSL_ERROR_WANT_WRITE) waitSocket(socket_, false, true, wait_);+ else throw TransportError(TransportError::Kind::Tls, "TLS write failed");+ } else {+ const int n = send(socket_, data.data() + sent, chunk, 0);+ if (n > 0) { sent += size_t(n); continue; }+ if (WSAGetLastError() == WSAEWOULDBLOCK) waitSocket(socket_, false, true, wait_);+ else throw TransportError(TransportError::Kind::Connect, "send failed");+ }+ }+ }++ // 0 means the peer closed the connection.+ size_t read(char* buffer, size_t capacity) {+ for (;;) {+ check(wait_);+ if (ssl_) {+ const int n = SSL_read(ssl_, buffer, int(std::min<size_t>(capacity, 1 << 16)));+ if (n > 0) { receivedAny_ = true; return size_t(n); }+ const int error = SSL_get_error(ssl_, n);+ if (error == SSL_ERROR_WANT_READ) waitSocket(socket_, true, false, wait_);+ else if (error == SSL_ERROR_WANT_WRITE) waitSocket(socket_, false, true, wait_);+ else if (error == SSL_ERROR_ZERO_RETURN) return 0;+ // A host that closes without a TLS close_notify after answering is still a complete answer.+ else if (error == SSL_ERROR_SYSCALL && receivedAny_) return 0;+ else throw TransportError(TransportError::Kind::Tls, "TLS read failed");+ } else {+ const int n = recv(socket_, buffer, int(std::min<size_t>(capacity, 1 << 16)), 0);+ if (n > 0) { receivedAny_ = true; return size_t(n); }+ if (n == 0) return 0;+ if (WSAGetLastError() == WSAEWOULDBLOCK) waitSocket(socket_, true, false, wait_);+ else if (receivedAny_) return 0;+ else throw TransportError(TransportError::Kind::Connect, "receive failed");+ }+ }+ }++private:+ SOCKET socket_;+ SSL* ssl_;+ Wait wait_;+ bool receivedAny_ = false;+};++std::string lower(std::string text) {+ std::transform(text.begin(), text.end(), text.begin(), [](unsigned char c) { return char(std::tolower(c)); });+ return text;+}++std::string trim(std::string_view text) {+ while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) text.remove_prefix(1);+ while (!text.empty() && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r')) text.remove_suffix(1);+ return std::string(text);+}++HttpResponse readResponse(Connection& connection, size_t maxBody) {+ std::string buffer;+ char chunk[8192];+ size_t headerEnd = std::string::npos;+ while ((headerEnd = buffer.find("\r\n\r\n")) == std::string::npos) {+ if (buffer.size() > (1u << 16)) throw TransportError(TransportError::Kind::Protocol, "response headers too large");+ const size_t n = connection.read(chunk, sizeof(chunk));+ if (n == 0) throw TransportError(TransportError::Kind::Protocol, "connection closed before the response headers ended");+ buffer.append(chunk, n);+ }+ HttpResponse response;+ const std::string head = buffer.substr(0, headerEnd);+ std::string body = buffer.substr(headerEnd + 4);++ const auto firstLineEnd = head.find("\r\n");+ const std::string statusLine = head.substr(0, firstLineEnd);+ if (statusLine.rfind("HTTP/1.", 0) != 0 || statusLine.size() < 12)+ throw TransportError(TransportError::Kind::Protocol, "malformed HTTP status line");+ response.status = std::atoi(statusLine.c_str() + 9);++ long long contentLength = -1;+ bool chunked = false;+ size_t position = firstLineEnd == std::string::npos ? head.size() : firstLineEnd + 2;+ while (position < head.size()) {+ const auto end = head.find("\r\n", position);+ const std::string line = head.substr(position, end == std::string::npos ? std::string::npos : end - position);+ position = end == std::string::npos ? head.size() : end + 2;+ const auto colon = line.find(':');+ if (colon == std::string::npos) continue;+ const std::string name = lower(line.substr(0, colon));+ const std::string value = trim(std::string_view(line).substr(colon + 1));+ if (name == "content-length") contentLength = std::atoll(value.c_str());+ else if (name == "transfer-encoding" && lower(value).find("chunked") != std::string::npos) chunked = true;+ }+ if (contentLength > 0 && size_t(contentLength) > maxBody) throw TransportError(TransportError::Kind::Protocol, "response body too large");++ if (chunked) {+ std::string decoded;+ size_t cursor = 0;+ for (;;) {+ // Make sure a full chunk-size line is buffered.+ size_t lineEnd;+ while ((lineEnd = body.find("\r\n", cursor)) == std::string::npos) {+ const size_t n = connection.read(chunk, sizeof(chunk));+ if (n == 0) throw TransportError(TransportError::Kind::Protocol, "connection closed inside a chunked body");+ body.append(chunk, n);+ }+ const size_t size = std::strtoull(body.substr(cursor, lineEnd - cursor).c_str(), nullptr, 16);+ cursor = lineEnd + 2;+ if (size == 0) break;+ if (decoded.size() + size > maxBody) throw TransportError(TransportError::Kind::Protocol, "response body too large");+ while (body.size() < cursor + size + 2) {+ const size_t n = connection.read(chunk, sizeof(chunk));+ if (n == 0) throw TransportError(TransportError::Kind::Protocol, "connection closed inside a chunked body");+ body.append(chunk, n);+ }+ decoded.append(body, cursor, size);+ cursor += size + 2;+ }+ response.body = std::move(decoded);+ } else if (contentLength >= 0) {+ while (body.size() < size_t(contentLength)) {+ const size_t n = connection.read(chunk, sizeof(chunk));+ if (n == 0) throw TransportError(TransportError::Kind::Protocol, "connection closed before the body was complete");+ body.append(chunk, n);+ }+ body.resize(size_t(contentLength));+ response.body = std::move(body);+ } else {+ for (;;) {+ const size_t n = connection.read(chunk, sizeof(chunk));+ if (n == 0) break;+ if (body.size() + n > maxBody) throw TransportError(TransportError::Kind::Protocol, "response body too large");+ body.append(chunk, n);+ }+ response.body = std::move(body);+ }+ return response;+}++} // namespace++HttpClient::HttpClient(const Identity* identity, std::string pinnedServerCertPem)+ : identity_(identity), pinned_(std::move(pinnedServerCertPem)) {}++HttpResponse HttpClient::get(const HttpTarget& target, const std::string& pathAndQuery, const HttpOptions& options) const {+ ensureWinsock();+ Wait wait;+ wait.infinite = options.timeoutMs <= 0;+ wait.deadline = Clock::now() + std::chrono::milliseconds(std::max(0, options.timeoutMs));+ wait.cancel = options.cancel;+ if (target.tls && (!identity_ || pinned_.empty()))+ throw TransportError(TransportError::Kind::Tls, "HTTPS needs a client identity and a pinned server certificate");++ Socket socket(connectSocket(target.host, target.port, wait));++ std::unique_ptr<SSL_CTX, CtxFree> context;+ std::unique_ptr<SSL, SslFree> ssl;+ if (target.tls) {+ context = makeContext(*identity_);+ ssl.reset(SSL_new(context.get()));+ if (!ssl) throw std::bad_alloc();+ SSL_set_fd(ssl.get(), static_cast<int>(socket.handle));+ SSL_set_connect_state(ssl.get());+ for (;;) {+ const int result = SSL_connect(ssl.get());+ if (result == 1) break;+ const int error = SSL_get_error(ssl.get(), result);+ if (error == SSL_ERROR_WANT_READ) waitSocket(socket.handle, true, false, wait);+ else if (error == SSL_ERROR_WANT_WRITE) waitSocket(socket.handle, false, true, wait);+ else throw TransportError(TransportError::Kind::Tls, "TLS handshake failed");+ }+ std::unique_ptr<X509, X509Free> peer(SSL_get1_peer_certificate(ssl.get()));+ std::unique_ptr<BIO, BioFree> pinBio(BIO_new_mem_buf(pinned_.data(), int(pinned_.size())));+ std::unique_ptr<X509, X509Free> pin(pinBio ? PEM_read_bio_X509(pinBio.get(), nullptr, nullptr, nullptr) : nullptr);+ if (!peer || !pin || X509_cmp(peer.get(), pin.get()) != 0)+ throw TransportError(TransportError::Kind::Tls, "the server certificate does not match the paired one");+ }++ const bool defaultPort = (target.tls && target.port == 443) || (!target.tls && target.port == 80);+ const bool ipv6 = target.host.find(':') != std::string::npos;+ std::string hostHeader = ipv6 ? "[" + target.host + "]" : target.host;+ if (!defaultPort) hostHeader += ":" + std::to_string(target.port);+ const std::string request = "GET " + pathAndQuery + " HTTP/1.1\r\nHost: " + hostHeader ++ "\r\nConnection: close\r\nAccept: */*\r\nUser-Agent: Veyra\r\n\r\n";++ Connection connection(socket.handle, ssl.get(), wait);+ connection.writeAll(request);+ return readResponse(connection, options.maxBodyBytes);+}++} // namespace veyra::moonlightdiff --git a/src/moonlight/IdentityStore.cpp b/src/moonlight/IdentityStore.cppnew file mode 100644index 00000000..1159e791--- /dev/null+++ b/src/moonlight/IdentityStore.cpp@@ -0,0 +1,116 @@+// SPDX-License-Identifier: GPL-3.0-only+#include "veyra/moonlight/IdentityStore.h"++#include <windows.h>+#include <shlobj.h>+#include <wincrypt.h>++#include <cstring>+#include <fstream>+#include <iterator>+#include <stdexcept>+#include <vector>++namespace veyra::moonlight {++namespace {++constexpr char kMagic[4] = {'V', 'M', 'L', '1'};++struct Secret {+ std::vector<uint8_t> bytes;+ ~Secret() { if (!bytes.empty()) SecureZeroMemory(bytes.data(), bytes.size()); }+};++struct Blob {+ DATA_BLOB value{};+ ~Blob() {+ if (value.pbData) { SecureZeroMemory(value.pbData, value.cbData); LocalFree(value.pbData); }+ }+};++void put(std::vector<uint8_t>& out, const std::string& text) {+ const uint32_t size = uint32_t(text.size());+ for (unsigned i = 0; i < 4; ++i) out.push_back(uint8_t(size >> (8 * i)));+ out.insert(out.end(), text.begin(), text.end());+}++bool take(const uint8_t*& cursor, const uint8_t* end, std::string& text) {+ if (end - cursor < 4) return false;+ const uint32_t size = uint32_t(cursor[0]) | (uint32_t(cursor[1]) << 8) | (uint32_t(cursor[2]) << 16) | (uint32_t(cursor[3]) << 24);+ cursor += 4;+ if (size > (1u << 16) || size_t(end - cursor) < size) return false;+ text.assign(reinterpret_cast<const char*>(cursor), size);+ cursor += size;+ return true;+}++} // namespace++std::filesystem::path dataDirectory() {+ PWSTR raw = nullptr;+ if (FAILED(SHGetKnownFolderPath(FOLDERID_LocalAppData, 0, nullptr, &raw)))+ throw std::runtime_error("Cannot resolve the user data directory");+ std::filesystem::path result(raw);+ CoTaskMemFree(raw);+ return result / L"Veyra" / L"moonlight";+}++std::optional<Identity> loadIdentity(const std::filesystem::path& file) {+ std::ifstream in(file, std::ios::binary);+ if (!in) return std::nullopt;+ std::vector<uint8_t> encrypted((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());+ if (encrypted.empty() || encrypted.size() > (1u << 20)) return std::nullopt;+ DATA_BLOB input{DWORD(encrypted.size()), encrypted.data()};+ Blob plain;+ if (!CryptUnprotectData(&input, nullptr, nullptr, nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN, &plain.value)) return std::nullopt;+ const uint8_t* cursor = plain.value.pbData;+ const uint8_t* end = cursor + plain.value.cbData;+ if (end - cursor < 4 || std::memcmp(cursor, kMagic, 4) != 0) return std::nullopt;+ cursor += 4;+ Identity identity;+ if (!take(cursor, end, identity.uniqueId) || !take(cursor, end, identity.certPem) || !take(cursor, end, identity.keyPem) || cursor != end)+ return std::nullopt;+ if (!identity.valid()) return std::nullopt;+ return identity;+}++bool saveIdentity(const std::filesystem::path& file, const Identity& identity) {+ if (!identity.valid()) return false;+ Secret plain;+ plain.bytes.insert(plain.bytes.end(), kMagic, kMagic + 4);+ put(plain.bytes, identity.uniqueId);+ put(plain.bytes, identity.certPem);+ put(plain.bytes, identity.keyPem);+ DATA_BLOB input{DWORD(plain.bytes.size()), plain.bytes.data()};+ Blob encrypted;+ if (!CryptProtectData(&input, L"Veyra Moonlight identity", nullptr, nullptr, nullptr, CRYPTPROTECT_UI_FORBIDDEN, &encrypted.value)) return false;++ std::error_code ec;+ std::filesystem::create_directories(file.parent_path(), ec);+ if (ec) return false;+ auto temp = file;+ temp += L"." + std::to_wstring(GetCurrentProcessId()) + L"." + std::to_wstring(GetTickCount64()) + L".tmp";+ HANDLE handle = CreateFileW(temp.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr);+ if (handle == INVALID_HANDLE_VALUE) return false;+ DWORD written = 0;+ bool ok = WriteFile(handle, encrypted.value.pbData, encrypted.value.cbData, &written, nullptr) && written == encrypted.value.cbData;+ if (ok) ok = FlushFileBuffers(handle) != FALSE;+ CloseHandle(handle);+ if (ok) ok = MoveFileExW(temp.c_str(), file.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != FALSE;+ if (!ok) DeleteFileW(temp.c_str());+ return ok;+}++Identity loadOrCreateIdentity(const std::filesystem::path& file, bool* created) {+ if (auto existing = loadIdentity(file)) {+ if (created) *created = false;+ return *existing;+ }+ Identity fresh = createIdentity();+ if (!saveIdentity(file, fresh)) throw std::runtime_error("The Moonlight identity could not be saved");+ if (created) *created = true;+ return fresh;+}++} // namespace veyra::moonlightdiff --git a/src/moonlight/Pairing.cpp b/src/moonlight/Pairing.cppnew file mode 100644index 00000000..d65eb54b--- /dev/null+++ b/src/moonlight/Pairing.cpp@@ -0,0 +1,140 @@+// SPDX-License-Identifier: GPL-3.0-only+#include "veyra/moonlight/Pairing.h"++#include <cstdio>++namespace veyra::moonlight {++namespace {++constexpr int kRequestTimeoutMs = 5000;+// What Sunshine shows in its list of paired clients.+constexpr const char* kDeviceName = "Veyra";++std::string tag(const xml::Node& root, const char* name) { return xml::textOf(root, name); }++// The steps after the first check "paired == 1"; anything else aborts the pairing.+bool pairedFlag(const xml::Node& root) { return tag(root, "paired") == "1"; }++} // namespace++std::string generatePin() {+ const std::string random = crypto::randomBytes(4);+ uint32_t value = 0;+ for (unsigned char c : random) value = (value << 8) | c;+ char text[8];+ std::snprintf(text, sizeof(text), "%04u", value % 10000u);+ return text;+}++PairOutcome pairWithHost(const ServerClient& original, const Identity& identity, const ServerInfo& host,+ const std::string& pin, const std::atomic<bool>* cancel) {+ ServerClient client(original);+ client.setCancel(cancel);+ PairOutcome outcome;+ const auto fail = [&](const char* detail) {+ outcome.result = PairResult::Failed;+ outcome.detail = detail;+ return outcome;+ };+ // Best effort: tell the host to forget a half finished pairing. It must not be+ // cancelled by the same flag, and failing is fine.+ const auto unpair = [&]() {+ try {+ ServerClient cleanup(original);+ cleanup.request(false, "unpair", "", 2000);+ } catch (...) {}+ };++ const bool sha256 = host.appVersionMajor() >= 7; // generation 7 and later hash with SHA-256+ const size_t hashLength = sha256 ? 32 : 20;+ const std::string common = std::string("devicename=") + kDeviceName + "&updateState=1&";++ try {+ const std::string salt = crypto::randomBytes(16);+ std::string aesKey = crypto::digest(salt + pin, sha256);+ aesKey.resize(16);++ // Stage 1: send our certificate, get the host's. This blocks until the PIN is entered.+ const xml::Node getCert = ServerClient::checkedRoot(client.request(false, "pair",+ common + "phrase=getservercert&salt=" + xml::toHex(salt) + "&clientcert=" + xml::toHex(identity.certPem), 0));+ if (!pairedFlag(getCert)) return fail("stage 1: the host refused the pairing request");+ const auto serverCertBytes = xml::fromHex(tag(getCert, "plaincert"));+ if (!serverCertBytes || serverCertBytes->empty()) {+ // The host is already pairing another client.+ unpair();+ outcome.result = PairResult::AlreadyInProgress;+ outcome.detail = "the host is already pairing";+ return outcome;+ }+ const std::string serverCert = *serverCertBytes;+ if (crypto::certificateDer(serverCert).empty()) { unpair(); return fail("stage 1: unreadable server certificate"); }++ // Stage 2: the host proves it knows the PIN.+ const std::string randomChallenge = crypto::randomBytes(16);+ const xml::Node challenge = ServerClient::checkedRoot(client.request(false, "pair",+ common + "clientchallenge=" + xml::toHex(crypto::aesEcbEncrypt(randomChallenge, aesKey)), kRequestTimeoutMs));+ if (!pairedFlag(challenge)) { unpair(); return fail("stage 2: challenge rejected"); }+ const auto responseBytes = xml::fromHex(tag(challenge, "challengeresponse"));+ const std::string challengeResponse = responseBytes ? crypto::aesEcbDecrypt(*responseBytes, aesKey) : std::string();+ if (challengeResponse.size() < hashLength + 16) { unpair(); return fail("stage 2: challenge response too short"); }++ // Stage 3: answer the host's challenge with a hash over it, our certificate signature and a secret.+ const std::string clientSecret = crypto::randomBytes(16);+ const std::string serverResponse = challengeResponse.substr(0, hashLength);+ std::string mix = challengeResponse.substr(hashLength, 16);+ mix += crypto::certificateSignature(identity.certPem);+ mix += clientSecret;+ std::string padded = crypto::digest(mix, sha256);+ padded.resize(32);+ const xml::Node secretStage = ServerClient::checkedRoot(client.request(false, "pair",+ common + "serverchallengeresp=" + xml::toHex(crypto::aesEcbEncrypt(padded, aesKey)), kRequestTimeoutMs));+ if (!pairedFlag(secretStage)) { unpair(); return fail("stage 3: response rejected"); }+ const auto pairingSecret = xml::fromHex(tag(secretStage, "pairingsecret"));+ if (!pairingSecret || pairingSecret->size() <= 16) { unpair(); return fail("stage 3: pairing secret too short"); }++ // The host signed its secret with the key of the certificate it gave us: a+ // mismatch means somebody else answered (man in the middle).+ const std::string serverSecret = pairingSecret->substr(0, 16);+ if (!crypto::verify(serverSecret, pairingSecret->substr(16), serverCert)) { unpair(); return fail("signature check failed: possible man in the middle"); }++ // The host's hash over our challenge proves it used the same PIN.+ std::string expected = randomChallenge;+ expected += crypto::certificateSignature(serverCert);+ expected += serverSecret;+ if (crypto::digest(expected, sha256) != serverResponse) {+ unpair();+ outcome.result = PairResult::PinWrong;+ outcome.detail = "the PIN does not match";+ return outcome;+ }++ // Stage 4: our own secret, signed, so the host can check us the same way.+ const xml::Node clientSecretStage = ServerClient::checkedRoot(client.request(false, "pair",+ common + "clientpairingsecret=" + xml::toHex(clientSecret + crypto::sign(identity, clientSecret)), kRequestTimeoutMs));+ if (!pairedFlag(clientSecretStage)) { unpair(); return fail("stage 4: pairing secret rejected"); }++ // Stage 5: prove the new pairing works over HTTPS with the pinned certificate.+ client.setPinnedServerCertificate(serverCert);+ const xml::Node finalStage = ServerClient::checkedRoot(client.request(true, "pair", common + "phrase=pairchallenge", kRequestTimeoutMs));+ if (!pairedFlag(finalStage)) { unpair(); return fail("stage 5: HTTPS check failed"); }++ outcome.result = PairResult::Paired;+ outcome.serverCertPem = serverCert;+ return outcome;+ } catch (const TransportError& e) {+ if (e.kind == TransportError::Kind::Cancelled) {+ unpair();+ outcome.result = PairResult::Cancelled;+ outcome.detail = "cancelled";+ return outcome;+ }+ unpair();+ return fail(e.what());+ } catch (const StatusError& e) {+ unpair();+ return fail(e.what());+ }+}++} // namespace veyra::moonlightdiff --git a/src/moonlight/Xml.cpp b/src/moonlight/Xml.cppnew file mode 100644index 00000000..2de74964--- /dev/null+++ b/src/moonlight/Xml.cpp@@ -0,0 +1,228 @@+// SPDX-License-Identifier: GPL-3.0-only+#include "veyra/moonlight/Xml.h"++#include <cctype>+#include <cstdint>++namespace veyra::moonlight::xml {++namespace {++bool isNameChar(char c) {+ return std::isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '-' || c == ':' || c == '.';+}++void appendUtf8(std::string& out, uint32_t code) {+ if (code < 0x80) out.push_back(char(code));+ else if (code < 0x800) { out.push_back(char(0xC0 | (code >> 6))); out.push_back(char(0x80 | (code & 0x3F))); }+ else if (code < 0x10000) {+ out.push_back(char(0xE0 | (code >> 12))); out.push_back(char(0x80 | ((code >> 6) & 0x3F))); out.push_back(char(0x80 | (code & 0x3F)));+ } else if (code <= 0x10FFFF) {+ out.push_back(char(0xF0 | (code >> 18))); out.push_back(char(0x80 | ((code >> 12) & 0x3F)));+ out.push_back(char(0x80 | ((code >> 6) & 0x3F))); out.push_back(char(0x80 | (code & 0x3F)));+ }+}++class Parser {+public:+ explicit Parser(std::string_view text) : s_(text) {}++ std::optional<Node> parseDocument() {+ if (s_.size() > kMaxDocumentBytes) return std::nullopt;+ skipMisc();+ Node root;+ if (!parseElement(root, 0)) return std::nullopt;+ return root;+ }++private:+ bool atEnd() const { return i_ >= s_.size(); }+ bool startsWith(std::string_view prefix) const { return s_.substr(i_, prefix.size()) == prefix; }+ void skipSpace() { while (!atEnd() && std::isspace(static_cast<unsigned char>(s_[i_]))) ++i_; }++ // Whitespace, the XML declaration, comments and a DOCTYPE before/after the root.+ void skipMisc() {+ for (;;) {+ skipSpace();+ if (startsWith("<?")) {+ const auto end = s_.find("?>", i_);+ if (end == std::string_view::npos) { i_ = s_.size(); return; }+ i_ = end + 2;+ } else if (startsWith("<!--")) {+ const auto end = s_.find("-->", i_ + 4);+ if (end == std::string_view::npos) { i_ = s_.size(); return; }+ i_ = end + 3;+ } else if (startsWith("<!DOCTYPE")) {+ const auto end = s_.find('>', i_);+ if (end == std::string_view::npos) { i_ = s_.size(); return; }+ i_ = end + 1;+ } else return;+ }+ }++ bool parseName(std::string& name) {+ const size_t start = i_;+ while (!atEnd() && isNameChar(s_[i_])) ++i_;+ if (i_ == start) return false;+ name.assign(s_.substr(start, i_ - start));+ return true;+ }++ bool parseAttributes(Node& node, bool& selfClosing) {+ selfClosing = false;+ for (;;) {+ skipSpace();+ if (atEnd()) return false;+ if (s_[i_] == '>') { ++i_; return true; }+ if (startsWith("/>")) { i_ += 2; selfClosing = true; return true; }+ std::string key;+ if (!parseName(key)) return false;+ skipSpace();+ if (atEnd() || s_[i_] != '=') return false;+ ++i_;+ skipSpace();+ if (atEnd() || (s_[i_] != '"' && s_[i_] != '\'')) return false;+ const char quote = s_[i_++];+ const auto end = s_.find(quote, i_);+ if (end == std::string_view::npos) return false;+ node.attributes[key] = decodeEntities(s_.substr(i_, end - i_));+ i_ = end + 1;+ }+ }++ bool parseElement(Node& node, int depth) {+ if (depth > kMaxDepth || atEnd() || s_[i_] != '<') return false;+ ++i_;+ if (!parseName(node.name)) return false;+ bool selfClosing = false;+ if (!parseAttributes(node, selfClosing)) return false;+ if (selfClosing) return true;+ for (;;) {+ if (atEnd()) return false;+ if (startsWith("</")) {+ i_ += 2;+ std::string closing;+ if (!parseName(closing) || closing != node.name) return false;+ skipSpace();+ if (atEnd() || s_[i_] != '>') return false;+ ++i_;+ return true;+ }+ if (startsWith("<!--")) {+ const auto end = s_.find("-->", i_ + 4);+ if (end == std::string_view::npos) return false;+ i_ = end + 3;+ } else if (startsWith("<![CDATA[")) {+ const auto end = s_.find("]]>", i_ + 9);+ if (end == std::string_view::npos) return false;+ node.text.append(s_.substr(i_ + 9, end - (i_ + 9)));+ i_ = end + 3;+ } else if (startsWith("<?")) {+ const auto end = s_.find("?>", i_);+ if (end == std::string_view::npos) return false;+ i_ = end + 2;+ } else if (s_[i_] == '<') {+ Node child;+ if (!parseElement(child, depth + 1)) return false;+ node.children.push_back(std::move(child));+ } else {+ const auto end = s_.find('<', i_);+ const auto stop = end == std::string_view::npos ? s_.size() : end;+ node.text.append(decodeEntities(s_.substr(i_, stop - i_)));+ i_ = stop;+ }+ }+ }++ std::string_view s_;+ size_t i_ = 0;+};++void collect(const Node& node, std::string_view name, std::vector<const Node*>& out) {+ for (const auto& child : node.children) {+ if (child.name == name) out.push_back(&child);+ collect(child, name, out);+ }+}++int hexDigit(char c) {+ if (c >= '0' && c <= '9') return c - '0';+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;+ return -1;+}++} // namespace++const Node* Node::find(std::string_view elementName) const {+ for (const auto& child : children) {+ if (child.name == elementName) return &child;+ if (const Node* deeper = child.find(elementName)) return deeper;+ }+ return nullptr;+}++std::vector<const Node*> Node::findAll(std::string_view elementName) const {+ std::vector<const Node*> out;+ collect(*this, elementName, out);+ return out;+}++std::optional<Node> parse(std::string_view document) { return Parser(document).parseDocument(); }++std::string decodeEntities(std::string_view text) {+ std::string out;+ out.reserve(text.size());+ for (size_t i = 0; i < text.size(); ++i) {+ if (text[i] != '&') { out.push_back(text[i]); continue; }+ const auto semi = text.find(';', i);+ if (semi == std::string_view::npos || semi - i > 10) { out.push_back('&'); continue; }+ const auto entity = text.substr(i + 1, semi - i - 1);+ if (entity == "amp") out.push_back('&');+ else if (entity == "lt") out.push_back('<');+ else if (entity == "gt") out.push_back('>');+ else if (entity == "quot") out.push_back('"');+ else if (entity == "apos") out.push_back('\'');+ else if (entity.size() > 1 && entity[0] == '#') {+ uint32_t code = 0;+ bool ok = true;+ const bool hex = entity[1] == 'x' || entity[1] == 'X';+ for (size_t k = hex ? 2 : 1; k < entity.size() && ok; ++k) {+ const int d = hex ? hexDigit(entity[k]) : (entity[k] >= '0' && entity[k] <= '9' ? entity[k] - '0' : -1);+ if (d < 0) ok = false; else code = code * (hex ? 16 : 10) + uint32_t(d);+ if (code > 0x10FFFF) ok = false;+ }+ if (ok && (hex ? entity.size() > 2 : true)) appendUtf8(out, code); else { out.push_back('&'); continue; }+ } else { out.push_back('&'); continue; }+ i = semi;+ }+ return out;+}++std::string textOf(const Node& root, std::string_view tag) {+ if (root.name == tag) return root.text;+ const Node* node = root.find(tag);+ return node ? node->text : std::string();+}++std::string toHex(const std::string& bytes) {+ static constexpr char digits[] = "0123456789abcdef";+ std::string out;+ out.reserve(bytes.size() * 2);+ for (unsigned char c : bytes) { out.push_back(digits[c >> 4]); out.push_back(digits[c & 15]); }+ return out;+}++std::optional<std::string> fromHex(std::string_view hex) {+ if (hex.size() % 2) return std::nullopt;+ std::string out;+ out.reserve(hex.size() / 2);+ for (size_t i = 0; i < hex.size(); i += 2) {+ const int hi = hexDigit(hex[i]), lo = hexDigit(hex[i + 1]);+ if (hi < 0 || lo < 0) return std::nullopt;+ out.push_back(char((hi << 4) | lo));+ }+ return out;+}++} // namespace veyra::moonlight::xmldiff --git a/tests/moonlight/ProtocolTests.cpp b/tests/moonlight/ProtocolTests.cppnew file mode 100644index 00000000..a3c2eba3--- /dev/null+++ b/tests/moonlight/ProtocolTests.cpp@@ -0,0 +1,535 @@+// SPDX-License-Identifier: GPL-3.0-only+// Offline tests for the Moonlight host protocol layer. No real host is involved:+// a mock host on the loopback interface implements the host side of the+// GameStream pairing handshake, so the client's cryptography, TLS certificate+// pinning, HTTP parsing and every pairing failure path are exercised end to end.+// The mock is written from the same protocol description as the client, so it+// proves the client is self-consistent and safe against bad answers; interop with+// a real Sunshine host is verified separately on real machines.+#include <winsock2.h>+#include <ws2tcpip.h>++#include <openssl/bio.h>+#include <openssl/pem.h>+#include <openssl/ssl.h>+#include <openssl/x509.h>++#include <atomic>+#include <chrono>+#include <cstdio>+#include <filesystem>+#include <fstream>+#include <iterator>+#include <map>+#include <mutex>+#include <string>+#include <thread>++#include "veyra/moonlight/Client.h"+#include "veyra/moonlight/Crypto.h"+#include "veyra/moonlight/Http.h"+#include "veyra/moonlight/IdentityStore.h"+#include "veyra/moonlight/Pairing.h"+#include "veyra/moonlight/Xml.h"++using namespace veyra::moonlight;++namespace {++int g_failures = 0;+int g_checks = 0;++void check(bool ok, const char* what) {+ ++g_checks;+ if (!ok) { ++g_failures; std::printf("FAIL %s\n", what); }+}++// ---------------------------------------------------------------- fixtures++const char* kServerInfoXml =+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"+ "<root status_code=\"200\"><hostname>DESKTOP-TEST</hostname><appversion>7.1.431.-1</appversion>"+ "<GfeVersion>3.23.0.74</GfeVersion><uniqueid>ABCD1234EF567890</uniqueid><HttpsPort>48000</HttpsPort>"+ "<ExternalPort>47999</ExternalPort><MaxLumaPixelsHEVC>1869449984</MaxLumaPixelsHEVC><mac>AA:BB:CC:DD:EE:FF</mac>"+ "<LocalIP>192.168.1.20</LocalIP><ServerCodecModeSupport>197377</ServerCodecModeSupport>"+ "<SupportedDisplayMode><DisplayMode><Width>3840</Width><Height>2160</Height><RefreshRate>60</RefreshRate></DisplayMode>"+ "<DisplayMode><Width>1920</Width><Height>1080</Height><RefreshRate>60</RefreshRate></DisplayMode></SupportedDisplayMode>"+ "<PairStatus>1</PairStatus><currentgame>7</currentgame><state>SUNSHINE_SERVER_BUSY</state></root>";++const char* kAppListXml =+ "<?xml version=\"1.0\" encoding=\"utf-8\"?>"+ "<root status_code=\"200\">"+ "<App><IsHdrSupported>1</IsHdrSupported><AppTitle>Desktop</AppTitle><ID>881448767</ID></App>"+ "<App><IsHdrSupported>0</IsHdrSupported><AppTitle>Tom & Jerry <Deluxe> 中</AppTitle><ID>12</ID></App>"+ "<App><AppTitle/><ID>13</ID></App>"+ "</root>";++// ---------------------------------------------------------------- mock host++std::string hexOf(const std::string& bytes) { return xml::toHex(bytes); }++struct Query {+ std::string command;+ std::map<std::string, std::string> args;+};++Query parseRequestLine(const std::string& request) {+ Query q;+ const auto space1 = request.find(' ');+ const auto space2 = request.find(' ', space1 + 1);+ std::string target = request.substr(space1 + 1, space2 - space1 - 1);+ const auto mark = target.find('?');+ q.command = target.substr(1, mark == std::string::npos ? std::string::npos : mark - 1);+ if (mark != std::string::npos) {+ size_t pos = mark + 1;+ while (pos < target.size()) {+ const auto amp = target.find('&', pos);+ const std::string pair = target.substr(pos, amp == std::string::npos ? std::string::npos : amp - pos);+ const auto eq = pair.find('=');+ q.args[pair.substr(0, eq)] = eq == std::string::npos ? "" : pair.substr(eq + 1);+ pos = amp == std::string::npos ? target.size() : amp + 1;+ }+ }+ return q;+}++class MockHost {+public:+ explicit MockHost(const std::string& pin) : pin_(pin) {+ identity = createIdentity();+ WSADATA data;+ WSAStartup(MAKEWORD(2, 2), &data);+ httpListen_ = listenOnLoopback(httpPort);+ httpsListen_ = listenOnLoopback(httpsPort);+ ctx_ = SSL_CTX_new(TLS_server_method());+ BIO* certBio = BIO_new_mem_buf(identity.certPem.data(), int(identity.certPem.size()));+ BIO* keyBio = BIO_new_mem_buf(identity.keyPem.data(), int(identity.keyPem.size()));+ X509* cert = PEM_read_bio_X509(certBio, nullptr, nullptr, nullptr);+ EVP_PKEY* key = PEM_read_bio_PrivateKey(keyBio, nullptr, nullptr, nullptr);+ SSL_CTX_use_certificate(ctx_, cert);+ SSL_CTX_use_PrivateKey(ctx_, key);+ X509_free(cert); EVP_PKEY_free(key); BIO_free(certBio); BIO_free(keyBio);+ SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, nullptr);+ // Only the client certificate that completed pairing may use HTTPS.+ SSL_CTX_set_cert_verify_callback(ctx_, [](X509_STORE_CTX* store, void* arg) -> int {+ auto* self = static_cast<MockHost*>(arg);+ X509* peer = X509_STORE_CTX_get0_cert(store);+ unsigned char* der = nullptr;+ const int length = i2d_X509(peer, &der);+ std::string presented(reinterpret_cast<char*>(der), size_t(length));+ OPENSSL_free(der);+ std::lock_guard lock(self->mutex_);+ return !self->pairedClientDer_.empty() && presented == self->pairedClientDer_ ? 1 : 0;+ }, this);+ httpThread_ = std::thread([this] { acceptLoop(httpListen_, false); });+ httpsThread_ = std::thread([this] { acceptLoop(httpsListen_, true); });+ }++ ~MockHost() {+ stop_ = true;+ closesocket(httpListen_);+ closesocket(httpsListen_);+ if (httpThread_.joinable()) httpThread_.join();+ if (httpsThread_.joinable()) httpsThread_.join();+ SSL_CTX_free(ctx_);+ }++ void enterPin() { pinEntered_ = true; }+ void forgetPairing() {+ std::lock_guard lock(mutex_);+ pairedClientDer_.clear();+ }+ void presentDifferentCertificate() {+ // Swap to a new identity the client has never pinned.+ Identity other = createIdentity();+ BIO* certBio = BIO_new_mem_buf(other.certPem.data(), int(other.certPem.size()));+ BIO* keyBio = BIO_new_mem_buf(other.keyPem.data(), int(other.keyPem.size()));+ X509* cert = PEM_read_bio_X509(certBio, nullptr, nullptr, nullptr);+ EVP_PKEY* key = PEM_read_bio_PrivateKey(keyBio, nullptr, nullptr, nullptr);+ SSL_CTX_use_certificate(ctx_, cert);+ SSL_CTX_use_PrivateKey(ctx_, key);+ X509_free(cert); EVP_PKEY_free(key); BIO_free(certBio); BIO_free(keyBio);+ }++ Identity identity;+ uint16_t httpPort = 0, httpsPort = 0;+ std::atomic<bool> busyPairing{false};+ std::atomic<int> unpairCalls{0};+ std::atomic<int> launchCalls{0};+ std::string lastLaunch; // guarded by mutex_++ std::string launchQuery() { std::lock_guard lock(mutex_); return lastLaunch; }++private:+ SOCKET listenOnLoopback(uint16_t& port) {+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);+ sockaddr_in address{};+ address.sin_family = AF_INET;+ address.sin_addr.s_addr = htonl(INADDR_LOOPBACK);+ address.sin_port = 0;+ bind(s, reinterpret_cast<sockaddr*>(&address), sizeof(address));+ listen(s, 8);+ int length = sizeof(address);+ getsockname(s, reinterpret_cast<sockaddr*>(&address), &length);+ port = ntohs(address.sin_port);+ return s;+ }++ void acceptLoop(SOCKET listener, bool tls) {+ while (!stop_) {+ SOCKET client = accept(listener, nullptr, nullptr);+ if (client == INVALID_SOCKET) return;+ std::thread([this, client, tls] { serve(client, tls); }).detach();+ }+ }++ void serve(SOCKET client, bool tls) {+ SSL* ssl = nullptr;+ if (tls) {+ ssl = SSL_new(ctx_);+ SSL_set_fd(ssl, static_cast<int>(client));+ if (SSL_accept(ssl) != 1) { SSL_free(ssl); closesocket(client); return; }+ }+ auto readBytes = [&](char* buffer, int size) { return ssl ? SSL_read(ssl, buffer, size) : recv(client, buffer, size, 0); };+ auto writeBytes = [&](const std::string& data) {+ size_t sent = 0;+ while (sent < data.size()) {+ const int n = ssl ? SSL_write(ssl, data.data() + sent, int(data.size() - sent)) : send(client, data.data() + sent, int(data.size() - sent), 0);+ if (n <= 0) return;+ sent += size_t(n);+ }+ };+ std::string request;+ char chunk[2048];+ while (request.find("\r\n\r\n") == std::string::npos) {+ const int n = readBytes(chunk, sizeof(chunk));+ if (n <= 0) break;+ request.append(chunk, size_t(n));+ }+ if (request.find("\r\n\r\n") != std::string::npos) {+ const Query q = parseRequestLine(request);+ std::string body = route(q, tls);+ writeBytes(respond(q, tls, body));+ }+ if (ssl) { SSL_shutdown(ssl); SSL_free(ssl); }+ closesocket(client);+ }++ // The three framings a real host uses must all parse: content-length, chunked, close-delimited.+ std::string respond(const Query& q, bool tls, const std::string& body) {+ if (!tls && q.command == "serverinfo") {+ std::string out = "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n";+ const size_t half = body.size() / 2;+ char size[16];+ std::snprintf(size, sizeof(size), "%zx\r\n", half);+ out += size + body.substr(0, half) + "\r\n";+ std::snprintf(size, sizeof(size), "%zx\r\n", body.size() - half);+ out += size + body.substr(half) + "\r\n0\r\n\r\n";+ return out;+ }+ if (q.command == "applist") return "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nConnection: close\r\n\r\n" + body;+ return "HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nContent-Length: " + std::to_string(body.size()) + "\r\nConnection: close\r\n\r\n" + body;+ }++ static std::string ok(const std::string& inner) { return "<?xml version=\"1.0\" encoding=\"utf-8\"?><root status_code=\"200\">" + inner + "</root>"; }+ static std::string fail(int code, const std::string& message) {+ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><root status_code=\"" + std::to_string(code) + "\" status_message=\"" + message + "\"></root>";+ }++ std::string route(const Query& q, bool tls) {+ std::lock_guard lock(mutex_);+ if (q.command == "serverinfo") {+ std::string info = kServerInfoXml;+ // Report the real ports and the real pairing state of this mock.+ const auto replace = [&](const std::string& from, const std::string& to) { const auto at = info.find(from); if (at != std::string::npos) info.replace(at, from.size(), to); };+ replace("<HttpsPort>48000</HttpsPort>", "<HttpsPort>" + std::to_string(httpsPort) + "</HttpsPort>");+ replace("<PairStatus>1</PairStatus>", std::string("<PairStatus>") + (pairedClientDer_.empty() ? "0" : "1") + "</PairStatus>");+ return info;+ }+ if (q.command == "applist") return tls ? kAppListXml : fail(401, "The client is not authorized");+ if (q.command == "unpair") { ++unpairCalls; pairedClientDer_.clear(); stage_ = 0; return ok(""); }+ if (q.command == "launch" || q.command == "resume") { ++launchCalls; lastLaunch = q.command; for (const auto& [k, v] : q.args) lastLaunch += "&" + k + "=" + v; return ok("<sessionUrl0>rtsp://127.0.0.1:48010</sessionUrl0><gamesession>1</gamesession>"); }+ if (q.command == "cancel") return ok("<cancel>1</cancel>");+ if (q.command == "appasset") return "\x89PNG-MOCK";+ if (q.command == "pair") return pair(q, tls);+ return fail(404, "unknown");+ }++ // The host side of the five stage pairing handshake.+ std::string pair(const Query& q, bool tls) {+ const bool sha256 = true; // appversion 7.x+ const size_t hashLength = 32;+ const auto get = [&](const char* name) { const auto it = q.args.find(name); return it == q.args.end() ? std::string() : it->second; };+ if (!tls && get("phrase") == "getservercert") {+ if (busyPairing) return ok("<paired>1</paired><plaincert></plaincert>");+ mutex_.unlock(); // the PIN is typed by a human; do not hold the lock while waiting+ for (int i = 0; i < 100 && !pinEntered_; ++i) std::this_thread::sleep_for(std::chrono::milliseconds(50));+ mutex_.lock();+ if (!pinEntered_) return fail(500, "pin timeout");+ salt_ = *xml::fromHex(get("salt"));+ clientCertPem_ = *xml::fromHex(get("clientcert"));+ aesKey_ = crypto::digest(salt_ + pin_, sha256).substr(0, 16);+ stage_ = 1;+ return ok("<paired>1</paired><plaincert>" + hexOf(identity.certPem) + "</plaincert>");+ }+ if (!tls && !get("clientchallenge").empty() && stage_ == 1) {+ const std::string challenge = crypto::aesEcbDecrypt(*xml::fromHex(get("clientchallenge")), aesKey_);+ serverSecret_ = crypto::randomBytes(16);+ serverChallenge_ = crypto::randomBytes(16);+ const std::string hash = crypto::digest(challenge + crypto::certificateSignature(identity.certPem) + serverSecret_, sha256);+ stage_ = 2;+ return ok("<paired>1</paired><challengeresponse>" + hexOf(crypto::aesEcbEncrypt(hash + serverChallenge_, aesKey_)) + "</challengeresponse>");+ }+ if (!tls && !get("serverchallengeresp").empty() && stage_ == 2) {+ clientHash_ = crypto::aesEcbDecrypt(*xml::fromHex(get("serverchallengeresp")), aesKey_).substr(0, hashLength);+ stage_ = 3;+ return ok("<paired>1</paired><pairingsecret>" + hexOf(serverSecret_ + crypto::sign(identity, serverSecret_)) + "</pairingsecret>");+ }+ if (!tls && !get("clientpairingsecret").empty() && stage_ == 3) {+ const std::string blob = *xml::fromHex(get("clientpairingsecret"));+ const std::string clientSecret = blob.substr(0, 16);+ const bool signatureOk = crypto::verify(clientSecret, blob.substr(16), clientCertPem_);+ const bool hashOk = crypto::digest(serverChallenge_ + crypto::certificateSignature(clientCertPem_) + clientSecret, sha256) == clientHash_;+ if (!signatureOk || !hashOk) { stage_ = 0; return ok("<paired>0</paired>"); }+ pairedClientDer_ = crypto::certificateDer(clientCertPem_);+ stage_ = 4;+ return ok("<paired>1</paired>");+ }+ if (tls && get("phrase") == "pairchallenge") return ok("<paired>1</paired>");+ return fail(400, "unexpected pairing request");+ }++ std::string pin_;+ std::atomic<bool> pinEntered_{false};+ std::atomic<bool> stop_{false};+ SOCKET httpListen_ = INVALID_SOCKET, httpsListen_ = INVALID_SOCKET;+ SSL_CTX* ctx_ = nullptr;+ std::thread httpThread_, httpsThread_;+ std::mutex mutex_;+ int stage_ = 0;+ std::string salt_, aesKey_, clientCertPem_, pairedClientDer_, serverSecret_, serverChallenge_, clientHash_;+};++// ---------------------------------------------------------------- tests++void xmlTests() {+ const auto root = xml::parse(kServerInfoXml);+ check(root.has_value(), "serverinfo parses");+ const auto info = ServerClient::parseServerInfo(*root);+ check(info.hostname == "DESKTOP-TEST", "hostname");+ check(info.appVersionMajor() == 7, "appversion major");+ check(info.httpsPort == 48000, "https port from serverinfo");+ check(info.externalPort == 47999, "external port");+ check(info.serverCodecModeSupport == 197377, "codec support bits");+ check((info.serverCodecModeSupport & kServerAv1Main10) != 0, "AV1 10-bit advertised");+ check(info.paired, "pair status");+ check(!info.nvidiaServerSoftware, "sunshine is not GFE");+ check(info.currentGame == 7, "busy server reports the running game");+ check(info.displayModes.size() == 2 && info.displayModes[0].width == 1920 && info.displayModes[1].width == 3840, "display modes sorted ascending");+ check(info.gfeVersion == "3.23.0.74", "gfe version");++ // An idle server must report no current game even if the tag is set (GFE 2.8+ behaviour).+ std::string idle = kServerInfoXml;+ idle.replace(idle.find("SUNSHINE_SERVER_BUSY"), 20, "SUNSHINE_SERVER_FREE");+ check(ServerClient::parseServerInfo(*xml::parse(idle)).currentGame == 0, "idle server has no current game");++ const auto apps = ServerClient::parseAppList(*xml::parse(kAppListXml));+ check(apps.size() == 3, "three apps");+ check(apps[0].name == "Desktop" && apps[0].id == 881448767 && apps[0].hdrSupported, "desktop app");+ check(apps[1].name == "Tom & Jerry <Deluxe> \xE4\xB8\xAD", "entities and numeric character reference decoded");+ check(apps[2].name.empty() && apps[2].id == 13, "empty AppTitle is an empty name");++ check(!xml::parse("<root><a></b></root>").has_value(), "mismatched tags rejected");+ check(!xml::parse("").has_value(), "empty document rejected");+ check(!xml::parse("<root>").has_value(), "unterminated document rejected");+ std::string deep;+ for (int i = 0; i < 64; ++i) deep += "<a>";+ for (int i = 0; i < 64; ++i) deep += "</a>";+ check(!xml::parse(deep).has_value(), "excessive nesting rejected");++ bool threw = false;+ try { ServerClient::checkedRoot("<root status_code=\"401\" status_message=\"denied\"/>"); }+ catch (const StatusError& e) { threw = e.status == 401; }+ check(threw, "non-200 status raises StatusError with the code");+ threw = false;+ try { ServerClient::checkedRoot("<root status_code=\"4294967295\" status_message=\"Invalid\"/>"); }+ catch (const StatusError& e) { threw = e.status == 418; }+ check(threw, "GFE audio capture error is translated");+ threw = false;+ try { ServerClient::checkedRoot("not xml"); }+ catch (const StatusError& e) { threw = e.status == -1; }+ check(threw, "malformed body raises StatusError(-1)");++ check(xml::fromHex("0aFf").value() == std::string("\x0a\xff", 2), "hex decoding");+ check(!xml::fromHex("abc").has_value() && !xml::fromHex("zz").has_value(), "invalid hex rejected");+}++void cryptoTests() {+ // FIPS-197 appendix C.1 known answer.+ std::string key, plain;+ for (int i = 0; i < 16; ++i) { key.push_back(char(i)); plain.push_back(char(i * 0x11)); }+ const std::string cipher = crypto::aesEcbEncrypt(plain, key);+ check(xml::toHex(cipher) == "69c4e0d86a7b0430d8cdb78070b4c55a", "AES-128 known answer");+ check(crypto::aesEcbDecrypt(cipher, key) == plain, "AES round trip");+ check(crypto::aesEcbEncrypt("short", key).empty(), "AES rejects non block sized input");++ check(xml::toHex(crypto::digest("abc", true)) == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "SHA-256 known answer");+ check(xml::toHex(crypto::digest("abc", false)) == "a9993e364706816aba3e25717850c26c9cd0d89d", "SHA-1 known answer");++ const Identity id = createIdentity();+ check(id.valid(), "new identity is valid");+ check(id.uniqueId.size() == 16, "unique id length");+ const std::string signature = crypto::sign(id, "message");+ check(!signature.empty() && crypto::verify("message", signature, id.certPem), "sign/verify");+ check(!crypto::verify("other", signature, id.certPem), "verify rejects another message");+ check(!crypto::verify("message", signature, createIdentity().certPem), "verify rejects another certificate");+ check(crypto::certificateSignature(id.certPem).size() == 256, "certificate signature is the RSA-2048 block");+ check(!crypto::certificateDer(id.certPem).empty(), "certificate DER");++ Identity broken = id;+ broken.keyPem = createIdentity().keyPem;+ check(!broken.valid(), "a key that does not belong to the certificate is invalid");+ check(crypto::randomBytes(16) != crypto::randomBytes(16), "random bytes differ");+ check(generatePin().size() == 4, "pin has four digits");+}++void storeTests() {+ wchar_t temp[MAX_PATH];+ GetTempPathW(MAX_PATH, temp);+ const auto file = std::filesystem::path(temp) / (L"veyra-moonlight-test-" + std::to_wstring(GetCurrentProcessId()) + L".dat");+ std::filesystem::remove(file);+ bool created = false;+ const Identity first = loadOrCreateIdentity(file, &created);+ check(created && first.valid(), "identity created on first use");+ const Identity second = loadOrCreateIdentity(file, &created);+ check(!created && second.certPem == first.certPem && second.uniqueId == first.uniqueId, "identity reloaded unchanged");+ // The key must not be readable in the file.+ std::ifstream in(file, std::ios::binary);+ std::string raw((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());+ check(raw.find("PRIVATE KEY") == std::string::npos && raw.find(first.uniqueId) == std::string::npos, "identity file is encrypted");+ in.close();+ { // A damaged file is not an identity.+ std::ofstream out(file, std::ios::binary | std::ios::trunc);+ out << "garbage";+ }+ check(!loadIdentity(file).has_value(), "damaged file is rejected");+ std::filesystem::remove(file);+}++ServerClient makeClient(const Identity& id, const MockHost& host, const std::string& pinned = {}) {+ return ServerClient(id, HostAddress{"127.0.0.1", host.httpPort}, pinned, host.httpsPort, true);+}++void protocolTests() {+ const Identity client = createIdentity();++ try { // --- pairing with the right PIN+ MockHost host("4242");+ ServerClient http = makeClient(client, host);+ ServerInfo info = http.serverInfo(); // plain HTTP, chunked answer+ check(info.hostname == "DESKTOP-TEST" && !info.paired, "serverinfo over HTTP before pairing");+ check(http.httpsPort() == host.httpsPort, "HTTPS port learnt from serverinfo");++ std::atomic<bool> cancel{false};+ host.enterPin();+ const PairOutcome outcome = pairWithHost(http, client, info, "4242", &cancel);+ check(outcome.result == PairResult::Paired, "pairing with the right PIN succeeds");+ check(outcome.serverCertPem == host.identity.certPem, "the host certificate is returned for pinning");++ ServerClient paired = makeClient(client, host, outcome.serverCertPem);+ paired.setHttpsPort(host.httpsPort);+ info = paired.serverInfo(); // HTTPS with the pinned certificate+ check(info.paired, "serverinfo over pinned HTTPS reports paired");+ const auto apps = paired.appList();+ check(apps.size() == 3, "applist over pinned HTTPS");+ check(paired.boxArt(12) == "\x89PNG-MOCK", "box art bytes");++ LaunchRequest launch;+ launch.appId = 881448767; launch.width = 3840; launch.height = 2160; launch.fps = 60;+ for (size_t i = 0; i < 16; ++i) launch.remoteInputKey[i] = uint8_t(i);+ launch.remoteInputKeyId = {0x80, 0x00, 0x00, 0x01};+ launch.hdr = true; launch.surroundAudioInfo = 196610; launch.gamepadMask = 3; launch.extraQuery = "&corever=1";+ const std::string url = paired.launch("launch", launch, false);+ check(url == "rtsp://127.0.0.1:48010", "launch returns the RTSP session URL");+ const std::string sent = host.launchQuery();+ check(sent.find("&mode=3840x2160x60") != std::string::npos, "mode is WIDTHxHEIGHTxFPS");+ check(sent.find("&rikey=000102030405060708090a0b0c0d0e0f") != std::string::npos, "remote input key is hex encoded");+ check(sent.find("&rikeyid=-2147483647") != std::string::npos, "remote input key id is the big endian int32 of the IV prefix");+ check(sent.find("&hdrMode=1") != std::string::npos, "HDR mode requested for a 10-bit format");+ check(sent.find("&corever=1") != std::string::npos, "library query parameters appended");+ check(sent.find("&uniqueid=" + client.uniqueId) != std::string::npos, "the true unique id is sent to Sunshine");+ launch.fps = 120;+ paired.launch("resume", launch, true);+ check(host.launchQuery().find("&mode=3840x2160x0") != std::string::npos, "GFE gets fps 0 above 60 (SOPS workaround)");++ // The host forgets us: HTTPS no longer works, serverinfo falls back to HTTP and says so.+ host.forgetPairing();+ info = paired.serverInfo();+ check(!info.paired, "after the host forgets the client, serverinfo falls back to HTTP and reports not paired");++ // A different server certificate than the pinned one is refused before anything is sent.+ host.presentDifferentCertificate();+ bool mismatch = false;+ try { paired.request(true, "applist", "", 3000); }+ catch (const TransportError& e) { mismatch = e.kind == TransportError::Kind::Tls; }+ check(mismatch, "a server certificate that is not the pinned one is rejected");+ } catch (const std::exception& e) { ++g_failures; std::printf("FAIL exception: %s\n", e.what()); }++ try { // --- wrong PIN+ MockHost host("1111");+ ServerClient http = makeClient(client, host);+ const ServerInfo info = http.serverInfo();+ host.enterPin();+ std::atomic<bool> cancel{false};+ const PairOutcome outcome = pairWithHost(http, client, info, "2222", &cancel);+ check(outcome.result == PairResult::PinWrong, "a wrong PIN is reported as PinWrong");+ check(host.unpairCalls >= 1, "a failed pairing tells the host to forget it");+ } catch (const std::exception& e) { ++g_failures; std::printf("FAIL exception: %s\n", e.what()); }++ try { // --- the host is busy with another client+ MockHost host("1111");+ host.busyPairing = true;+ ServerClient http = makeClient(client, host);+ const ServerInfo info = http.serverInfo();+ std::atomic<bool> cancel{false};+ const PairOutcome outcome = pairWithHost(http, client, info, "1111", &cancel);+ check(outcome.result == PairResult::AlreadyInProgress, "a busy host is reported as AlreadyInProgress");+ } catch (const std::exception& e) { ++g_failures; std::printf("FAIL exception: %s\n", e.what()); }++ try { // --- cancelled while waiting for the PIN to be typed on the host+ MockHost host("1111");+ ServerClient http = makeClient(client, host);+ const ServerInfo info = http.serverInfo();+ std::atomic<bool> cancel{false};+ std::thread canceller([&] { std::this_thread::sleep_for(std::chrono::milliseconds(300)); cancel = true; });+ const auto begin = std::chrono::steady_clock::now();+ const PairOutcome outcome = pairWithHost(http, client, info, "1111", &cancel);+ canceller.join();+ check(outcome.result == PairResult::Cancelled, "cancelling while waiting for the PIN returns Cancelled");+ check(std::chrono::steady_clock::now() - begin < std::chrono::seconds(3), "cancel is prompt");+ } catch (const std::exception& e) { ++g_failures; std::printf("FAIL exception: %s\n", e.what()); }++ try { // --- transport failures+ ServerClient http(client, HostAddress{"127.0.0.1", 1}, {}, 2, true); // nothing listens on port 1+ bool refused = false;+ try { http.serverInfo(true); } catch (const TransportError& e) { refused = e.kind == TransportError::Kind::Connect || e.kind == TransportError::Kind::Timeout; }+ check(refused, "an unreachable host is a Connect or Timeout error (Windows can take ~2 s to report a refused loopback connect)");++ HttpClient bare(&client, {});+ bool needsPin = false;+ try { bare.get(HttpTarget{"127.0.0.1", 1, true}, "/x", HttpOptions{}); }+ catch (const TransportError& e) { needsPin = e.kind == TransportError::Kind::Tls; }+ check(needsPin, "HTTPS without a pinned certificate is refused");+ } catch (const std::exception& e) { ++g_failures; std::printf("FAIL exception: %s\n", e.what()); }+}++} // namespace++int main() {+ xmlTests();+ cryptoTests();+ storeTests();+ protocolTests();+ std::printf("moonlight protocol tests: %d checks, %d failures\n", g_checks, g_failures);+ return g_failures == 0 ? 0 : 1;+}