Merge origin/main into feat/vmref-driver-start

Adapt Intel VM suspend/resume to driver.SuspendDriver and lifecycle.Service, move native VM close confirmation into internal/host, migrate vm-suspend legacy capability detection, drop moved runtime build tooling, and regenerate i18n and Wails bindings.
This commit is contained in:
Nwflower committed 2026-12-01 03:47:20 -07:00
commit aacaec535d
133 files changed
+7845 -3750

No files matched your search

+1
View File
@@ -1,2 +1,3 @@
*.patch -text
*.diff -text
internal/guesttools/file_sync.sh text eol=lf
-291
View File
@@ -1,291 +0,0 @@
name: Build Portable Runtime (Alpha)
# Daily: build the newest steelbrain/reims-vgpu commit with the patch queue
# (patches/series.txt) and publish it as a GitHub prerelease = the alpha
# channel (portable-runtime-spec.md section 6). Never publishes stable:
# promotion needs a real-host smoke test and a person (AGENTS.md rule 6).
on:
schedule:
- cron: "23 3 * * *" # 03:23 UTC daily; skipped when upstream has not moved
workflow_dispatch:
inputs:
upstream_commit:
description: "steelbrain/reims-vgpu commit (empty = upstream default branch HEAD)"
required: false
default: ""
publish:
description: "Publish as an alpha prerelease (never stable)"
type: boolean
default: true
rebuild:
description: "Build a new patch revision (runtime-<commit>-pN) even if this upstream commit is already released"
type: boolean
default: false
permissions:
contents: write
issues: write
concurrency:
group: build-runtime
cancel-in-progress: false
env:
UPSTREAM_URL: https://github.com/steelbrain/reims-vgpu.git
KEEP_ALPHAS: "7" # unpromoted alpha prereleases kept; older ones are deleted
jobs:
resolve:
runs-on: ubuntu-latest
outputs:
commit: ${{ steps.r.outputs.commit }}
skip: ${{ steps.r.outputs.skip }}
suffix: ${{ steps.r.outputs.suffix }}
steps:
- id: r
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
WANT: ${{ inputs.upstream_commit }}
REBUILD: ${{ inputs.rebuild }}
run: |
set -euo pipefail
git clone -q --filter=blob:none --no-checkout "$UPSTREAM_URL" up
commit="$(git -C up rev-parse --verify "${WANT:-HEAD}^{commit}")"
echo "commit=$commit" >> "$GITHUB_OUTPUT"
# Already published (alpha or stable) under any short-hash length or -pN revision?
max_rev=0
for tag in $(gh release list -R "$GITHUB_REPOSITORY" --limit 1000 --json tagName -q '.[].tagName' | grep '^runtime-' || true); do
rest="${tag#runtime-}"
base="${rest%%-p*}"
case "$commit" in
"$base"*)
rev=1
if [ "$rest" != "$base" ]; then
num="${rest#"$base"-p}"
case "$num" in
''|*[!0-9]*) ;;
*) rev="$num" ;;
esac
fi
if [ "$rev" -gt "$max_rev" ]; then max_rev="$rev"; fi
echo "Upstream $commit is already released as $tag (rev $rev)"
;;
esac
done
skip=false
suffix=""
if [ "$max_rev" -gt 0 ]; then
if [ "$REBUILD" = "true" ]; then
suffix="-p$((max_rev + 1))"
echo "Rebuild requested: will publish with suffix $suffix"
else
skip=true
fi
fi
echo "skip=$skip" >> "$GITHUB_OUTPUT"
echo "suffix=$suffix" >> "$GITHUB_OUTPUT"
build:
needs: resolve
if: needs.resolve.outputs.skip != 'true'
runs-on: windows-latest
timeout-minutes: 150
outputs:
short: ${{ steps.patches.outputs.short }}
release_id: ${{ steps.patches.outputs.release_id }}
applied: ${{ steps.patches.outputs.applied }}
merged: ${{ steps.patches.outputs.merged }}
conflict: ${{ steps.patches.outputs.conflict }}
steps:
- uses: actions/checkout@v4
- name: Setup MSYS2 CLANG64
id: msys2
uses: msys2/setup-msys2@v2
with:
msystem: CLANG64
update: true
install: >-
git zstd tar mingw-w64-clang-x86_64-toolchain
mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-meson
mingw-w64-clang-x86_64-ninja mingw-w64-clang-x86_64-pkgconf
mingw-w64-clang-x86_64-glib2 mingw-w64-clang-x86_64-pixman
mingw-w64-clang-x86_64-gtk3 mingw-w64-clang-x86_64-libslirp
mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-libva
mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
- name: Check out upstream and apply the patch queue
id: patches
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
foreach ($d in 'cargo', 'xdg-data', 'xdg-cache') { New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP $d) | Out-Null }
# The runner's git defaults to core.autocrlf=true; LF patches need an LF
# checkout (upstream also rewrites CRLF files to LF, install-ctl.sh).
git config --global core.autocrlf false
git clone -q $env:UPSTREAM_URL $work
if ($LASTEXITCODE) { throw 'clone failed' }
git -C $work checkout -q '${{ needs.resolve.outputs.commit }}'
if ($LASTEXITCODE) { throw 'checkout failed' }
git -C $work submodule update --init --depth 1 vendor/qemu
if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu }
if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' }
$short = (git -C $work rev-parse --short=7 HEAD).Trim()
$releaseId = "$short${{ needs.resolve.outputs.suffix }}"
"short=$short" >> $env:GITHUB_OUTPUT
"release_id=$releaseId" >> $env:GITHUB_OUTPUT
# Applies what applies, skips what upstream already has, stops on a
# conflict without touching the patch (AGENTS.md rule 4).
$resultFile = Join-Path $env:RUNNER_TEMP 'patches.json'
try {
pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -ResultFile $resultFile
$ok = $LASTEXITCODE -eq 0
} finally {
if (Test-Path $resultFile) {
$r = Get-Content -Raw $resultFile | ConvertFrom-Json
"applied=$(@($r.applied) -join ',')" >> $env:GITHUB_OUTPUT
"merged=$(@($r.merged) -join ',')" >> $env:GITHUB_OUTPUT
"conflict=$($r.conflict)" >> $env:GITHUB_OUTPUT
"APPLIED_PATCHES=$(@($r.applied) -join ',')" >> $env:GITHUB_ENV
}
}
if (-not $ok) { throw 'patch queue does not apply' }
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
"RELEASE_ID=$releaseId" >> $env:GITHUB_ENV
"CARGO_HOME=$(Join-Path $env:RUNNER_TEMP 'cargo')" >> $env:GITHUB_ENV
"XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV
"XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV
- name: Build upstream runtime in MSYS2 CLANG64
shell: msys2 {0}
env:
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
run: |
set -euo pipefail
cd "$(cygpath -u "$UPSTREAM_DIR")"
# Upstream's own non-interactive CLANG64 build script.
bash scripts/install-ctl.sh --yes
- name: Package alpha runtime and source archives
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$outDir = Join-Path $env:RUNNER_TEMP 'releases'
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
# In-process call, so an empty list (every patch already upstream) binds
# as an empty array rather than being dropped as an empty argument.
$applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
& ./scripts/pack-runtime.ps1 `
-ReimsRepo $env:UPSTREAM_DIR `
-CargoHome $env:CARGO_HOME `
-QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') `
-Msys2 '${{ steps.msys2.outputs.msys2-location }}' `
-OutDir $outDir `
-TempRoot $env:RUNNER_TEMP `
-Channel alpha `
-ReleaseId $env:RELEASE_ID `
-Patches $applied
- name: Alpha entry gate
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
& ./scripts/check-runtime-alpha.ps1 `
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
-Commit $env:RELEASE_ID -RequireSlim `
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
- name: Upload alpha artifacts
uses: actions/upload-artifact@v4
with:
name: reims-runtime-win-x64-${{ env.RELEASE_ID }}-alpha
path: |
${{ runner.temp }}/releases/reims-runtime-*.tar.zst
${{ runner.temp }}/releases/SHA256SUMS.txt
retention-days: 14
- name: Publish alpha prerelease (never stable)
if: github.event_name == 'schedule' || inputs.publish
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
MERGED: ${{ steps.patches.outputs.merged }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$c = $env:RELEASE_ID
$short = $env:SHORT_COMMIT
$dir = Join-Path $env:RUNNER_TEMP 'releases'
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", "reims-runtime-symbols-$c.tar.zst", 'SHA256SUMS.txt') |
ForEach-Object { Join-Path $dir $_ }
$applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' }
$merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' }
$notes = @"
**Alpha** runtime (``$c``), built automatically from upstream [steelbrain/reims-vgpu@$short](https://github.com/steelbrain/reims-vgpu/commit/${{ needs.resolve.outputs.commit }}).
Not smoke-tested on a real host. It becomes stable only after ``scripts/smoke-runtime.ps1`` passes on a real Windows host and a person approves (portable-runtime-spec.md section 6).
Local patches applied (sources and patches are in the attached source packages):
$applied$merged
The optional ``reims-runtime-symbols-$c.tar.zst`` contains matching debug files for crash analysis.
Build: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID
"@
gh release create "runtime-$c" @assets --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
- name: Prune old alpha prereleases
if: github.event_name == 'schedule' || inputs.publish
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: pwsh
run: |
# Only unpromoted runtime prereleases; stable releases are never touched.
$alphas = gh release list -R $env:GITHUB_REPOSITORY --limit 1000 --json tagName,isPrerelease,isDraft,createdAt | ConvertFrom-Json |
Where-Object { $_.tagName -like 'runtime-*' -and $_.isPrerelease -and -not $_.isDraft } |
Sort-Object createdAt -Descending
$alphas | Select-Object -Skip ([int]$env:KEEP_ALPHAS) | ForEach-Object {
Write-Host "Deleting old alpha $($_.tagName)"
gh release delete $_.tagName -R $env:GITHUB_REPOSITORY --yes --cleanup-tag
}
report:
needs: [resolve, build]
if: always() && needs.resolve.outputs.skip != 'true' && (failure() || needs.build.outputs.merged != '')
runs-on: ubuntu-latest
steps:
- env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RESULT: ${{ needs.build.result }}
COMMIT: ${{ needs.resolve.outputs.commit }}
CONFLICT: ${{ needs.build.outputs.conflict }}
MERGED: ${{ needs.build.outputs.merged }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
# One open issue per kind; later runs add a comment instead of a new issue.
file_issue() {
local title="$1" body="$2" n
n="$(gh issue list -R "$GITHUB_REPOSITORY" --state open --search "in:title \"$title\"" --json number,title -q ".[] | select(.title == \"$title\") | .number" | head -n1)"
if [ -n "$n" ]; then
gh issue comment "$n" -R "$GITHUB_REPOSITORY" --body "$body"
else
gh issue create -R "$GITHUB_REPOSITORY" --title "$title" --body "$body"
fi
}
if [ "$RESULT" != "success" ]; then
if [ -n "$CONFLICT" ]; then
why="Patch \`$CONFLICT\` neither applies to upstream \`$COMMIT\` nor is already there. Per AGENTS.md rule 4 the patch was not edited; a person decides how to rebase or retire it."
else
why="The build, packaging or alpha gate failed for upstream \`$COMMIT\`; see the log."
fi
file_issue "Runtime alpha build failed" "$why"$'\n\n'"Run: $RUN_URL"$'\n\n'"No alpha was published."
fi
if [ -n "$MERGED" ]; then
file_issue "Patch queue: patches already upstream" "Upstream \`$COMMIT\` already contains: \`$MERGED\`. They were skipped. Record the merge commit in portable-runtime-spec.md section 5, then remove them from patches/ and patches/series.txt."$'\n\n'"Run: $RUN_URL"
fi
+6 -5
View File
@@ -8,7 +8,7 @@
与上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的分工:
- **`reims-vgpu`**:底层引擎(QEMU 分支、`reims-graphics-pci`、`metal2vulkan`、`reims-ctl`、`reims-util`)。
- **`reims-go`(本仓库)**:桌面应用、命令行包装与便携运行时打包/分发流水线,提供开箱即用的环境体检、离线装机、硬件调优、Guest Tools、恢复点与 CoW 派生能力。
- **`reims-go`(本仓库)**:桌面应用、命令行包装与运行时下载管理,提供开箱即用的环境体检、离线装机、硬件调优、Guest Tools、恢复点与 CoW 派生能力。
## 存储与产物边界
@@ -32,7 +32,7 @@
- 用户显式要求工单,或任务需要跨会话恢复、多人/多 Agent 交接、持续积累验收证据时,再通过 `work.mjs` 建立或复用工单。
- 一次性产物用 `node scripts/debug/tmp.mjs new <label>` 或 `run <label> -- <command>`(向子进程注入 `REIMS_TMP_DIR`):正常结束(退出码 0)自动删除目录,失败保留证据供排查;超期(24 小时)且属主进程已退出的残留由 `gc --yes` 回收,存活进程与符号链接/Junction 受保护。
- 工单按 `draft → active → review → close` 流转;`close` 校验通过后删除整个工单目录。
- **持久文档零引用**:`README.md`、`README.en.md`、`CHANGELOG.md`、`AGENTS.md`、`docs/` 与 `patches/README.md` 严禁引用具体工单 ID 或 `.debug/tmp/` 会话实例路径。
- **持久文档零引用**:`README.md`、`README.en.md`、`CHANGELOG.md`、`AGENTS.md` 与 `docs/` 严禁引用具体工单 ID 或 `.debug/tmp/` 会话实例路径。
| 命令 | 用途 |
| :--- | :--- |
@@ -48,9 +48,9 @@
## 事实核验与安全规则
1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时核对对应上游 commit 与 `文件:行号`;未实测项显式标注「待验证」。
2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:[`.github/workflows/build-runtime.yml`](.github/workflows/build-runtime.yml) 每日从上游构建,通过 `alpha` 准入检查后自动发布为 GitHub 预发布(`alpha` 通道),并自动清理较旧的未升级 `alpha` 预发布。
2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:Reims vGPU fork 的 Preview 工作流每天构建,通过 `alpha` 准入检查后在运行时仓库发布 GitHub 预发布。
3. **敏感与专有内容零入库**:严禁提交 SMC OSK、SMBIOS 真实序列号、MAC 地址、任何 Apple IPSW / BaseSystem / 解密固件或闭源二进制。
4. **对上游的修改只走补丁队列**:不长期维护 fork。补丁放 [`patches/`](patches/),顺序与状态统一在 [`patches/series.txt`](patches/series.txt) 与 [`patches/README.md`](patches/README.md) 维护,目标是清零。补丁打不上就停下报告,不要自动改写补丁。
4. **构建职责**:本仓库构建并发布客户端。便携运行时的编译、打包、依赖补丁和 Preview 发布由 [Reims vGPU fork 的 CI](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 负责。
5. **运行时包如实声明来源**:`manifest.json` 必须写清上游各仓库 commit 与实际应用的全部补丁;带补丁的包不得宣称为纯上游构建。
6. **默认用户只拿 `stable` 通道**:CI 产物先入 `alpha`,经真实宿主冒烟并人工确认后才升为 `stable`(见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。
7. **配置写入只走 `reims-ctl set`**:不直接改写 `vm.toml`,保证上游校验与 OpenCore 重建生效(见 [`docs/design-guidelines.md`](docs/design-guidelines.md))。
@@ -69,7 +69,8 @@
- [`docs/roadmap.md`](docs/roadmap.md) — 公开路线图与近期重点
- [`docs/architecture.md`](docs/architecture.md) — 系统架构、模块职责与安全边界
- [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案)
- [`docs/pr-review-guidelines.md`](docs/pr-review-guidelines.md) — PR 变更归属、跨仓交付与客户端独立性审查
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范
- [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范
- [`docs/guest-plugin-migration.md`](docs/guest-plugin-migration.md) — 客体插件化与 macOS 剥离的迁移路径
- [`patches/README.md`](patches/README.md) — 上游临时补丁队列与 PR 跟踪
- [运行时补丁与上游跟踪](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) — 运行时源码入口与依赖补丁
+3 -2
View File
@@ -3,8 +3,9 @@
`Reims-Go` itself (Go backend and desktop frontend) is licensed under the Apache
License, Version 2.0 (see `LICENSE`). That license applies to Reims-Go's own code
only and is separate from the portable runtime bundle it invokes as an external
child process. Local compatibility patches under `patches/` are licensed under
terms compatible with their target upstream projects (see `patches/LICENSE`).
child process. Compatibility patches in the runtime repository are licensed
under terms compatible with their target upstream projects (see [runtime patch
licenses](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)).
The Reims-Go desktop executable also incorporates open-source Go and frontend
libraries (including Wails, React, Radix UI, Lucide, Inter font, Go `golang.org/x`
-1
View File
@@ -74,7 +74,6 @@ flowchart TB
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)、轻量 ICU 格式化引擎、多跳语言回退链与带稳定排障码的结构化错误(`CodedError`) |
| `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 |
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`macos/`(macOS 专属页面与组件)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
| `patches/` | 上游临时补丁队列与 PR 跟踪,见 [`patches/README.md`](../patches/README.md) |
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本,以及 `scripts/debug/` 本地调试目录管理与卫生校验脚本 |
---
+6 -3
View File
@@ -20,7 +20,7 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
| :--- | :--- |
| **声明式配置** | 一台虚拟机对应一份声明式配置,界面只编辑配置项,不让用户直接拼 QEMU 命令行参数。 |
| **先校验,后保存** | 保存前在 Go 端完成前置校验(CPU 核数、可用提交内存上限、Vulkan ICD 路径存在性、切换磁盘控制器前是否已弹出安装盘),非法值在提交前拦截。 |
| **随时可编辑,标明生效时机** | 无论虚拟机运行与否,设置面板均可打开编辑;每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 |
| **标明设置的生效时机** | 虚拟机运行中或已停止时可编辑设置。每项设置明确标注生效时机。运行中保存「下次启动生效」的修改时,详情页汇总待生效项并提供「重启以应用」。 |
**写入约束**:凡属于上游 `reims-ctl` 管理的配置项,一律通过 `reims-ctl set` 写入,不直接改写 `vm.toml`,确保上游校验与 OpenCore 重建逻辑照常生效。
@@ -55,11 +55,14 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台
| **正在创建** | 创建流程进行中 | 无(展示分步进度) | 取消创建 |
| **已停止** | 上游 `stopped` | **启动** | 设置、恢复点、更多(派生副本、扩容/回收、打开目录、删除) |
| **正在启动** | 发起 `start` 至 `running` | 启动中(忙碌态,禁用) | 设置、强制关机 |
| **运行中** | 上游 `running` | **显示 VM 窗口** | 关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) |
| **运行中** | 上游 `running` | **显示 VM 窗口** | 挂起(需支持此功能的内核)、关机、截屏、设置、更多(重启、强制关机、发送文本、进入/退出恢复模式、导出排障包) |
| **正在停止** | 发起 `stop` 至 `stopped` | 停止中(忙碌态,禁用) | 强制关机 |
| **正在挂起** | 正在保存运行状态 | 挂起中(忙碌态,禁用) | 强制关机 |
| **已挂起** | 运行状态已保存到磁盘 | **恢复**(需支持此功能的内核) | 更多(放弃挂起状态、打开目录) |
| **正在恢复** | 正在从磁盘恢复运行状态 | 恢复中(忙碌态,禁用) | 强制关机 |
| **配置损坏** | 上游 `broken` | **查看问题** | 打开目录、删除 |
- 暂不提供暂停或运行中热快照状态(`paused` / `saving` / `restoring`),直到上游验证 `reims-vgpu` 显存与设备状态序列化。
- 已挂起时,恢复或放弃挂起状态后才可修改配置、管理磁盘和安装或弹出 Guest Tools。切换到不支持挂起的内核时,禁用恢复并提示用户切换内核。放弃挂起状态须经破坏性操作确认框确认。
- 禁用按钮不占据主操作位置;状态变化时直接切换为当前最合适的主操作。
---
+2 -2
View File
@@ -1,7 +1,7 @@
# 插件系统架构(Plugin Architecture)
> 状态:**核心内核、内置扩展、主题引擎、Sidecar 托管与 CLI/GUI 管理已落地**;市场远端索引与 L2 脚本层按需迭代。
> 关联文档:[`architecture.md`](architecture.md) · [`design-guidelines.md`](design-guidelines.md) · [`portable-runtime-spec.md`](portable-runtime-spec.md) · [`patches/README.md`](../patches/README.md)
> 关联文档:[`architecture.md`](architecture.md) · [`design-guidelines.md`](design-guidelines.md) · [`portable-runtime-spec.md`](portable-runtime-spec.md)
---
@@ -281,7 +281,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| 类别 | 归属 | 原则 |
| :--- | :--- | :--- |
| 引擎内部崩溃与 Hypervisor 层修复(WHPX 兼容、协程、构建锁文件等) | [`patches/`](../patches/)(编译期) | 外部插件无法等价替代;坚持上游 PR,合入即退役 |
| 引擎内部崩溃与 Hypervisor 层修复(WHPX 兼容、协程、构建锁文件等) | [运行时源码与补丁](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md)(编译期) | 外部插件无法等价替代,修复交由运行时仓库维护 |
| 窗口内部消息循环拦截(如 SDL 窗口内字符消息) | `patches/`,宿主侧做部分补偿 | 跨进程拦截需 DLL 注入,杀软误报风险高,不做成插件 |
| 宿主侧绕过、兜底补偿与宿客桥接 | 内置扩展(§5.4) | 运行时缺少对应补丁时平滑降级;依据运行时 `capabilities` 判断 |
+19 -21
View File
@@ -39,7 +39,7 @@ reims-runtime-<commit>/
### 2.2 裁剪与调试符号分离
打包脚本 [`scripts/stage-runtime-binaries.ps1`](../scripts/stage-runtime-binaries.ps1) 执行两项体积优化,在缩小下载体积的同时保留完整调试能力:
运行时仓库的 [`stage-runtime-binaries.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/stage-runtime-binaries.ps1) 执行两项体积优化,在缩小下载体积的同时保留完整调试能力:
1. **裁剪非必要工具与异架构固件**:仅移除 Windows x64 启动器不会调用的 `qemu-system-x86_64w.exe`、`elf2dmp.exe`、`qemu-edid.exe`、`qemu-io.exe`、`qemu-nbd.exe`、`qemu-storage-daemon.exe`,以及 ARM64、RISC-V、LoongArch64 的 EDK2 固件与描述文件;完整保留 x64 固件、BIOS、ROM、keymaps、动态加载的 `libva` 视频驱动与全部 DLL。
2. **独立发布调试符号**:使用 MSYS2 CLANG64 的 `llvm-objcopy` 从 5 个主可执行文件(`reims-ctl.exe`、`reims-util.exe`、`qemu-system-x86_64.exe`、`qemu-img.exe`、`reims-vgpu-compile.exe`)提取 `.debug` 符号并写入 GNU debug link,打包为同 Release 下的 `reims-runtime-symbols-<commit>.tar.zst`(客户端默认不下载符号包)。`manifest.json` 记录最终剥离后可执行文件的 SHA-256。
@@ -73,38 +73,36 @@ reims-runtime-<commit>/
## 3. 打包与 CI 自动构建
### 3.1 本地打包
运行 `pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出以下发布附件:
### 3.1 运行时发布附件
运行时仓库的 [`pack-runtime.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-runtime.ps1) 产出以下发布附件。
1. `reims-runtime-win-x64-<commit>.tar.zst`(运行时主体)
2. `reims-runtime-symbols-<commit>.tar.zst`(独立调试符号包)
3. `reims-runtime-src-<commit>.tar.zst`(上游源码 + 补丁原文 + 重建说明)
4. `reims-runtime-msys2-src-<commit>.tar.zst`(MSYS2 copyleft DLL 源码包,由 [`scripts/pack-msys2-sources.ps1`](../scripts/pack-msys2-sources.ps1) 生成)
3. `reims-runtime-src-<commit>.tar.zst`(运行时源码、依赖补丁和重建说明)
4. `reims-runtime-msys2-src-<commit>.tar.zst`(MSYS2 copyleft DLL 源码包,由 [`pack-msys2-sources.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-msys2-sources.ps1) 生成)
5. `SHA256SUMS.txt`(覆盖上述压缩包的统一校验清单)
打包前脚本会核对构建目录的 `git diff` 是否与声明的补丁逐字节一致;存在未声明修改或补丁不匹配时立即停止。
### 3.2 每日 CI 构建
[`.github/workflows/build-runtime.yml`](../.github/workflows/build-runtime.yml) 每日定时(也支持手动指定 commit)在 `windows-latest`(MSYS2 CLANG64)执行:
1. 读取上游默认分支 `HEAD`;若已存在 `runtime-<commit>` Release(不论 `alpha` 或 `stable`)则跳过。
2. 由 [`scripts/apply-patch-series.ps1`](../scripts/apply-patch-series.ps1) 按 [`patches/series.txt`](../patches/series.txt) 顺序打补丁:可正常应用的直接应用;已合入上游的自动跳过并开 Issue 提醒退役;遇到冲突则中止构建。
3. 执行上游 `scripts/install-ctl.sh --yes` 编译,调用 `scripts/pack-runtime.ps1 -Channel alpha` 打包。
4. 运行 [`scripts/check-runtime-alpha.ps1`](../scripts/check-runtime-alpha.ps1) 校验 5 个附件、`SHA256SUMS.txt`、`manifest.json` 哈希一致、许可证齐全,以及在不含 MSYS2 的纯净 `PATH` 下验证 vGPU 设备枚举、CLI 版本与 `qcow2` 创建读取。
5. 通过后发布为 GitHub 预发布(`alpha`),并自动清理超过保留上限(最近 7 个)的旧 `alpha` 预发布;正式版不受影响。
Reims vGPU fork 的 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 每日构建,也支持手动指定提交。工作流从运行时仓库读取打包脚本和依赖补丁,在 `windows-latest`(MSYS2 CLANG64)执行以下步骤。
1. 读取 Reims vGPU fork 的运行时分支,并检出其中固定的 QEMU fork 提交。若该 Reims vGPU 提交已有运行时 Release,则跳过。
2. 按 [`series.txt`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/series.txt) 顺序为固定的依赖版本应用补丁。已合入上游的补丁会跳过并报告,遇到冲突时中止构建。
3. 运行 Reims vGPU 源码中的 `scripts/install-ctl.sh --yes` 编译,再调用运行时仓库的打包脚本。
4. 运行 [`check-runtime-alpha.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/check-runtime-alpha.ps1) 校验附件哈希、许可证、挂起能力声明,以及在不含 MSYS2 的 `PATH` 下验证 vGPU 设备枚举、CLI 版本和 `qcow2` 创建读取。
5. 通过后在 Reims vGPU fork 的 Releases 发布 Preview,标记为 GitHub 预发布(`alpha`)。手动构建可通过 `publish=false` 仅下载 CI 产物进行验证。
> **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。
### 3.3 客户端下载与安装
`internal/runtime` 默认从 GitHub Releases(tag `runtime-<commit>`)拉取,沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。
`internal/runtime` 从 `yxc0915/reims-vgpu` 的 GitHub Releases 查找 `runtime-<commit>`。默认列出正式运行时,开启内核 Alpha 后同时列出 Preview。下载沿用环境变量与 Windows 系统代理,支持 HTTP `Range` 续传、强制 `SHA256SUMS.txt` 校验、临时目录原子解压与多版本切换。
---
## 4. 补丁队列
本仓库不维护长期 fork,所有尚未合入上游的最小兼容性补丁统一维护在 [`patches/`](../patches/)。补丁清单、作用对象、上游化进展与退役检查表见:
- 机器清单:[`patches/series.txt`](../patches/series.txt)
- 维护文档:[`patches/README.md`](../patches/README.md)
Reims vGPU 和 QEMU 的修改由各自的 fork 维护。Reims vGPU fork 的 [依赖补丁目录](https://github.com/yxc0915/reims-vgpu/tree/master/packaging/windows-runtime/patches) 保存构建时应用的补丁与维护说明。
运行时包的 `manifest.json` 必须如实列出所有实际应用的补丁与哈希,带补丁的构建不得标注为纯上游版本。
运行时包的 `manifest.json` 记录源码仓库、提交、运行时能力及打包时应用的依赖补丁和哈希。
---
@@ -114,11 +112,11 @@ reims-runtime-<commit>/
| 通道 | GitHub Release 形态 | 准入条件 |
| :--- | :--- | :--- |
| **`alpha`** | 预发布(Pre-release) | CI 每日自动构建并通过 `scripts/check-runtime-alpha.ps1` 全部校验 |
| **`stable`** | 正式发布(Release) | 从 `alpha` 晋升:在真实 Windows 10/11 宿主运行 [`scripts/smoke-runtime.ps1`](../scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 |
| **`alpha`** | 预发布(Pre-release) | 运行时 CI 自动构建并通过 Alpha 准入检查 |
| **`stable`** | 正式发布(Release) | 从 `alpha` 晋升。在真实 Windows 10/11 宿主运行 [`smoke-runtime.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 |
- 客户端默认仅获取 `stable` 通道;`alpha` 需用户在界面开启「接收 Alpha 版」或在 CLI 传入 `--alpha`。
- 晋升 `stable` 不重新打包,仅将既有 GitHub 预发布转为正式发布,确保用户下载的二进制与冒烟验证的资产完全一致(因此包内 `manifest.json` 的构建通道字段保持 `alpha`,客户端以 Release 状态区分通道)。
- 晋升 `stable` 时,在运行时仓库将已通过冒烟的 Preview 改为正式 Release,并移除标题中的 Alpha 标记。保留原资产、校验清单和 `manifest.json` 的构建通道。
---
@@ -129,6 +127,6 @@ Reims-Go 本体(Go 后端与前端外壳)采用 [Apache-2.0](../LICENSE) 协
由于便携运行时包含 GPLv2(QEMU)、`GPL-2.0-or-later OR LGPL-3.0-or-later`(`reims-vgpu` / `reims-ctl` / `metal2vulkan`)以及 MSYS2 CLANG64 / libva 动态库,每个公开运行时 Release **必须同处附带完整对应源码与许可证文本**:
1. **上游源码包(`reims-runtime-src-<commit>.tar.zst`)**:导出所用 commit 的四个上游仓库源码树、构建所需的 QEMU meson 子项目、`patches/` 中的全部补丁原文及重建说明。
2. **MSYS2 copyleft 源码包(`reims-runtime-msys2-src-<commit>.tar.zst`)**:由 [`scripts/pack-msys2-sources.ps1`](../scripts/pack-msys2-sources.ps1) 根据本机 pacman 元数据自动筛选全部无宽松替代协议的 GPL / LGPL / MPL 依赖包,下载官方 `.src.tar.zst` 并使用 `gpgv` 与 MSYS2 密钥逐一验签,同时附带 `MSYS2-PACKAGES.txt` 说明全部 DLL 归属与许可。
3. **许可证与声明**:运行时包根目录内置 [`NOTICE.md`](../NOTICE.md) 与 `licenses/` 全文。
2. **MSYS2 copyleft 源码包(`reims-runtime-msys2-src-<commit>.tar.zst`)**:由 [`pack-msys2-sources.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-msys2-sources.ps1) 根据本机 pacman 元数据自动筛选全部无宽松替代协议的 GPL / LGPL / MPL 依赖包,下载官方 `.src.tar.zst` 并使用 `gpgv` 与 MSYS2 密钥逐一验签,同时附带 `MSYS2-PACKAGES.txt` 说明全部 DLL 归属与许可。
3. **许可证与声明**:运行时包根目录内置 [`NOTICE.md`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/NOTICE.md) 与 `licenses/` 全文。
4. **不含 Apple 专有文件**:任何仓库目录或运行时 Release 均不包含 macOS 安装包、恢复镜像、解密固件或 SMC 密钥;系统安装包均由用户端直连 Apple 服务器获取。
+53
View File
@@ -0,0 +1,53 @@
# PR 变更归属审查
> 以产生行为的实现为准。先定位改动发生在哪个组件,再决定提交仓库和验证范围。桌面或 CLI 是否有入口,只决定客户端是否也需要改动。
## 1. 确认归属
以 PR 实际目标分支与提交的差异为准。使用 GitHub 的「Files changed」或本地 `git diff <base>...<head>`,同时检查生成文件对应的源文件、补丁目标、依赖锁定和 CI 变更。先从用户入口沿调用链找到行为的实现,再按下表归属。
| 类别 | 行为或改动 | 实现归属 |
| :--- | :--- | :--- |
| 客户端 | GUI、CLI、虚拟机流程编排、宿主机体检及窗口集成、Guest Tools、运行时下载和安装 | `Reims-Go`。主要入口和模块见[系统架构](architecture.md)。 |
| 客户端运行时适配 | 构造命令和环境、调用已发布的 CLI / QMP 接口、解析结果以及处理版本、能力或错误 | `Reims-Go`。生效行为仍由被调用的组件实现。 |
| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 的实际构建提交为准。 |
| QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 |
| 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 |
| 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 |
| 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 |
| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时规范](portable-runtime-spec.md)。 |
同一项功能可以涉及多个仓库。窗口安装引导调用已有运行时能力时,浮层、进度和流程编排属于客户端。若同时调整 Reims 原生窗口的事件语义,窗口实现属于 `reims-vgpu`,调用和交互留在客户端。挂起功能同理,GUI / CLI 和任务状态属于客户端,QEMU 的迁移或设备状态实现属于 QEMU;运行时再负责选取具备该能力的版本。
## 2. 审查客户端独立性
- **构建与发布**:客户端 CI 仅从 `Reims-Go` 源码检出完成前端构建、Go 检查和应用产物构建。运行时源码、编译工具链和运行时发布产物由运行时仓库管理。客户端自行发布应用,并在虚拟机运行前下载、校验或导入兼容的独立运行时。
- **接口边界**:客户端通过约定的子进程接口和协议调用运行时。配置写入沿用 [`reims-ctl set`](design-guidelines.md#2-配置原语)。需要新增命令、参数、字段或能力时,在负责组件实现,并在客户端附上对应接口证据。
- **运行时兼容**:客户端 PR 写明验证使用的运行时与最低要求。若依赖新能力,优先使用运行时明确声明的能力或版本,在旧版、缺失运行时和不支持该能力的场景下明确禁用、提示或保留既有流程。客户端合入与运行时发布各自按其流程验收,用户默认仍走受支持的 `stable` 通道。
- **跨仓交付**:按归属拆分 PR。客户端 PR 链接底层 PR、提交或运行时版本,列出合并顺序和兼容路径。临时依赖补丁由运行时仓库记录,注明目标仓库、适用提交和退役条件。跨仓定位以源码、依赖锁定和产物清单为证据。
## 3. PR 描述与合并检查
提交者在 PR 描述中附上以下信息。纯文档或纯客户端改动可将无关字段写为「不适用」。
```markdown
## 变更归属
- 用户可见行为
- 变更位置与责任仓库
- 上游证据(仓库、commit、文件及行号)
- 跨仓依赖(关联 PR、合并顺序、运行时要求)
- 旧版或缺失运行时的表现
## 验证
- 已通过的检查及运行时版本
- 待验证场景及其影响
```
审查者在合并前核对以下各项。
- [ ] 差异中的客户端、内核、独立依赖和分发变更均已注明归属。跨仓实现已拆分并可追溯。
- [ ] 客户端能独立通过其 CI。行为变更已按影响验证 GUI、CLI 或两者的正常入口。
- [ ] 底层或打包改动有负责仓库的验证证据。涉及运行时发布时,核对 `manifest.json` 中的来源提交、补丁与能力声明,以及相应的 [`alpha` 准入与 `stable` 冒烟要求](portable-runtime-spec.md#5-发布通道alpha--stable)。
- [ ] 上游行为已定位到对应提交和源码行号。真机或兼容性覆盖不足的场景标明「待验证」,合并前明确其对客户端发布和能力开放的影响。
+2 -2
View File
@@ -33,12 +33,12 @@
优先打磨和验证已有能力,在 P0 任务稳定前不堆砌新子系统。
### 1. 首次装机与发版闭环
- 在 GitHub Actions 上实跑 `build-runtime.yml` 每日构建与 `alpha` 准入流程,验证公开资产的 `manifest.json`、补丁队列与源码包一致性。
- 在运行时仓库的 [Preview CI](https://github.com/yxc0915/reims-vgpu/actions/workflows/runtime-preview.yml) 验证公开资产的 `manifest.json`、补丁队列与源码包一致性。
- 在多种受支持的 Windows 10 / 11、GPU 与 macOS 组合上跑通完整开箱流程(干净目录 → 体检 → 安装运行时 → 下载离线包 → 装机 → 退出恢复模式)。
- 完善中断与异常场景的故障恢复(断网续传、磁盘不足、取消 UAC、运行时损坏),确保失败后可安全重试且不残留半配置虚拟机。
### 2. 日常主力体验与上游性能跟进
- 持续跟进上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的 Windows 图形与窗口改进(热切全屏、无黑边窗口缩放、原生 Windows Vulkan 后端、首帧延迟优化、自由指针 `Win → Command` 映射),合入后经 `alpha` 冒烟升级至 `stable`(跟踪明细见 [patches/README.md](../patches/README.md))。
- 持续跟进上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的 Windows 图形与窗口改进(热切全屏、无黑边窗口缩放、原生 Windows Vulkan 后端、首帧延迟优化、自由指针 `Win → Command` 映射),合入后经 `alpha` 冒烟升级至 `stable`。跟踪明细见[运行时补丁文档](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md)。
- 推动当前本地兼容性补丁上游化,并逐步清零 `patches/` 队列。
- 在真实宿主完成长时间开发负载验证(编译、浏览器、多任务、图文剪贴板、WebDAV 挂载、Windows 盘符只读共享、音频/麦克风与休眠唤醒恢复)。
- 修复 WebDAV 共享目录可经 Junction 逃逸的路径校验缺陷,并把共享目录与只读盘统一到基于 `os.Root` 的路径安全层;随后按测量结果推进小文件 I/O 优化。
+55 -10
View File
@@ -22,7 +22,7 @@ import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDr
import { vmRefKey } from './lib/vmRef'
import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types'
import { Button, Tip, TooltipProvider } from './ui/controls'
import { Modal } from './ui/dialog'
import { ConfirmDialog, Modal } from './ui/dialog'
import { Toaster, useToasts } from './ui/toast'
import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails'
@@ -43,6 +43,9 @@ const errText = (e: unknown) => parseAppError(e).summary
const failKey: Record<VMAction, I18nKey> = {
start: 'failStart',
suspend: 'failSuspend',
resume: 'failResume',
discardSuspend: 'failDiscardSuspend',
focus: 'failFocus',
fullscreen: 'failFullscreen',
screenshot: 'failScreenshot',
@@ -87,6 +90,7 @@ export const App: React.FC = () => {
const [affinityTarget, setAffinityTarget] = useState<{ name: string; driverID: string } | null>(null)
const [affinityVersion, setAffinityVersion] = useState(0)
const [deleteTarget, setDeleteTarget] = useState<string | null>(null)
const [discardSuspendTarget, setDiscardSuspendTarget] = useState<string | null>(null)
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
@@ -333,6 +337,7 @@ export const App: React.FC = () => {
const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : ''
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
const canSuspend = state?.can_suspend ?? false
onTaskRef.current = (task: Task) => {
if (task.kind === 'app-update' && task.status === 'failed' && !notifiedTasks.current.has(task.id)) {
@@ -665,6 +670,7 @@ export const App: React.FC = () => {
const actionVM = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
const actionDriverID = actionVM?.driver_id ?? ''
name = actionVM?.name ?? name
if (!canSuspend && (action === 'suspend' || action === 'resume')) return
const activeBusy = activeVMBusy(name)
if (
activeBusy
@@ -676,6 +682,9 @@ export const App: React.FC = () => {
}
switch (action) {
case 'start': return runVMAction(name, action, () => api.StartVMWithDriver(actionDriverID, name))
case 'suspend': return runVMAction(name, action, () => api.SuspendVMWithDriver(actionDriverID, name), tr('toastSuspended', { name }))
case 'resume': return runVMAction(name, action, () => api.ResumeVMWithDriver(actionDriverID, name), tr('toastResumed', { name }))
case 'discardSuspend': return setDiscardSuspendTarget(actionVM ? vmRefKey(actionVM) : name)
case 'focus': return api.FocusVMWindowWithDriver(actionDriverID, name).catch((e) => fail(tr('failFocus'), e))
case 'fullscreen':
return runVMAction(name, action, async () => {
@@ -715,23 +724,26 @@ export const App: React.FC = () => {
const onSidebarContextAction = (name: string, action: VMAction | 'settings') => {
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
const st = state?.transitions[vm ? vmRefKey(vm) : name] ?? vm?.state ?? 'stopped'
if (action === 'settings') {
if (st === 'suspended' || st === 'suspending' || st === 'resuming') return
setSelected(name)
api.GetVMDetail(vm?.name ?? name).then((d) => { setDetail(d); setShowSettings(true) }).catch((e) => fail(tr('failGeneric'), e))
return
}
const st = state?.transitions[vm ? vmRefKey(vm) : name] ?? vm?.state ?? 'stopped'
onVMActionFor(name, action, st === 'running')
}
// The state's own main action (Start, or Show Window while running), shared by
// The state's own main action (Start, Resume while suspended, or Show Window while running), shared by
// Ctrl+Enter and a double-click in the sidebar.
const primaryAction = (name: string) => {
const vm = vms.find((v) => vmRefKey(v) === name) ?? vms.find((v) => v.name === name)
if (!vm || activeVMBusy(vm.name)) return
const st = state?.transitions[vmRefKey(vm)] ?? vm.state
if (st === 'stopped') onVMActionFor(vmRefKey(vm), 'start', false)
else if (st === 'running') onVMActionFor(vmRefKey(vm), 'focus', true)
const key = vmRefKey(vm)
const st = state?.transitions[key] ?? vm.state
if (st === 'stopped') onVMActionFor(key, 'start', false)
else if (st === 'suspended') onVMActionFor(key, 'resume', false)
else if (st === 'running') onVMActionFor(key, 'focus', true)
}
const confirmDelete = (keepFiles: boolean) => {
@@ -743,6 +755,15 @@ export const App: React.FC = () => {
if (name) runVMAction(name, 'delete', () => api.DeleteVMWithDriver(driverID, name, keepFiles), tr('toastDeleted', { name }))
}
const confirmDiscardSuspend = () => {
const target = discardSuspendTarget
setDiscardSuspendTarget(null)
const targetVM = vms.find((v) => vmRefKey(v) === target) ?? vms.find((v) => v.name === target)
const name = targetVM?.name ?? target
const driverID = targetVM?.driver_id ?? ''
if (name) runVMAction(name, 'discardSuspend', () => api.DiscardSuspendWithDriver(driverID, name), tr('toastDiscardSuspend', { name }))
}
const confirmOnlineRecovery = () => {
const name = onlineRecoveryTarget
setOnlineRecoveryTarget(null)
@@ -869,13 +890,15 @@ export const App: React.FC = () => {
// Global shortcuts (docs/design-guidelines.md §6). Dialogs own the keyboard while open.
const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {})
const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget ||
discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate
shortcutRef.current = (e: KeyboardEvent) => {
if (!e.ctrlKey || e.altKey || e.metaKey) return
if (showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate) return
if (appDialogOpen) return
if (document.querySelector('[role="dialog"], [role="alertdialog"]')) return
const k = e.key.toLowerCase()
if (k === 'n') { e.preventDefault(); openWizard() }
else if (k === ',' && detail) { e.preventDefault(); setShowSettings(true) }
else if (k === ',' && detail && effectiveState !== 'suspended' && effectiveState !== 'suspending' && effectiveState !== 'resuming') { e.preventDefault(); setShowSettings(true) }
else if (k === 'l') { e.preventDefault(); toggleLogs() }
else if (k === 'b' && !showSetup) { e.preventDefault(); toggleSidebar() }
else if (k === 'enter' && selectedVM && !e.shiftKey) { e.preventDefault(); primaryAction(vmRefKey(selectedVM)) }
@@ -893,7 +916,11 @@ export const App: React.FC = () => {
useEffect(() => {
const offSelect = events.onTraySelectVM((name) => { setSelected(name) })
const offNew = events.onTrayNewVM(() => { openWizardRef.current() })
return () => { offSelect(); offNew() }
const offDiscard = events.onTrayDiscardSuspend((name) => {
setSelected(name)
setDiscardSuspendTarget(name)
})
return () => { offSelect(); offNew(); offDiscard() }
}, [])
// Native Wails file drag-and-drop delivery into the selected VM's shared folder.
@@ -963,10 +990,11 @@ export const App: React.FC = () => {
state: effectiveState,
busy: Object.prototype.hasOwnProperty.call(busy, selectedVM.name),
graphics: detail?.name === selectedVM.name ? detail.graphics : undefined,
canSuspend,
} : null}
onNewVM={openWizard}
onVMAction={onVMAction}
onVMSettings={() => { if (detail) setShowSettings(true) }}
onVMSettings={() => { if (detail && effectiveState !== 'suspended') setShowSettings(true) }}
onVMDelete={() => { if (selectedVM) setDeleteTarget(selectedVM.name) }}
onNavigate={setSelected}
onOpenURL={(url) => { api.OpenURL(url).catch((e) => fail(tr('failGeneric'), e)) }}
@@ -1040,6 +1068,7 @@ export const App: React.FC = () => {
busyActions={busy}
selected={selected}
hostReady={hostReady}
canSuspend={canSuspend}
onSelect={setSelected}
displayNames={displayNames}
macosMajors={macosMajors}
@@ -1099,6 +1128,7 @@ export const App: React.FC = () => {
onDisplayNameSaved={(n) => setDisplayNames((m) => ({ ...m, [selectedVM.name]: n }))}
macosMajor={macosMajors[selectedVM.name] ?? null}
state={effectiveState}
canSuspend={canSuspend}
guideActive={state.active_guides?.includes(selectedVM.name) ?? false}
installGuideEnabled={!!state.install_guide_enabled}
detail={detail}
@@ -1305,6 +1335,21 @@ export const App: React.FC = () => {
<DeleteDialog locale={locale} name={deleteTarget} onCancel={() => setDeleteTarget(null)} onConfirm={confirmDelete} />
)}
{discardSuspendTarget && (() => {
const targetVM = vms.find((v) => vmRefKey(v) === discardSuspendTarget) ?? vms.find((v) => v.name === discardSuspendTarget)
const targetName = targetVM?.name ?? discardSuspendTarget
return (
<ConfirmDialog
title={tr('discardSuspendTitle', { name: displayNames[targetName] || targetName })}
description={tr('discardSuspendDesc')}
cancelLabel={tr('cancel')}
confirmLabel={tr('discardSuspendConfirm')}
onCancel={() => setDiscardSuspendTarget(null)}
onConfirm={confirmDiscardSuspend}
/>
)
})()}
{cloneSource && (
<CloneDialog
locale={locale}
+14 -28
View File
@@ -1,7 +1,7 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import React, { useState } from 'react'
import { t } from '../i18n'
import { Locale } from '../types'
import { ConfirmDialog } from '../ui/dialog'
interface Props {
locale: Locale
@@ -13,32 +13,18 @@ interface Props {
export const DeleteDialog: React.FC<Props> = ({ locale, name, onCancel, onConfirm }) => {
const [keepFiles, setKeepFiles] = useState(false)
return (
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<div className="dialog-body">
<Alert.Title className="dialog-title">{t(locale, 'deleteTitle', { name })}</Alert.Title>
<Alert.Description className="dialog-desc">
{t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')}
</Alert.Description>
<label className="choice">
<input type="checkbox" checked={keepFiles} onChange={(e) => setKeepFiles(e.target.checked)} />
{t(locale, 'deleteKeepFiles')}
</label>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild>
<button type="button" className="btn">{t(locale, 'cancel')}</button>
</Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn btn-danger" onClick={() => onConfirm(keepFiles)}>
{t(locale, 'deleteConfirm')}
</button>
</Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
<ConfirmDialog
title={t(locale, 'deleteTitle', { name })}
description={t(locale, keepFiles ? 'deleteDescKeep' : 'deleteDesc')}
cancelLabel={t(locale, 'cancel')}
confirmLabel={t(locale, 'deleteConfirm')}
onCancel={onCancel}
onConfirm={() => onConfirm(keepFiles)}
>
<label className="choice">
<input type="checkbox" checked={keepFiles} onChange={(e) => setKeepFiles(e.target.checked)} />
{t(locale, 'deleteKeepFiles')}
</label>
</ConfirmDialog>
)
}
+24 -5
View File
@@ -1,5 +1,5 @@
import * as Ctx from '@radix-ui/react-context-menu'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2, Pause, Play, Plus, Power, Puzzle, RotateCw, Settings, Square, Trash } from 'lucide-react'
import React, { useRef } from 'react'
import { I18nKey, t } from '../i18n'
import { Locale, VMListItem } from '../types'
@@ -25,6 +25,8 @@ interface Props {
busyActions?: Record<string, VMAction>
selected: string
hostReady: boolean
/** Whether the active runtime supports VM suspend/resume. */
canSuspend: boolean
onSelect: (id: string) => void
/** VM name → display name (its note); empty or missing shows the name. */
displayNames?: Record<string, string>
@@ -45,7 +47,7 @@ interface Props {
}
export const Sidebar: React.FC<Props> = ({
locale, vms, transitions, busyActions = {}, selected, hostReady, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot,
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot,
}) => {
const tr = (k: I18nKey) => t(locale, k)
const listRef = useRef<HTMLDivElement>(null)
@@ -119,7 +121,8 @@ export const Sidebar: React.FC<Props> = ({
const st = transitions[vmRefKey(vm)] ?? vm.state
const running = st === 'running'
const stopped = st === 'stopped'
const transitioning = st === 'starting' || st === 'stopping'
const suspended = st === 'suspended'
const transitioning = st === 'starting' || st === 'stopping' || st === 'suspending' || st === 'resuming'
const busyAction = Object.prototype.hasOwnProperty.call(busyActions, vm.name) ? busyActions[vm.name] : undefined
const vmBusy = !!busyAction
const label = displayNames[vm.name] || vm.name
@@ -160,6 +163,17 @@ export const Sidebar: React.FC<Props> = ({
<Play size={14} /> {tr('start')}
</Ctx.Item>
)}
{suspended && (
<>
<Ctx.Item className="menu-item" disabled={vmBusy || !canSuspend} onSelect={() => onVMContextAction(vmRefKey(vm), 'resume')}>
<Play size={14} /> {tr('resume')}
</Ctx.Item>
{!canSuspend && <Ctx.Label className="menu-group-label">{tr('resumeUnavailable')}</Ctx.Label>}
<Ctx.Item className="menu-item danger" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'discardSuspend')}>
<Power size={14} /> {tr('discardSuspend')}
</Ctx.Item>
</>
)}
{running && (
<>
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'focus')}>
@@ -171,6 +185,11 @@ export const Sidebar: React.FC<Props> = ({
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'screenshot')}>
<Camera size={14} /> {tr('copyScreenshot')}
</Ctx.Item>
{canSuspend && (
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'suspend')}>
<Pause size={14} /> {tr('suspend')}
</Ctx.Item>
)}
<Ctx.Item className="menu-item" disabled={vmBusy} onSelect={() => onVMContextAction(vmRefKey(vm), 'stop')}>
<Square size={14} /> {tr('stop')}
</Ctx.Item>
@@ -185,7 +204,7 @@ export const Sidebar: React.FC<Props> = ({
</Ctx.Item>
)}
<Ctx.Separator className="menu-sep" />
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'settings')}>
<Ctx.Item className="menu-item" disabled={suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'settings')}>
<Settings size={14} /> {tr('settingsEllipsis')}
</Ctx.Item>
<Ctx.Item className="menu-item" onSelect={() => onVMContextAction(vmRefKey(vm), 'openSharedFolder')}>
@@ -200,7 +219,7 @@ export const Sidebar: React.FC<Props> = ({
<FolderOpen size={14} /> {tr('openFolder')}
</Ctx.Item>
<Ctx.Separator className="menu-sep" />
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'delete')}>
<Ctx.Item className="menu-item danger" disabled={vmBusy || running || suspended || transitioning} onSelect={() => onVMContextAction(vmRefKey(vm), 'delete')}>
<Trash size={14} /> {tr('delete')}
</Ctx.Item>
</Ctx.Content>
+11 -5
View File
@@ -27,7 +27,7 @@ interface Props {
canDark?: boolean
onThemeMode: (mode: ThemeMode) => void
/** The selected VM and its current state, or null on the system pages. */
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string } | null
vm: { name: string; driver_id?: string; state: string; busy: boolean; graphics?: string; canSuspend: boolean } | null
onNewVM: () => void
onVMAction: (action: VMAction) => void
onVMSettings: () => void
@@ -62,7 +62,8 @@ export const TitleMenus: React.FC<Props> = ({
const running = vm?.state === 'running'
const stopped = vm?.state === 'stopped'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping'
const suspended = vm?.state === 'suspended'
const transitioning = vm?.state === 'starting' || vm?.state === 'stopping' || vm?.state === 'suspending' || vm?.state === 'resuming'
const vmBusy = !vm || vm.busy
const canFullscreen = running && vm?.graphics !== 'vmware-svga'
const stats = useVMStats(vm?.driver_id ?? '', canFullscreen && vm ? vm.name : null, running)
@@ -218,17 +219,22 @@ export const TitleMenus: React.FC<Props> = ({
<Menu.Separator className="menu-sep" />
{running
? item(tr('showWindow'), () => onVMAction('focus'), { shortcut: 'Ctrl+Enter', disabled: vmBusy })
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
: suspended
? item(tr('resume'), () => onVMAction('resume'), { shortcut: vm?.canSuspend ? 'Ctrl+Enter' : undefined, disabled: vmBusy || !vm?.canSuspend })
: item(tr('start'), () => onVMAction('start'), { shortcut: 'Ctrl+Enter', disabled: vmBusy || !stopped })}
{suspended && !vm?.canSuspend && <Menu.Label className="menu-group-label">{tr('resumeUnavailable')}</Menu.Label>}
{item(fullscreenLabel, () => onVMAction('fullscreen'), { disabled: vmBusy || !canFullscreen })}
{item(tr('suspend'), () => onVMAction('suspend'), { disabled: vmBusy || !running || !vm?.canSuspend })}
{item(tr('stop'), () => onVMAction('stop'), { disabled: vmBusy || !running })}
{item(tr('restart'), () => onVMAction('restart'), { disabled: vmBusy || !running })}
{item(tr('copyScreenshot'), () => onVMAction('screenshot'), { disabled: vmBusy || !running })}
<Menu.Separator className="menu-sep" />
{item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm })}
{item(tr('settingsEllipsis'), onVMSettings, { shortcut: 'Ctrl+,', disabled: !vm || suspended || transitioning })}
{item(tr('openFolder'), () => onVMAction('openFolder'), { disabled: !vm })}
<Menu.Separator className="menu-sep" />
{suspended && item(tr('discardSuspend'), () => onVMAction('discardSuspend'), { danger: true, disabled: vmBusy })}
{item(tr('forceStop'), () => onVMAction('forceStop'), { danger: true, disabled: !vm || !(running || transitioning) })}
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || transitioning })}
{item(tr('deleteEllipsis'), onVMDelete, { danger: true, disabled: vmBusy || running || suspended || transitioning })}
</>
))}
{menu('view', tr('menuView'), (
+114 -30
View File
@@ -27,6 +27,7 @@ import {
Minimize2,
Monitor,
Network,
Pause,
Pencil,
Play,
Plus,
@@ -40,7 +41,7 @@ import {
Upload,
UserRound,
} from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import React, { useEffect, useId, useRef, useState } from 'react'
import { I18nKey, locText, t } from '../i18n'
import {
controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel,
@@ -55,6 +56,9 @@ import { VersionArt } from '../macos/VersionArt'
export type VMAction =
| 'start'
| 'suspend'
| 'resume'
| 'discardSuspend'
| 'stop'
| 'forceStop'
| 'restart'
@@ -93,6 +97,8 @@ interface Props {
/** macOS major version (26, 15, …) for the artwork shown before a first frame; null if unknown. */
macosMajor: number | null
state: string
/** Whether the active runtime supports VM suspend/resume. */
canSuspend: boolean
/** Whether the native VM-window installation guide is currently active for this boot. */
guideActive: boolean
/** Whether the builtin.install-guide plugin is enabled. */
@@ -133,13 +139,17 @@ interface Spec {
}
export const VMPage: React.FC<Props> = ({
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
locale, name, driverID, displayName, onDisplayNameSaved, macosMajor, state, canSuspend, guideActive, installGuideEnabled, detail, host, pending, busyAction, onAction, onSettings, onOpenAffinity, onDelete, onViewLogs, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile, onToast, onError, dropping, pluginUI,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
const running = state === 'running'
const suspended = state === 'suspended'
const guestToolsLocked = suspended || state === 'suspending' || state === 'resuming'
const resumeHintId = useId()
const guestToolsHintId = useId()
const installing = !!detail && (detail.has_installer || detail.recovery_mode)
const transitioning = state === 'starting' || state === 'stopping'
const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming'
// Polled here rather than in App so each tick re-renders only this page.
const stats = useVMStats(driverID, name, running)
@@ -319,7 +329,7 @@ export const VMPage: React.FC<Props> = ({
}
// One primary action per state (docs/design-guidelines.md §4): Start while
// stopped, Show Window while running. Ctrl+Enter triggers it (App.tsx).
// stopped, Resume while suspended, Show Window while running. Ctrl+Enter triggers it (App.tsx).
let primary: React.ReactNode = null
let secondary: React.ReactNode = null
if (state === 'stopped') {
@@ -330,10 +340,29 @@ export const VMPage: React.FC<Props> = ({
</Button>
</Tip>
)
} else if (suspended) {
primary = (
<Tip label={tr('resume')} shortcut={PRIMARY_SHORTCUT} disabled={!canSuspend}>
<Button
variant={canSuspend ? 'primary' : 'secondary'}
icon={<Play size={14} aria-hidden="true" />}
busy={busyAction === 'resume'}
disabled={busy || !canSuspend}
aria-describedby={!canSuspend ? resumeHintId : undefined}
onClick={() => onAction('resume')}
>
{tr('resume')}
</Button>
</Tip>
)
} else if (state === 'starting') {
primary = <Button variant="primary" busy>{tr('state_starting')}</Button>
} else if (state === 'stopping') {
primary = <Button busy>{tr('state_stopping')}</Button>
} else if (state === 'suspending') {
primary = <Button busy>{tr('state_suspending')}</Button>
} else if (state === 'resuming') {
primary = <Button variant="primary" busy>{tr('state_resuming')}</Button>
} else if (running) {
const showLabel = tr(guideActive ? 'showInstallGuide' : 'showWindow')
primary = (
@@ -344,7 +373,14 @@ export const VMPage: React.FC<Props> = ({
</Tip>
)
secondary = (
<Button icon={<Square size={12} aria-hidden="true" />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
<>
{canSuspend && (
<Button icon={<Pause size={13} aria-hidden="true" />} busy={busyAction === 'suspend'} disabled={busy} onClick={() => onAction('suspend')}>
{tr('suspend')}
</Button>
)}
<Button icon={<Square size={12} aria-hidden="true" />} busy={busyAction === 'stop'} disabled={busy} onClick={() => onAction('stop')}>{tr('stop')}</Button>
</>
)
} else if (state === 'broken') {
primary = <Button variant="primary" icon={<Terminal size={14} aria-hidden="true" />} onClick={onViewLogs}>{tr('viewLogs')}</Button>
@@ -432,15 +468,15 @@ export const VMPage: React.FC<Props> = ({
{detail && (
<>
{installing ? (
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('finishInstall')}>
<Menu.Item className="menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('finishInstall')}>
<LifeBuoy size={14} /> {tr('finishInstall')}
</Menu.Item>
) : (
<>
<Menu.Item className="menu-item" disabled={busy || transitioning} onSelect={() => onAction('enterRecovery')}>
<Menu.Item className="menu-item" disabled={busy || suspended || transitioning} onSelect={() => onAction('enterRecovery')}>
<LifeBuoy size={14} /> {tr('enterRecovery')}
</Menu.Item>
<Menu.Item className="menu-item" disabled={running || transitioning || busy} onSelect={() => onAction('cloneVM')}>
<Menu.Item className="menu-item" disabled={running || suspended || transitioning || busy} onSelect={() => onAction('cloneVM')}>
<CopyPlus size={14} /> {tr('cloneVM')}
</Menu.Item>
</>
@@ -479,12 +515,17 @@ export const VMPage: React.FC<Props> = ({
</Menu.Item>
))}
<Menu.Separator className="menu-sep" />
{suspended && (
<Menu.Item className="menu-item danger" disabled={busy} onSelect={() => onAction('discardSuspend')}>
<Power size={14} /> {tr('discardSuspend')}
</Menu.Item>
)}
{(running || transitioning) && (
<Menu.Item className="menu-item danger" disabled={busyAction === 'forceStop'} onSelect={() => onAction('forceStop')}>
<Power size={14} /> {tr('forceStop')}
</Menu.Item>
)}
<Menu.Item className="menu-item danger" disabled={running || transitioning || busy} onSelect={onDelete}>
<Menu.Item className="menu-item danger" disabled={running || suspended || transitioning || busy} onSelect={onDelete}>
<Trash size={14} /> {tr('delete')}
</Menu.Item>
</Menu.Content>
@@ -564,11 +605,23 @@ export const VMPage: React.FC<Props> = ({
onCopy(rows.join('\n'))
}
const pillClass = running ? ' is-running' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : ''
const pillClass = running ? ' is-running' : suspended ? ' is-suspended' : state === 'broken' ? ' is-broken' : transitioning ? ' is-busy' : ''
const dropStyle = detail && !installing
? ({ '--wails-drop-target': 'drop' } as React.CSSProperties)
: undefined
const formatSuspendTime = (iso?: string) => {
if (!iso) return ''
const ms = Date.parse(iso)
if (!Number.isFinite(ms)) return ''
try {
const loc = locale === 'en-XA' ? 'en-US' : locale
return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(ms))
} catch {
return ''
}
}
return (
<div className="page vm-page vm-page-drop rg-p-vm-page" style={dropStyle}>
{dropping && (
@@ -589,10 +642,10 @@ export const VMPage: React.FC<Props> = ({
thumb={thumb}
art={<VersionArt shape="screen" className="vm-screen-art" major={macosMajor} name={shownName} />}
running={running}
startLabel={tr('start')}
startLabel={suspended ? tr('resume') : tr('start')}
showLabel={tr('showWindow')}
shotLabel={tr('copyScreenshot')}
onStart={state === 'stopped' && !busy ? () => onAction('start') : undefined}
onStart={!busy && (state === 'stopped' || (suspended && canSuspend)) ? () => onAction(suspended ? 'resume' : 'start') : undefined}
onShow={running && !busy ? () => onAction('focus') : undefined}
onScreenshot={running && !busy ? () => onAction('screenshot') : undefined}
/>
@@ -632,8 +685,10 @@ export const VMPage: React.FC<Props> = ({
<div className="vm-hero-actions">
{primary}
{secondary}
<Tip label={tr('settings')} shortcut="Ctrl+,">
<Button icon={<Settings size={14} aria-hidden="true" />} disabled={!detail} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
<Tip label={suspended ? tr('suspendedSettingsHint') : tr('settings')} shortcut={suspended ? undefined : 'Ctrl+,'}>
<span>
<Button icon={<Settings size={14} aria-hidden="true" />} disabled={!detail || suspended || transitioning} onClick={onSettings}>{tr('settingsEllipsis')}</Button>
</span>
</Tip>
{menu}
</div>
@@ -668,6 +723,29 @@ export const VMPage: React.FC<Props> = ({
</div>
)}
{suspended && (() => {
const suspTime = formatSuspendTime(detail?.suspend_info?.created_at)
const suspSize = detail?.suspend_info?.vmstate_size
? formatBytes(detail.suspend_info.vmstate_size, locale)
: (detail?.memory ? formatMemory(detail.memory, locale) : '—')
return (
<div className="notice notice-info">
<span className="notice-main">
<Pause size={15} className="notice-icon" aria-hidden="true" />
<span className="notice-text">
<span className="notice-title">{tr('suspendedNoticeTitle')}</span>
<span className="notice-sub">
{suspTime
? tr('suspendedNoticeDescWithTime', { time: suspTime, size: suspSize })
: tr('suspendedNoticeDesc', { size: suspSize })}
</span>
{!canSuspend && <span id={resumeHintId} className="notice-sub">{tr('resumeUnavailable')}</span>}
</span>
</span>
</div>
)
})()}
{pending.length > 0 && (
<div className="notice notice-info">
<span className="notice-main">
@@ -854,9 +932,15 @@ export const VMPage: React.FC<Props> = ({
const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
const needsUpgrade = gtConnected && (detail.guest_tools_agent_version ?? 0) > 0 && (detail.guest_tools_agent_version ?? 0) < 3
const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const minimumAgentVersion = gtMountMode === 'sync' ? 7 : 3
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < minimumAgentVersion
// Plugin switched off: show the state and hide controls that would only fail.
const gtOff = !!detail.guest_tools_disabled
const gtAttached = detail.guest_tools_attached
const showToolsAction = !gtOff && (gtAttached || !gtConnected || needsUpgrade)
const toolsAction = gtAttached ? 'detachGuestTools' : 'attachGuestTools'
const toolsActionLabel = gtAttached ? 'detachGuestTools' : needsUpgrade ? 'gtUpdate' : 'gtInstall'
// One status word per state; how files are shared goes in the tooltip.
let gtTone: 'ok' | 'warn' | 'idle' = 'idle'
@@ -969,20 +1053,20 @@ export const VMPage: React.FC<Props> = ({
</span>
</Tip>
</div>
{suspended && showToolsAction && (
<span id={guestToolsHintId} className="hint">{tr('suspendedGuestToolsHint')}</span>
)}
<div className="conn-ctrl">
{gtOff ? null : detail.guest_tools_attached ? (
<Button busy={busyAction === 'detachGuestTools'} disabled={busy} onClick={() => onAction('detachGuestTools')}>
{tr('detachGuestTools')}
</Button>
) : (!gtConnected || needsUpgrade) && (
{showToolsAction && (
<Button
variant={detail.guest_tools_configured ? 'secondary' : 'primary'}
icon={<Disc size={13} aria-hidden="true" />}
busy={busyAction === 'attachGuestTools'}
disabled={busy}
onClick={() => onAction('attachGuestTools')}
variant={gtAttached || detail.guest_tools_configured || guestToolsLocked ? 'secondary' : 'primary'}
icon={gtAttached ? undefined : <Disc size={13} aria-hidden="true" />}
busy={busyAction === toolsAction}
disabled={busy || guestToolsLocked}
aria-describedby={suspended ? guestToolsHintId : undefined}
onClick={() => onAction(toolsAction)}
>
{needsUpgrade ? tr('gtUpdate') : tr('gtInstall')}
{tr(toolsActionLabel)}
</Button>
)}
</div>
@@ -1042,12 +1126,12 @@ export const VMPage: React.FC<Props> = ({
<span>{tr('snapshotsTitle')}</span>
<span className="snap-meta-hint">· {tr('snapshotHint')}</span>
</span>
<Tip label={running || transitioning ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
<Tip label={running || suspended || transitioning ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
<span>
<Button
variant="ghost"
icon={<Plus size={13} aria-hidden="true" />}
disabled={running || transitioning || !!snapBusy}
disabled={running || suspended || transitioning || !!snapBusy}
onClick={() => setCreatingSnap((v) => !v)}
>
{tr('snapshotCreate')}
@@ -1093,7 +1177,7 @@ export const VMPage: React.FC<Props> = ({
<Button
icon={<RotateCcw size={13} aria-hidden="true" />}
busy={snapBusy === `restore:${s.name}`}
disabled={running || transitioning || !!snapBusy}
disabled={running || suspended || transitioning || !!snapBusy}
onClick={() => setRestoreTarget(s.name)}
>
{tr('snapshotRestore')}
@@ -1103,7 +1187,7 @@ export const VMPage: React.FC<Props> = ({
label={tr('snapshotDelete')}
icon={<Trash size={14} />}
busy={snapBusy === `delete:${s.name}`}
disabled={running || transitioning || !!snapBusy}
disabled={running || suspended || transitioning || !!snapBusy}
onClick={() => void handleDeleteSnapshot(s.name)}
/>
</div>
+42
View File
@@ -24,6 +24,10 @@ export const vmZh: Record<string, string> = {
"diagBackingChainWarn": "当前系统盘 CoW 派生链深度为 {depth} 层(≥ 2),未分配簇读穿透会拖慢小文件 I/O,建议合并为独立镜像或基于基础镜像重新派生",
"diagExternalDriveWarn": "数据目录在外置或网络盘上({dir}),读写会明显变慢",
"diagHighMemWarn": "宿主内存已用 {pct}%,虚拟机可能会卡顿",
"discardSuspend": "放弃挂起状态",
"discardSuspendConfirm": "放弃并关机",
"discardSuspendDesc": "将删除已保存的内存与设备状态并回到关机状态,macOS 中尚未保存的工作会丢失,且无法撤销。",
"discardSuspendTitle": "放弃「{name}」的挂起状态?",
"displayNameEdit": "点按以修改显示名称",
"displayNameEditEllipsis": "修改显示名称…",
"displayNameLabel": "显示名称",
@@ -41,6 +45,7 @@ export const vmZh: Record<string, string> = {
"failAttachInstaller": "挂载镜像失败",
"failCloneVM": "派生 CoW 副本失败",
"failDelete": "删除失败",
"failDiscardSuspend": "放弃挂起状态失败",
"failEject": "弹出安装盘失败",
"failEnterRecovery": "进入恢复模式失败",
"failExportDiagnostics": "导出排障日志失败",
@@ -50,10 +55,12 @@ export const vmZh: Record<string, string> = {
"failGuestTools": "Guest Tools 操作失败",
"failOpenFolder": "无法打开文件夹",
"failRestart": "重启失败",
"failResume": "恢复失败",
"failScreenshot": "截屏失败",
"failSnapshot": "恢复点操作失败",
"failStart": "启动失败",
"failStop": "关机失败",
"failSuspend": "挂起失败",
"failType": "键入失败",
"failUpgradeNVMe": "升级到 NVMe 失败",
"fieldAudio": "音频",
@@ -111,6 +118,8 @@ export const vmZh: Record<string, string> = {
"pendingTitle": "下次启动生效",
"pickRecoveryTitle": "选择离线镜像(.img / .dmg)",
"restartToApply": "重启以应用",
"resume": "恢复",
"resumeUnavailable": "切换到支持挂起的内核后可恢复",
"sendText": "发送文本到虚拟机…",
"sendTextConfirm": "发送 (Ctrl+Enter)",
"sendTextDesc": "支持中文、Emoji、宿主机输入法与语音输入,按 Ctrl+Enter 发送到 macOS 当前输入框。",
@@ -155,14 +164,24 @@ export const vmZh: Record<string, string> = {
"state_broken": "出错",
"state_creating": "正在创建",
"state_driver_unavailable": "驱动不可用",
"state_resuming": "恢复中",
"state_running": "运行中",
"state_starting": "启动中",
"state_stopped": "已停止",
"state_stopping": "停止中",
"state_suspended": "已挂起",
"state_suspending": "挂起中",
"suspend": "挂起",
"suspendedGuestToolsHint": "恢复或放弃挂起状态后可更改",
"suspendedNoticeDesc": "恢复后将回到挂起前的桌面与应用状态({size});修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
"suspendedNoticeDescWithTime": "挂起于 {time}({size})· 恢复后将回到原桌面与应用状态;修改硬件配置或管理磁盘前请先恢复或放弃挂起状态。",
"suspendedNoticeTitle": "已保存运行状态",
"suspendedSettingsHint": "请先恢复或放弃挂起状态后再修改配置",
"techInfo": "技术信息",
"toastCloned": "已派生 CoW 副本「{name}」",
"toastDeleted": "已删除 {name}",
"toastDiagExported": "已导出脱敏排障日志包 (.zip)",
"toastDiscardSuspend": "已放弃 {name} 的挂起状态",
"toastEjected": "已弹出安装盘",
"toastEnterRecovery": "已进入恢复模式,启动后可在引导菜单选 Recovery",
"toastEnterRecoveryNextStart": "已准备进入恢复模式,重启后显示引导菜单",
@@ -182,11 +201,13 @@ export const vmZh: Record<string, string> = {
"toastOnlineRecoveryStarted": "正在拉取在线恢复镜像(约 1 GB),完成后自动挂载",
"toastPreventSleepOff": "已关闭 macOS 防休眠守护",
"toastPreventSleepOn": "已开启 macOS 防休眠守护",
"toastResumed": "{name} 已恢复",
"toastScreenshotCopied": "已复制虚拟机画面",
"toastSnapshotCreated": "已创建恢复点 {name}",
"toastSnapshotDeleted": "已删除恢复点 {name}",
"toastSnapshotRestored": "已回滚到 {name}",
"toastStopped": "{name} 已关机",
"toastSuspended": "{name} 已挂起",
"toastTyped": "{n, plural, other {已键入 # 个字符}}",
"toggleFullscreen": "切换全屏",
"typeClipboard": "粘贴剪贴板到虚拟机",
@@ -219,6 +240,10 @@ export const vmEn: Record<string, string> = {
"diagBackingChainWarn": "System disk CoW backing chain is {depth} layers deep (\u003e= 2); read-through slows small-file I/O — consider flattening or re-deriving from the base image",
"diagExternalDriveWarn": "The data folder is on an external or network drive ({dir}); disk access will be slow",
"diagHighMemWarn": "Host memory is {pct}% used; the VM may stutter",
"discardSuspend": "Discard saved state",
"discardSuspendConfirm": "Discard \u0026 Power Off",
"discardSuspendDesc": "Removes the saved memory and device state and returns the VM to powered off. Any unsaved work inside macOS will be lost and can’t be undone.",
"discardSuspendTitle": "Discard saved state for “{name}”?",
"displayNameEdit": "Click to change the display name",
"displayNameEditEllipsis": "Change Display Name…",
"displayNameLabel": "Display name",
@@ -236,6 +261,7 @@ export const vmEn: Record<string, string> = {
"failAttachInstaller": "Couldn’t attach the image",
"failCloneVM": "Couldn’t create CoW clone",
"failDelete": "Couldn’t delete",
"failDiscardSuspend": "Couldn’t discard saved state",
"failEject": "Couldn’t eject the installer",
"failEnterRecovery": "Couldn’t enter recovery mode",
"failExportDiagnostics": "Couldn’t export diagnostics",
@@ -245,10 +271,12 @@ export const vmEn: Record<string, string> = {
"failGuestTools": "Guest Tools operation failed",
"failOpenFolder": "Couldn’t open the folder",
"failRestart": "Couldn’t restart",
"failResume": "Couldn’t resume",
"failScreenshot": "Screenshot failed",
"failSnapshot": "Restore point failed",
"failStart": "Couldn’t start",
"failStop": "Couldn’t shut down",
"failSuspend": "Couldn’t suspend",
"failType": "Couldn’t type into the VM",
"failUpgradeNVMe": "Couldn’t upgrade to NVMe",
"fieldAudio": "Audio",
@@ -306,6 +334,8 @@ export const vmEn: Record<string, string> = {
"pendingTitle": "Applies on next start",
"pickRecoveryTitle": "Choose an offline image (.img / .dmg)",
"restartToApply": "Restart to apply",
"resume": "Resume",
"resumeUnavailable": "Switch to a runtime that supports suspend to resume this VM",
"sendText": "Send text to VM…",
"sendTextConfirm": "Send (Ctrl+Enter)",
"sendTextDesc": "Supports Chinese, emoji, host IME, and dictation. Press Ctrl+Enter to inject into the focused macOS field.",
@@ -350,14 +380,24 @@ export const vmEn: Record<string, string> = {
"state_broken": "Error",
"state_creating": "Creating",
"state_driver_unavailable": "Driver unavailable",
"state_resuming": "Resuming",
"state_running": "Running",
"state_starting": "Starting",
"state_stopped": "Stopped",
"state_stopping": "Stopping",
"state_suspended": "Suspended",
"state_suspending": "Suspending",
"suspend": "Suspend",
"suspendedGuestToolsHint": "Resume or discard saved state to make changes",
"suspendedNoticeDesc": "Resuming restores your desktop and running apps ({size}). Resume or discard the saved state before changing settings or managing disks.",
"suspendedNoticeDescWithTime": "Suspended {time} ({size}) · Resuming restores your desktop and running apps. Resume or discard before changing settings or disks.",
"suspendedNoticeTitle": "Saved state ready",
"suspendedSettingsHint": "Resume or discard saved state before changing settings",
"techInfo": "Technical details",
"toastCloned": "CoW clone “{name}” created",
"toastDeleted": "{name} deleted",
"toastDiagExported": "Redacted diagnostics archive exported (.zip)",
"toastDiscardSuspend": "Discarded saved state for {name}",
"toastEjected": "Installer ejected",
"toastEnterRecovery": "Recovery mode ready — pick Recovery in OpenCore on next start",
"toastEnterRecoveryNextStart": "Recovery mode ready — restart to open the boot menu",
@@ -377,11 +417,13 @@ export const vmEn: Record<string, string> = {
"toastOnlineRecoveryStarted": "Downloading online recovery image (~1 GB); will attach when ready",
"toastPreventSleepOff": "Prevent-sleep guard disabled",
"toastPreventSleepOn": "Prevent-sleep guard enabled",
"toastResumed": "{name} resumed",
"toastScreenshotCopied": "VM screenshot copied",
"toastSnapshotCreated": "Created restore point {name}",
"toastSnapshotDeleted": "Deleted restore point {name}",
"toastSnapshotRestored": "Restored to {name}",
"toastStopped": "{name} shut down",
"toastSuspended": "{name} suspended",
"toastTyped": "{n, plural, one {Typed # character} other {Typed # characters}}",
"toggleFullscreen": "Toggle full screen",
"typeClipboard": "Send clipboard to VM",
+21
View File
@@ -144,6 +144,10 @@ export type I18nKey =
| "diagBackingChainWarn"
| "diagExternalDriveWarn"
| "diagHighMemWarn"
| "discardSuspend"
| "discardSuspendConfirm"
| "discardSuspendDesc"
| "discardSuspendTitle"
| "diskCompactAction"
| "diskCompactDesc"
| "diskCompactDone"
@@ -209,6 +213,7 @@ export type I18nKey =
| "failCloneVM"
| "failCreate"
| "failDelete"
| "failDiscardSuspend"
| "failDownload"
| "failEject"
| "failEnterRecovery"
@@ -220,12 +225,14 @@ export type I18nKey =
| "failGuestTools"
| "failOpenFolder"
| "failRestart"
| "failResume"
| "failRuntime"
| "failSSH"
| "failScreenshot"
| "failSnapshot"
| "failStart"
| "failStop"
| "failSuspend"
| "failType"
| "failUpgradeNVMe"
| "fieldAudio"
@@ -627,6 +634,8 @@ export type I18nKey =
| "resolution"
| "restart"
| "restartToApply"
| "resume"
| "resumeUnavailable"
| "runtimeAlpha"
| "runtimeAlphaHint"
| "runtimeChannel_alpha"
@@ -750,10 +759,13 @@ export type I18nKey =
| "state_broken"
| "state_creating"
| "state_driver_unavailable"
| "state_resuming"
| "state_running"
| "state_starting"
| "state_stopped"
| "state_stopping"
| "state_suspended"
| "state_suspending"
| "statsCPU"
| "statsDisk"
| "statsDiskSub"
@@ -784,6 +796,12 @@ export type I18nKey =
| "summarySSH"
| "summarySSHPort"
| "summarySource"
| "suspend"
| "suspendedGuestToolsHint"
| "suspendedNoticeDesc"
| "suspendedNoticeDescWithTime"
| "suspendedNoticeTitle"
| "suspendedSettingsHint"
| "taskAppUpdate"
| "taskCreate"
| "taskDownload"
@@ -810,6 +828,7 @@ export type I18nKey =
| "toastCreated"
| "toastDeleted"
| "toastDiagExported"
| "toastDiscardSuspend"
| "toastDownloadPaused"
| "toastEjected"
| "toastEnterRecovery"
@@ -832,6 +851,7 @@ export type I18nKey =
| "toastPreventSleepOff"
| "toastPreventSleepOn"
| "toastQueueCanceled"
| "toastResumed"
| "toastRuntimeReady"
| "toastSSHConfigWritten"
| "toastSSHUserSaved"
@@ -842,6 +862,7 @@ export type I18nKey =
| "toastSnapshotDeleted"
| "toastSnapshotRestored"
| "toastStopped"
| "toastSuspended"
| "toastTyped"
| "toggleFullscreen"
| "typeClipboard"
+9 -2
View File
@@ -292,6 +292,10 @@ h1, h2, h3, p { margin: 0; }
.status { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; display: inline-block; }
.status-running { background: var(--status-running); }
.status-stopped { border: 1.5px solid var(--status-idle); }
.status-suspended {
width: 7px; height: 8px; border-radius: 0;
background: linear-gradient(90deg, var(--status-busy) 0 2.5px, transparent 2.5px 4.5px, var(--status-busy) 4.5px 7px);
}
.status-busy { background: conic-gradient(var(--status-busy) 0 50%, transparent 50% 100%); border: 1.5px solid var(--status-busy); animation: pulse 1.4s ease-in-out infinite; }
.status-warn { background: var(--status-busy); }
.status-broken { background: var(--status-error); border-radius: 1.5px; transform: rotate(45deg); width: 7px; height: 7px; }
@@ -366,6 +370,7 @@ h1, h2, h3, p { margin: 0; }
.vm-hero-pill.is-running {
background: var(--ok-soft); border-color: transparent; color: var(--ok-text);
}
.vm-hero-pill.is-suspended,
.vm-hero-pill.is-busy {
background: var(--warn-soft); border-color: transparent; color: var(--warn-text);
}
@@ -952,8 +957,10 @@ button.status-issue + .status-metric { margin-left: 6px; }
.toast[data-swipe="cancel"] { transform: translateX(0); transition: transform var(--dur) var(--ease-out); }
.toast[data-swipe="end"] { animation: toast-swipe-out var(--dur-fast) var(--ease-out) both; }
:root[dir="rtl"] .toast[data-swipe="end"] { animation: toast-swipe-out-rtl var(--dur-fast) var(--ease-out) both; }
.toast-main-row { display: flex; align-items: flex-start; gap: var(--sp-3); width: 100%; min-width: 0; }
.toast-main-row > svg { margin-top: 2px; flex-shrink: 0; }
.toast-main-row { display: flex; align-items: center; gap: var(--sp-3); width: 100%; min-width: 0; }
.toast-main-row > svg { flex-shrink: 0; }
.toast-main-row:has(.toast-desc) { align-items: flex-start; }
.toast-main-row:has(.toast-desc) > svg { margin-top: 2px; }
.toast.ok .toast-main-row > svg { color: var(--status-running); }
.toast.error .toast-main-row > svg { color: var(--status-error); }
.toast-text { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 3px; }
+2 -1
View File
@@ -49,7 +49,7 @@ export type RemoteRuntime = Model<runtime.Remote> & {
export type VMListItem = Model<driver.VMListItem> & {
driver_id?: string
state: 'running' | 'stopped' | 'broken'
state: 'running' | 'stopped' | 'suspended' | 'broken'
}
export type PendingChange = app.PendingChange
@@ -64,6 +64,7 @@ export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizati
}
export type AppUpdateInfo = version.UpdateInfo
export type SuspendInfo = reims.SuspendInfo
export type VMDetail = reims.VMDetail
export type VMStats = app.VMStats
export type DriveShareSettings = Model<app.DriveShareSettings>
+3 -2
View File
@@ -87,11 +87,12 @@ export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
)
IconButton.displayName = 'IconButton'
export type StatusKind = 'running' | 'stopped' | 'busy' | 'broken' | 'warn'
export type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn'
export function statusKind(state: string): StatusKind {
if (state === 'running') return 'running'
if (state === 'starting' || state === 'stopping' || state === 'creating') return 'busy'
if (state === 'suspended') return 'suspended'
if (state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' || state === 'creating') return 'busy'
if (state === 'driver_unavailable') return 'warn'
if (state === 'broken') return 'broken'
return 'stopped'
+31 -1
View File
@@ -1,7 +1,37 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import * as RDialog from '@radix-ui/react-dialog'
import { X } from 'lucide-react'
import React from 'react'
import { IconButton } from './controls'
import { Button, IconButton } from './controls'
interface ConfirmDialogProps {
title: string
description: string
cancelLabel: string
confirmLabel: string
onCancel: () => void
onConfirm: () => void
children?: React.ReactNode
}
export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({ title, description, cancelLabel, confirmLabel, onCancel, onConfirm, children }) => (
<Alert.Root open onOpenChange={(open) => { if (!open) onCancel() }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog sm">
<div className="dialog-body">
<Alert.Title className="dialog-title">{title}</Alert.Title>
<Alert.Description className="dialog-desc">{description}</Alert.Description>
{children}
</div>
<div className="dialog-foot">
<Alert.Cancel asChild><Button>{cancelLabel}</Button></Alert.Cancel>
<Alert.Action asChild><Button variant="danger" onClick={onConfirm}>{confirmLabel}</Button></Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)
interface Props {
title: string
+1
View File
@@ -182,6 +182,7 @@ export const events = {
// Tray menu (internal/app/app.go trayVMAction): "Show in Reims-Go" and "New VM…".
onTraySelectVM: (cb: (name: string) => void) => eventsOn('reims:tray-select-vm', cb),
onTrayNewVM: (cb: () => void) => eventsOn('reims:tray-new-vm', cb),
onTrayDiscardSuspend: (cb: (name: string) => void) => eventsOn('reims:tray-discard-suspend', cb),
// Renderer health watchdog & crash reporting (internal/app/ui_health.go).
onUIPing: (cb: () => void) => eventsOn('reims:ui-ping', cb),
emitUIPong: () => eventsEmit('reims:ui-pong'),
+12
View File
@@ -68,6 +68,10 @@ export function DetachGuestTools(arg1:string):Promise<void>;
export function DisablePlugin(arg1:string):Promise<void>;
export function DiscardSuspend(arg1:string):Promise<void>;
export function DiscardSuspendWithDriver(arg1:string,arg2:string):Promise<void>;
export function DismissTask(arg1:string):Promise<void>;
export function DoctorPlugin(arg1:string):Promise<Array<plugin.DoctorFinding>>;
@@ -230,6 +234,10 @@ export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
export function RestoreSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function ResumeVM(arg1:string):Promise<void>;
export function ResumeVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
export function ScanInstalledPlugin(arg1:string):Promise<plugin.ScanReport>;
@@ -278,6 +286,10 @@ export function SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
export function SuspendVM(arg1:string):Promise<void>;
export function SuspendVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
export function ToggleVMFullscreen(arg1:string):Promise<boolean>;
+24
View File
@@ -118,6 +118,14 @@ export function DisablePlugin(arg1) {
return window['go']['app']['App']['DisablePlugin'](arg1);
}
export function DiscardSuspend(arg1) {
return window['go']['app']['App']['DiscardSuspend'](arg1);
}
export function DiscardSuspendWithDriver(arg1, arg2) {
return window['go']['app']['App']['DiscardSuspendWithDriver'](arg1, arg2);
}
export function DismissTask(arg1) {
return window['go']['app']['App']['DismissTask'](arg1);
}
@@ -442,6 +450,14 @@ export function RestoreSnapshotWithDriver(arg1, arg2, arg3) {
return window['go']['app']['App']['RestoreSnapshotWithDriver'](arg1, arg2, arg3);
}
export function ResumeVM(arg1) {
return window['go']['app']['App']['ResumeVM'](arg1);
}
export function ResumeVMWithDriver(arg1, arg2) {
return window['go']['app']['App']['ResumeVMWithDriver'](arg1, arg2);
}
export function SaveCustomThemeScheme(arg1) {
return window['go']['app']['App']['SaveCustomThemeScheme'](arg1);
}
@@ -538,6 +554,14 @@ export function SuggestLanguagePack() {
return window['go']['app']['App']['SuggestLanguagePack']();
}
export function SuspendVM(arg1) {
return window['go']['app']['App']['SuspendVM'](arg1);
}
export function SuspendVMWithDriver(arg1, arg2) {
return window['go']['app']['App']['SuspendVMWithDriver'](arg1, arg2);
}
export function ToggleBorderless(arg1, arg2) {
return window['go']['app']['App']['ToggleBorderless'](arg1, arg2);
}
File diff suppressed because it is too large. Load diff
+37 -6
View File
@@ -40,6 +40,7 @@ type AppState struct {
Optimizations []host.Optimization `json:"optimizations"`
Runtimes []rt.Installed `json:"runtimes"`
ActiveRuntime *rt.Installed `json:"active_runtime,omitempty"`
CanSuspend bool `json:"can_suspend"`
VMs []driver.VMListItem `json:"vms"`
Transitions map[string]string `json:"transitions"`
PendingChanges map[string][]PendingChange `json:"pending_changes"`
@@ -107,6 +108,7 @@ type App struct {
runtimeKinds *rt.KindRegistry
uiHealth uiHealthState
themeMode string
vmClosePrompts sync.Map
}
// Lifecycle exposes Wails lifecycle callbacks without exporting them as
@@ -317,7 +319,10 @@ func (a *App) pollVMs(ctx context.Context) {
}
}
if tr, ok := a.transitions[key]; ok {
if (tr == "starting" && vm.State == "running") || (tr == "stopping" && vm.State == "stopped") {
if (tr == "starting" && vm.State == "running") ||
(tr == "stopping" && vm.State == "stopped") ||
(tr == "suspending" && (vm.State == "suspended" || vm.State == "stopped")) ||
(tr == "resuming" && vm.State == "running") {
delete(a.transitions, key)
if vm.State == "stopped" {
delete(a.pendingChanges, key)
@@ -483,10 +488,14 @@ func (a *App) listVMsInternal(ctx context.Context) ([]driver.VMListItem, error)
return nil, err
}
vms, err := c.List(ctx)
if err != nil {
return nil, err
}
for i := range vms {
vms[i].DriverID = driver.BuiltinReimsMacOSDriverID
}
return vms, err
enrichMacOSVMListStates(vms)
return vms, nil
}
// qemuImage is the executable reims-ctl reports as a running VM's PID.
@@ -672,6 +681,7 @@ func (a *App) GetState() AppState {
Optimizations: opts,
Runtimes: runtimes,
ActiveRuntime: active,
CanSuspend: active != nil && active.Manifest.HasCapability("vm-suspend"),
VMs: vms,
Transitions: trCopy,
PendingChanges: pcCopy,
@@ -777,6 +787,7 @@ func (a *App) startTray() {
},
GetSnapshot: func() tray.Snapshot {
a.mu.Lock()
cfgCopy := *a.cfg
loc := a.cfg.Locale
cached := append([]driver.VMListItem(nil), a.lastVMs...)
transitions := make(map[string]string, len(a.transitions))
@@ -784,6 +795,10 @@ func (a *App) startTray() {
transitions[k] = v
}
a.mu.Unlock()
canSuspend := false
if active, err := rt.ResolveActive(&cfgCopy); err == nil && active != nil {
canSuspend = active.Manifest.HasCapability("vm-suspend")
}
if len(cached) == 0 {
if vms, err := a.listVMsInternal(context.Background()); err == nil {
cached = vms
@@ -807,9 +822,10 @@ func (a *App) startTray() {
}
effLoc := i18n.EffectiveLocale(loc)
return tray.Snapshot{
Locale: effLoc,
LocaleZh: effLoc == i18n.ZhCN,
VMs: items,
Locale: effLoc,
LocaleZh: effLoc == i18n.ZhCN,
CanSuspend: canSuspend,
VMs: items,
}
},
})
@@ -837,6 +853,15 @@ func (a *App) trayVMAction(driverID, name string, act tray.Action) {
switch act {
case tray.ActStart:
err, failTitle = a.StartVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.start_fail", vars)
case tray.ActSuspend:
err, failTitle = a.SuspendVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.suspend_fail", vars)
case tray.ActResume:
err, failTitle = a.ResumeVMWithDriver(driverID, name), i18n.M(loc, "tray.notify.resume_fail", vars)
case tray.ActDiscardSuspend:
a.ShowMainWindow()
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:tray-discard-suspend", name)
}
case tray.ActStop:
err, failTitle = a.StopVMWithDriver(driverID, name, false), i18n.M(loc, "tray.notify.stop_fail", vars)
case tray.ActForceStop:
@@ -888,7 +913,13 @@ func (a *App) SetDataRoot(dir string) error {
curAppUpdateChannel := a.cfg.AppUpdateChannel
curMinToTray := a.cfg.MinimizeToTray
for _, v := range a.lastVMs {
if v.State == "running" || v.State == "starting" || v.State == "stopping" {
if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
}
for _, tr := range a.transitions {
if tr != "" {
a.mu.Unlock()
return i18n.NewCodedError(loc, "E_DATAROOT_BUSY_VMS", "err.dataroot.busy_vms", nil, nil)
}
+5 -5
View File
@@ -14,6 +14,7 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/plugin/builtin"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
@@ -239,13 +240,11 @@ func (a *App) AttachGuestTools(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
if d.Directory == "" {
return fmt.Errorf("VM %s has no directory", name)
}
defer release()
srv, port, err := a.ensureGuestToolsBridge()
if err != nil {
return err
@@ -295,10 +294,11 @@ func (a *App) DetachGuestTools(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
stripped := reims.StripGuestToolsArgs(d.ExtraArgs)
ctx := context.Background()
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
+36 -14
View File
@@ -113,10 +113,11 @@ func (a *App) enterRecoveryLegacy(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
ctx := context.Background()
@@ -159,9 +160,22 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
if err != nil {
return "", err
}
d, err := a.GetVMDetail(name)
if err != nil {
return "", err
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
var d reims.VMDetail
if svc == nil {
var release func()
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return "", err
}
defer release()
} else {
d, err = c.Show(a.baseCtx(), name)
if err != nil {
return "", err
}
}
path := strings.TrimSpace(installerPath)
if path == "" {
@@ -178,9 +192,6 @@ func (a *App) AttachInstaller(name, installerPath string) (string, error) {
base := filepath.Base(path)
a.emitVMLog(name, "Attaching installer image to "+name+": "+base)
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
if svc != nil {
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "insert", map[string]any{"path": path})
} else {
@@ -318,10 +329,11 @@ func (a *App) finishInstallLegacy(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
d, release, err := startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
ctx := context.Background()
@@ -411,9 +423,22 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
if err != nil {
return err
}
d, err := a.GetVMDetail(name)
if err != nil {
return err
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
var d reims.VMDetail
if svc == nil {
var release func()
d, release, err = startprep.LockMutableVM(a.baseCtx(), c, name)
if err != nil {
return err
}
defer release()
} else {
d, err = c.Show(a.baseCtx(), name)
if err != nil {
return err
}
}
if d.HasInstaller {
return errors.New("exit recovery mode (eject installer) before switching disk controller")
@@ -424,9 +449,6 @@ func (a *App) UpgradeDiskToNVMe(name string) error {
w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) })
ctx := context.Background()
a.emitVMLog(name, "Upgrading disk controller for "+name+" to NVMe...")
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
if svc != nil {
_, err = svc.InvokeAction(ctx, driver.NewVMRef("", name), "upgrade_nvme", nil)
} else {
+3
View File
@@ -112,6 +112,9 @@ func (a *App) StartVMWithDriver(driverID, name string) error {
return err
}
ref := vm.Ref()
if vm.State == "suspended" {
return a.ResumeVMWithDriver(ref.DriverID, ref.Name)
}
key := ref.Key()
detail := vm
a.mu.Lock()
+9
View File
@@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/guest"
"github.com/Nwflower/reims-go/internal/macos/reims"
@@ -38,3 +39,11 @@ func (a *App) client() (*reims.Client, error) {
}
return reims.NewClient(cfg, *active), nil
}
func enrichMacOSVMListStates(vms []driver.VMListItem) {
for i := range vms {
if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) {
vms[i].State = "suspended"
}
}
}
+11
View File
@@ -62,6 +62,7 @@ func (a *App) getVMDetailLegacy(name string) (reims.VMDetail, error) {
d.RecoveryMode = isRecoveryModeActive(d)
a.populateGuestToolsDetail(&d)
a.populateGuestLangDetail(&d)
populateSuspendDetail(&d)
return d, nil
}
@@ -90,5 +91,15 @@ func (a *App) GetVMDetail(name string) (reims.VMDetail, error) {
d.RecoveryMode = isRecoveryModeActive(d)
a.populateGuestToolsDetail(&d)
a.populateGuestLangDetail(&d)
populateSuspendDetail(&d)
return d, nil
}
func populateSuspendDetail(d *reims.VMDetail) {
if d != nil && d.State == "stopped" && reims.HasSuspendState(d.Directory) {
d.State = "suspended"
if info, err := reims.ReadSuspendInfo(d.Directory); err == nil {
d.SuspendInfo = info
}
}
}
+5 -1
View File
@@ -109,7 +109,7 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) {
a.mu.Lock()
tr := a.transitions[vmKey(name)]
a.mu.Unlock()
if tr == "stopping" {
if tr == "stopping" || tr == "suspending" {
return
}
@@ -187,6 +187,7 @@ func stripLegacyManagedExtraArgs(extraArgs string) string {
s := reims.StripGuestToolsArgs(extraArgs)
s = reims.StripOfflineHelperArgs(s)
s = qmp.StripLegacyWin10RebootArgs(s)
s = reims.StripIncomingDeferArgs(s)
return strings.TrimSpace(s)
}
@@ -304,6 +305,9 @@ func (a *App) startVMLegacy(name string) error {
host.ShouldUseFixedGuestMode(curDetail.Borderless, curDetail.Resolution, rep.PrimaryDisplay) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
if prep.Runtime.Manifest.HasCapability("client-window-close") {
c.Env = append(c.Env, vmstart.CloseRequestEnv(name)...)
}
a.mu.Lock()
a.transitions[vmKey(name)] = "starting"
+6
View File
@@ -10,6 +10,7 @@ import (
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
@@ -91,6 +92,11 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error {
if err != nil {
return err
}
_, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name)
if err != nil {
return err
}
defer release()
if reims.HasCtlSetChanges(opts) {
if err := c.Set(context.Background(), opts, w, w); err != nil {
a.emitVMLog(opts.Name, "Set error: "+err.Error())
+6 -3
View File
@@ -24,9 +24,11 @@ type VMStats struct {
DiskBackingBroken bool `json:"disk_backing_broken,omitempty"`
DiskBackingDepthWarn bool `json:"disk_backing_depth_warn,omitempty"`
UptimeSeconds int64 `json:"uptime_seconds"`
GuestToolsConnected bool `json:"guest_tools_connected"`
GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"`
GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"`
GuestToolsConnected bool `json:"guest_tools_connected"`
GuestToolsMountMode string `json:"guest_tools_mount_mode,omitempty"`
GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"`
GuestToolsSleepGuard bool `json:"guest_tools_sleep_guard"`
}
// GetVMStats samples host-side process and disk telemetry through the owning driver.
@@ -88,6 +90,7 @@ func (a *App) GetVMStatsWithDriver(driverID, name string) (VMStats, error) {
st := srv.Status(vm.Name, 15*time.Second)
stats.GuestToolsConnected = st.Connected
stats.GuestToolsMountMode = st.MountMode
stats.GuestToolsAgentVersion = st.AgentVersion
stats.GuestToolsSleepGuard = st.SleepActive
}
}
+207
View File
@@ -0,0 +1,207 @@
package app
import (
"context"
"errors"
"fmt"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime"
)
// SuspendVM saves a VM's running state and closes its QEMU process.
func (a *App) SuspendVM(name string) error {
return a.SuspendVMWithDriver("", name)
}
func (a *App) SuspendVMWithDriver(driverID, name string) error {
if err := a.requireWritableDataRoot(); err != nil {
return err
}
a.mu.Lock()
svc, gt := a.lifecycleSvc, a.guestTools
a.mu.Unlock()
if svc == nil {
return errors.New("driver lifecycle is not initialized")
}
ctx := a.baseCtx()
_, vm, err := svc.Resolve(ctx, driverID, name)
if err != nil {
return err
}
ref := vm.Ref()
key := ref.Key()
end, err := a.beginSuspendTransition(key, ref.Name, "suspending")
if err != nil {
return err
}
defer end()
lastPct := -1
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
res, err := svc.Suspend(ctx, ref, func(p driver.SuspendProgress) {
if pct, ok := suspendProgressPercent(p); ok {
if pct >= lastPct+25 || p.Status == "completed" {
lastPct = pct
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspend progress: %s (%d%%)", p.Status, pct))
}
}
}, w, w)
if err != nil {
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Suspend error: "+err.Error())
return err
}
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcherKey(key)
stopVMMonitor(ref.Name)
}
if gt != nil {
gt.UnregisterVM(key)
}
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Suspended %s (%.2f GiB saved)", ref.Name, float64(res.VMStateSize)/float64(1<<30)))
return nil
}
// ResumeVM restores a suspended VM with its original media and devices.
func (a *App) ResumeVM(name string) error {
return a.ResumeVMWithDriver("", name)
}
func (a *App) ResumeVMWithDriver(driverID, name string) error {
if err := a.requireWritableDataRoot(); err != nil {
return err
}
a.mu.Lock()
svc := a.lifecycleSvc
cfgCopy := *a.cfg
a.mu.Unlock()
if svc == nil {
return errors.New("driver lifecycle is not initialized")
}
ctx := a.baseCtx()
_, vm, err := svc.Resolve(ctx, driverID, name)
if err != nil {
return err
}
ref := vm.Ref()
key := ref.Key()
end, err := a.beginSuspendTransition(key, ref.Name, "resuming")
if err != nil {
return err
}
defer end()
var extraEnv []string
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
a.cancelRebootWatcherKey(key)
if active, rerr := rt.ResolveActive(&cfgCopy); rerr == nil && active != nil && active.Manifest.HasCapability("win32-unicode-input") {
extraEnv = append(extraEnv, a.inputBridgeEnv(ref.Name, vm.Directory)...)
}
}
startAt := time.Now()
w := vmstart.LineWriter(func(line string) { a.emitVMLogForDriver(ref.DriverID, ref.Name, line) })
result, err := svc.Resume(ctx, ref, extraEnv, w, w)
if err != nil {
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Resume error: "+err.Error())
return err
}
if ref.DriverID == driver.BuiltinReimsMacOSDriverID {
for _, action := range result.PostStart {
if action.Kind != "qmp.watch_cold_reboot" {
continue
}
if addr, _ := action.Params["qmp_addr"].(string); addr != "" {
a.watchWin10ColdReboot(ref.Name, addr)
}
}
a.startVMMonitor(ref.Name, vm, startAt)
}
a.emitVMLogForDriver(ref.DriverID, ref.Name, fmt.Sprintf("Resumed %s in %.1fs", ref.Name, time.Since(startAt).Seconds()))
return nil
}
// DiscardSuspend deletes a stopped VM's saved execution state.
func (a *App) DiscardSuspend(name string) error {
return a.DiscardSuspendWithDriver("", name)
}
func (a *App) DiscardSuspendWithDriver(driverID, name string) error {
if err := a.requireWritableDataRoot(); err != nil {
return err
}
a.mu.Lock()
svc := a.lifecycleSvc
a.mu.Unlock()
if svc == nil {
return errors.New("driver lifecycle is not initialized")
}
ctx := a.baseCtx()
_, vm, err := svc.Resolve(ctx, driverID, name)
if err != nil {
return err
}
ref := vm.Ref()
if err := svc.DiscardSuspend(ctx, ref); err != nil {
return err
}
a.emitVMLogForDriver(ref.DriverID, ref.Name, "Discarded suspend state for "+ref.Name)
a.wakePoll()
a.emitStateChanged()
return nil
}
func (a *App) beginSuspendTransition(key, displayName, state string) (func(), error) {
a.mu.Lock()
loc := a.cfg.Locale
if a.transitions[key] != "" {
a.mu.Unlock()
return nil, i18n.NewCodedError(loc, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": displayName}, nil)
}
a.transitions[key] = state
a.mu.Unlock()
a.emitStateChanged()
return func() {
a.mu.Lock()
delete(a.transitions, key)
a.mu.Unlock()
a.wakePoll()
a.emitStateChanged()
}, nil
}
func suspendProgressPercent(p driver.SuspendProgress) (int, bool) {
if p.Status == "completed" {
return 100, true
}
if p.Total <= 0 {
return 0, false
}
// With mapped-ram, zero pages are skipped so Transferred stays below Total;
// Total - Remaining tracks actual scan/save completion across all RAM.
done := p.Total - p.Remaining
if done < 0 {
done = 0
}
if done > p.Total {
done = p.Total
}
pct := int(done * 100 / p.Total)
if pct >= 100 {
pct = 99
}
return pct, true
}
func (a *App) emitStateChanged() {
if a.ctx != nil {
wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true)
}
}
// Keep context import used cleanly for future cancellation hooks.
var _ context.Context
+84
View File
@@ -0,0 +1,84 @@
package app
import (
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/macos/reims"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestEnrichVMListStatesAndPopulateSuspendDetail(t *testing.T) {
suspendedDir := t.TempDir()
stoppedDir := t.TempDir()
if err := os.WriteFile(reims.SuspendStatePath(suspendedDir)+".tmp", []byte("0123456789"), 0o600); err != nil {
t.Fatal(err)
}
media := filepath.Join(suspendedDir, "disk.qcow2")
for _, path := range []string{media, filepath.Join(suspendedDir, "vm.toml")} {
if err := os.WriteFile(path, []byte("state"), 0o600); err != nil {
t.Fatal(err)
}
}
if _, err := reims.SealSuspend(
reims.VMDetail{Name: "mac-a", Directory: suspendedDir, CPUs: 8, Memory: "8G", Graphics: "reims-vgpu"},
rt.Installed{Commit: "3731afd"},
[]string{media},
); err != nil {
t.Fatal(err)
}
vms := []driver.VMListItem{
{Name: "mac-a", Dir: suspendedDir, State: "stopped"},
{Name: "mac-b", Dir: stoppedDir, State: "stopped"},
{Name: "mac-c", Dir: suspendedDir, State: "running"},
}
enrichMacOSVMListStates(vms)
if vms[0].State != "suspended" {
t.Fatalf("mac-a state = %q, want suspended", vms[0].State)
}
if vms[1].State != "stopped" {
t.Fatalf("mac-b state = %q, want stopped", vms[1].State)
}
if vms[2].State != "running" {
t.Fatalf("running VM must stay running, got %q", vms[2].State)
}
det := reims.VMDetail{Name: "mac-a", Directory: suspendedDir, State: "stopped"}
populateSuspendDetail(&det)
if det.State != "suspended" || det.SuspendInfo == nil || det.SuspendInfo.VMStateSize != 10 {
t.Fatalf("populateSuspendDetail failed: %+v", det)
}
}
func TestStripLegacyManagedExtraArgsStripsIncomingDefer(t *testing.T) {
got := stripLegacyManagedExtraArgs("-machine kernel-irqchip=on -incoming defer")
if got != "-machine kernel-irqchip=on" {
t.Fatalf("stripLegacyManagedExtraArgs = %q", got)
}
}
func TestSuspendProgressPercentTracksRemainingAcrossSparseRAM(t *testing.T) {
cases := []struct {
name string
prog driver.SuspendProgress
pct int
ok bool
}{
{"setup", driver.SuspendProgress{Status: "setup"}, 0, false},
{"active sparse", driver.SuspendProgress{Status: "active", Transferred: 400, Remaining: 1000, Total: 2000}, 50, true},
{"device stage caps below 100", driver.SuspendProgress{Status: "device", Transferred: 1080, Remaining: 0, Total: 2000}, 99, true},
{"completed always 100", driver.SuspendProgress{Status: "completed", Transferred: 1080, Remaining: 0, Total: 2000}, 100, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
pct, ok := suspendProgressPercent(tc.prog)
if pct != tc.pct || ok != tc.ok {
t.Fatalf("suspendProgressPercent(%+v) = (%d, %t), want (%d, %t)", tc.prog, pct, ok, tc.pct, tc.ok)
}
})
}
}
+5
View File
@@ -0,0 +1,5 @@
//go:build !windows
package app
func (*App) confirmVMWindowClose(string) {}
+67
View File
@@ -0,0 +1,67 @@
//go:build windows
package app
import (
"slices"
"strings"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/tray"
)
func (a *App) confirmVMWindowClose(name string) {
if _, pending := a.vmClosePrompts.LoadOrStore(name, struct{}{}); pending {
return
}
defer a.vmClosePrompts.Delete(name)
ctx := a.baseCtx()
pid := a.cachedVMPID(name)
owner := host.ProcessDisplayWindow(uint32(pid))
if owner == 0 {
pid = a.findRunningVMPID(ctx, name)
owner = host.ProcessDisplayWindow(uint32(pid))
}
if owner == 0 {
a.emitLog(name, "Could not locate the VM display window for close confirmation")
return
}
a.mu.Lock()
loc := i18n.EffectiveLocale(a.cfg.Locale)
theme := a.themeMode
a.mu.Unlock()
ref := driver.NewVMRef("", name)
canSuspend := false
if vm, err := a.resolveVMInfo("", name); err == nil {
ref = vm.Ref()
canSuspend = slices.Contains(vm.Capabilities, driver.CapSuspend)
}
label := strings.TrimSpace(a.GetVMNote(ref.Name))
if label == "" {
label = ref.Name
}
choice, err := host.ConfirmVMClose(ctx, owner, label, loc, theme, canSuspend)
if err != nil {
a.emitVMLogForDriver(ref.DriverID, ref.Name, err.Error())
return
}
if choice == host.VMCloseCancel {
return
}
vms, err := a.listVMsInternal(ctx)
if err != nil {
a.emitVMLogForDriver(ref.DriverID, ref.Name, err.Error())
return
}
if current, running := findRunningVMPID(vms, ref.Name); !running || current != uint32(pid) {
return
}
if choice == host.VMCloseSuspend {
a.trayVMAction(ref.DriverID, ref.Name, tray.ActSuspend)
} else {
a.trayVMAction(ref.DriverID, ref.Name, tray.ActStop)
}
}
+4
View File
@@ -41,6 +41,10 @@ func (a *App) onSecondInstance(data options.SecondInstanceData) {
// (double-click while running in the tray) brings the window forward. A
// `vm start` handed over from the command line leaves the window as it is.
func (a *App) handleWindowArgs(w cli.WindowArgs, secondLaunch bool) {
if w.CloseVM != "" {
go a.confirmVMWindowClose(w.CloseVM)
return
}
if w.StartVM == "" {
if secondLaunch && !w.Background {
a.ShowMainWindow()
+34 -1
View File
@@ -133,6 +133,9 @@ func printUsage(loc i18n.Locale) {
"cli.usage.cmd_vm_compact",
"cli.usage.cmd_vm_start",
"cli.usage.cmd_vm_stop",
"cli.usage.cmd_vm_suspend",
"cli.usage.cmd_vm_resume",
"cli.usage.cmd_vm_discard_suspend",
"cli.usage.cmd_vm_type",
"cli.usage.cmd_inst_list",
"cli.usage.cmd_inst_dl",
@@ -369,7 +372,7 @@ func cmdRuntime(cfg *config.Config, loc i18n.Locale, args []string) error {
func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) error {
if len(args) == 0 {
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|eject|type>")
return fmt.Errorf("usage: reims-go vm <list|create|set|start|stop|suspend|resume|discard-suspend|eject|type>")
}
ctx := context.Background()
@@ -502,6 +505,36 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e
return fmt.Errorf("usage: reims-go vm stop [--driver <id>] <name>")
}
return stopVM(ctx, cfg, *driverID, fs.Arg(0), false)
case "suspend":
fs := flag.NewFlagSet("vm suspend", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm suspend [--driver <id>] <name>")
}
return suspendVM(ctx, cfg, *driverID, fs.Arg(0))
case "resume":
fs := flag.NewFlagSet("vm resume", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm resume [--driver <id>] <name>")
}
return resumeVM(ctx, cfg, *driverID, fs.Arg(0))
case "discard-suspend":
fs := flag.NewFlagSet("vm discard-suspend", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
if err := fs.Parse(args[1:]); err != nil {
return err
}
if fs.NArg() < 1 {
return fmt.Errorf("usage: reims-go vm discard-suspend [--driver <id>] <name>")
}
return discardSuspendVM(ctx, cfg, *driverID, fs.Arg(0))
case "delete":
fs := flag.NewFlagSet("vm delete", flag.ContinueOnError)
driverID := fs.String("driver", "", "Owning driver ID when VM names are ambiguous")
+3 -1
View File
@@ -9,6 +9,8 @@ const windowHandoffWorks = false
func findWindow() uintptr { return 0 }
func sendToWindow(uintptr, []string) error { return errors.ErrUnsupported }
func ForwardVMClose(string) bool { return false }
func sendToWindow(uintptr, []string, uint32) error { return errors.ErrUnsupported }
func spawnWindow([]string) error { return errors.ErrUnsupported }
+32 -4
View File
@@ -23,15 +23,19 @@ import (
const (
wmCopyData = 0x004A
wailsCopyDataID = 1542
smtoAbortIfHung = 0x0002
hwndMessage = ^uintptr(2) // HWND_MESSAGE, (HWND)-3
detachedProcess = 0x00000008
windowHandoffWorks = true
)
var (
user32 = syscall.NewLazyDLL("user32.dll")
procFindWindowExW = user32.NewProc("FindWindowExW")
procSendMessageW = user32.NewProc("SendMessageW")
user32 = syscall.NewLazyDLL("user32.dll")
procFindWindowExW = user32.NewProc("FindWindowExW")
procSendMessageW = user32.NewProc("SendMessageW")
procSendMessageTimeoutW = user32.NewProc("SendMessageTimeoutW")
procGetWindowPID = user32.NewProc("GetWindowThreadProcessId")
procAllowSetForeground = user32.NewProc("AllowSetForegroundWindow")
)
type copyDataStruct struct {
@@ -55,9 +59,23 @@ func findWindow() uintptr {
return h
}
// ForwardVMClose delegates both the request and the foreground permission
// inherited from the VM window that launched this helper.
func ForwardVMClose(name string) bool {
hwnd := findWindow()
if hwnd == 0 {
return false
}
var pid uint32
if tid, _, _ := procGetWindowPID.Call(hwnd, uintptr(unsafe.Pointer(&pid))); tid != 0 {
procAllowSetForeground.Call(uintptr(pid))
}
return sendToWindow(hwnd, WindowArgs{CloseVM: name}.Args(), 500) == nil
}
// sendToWindow delivers args to the running window as if a second
// `reims-go.exe <args>` had been launched.
func sendToWindow(hwnd uintptr, args []string) error {
func sendToWindow(hwnd uintptr, args []string, timeoutMS uint32) error {
wd, _ := os.Getwd()
payload, err := json.Marshal(options.SecondInstanceData{Args: args, WorkingDirectory: wd})
if err != nil {
@@ -72,6 +90,16 @@ func sendToWindow(hwnd uintptr, args []string) error {
cbData: uint32(len(buf) * 2),
lpData: uintptr(unsafe.Pointer(&buf[0])),
}
if timeoutMS != 0 {
var result uintptr
sent, _, _ := procSendMessageTimeoutW.Call(hwnd, wmCopyData, 0,
uintptr(unsafe.Pointer(&cds)), smtoAbortIfHung, uintptr(timeoutMS), uintptr(unsafe.Pointer(&result)))
runtime.KeepAlive(buf)
if sent == 0 {
return errors.New("desktop window did not respond")
}
return nil
}
procSendMessageW.Call(hwnd, wmCopyData, 0, uintptr(unsafe.Pointer(&cds)))
runtime.KeepAlive(buf)
return nil
+1 -1
View File
@@ -115,7 +115,7 @@ func startInWindow(ctx context.Context, cfg *config.Config, driverID, name strin
w := WindowArgs{StartVM: name, StartDriver: driverID, StartResult: result}
if hwnd := findWindow(); hwnd != 0 {
fmt.Fprintln(os.Stderr, i18n.M(cfg.Locale, "cli.start.handing_to_window", i18n.Vars{"name": name}))
if err := sendToWindow(hwnd, w.Args()); err != nil {
if err := sendToWindow(hwnd, w.Args(), 0); err != nil {
return err
}
} else {
+84
View File
@@ -0,0 +1,84 @@
package cli
import (
"context"
"fmt"
"os"
"time"
"github.com/Nwflower/reims-go/internal/config"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/lifecycle"
"github.com/Nwflower/reims-go/internal/vmstart"
)
func suspendVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
svc := lifecycle.New(mgr.Registry(), router, nil)
_, vm, err := svc.Resolve(ctx, driverID, name)
if err != nil {
return err
}
fmt.Fprintf(os.Stderr, "Suspending %s...\n", vm.Name)
res, err := svc.Suspend(ctx, vm.Ref(), nil, os.Stdout, os.Stderr)
if err != nil {
return err
}
fmt.Printf("Suspended %s (%.2f GiB saved)\n", vm.Name, float64(res.VMStateSize)/float64(1<<30))
return nil
}
func resumeVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
svc := lifecycle.New(mgr.Registry(), router, nil)
_, vm, err := svc.Resolve(ctx, driverID, name)
if err != nil {
return err
}
ref := vm.Ref()
fmt.Fprintf(os.Stderr, "Resuming %s...\n", ref.Name)
startAt := time.Now()
if _, err := svc.Resume(ctx, ref, nil, os.Stdout, os.Stderr); err != nil {
return err
}
rep := host.Inspect(cfg.DataRoot)
if list, err := svc.List(ctx); err == nil {
for _, item := range list {
if item.Ref() != ref || item.State != "running" || item.PID == nil || *item.PID <= 0 {
continue
}
vmDir := item.Directory
if vmDir == "" {
vmDir = vm.Directory
}
if line, _ := vmstart.ApplyVMAffinity(cfg.Locale, rep, vmDir, cfg.AutoPinPCores, *item.PID, vm.CPUs, false); line != "" {
fmt.Fprintln(os.Stderr, line)
}
}
}
fmt.Printf("Resumed %s in %.1fs\n", ref.Name, time.Since(startAt).Seconds())
return nil
}
func discardSuspendVM(ctx context.Context, cfg *config.Config, driverID, name string) error {
mgr, router, err := openCLIPluginManager(cfg, false)
if err != nil {
return err
}
defer mgr.Close()
svc := lifecycle.New(mgr.Registry(), router, nil)
if err := svc.DiscardSuspend(ctx, driver.VMRef{DriverID: driverID, Name: name}); err != nil {
return err
}
fmt.Printf("Discarded suspend state for %s\n", name)
return nil
}
+11
View File
@@ -15,6 +15,7 @@ const (
flagStartVM = "--start-vm="
flagStartDriver = "--start-driver="
flagStartResult = "--start-result="
flagCloseVM = "--close-vm="
flagWaitPID = "--wait-pid="
)
@@ -33,6 +34,8 @@ type WindowArgs struct {
// StartResult is a file the window writes a StartResult to once StartVM
// has returned, so the command that asked can report it.
StartResult string
// CloseVM asks the running client to show a confirmation over the VM display.
CloseVM string
// WaitPID is a Reims-Go process that is quitting after installing an
// update: the new window waits for it to exit before taking the
// single-instance lock, which it would otherwise hand straight back to it.
@@ -55,6 +58,11 @@ func ParseWindowArgs(args []string) (w WindowArgs, ok bool) {
w.StartDriver = strings.TrimPrefix(a, flagStartDriver)
case strings.HasPrefix(a, flagStartResult):
w.StartResult = strings.TrimPrefix(a, flagStartResult)
case strings.HasPrefix(a, flagCloseVM):
w.CloseVM = strings.TrimPrefix(a, flagCloseVM)
if w.CloseVM == "" {
return WindowArgs{}, false
}
case strings.HasPrefix(a, flagWaitPID):
pid, err := strconv.ParseUint(strings.TrimPrefix(a, flagWaitPID), 10, 32)
if err != nil || pid == 0 {
@@ -86,6 +94,9 @@ func (w WindowArgs) Args() []string {
if w.StartResult != "" {
out = append(out, flagStartResult+w.StartResult)
}
if w.CloseVM != "" {
out = append(out, flagCloseVM+w.CloseVM)
}
if w.WaitPID != 0 {
out = append(out, flagWaitPID+strconv.FormatUint(uint64(w.WaitPID), 10))
}
+9
View File
@@ -24,6 +24,8 @@ func TestParseWindowArgs(t *testing.T) {
{[]string{"--background", "vm", "list"}, WindowArgs{}, false},
{[]string{"--help"}, WindowArgs{}, false},
{[]string{"--start-vm", "m0"}, WindowArgs{}, false}, // value must be joined with =
{[]string{"--close-vm=mac os"}, WindowArgs{CloseVM: "mac os"}, true},
{[]string{"--close-vm="}, WindowArgs{}, false},
{[]string{"--wait-pid=4242"}, WindowArgs{WaitPID: 4242}, true},
{[]string{"--background", "--wait-pid=7"}, WindowArgs{Background: true, WaitPID: 7}, true},
{[]string{"--wait-pid=0"}, WindowArgs{}, false},
@@ -40,6 +42,13 @@ func TestParseWindowArgs(t *testing.T) {
}
}
func TestCloseWindowArgsRoundTrip(t *testing.T) {
want := WindowArgs{CloseVM: "macOS Test"}
if got, ok := ParseWindowArgs(want.Args()); !ok || got != want {
t.Fatalf("close request round trip = %+v, %v", got, ok)
}
}
func TestWindowArgsRoundTrip(t *testing.T) {
w := WindowArgs{Background: true, StartVM: "mac os", StartDriver: "test.driver.linux", StartResult: `D:\Data\tmp\cli-start-9.json`, WaitPID: 31337}
got, ok := ParseWindowArgs(w.Args())
+16
View File
@@ -6,6 +6,7 @@ import (
"os"
"path/filepath"
"runtime"
"strings"
"github.com/Nwflower/reims-go/internal/i18n"
)
@@ -53,6 +54,21 @@ func DefaultDataRoot() string {
return filepath.Join(home, "reims-go-data")
}
// ExpandHomePath resolves a leading ~ for the current user.
func ExpandHomePath(path string) string {
if path != "~" && !strings.HasPrefix(path, "~/") && !strings.HasPrefix(path, `~\`) {
return path
}
home, err := os.UserHomeDir()
if err != nil {
return path
}
if path == "~" {
return home
}
return filepath.Join(home, path[2:])
}
// CurrentDataRoot is the data folder in effect: REIMS_GO_DATA_ROOT, else the
// folder chosen at first launch (LocationPath), else DefaultDataRoot.
func CurrentDataRoot() string {
+40
View File
@@ -37,6 +37,7 @@ const (
CapRecovery = "recovery"
CapCloudInit = "cloud_init"
CapUEFIISO = "uefi_iso"
CapSuspend = "suspend"
)
// ValidationIssue reports a field-level validation error before Create/Set.
@@ -155,6 +156,45 @@ type LogDriver interface {
ReadLogs(context.Context, string, bool) (string, error)
}
// SuspendProgress reports incremental progress while saving VM execution state.
type SuspendProgress struct {
Status string
Transferred int64
Remaining int64
Total int64
}
// SuspendRequest carries a VM reference, optional progress callback, and log sinks.
type SuspendRequest struct {
Ref VMRef
Progress func(SuspendProgress)
Stdout io.Writer
Stderr io.Writer
}
// SuspendResult describes the saved suspend snapshot produced by Suspend.
type SuspendResult struct {
VMStateSize int64
SavedAt string
}
// ResumeRequest carries a VM reference, host-side process environment overrides,
// and log sinks for restoring a suspended VM.
type ResumeRequest struct {
Ref VMRef
ExtraEnv []string
Stdout io.Writer
Stderr io.Writer
}
// SuspendDriver is an optional interface for drivers that support saving and
// restoring live VM execution state across host restarts.
type SuspendDriver interface {
Suspend(ctx context.Context, req SuspendRequest) (SuspendResult, error)
Resume(ctx context.Context, req ResumeRequest) (StartResult, error)
DiscardSuspend(ctx context.Context, name string) error
}
// RenamedDriverIDs maps a driver ID that VM owner markers may still carry
// to the ID that now provides that driver, for when a driver moves to
// another plugin (e.g. the built-in macOS driver becoming a market plugin,
+294
View File
@@ -0,0 +1,294 @@
package guesttools
import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"testing"
)
func TestGuestAgentClipboardScript(t *testing.T) {
sh, err := exec.LookPath("sh")
if err != nil {
sh = "C:/Program Files/Git/bin/sh.exe"
if _, err := os.Stat(sh); err != nil {
t.Skip("POSIX sh is unavailable")
}
}
agent := string(GuestAgentScript())
start := strings.Index(agent, "read_local_clipboard() {")
end := strings.Index(agent, "sync_files() {")
if start < 0 || end <= start {
t.Fatal("missing generated clipboard code")
}
if !regexp.MustCompile(`agent_version\\":([6-9]|[1-9][0-9]+)\}`).MatchString(agent) {
t.Fatal("clipboard sync requires agent version 6 or newer")
}
if !strings.Contains(agent[start:end], `-H "Content-Type: $ct" ${1+"$@"}`) {
t.Fatal("POST must guard empty positional arguments under Bash 3.2 set -u")
}
for _, name := range []string{
"failed_png", "failed_text", "reencoded_png", "guest_changes_during_get",
"conflict", "conflict_skipped_host", "oversized", "disabled_upload", "post_error",
"guest_only_after_switch", "cold_guest_only", "cold_304", "empty_text_and_png_fallback",
} {
t.Run(name, func(t *testing.T) {
tmp := t.TempDir()
script := filepath.Join(tmp, "clipboard-test.sh")
code := "set -eu\n" + agent[start:end] + clipboardShellFixture
if err := os.WriteFile(script, []byte(code), 0o600); err != nil {
t.Fatal(err)
}
cmd := exec.Command(sh, script, name)
cmd.Dir = tmp
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("clipboard script: %v\n%s", err, out)
}
})
}
}
const clipboardShellFixture = `
PATH="/usr/bin:/bin:$PATH"
TMP_DIR=.
INJECT_LOCK=./injecting
REIMS_HOST_URL=http://stub
REIMS_TOKEN=token
printf A > local_value
: > calls
local_info="Unicode text"
flags=""
get_code=200
get_hash=B
get_seq=8
get_kind=text
get_value=B
post_code=200
post_hash=C
post_seq=9
check_post_base=0
hash_file() { cat "$1"; }
hash_png_file() { printf 'png:'; cat "$1"; }
pbpaste() { cat local_value; }
pbcopy() {
[ "$flags" != fail ] || return 1
cat > local_value
}
osascript() {
case "$2" in
'clipboard info')
if [ -f reencoded ]; then
printf 'PNGf\n'
else
printf '%s\n' "$local_info"
fi
;;
'set fp to open for access'*)
case "$6" in
*PNGf*)
[ -f reencoded ] || return 1
cat local_value > ./clip_in
;;
*TIFF*) printf 'tiff' > ./clip_in.tiff ;;
esac
;;
'set the clipboard'*)
[ "$flags" != fail ] || return 1
printf 'B-reencoded' > local_value
: > reencoded
;;
esac
}
sips() { printf 'tiff-converted' > "$6"; }
curl() {
method=GET
headers=""
output=""
base=""
body=""
url=""
while [ "$#" -gt 0 ]; do
case "$1" in
-X) method="$2"; shift ;;
-D) headers="$2"; shift ;;
-o) output="$2"; shift ;;
--data-binary) body="${2#@}"; shift ;;
-H)
case "$2" in
'X-Clip-Base-Seq: '*) base="$2" ;;
esac
shift
;;
http://*) url="$1" ;;
esac
shift
done
if [ "$method" = POST ]; then
printf '%s %s\n' "$method" "$base" >> calls
if [ "$check_post_base" = 1 ] && [ "$get_code" != 204 ] && [ "$base" != "X-Clip-Base-Seq: $get_seq" ]; then
printf 'X-Clip-Seq: %s\r\n' "$get_seq" > "$headers"
printf '409'
return
fi
if [ "$post_code" = 200 ]; then
cat "$body" > host_value
fi
printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\n' "$post_hash" "$post_seq" > "$headers"
printf '%s' "$post_code"
else
printf '%s %s\n' "$method" "$url" >> calls
printf 'X-Clip-Hash: %s\r\nX-Clip-Seq: %s\r\nX-Clip-Kind: %s\r\n' "$get_hash" "$get_seq" "$get_kind" > "$headers"
printf '%s' "$get_value" > "$output"
if [ "$flags" = guest_change ]; then
printf C > local_value
fi
printf '%s' "$get_code"
fi
}
expect() {
if [ "$1" != "$2" ]; then
printf 'expected <%s>, got <%s>\n' "$2" "$1" >&2
cat calls >&2
exit 1
fi
}
methods() { awk '{print $1}' calls | paste -sd ',' -; }
case "$1" in
failed_png|failed_text)
[ "$1" != failed_png ] || get_kind=png
last_local_hash=A
last_server_hash=A
last_server_seq=7
flags=fail
sync_clipboard
sync_clipboard
expect "$(methods)" GET,GET
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/A/7/A
;;
reencoded_png)
get_kind=png
get_hash=png:B
sync_clipboard
expect "$last_local_hash/$last_server_hash/$last_server_seq" png:B-reencoded/png:B/8
get_code=304
sync_clipboard
expect "$(methods)" GET,GET
grep -F 'since=png:B&' calls
;;
guest_changes_during_get)
last_local_hash=A
last_server_hash=A
last_server_seq=7
flags=guest_change
check_post_base=1
sync_clipboard
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/A/8/C
flags=""
sync_clipboard
expect "$(methods)" GET,POST
grep -Fx 'POST X-Clip-Base-Seq: 8' calls
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)/$(cat host_value)" C/C/9/C/C
;;
conflict|conflict_skipped_host|oversized|disabled_upload|post_error)
last_local_hash=old
last_server_hash=old-remote
last_server_seq=7
case "$1" in
conflict) post_code=409 ;;
conflict_skipped_host)
get_code=304
get_hash=""
check_post_base=1
printf host-image > host_value
;;
oversized) post_code=413 ;;
disabled_upload) post_code=204; get_code=304; get_hash=old-remote; get_seq=7 ;;
post_error) post_code=500 ;;
esac
sync_clipboard
expect "$(methods)" POST,GET
grep -Fx 'POST X-Clip-Base-Seq: 7' calls
grep -F 'since=old-remote&' calls
case "$1" in
conflict_skipped_host)
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/old-remote/8/A
sync_clipboard
expect "$(methods)" POST,GET,GET
expect "$(cat host_value)" host-image
printf C > local_value
sync_clipboard
expect "$(methods)" POST,GET,GET,POST
grep -Fx 'POST X-Clip-Base-Seq: 8' calls
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat host_value)" C/C/9/C
;;
disabled_upload)
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" A/old-remote/7/A
;;
*)
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat local_value)" B/B/8/B
;;
esac
if [ "$1" = oversized ]; then
get_code=304
sync_clipboard
expect "$(methods)" POST,GET,GET
fi
;;
guest_only_after_switch)
sync_clipboard
expect "$last_local_hash/$last_server_hash/$last_server_seq" B/B/8
check_post_base=1
get_code=204
get_seq=9
post_seq=10
printf 'new host' > host_value
printf C > local_value
sync_clipboard
expect "$(methods)" GET,POST
grep -Fx 'POST X-Clip-Base-Seq: 8' calls
expect "$(cat host_value)" C
sync_clipboard
expect "$(methods)" GET,POST,GET
expect "$last_local_hash/$last_server_hash/$last_server_seq" C/C/
;;
cold_guest_only|cold_304)
get_code=204
expected_base="POST "
if [ "$1" = cold_304 ]; then
get_code=304
get_hash=""
expected_base="POST X-Clip-Base-Seq: 8"
fi
sync_clipboard
expect "$last_local_hash/$last_server_hash" A/
printf C > local_value
sync_clipboard
expect "$(methods)" GET,POST
grep -Fx "$expected_base" calls
expect "$last_local_hash/$last_server_hash/$last_server_seq" C/C/9
if [ "$1" = cold_guest_only ]; then
check_post_base=1
get_seq=10
post_seq=11
post_hash=D
printf 'new host' > host_value
printf D > local_value
sync_clipboard
expect "$(methods)" GET,POST,POST
grep -Fx 'POST X-Clip-Base-Seq: 9' calls
expect "$last_local_hash/$last_server_hash/$last_server_seq/$(cat host_value)" D/D/11/D
fi
;;
empty_text_and_png_fallback)
local_info="Unicode text, PNGf, TIFF"
: > local_value
expect "$(read_local_clipboard ./clip_in)" png
expect "$(cat ./clip_in)" tiff-converted
;;
esac
`
+22 -10
View File
@@ -27,27 +27,39 @@ func (c *OSClipboard) ReadText() (string, error) {
}
func (c *OSClipboard) WriteText(text string) error {
c.mu.Lock()
defer c.mu.Unlock()
c.kind = ClipText
c.data = []byte(text)
c.seq++
return nil
_, err := c.writeClipboard(ClipPayload{Kind: ClipText, Data: []byte(text)}, nil)
return err
}
func (c *OSClipboard) Read() (ClipPayload, error) {
payload, _, err := c.readClipboard(true)
return payload, err
}
func (c *OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) {
c.mu.Lock()
defer c.mu.Unlock()
if !wantImage && c.kind == ClipPNG {
return ClipPayload{Kind: ClipEmpty}, c.seq, nil
}
cp := make([]byte, len(c.data))
copy(cp, c.data)
return ClipPayload{Kind: c.kind, Data: cp}, nil
return ClipPayload{Kind: c.kind, Data: cp}, c.seq, nil
}
func (c *OSClipboard) WritePNG(pngBytes []byte) error {
_, err := c.writeClipboard(ClipPayload{Kind: ClipPNG, Data: pngBytes}, nil)
return err
}
func (c *OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (uint32, error) {
c.mu.Lock()
defer c.mu.Unlock()
c.kind = ClipPNG
c.data = append([]byte(nil), pngBytes...)
if baseSeq != nil && c.seq != *baseSeq {
return c.seq, errClipboardConflict
}
c.kind = payload.Kind
c.data = append([]byte(nil), payload.Data...)
c.seq++
return nil
return c.seq, nil
}
+348
View File
@@ -0,0 +1,348 @@
package guesttools
import (
"bytes"
"encoding/binary"
"errors"
"image/color"
"image/png"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
)
func TestTrimPNG(t *testing.T) {
valid := makeSamplePNG(t, 1, 2, 3)
badLength := bytes.Clone(valid)
binary.BigEndian.PutUint32(badLength[8:12], 0xffffffff)
for _, tc := range []struct {
name string
raw []byte
ok bool
}{
{"PNG", valid, true},
{"padding", append(bytes.Clone(valid), make([]byte, 16)...), true},
{"truncated", valid[:len(valid)-1], false},
{"missing IEND", valid[:len(valid)-12], false},
{"illegal chunk length", badLength, false},
{"non-PNG", []byte("not an image"), false},
} {
t.Run(tc.name, func(t *testing.T) {
got, ok := TrimPNG(tc.raw)
if ok != tc.ok || (ok && !bytes.Equal(got, valid)) || (!ok && got != nil) {
t.Fatalf("TrimPNG returned %d bytes, ok=%t", len(got), ok)
}
})
}
}
func TestDecodeDIBFormats(t *testing.T) {
le := binary.LittleEndian
for _, tc := range []struct {
name string
header int
depth uint16
masks []uint32
palette []byte
topDown bool
pixels []byte
want []color.NRGBA
}{
{"24-bit RGB bottom-up", 40, 24, nil, nil, false,
[]byte{0, 0, 255, 0, 0, 255, 0, 0},
[]color.NRGBA{{G: 255, A: 255}, {R: 255, A: 255}}},
{"32-bit RGB zero alpha and optional palette", 40, 32, nil, []byte{4, 9, 14, 0}, false,
[]byte{100, 20, 30, 0}, []color.NRGBA{{R: 30, G: 20, B: 100, A: 255}}},
{"32-bit RGB with alpha", 40, 32, nil, nil, false,
[]byte{100, 20, 30, 70}, []color.NRGBA{{R: 30, G: 20, B: 100, A: 70}}},
{"swapped red and blue with external masks", 40, 32, []uint32{0xff, 0xff00, 0xff0000}, nil, false,
[]byte{34, 56, 78, 12}, []color.NRGBA{{R: 34, G: 56, B: 78, A: 255}}},
{"V4 explicit zero alpha", 108, 32, []uint32{0xff, 0xff00, 0xff0000, 0xff000000}, nil, false,
[]byte{34, 56, 78, 0}, []color.NRGBA{{R: 34, G: 56, B: 78}}},
{"V5 explicit zero alpha", 124, 32, []uint32{0xff0000, 0xff00, 0xff, 0xff000000}, nil, false,
[]byte{34, 56, 78, 0}, []color.NRGBA{{R: 78, G: 56, B: 34}}},
{"16-bit RGB565 top-down", 40, 16, []uint32{0xf800, 0x07e0, 0x1f}, nil, true,
[]byte{0x00, 0xfc, 0, 0, 0x1f, 0, 0, 0},
[]color.NRGBA{{R: 255, G: 130, A: 255}, {B: 255, A: 255}}},
} {
t.Run(tc.name, func(t *testing.T) {
header := make([]byte, tc.header)
height := int32(len(tc.want))
if tc.topDown {
height = -height
}
le.PutUint32(header, uint32(tc.header))
le.PutUint32(header[4:], 1)
le.PutUint32(header[8:], uint32(height))
le.PutUint16(header[12:], 1)
le.PutUint16(header[14:], tc.depth)
le.PutUint32(header[32:], uint32(len(tc.palette)/4))
if len(tc.masks) > 0 {
le.PutUint32(header[16:], 3)
if tc.header == 40 {
header = append(header, make([]byte, len(tc.masks)*4)...)
}
for i, mask := range tc.masks {
le.PutUint32(header[40+4*i:], mask)
}
}
data, err := DecodeDIBToPNG(append(append(header, tc.palette...), tc.pixels...))
if err != nil {
t.Fatal(err)
}
img, err := png.Decode(bytes.NewReader(data))
if err != nil {
t.Fatal(err)
}
for y, want := range tc.want {
if got := color.NRGBAModel.Convert(img.At(0, y)); got != want {
t.Errorf("pixel y=%d: got %+v, want %+v", y, got, want)
}
}
})
}
}
func clipboardRequest(t *testing.T, srv *Server, method, query, contentType, baseSeq string, body []byte) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(method, "/v1/clipboard"+query, bytes.NewReader(body))
req.Header.Set("Authorization", "Bearer clipboard-test-token")
req.Header.Set("Content-Type", contentType)
req.Header.Set("X-Clip-Base-Seq", baseSeq)
resp := httptest.NewRecorder()
srv.handleClipboard(resp, req)
return resp
}
func newClipboardTestServer(clip Clipboard) *Server {
srv := NewServer(clip)
srv.RegisterVM(VMConfig{VMName: "clipboard-test", Token: "clipboard-test-token"})
return srv
}
func TestClipboardPOSTSequenceConflict(t *testing.T) {
oldPNG := makeSamplePNG(t, 255, 0, 0)
newPNG := makeSamplePNG(t, 0, 255, 0)
clip := &memClipboard{kind: ClipPNG, data: oldPNG, seq: 7}
srv := newClipboardTestServer(clip)
get := clipboardRequest(t, srv, http.MethodGet, "?accept=image", "", "", nil)
if get.Code != http.StatusOK || get.Header().Get("X-Clip-Seq") != "7" {
t.Fatalf("initial GET: %d %v", get.Code, get.Header())
}
if err := clip.WritePNG(newPNG); err != nil {
t.Fatal(err)
}
stale := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "7", oldPNG)
if stale.Code != http.StatusConflict || stale.Header().Get("X-Clip-Seq") != "8" {
t.Fatalf("stale POST: %d %v", stale.Code, stale.Header())
}
got, _ := clip.Read()
if got.Kind != ClipPNG || !bytes.Equal(got.Data, newPNG) {
t.Fatal("stale POST changed the new host image")
}
for _, tc := range []struct{ base, seq string }{{"8", "9"}, {"", "10"}} {
post := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", tc.base, []byte(tc.seq))
if post.Code != http.StatusOK || post.Header().Get("X-Clip-Seq") != tc.seq {
t.Fatalf("POST with base %q: %d %v", tc.base, post.Code, post.Header())
}
poll := clipboardRequest(t, srv, http.MethodGet, "?since="+post.Header().Get("X-Clip-Hash"), "", "", nil)
if poll.Code != http.StatusNotModified || poll.Header().Get("X-Clip-Seq") != tc.seq {
t.Fatalf("unchanged GET: %d %v", poll.Code, poll.Header())
}
}
}
func TestClipboardGuestToHostIgnoresStaleBase(t *testing.T) {
for _, name := range []string{"after switching from bidirectional", "guest to host from startup"} {
t.Run(name, func(t *testing.T) {
clip := &memClipboard{kind: ClipText, data: []byte("initial host"), seq: 7}
srv := newClipboardTestServer(clip)
policy := DefaultClipboardPolicy()
policy.Direction = ClipboardGuestToHost
if name == "guest to host from startup" {
srv.SetGlobalClipboardPolicy(policy)
}
initial := clipboardRequest(t, srv, http.MethodGet, "", "", "", nil)
wantBase := "7"
if name == "guest to host from startup" {
if initial.Code != http.StatusNoContent {
t.Fatalf("initial GET: %d", initial.Code)
}
initial = clipboardRequest(t, srv, http.MethodPost, "", "text/plain", "", []byte("first guest"))
wantBase = "8"
} else {
srv.SetGlobalClipboardPolicy(policy)
}
base := initial.Header().Get("X-Clip-Seq")
if initial.Code != http.StatusOK || base != wantBase {
t.Fatalf("initial sync: %d %v", initial.Code, initial.Header())
}
if err := clip.WriteText("new host"); err != nil {
t.Fatal(err)
}
post := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", base, []byte("new guest"))
if post.Code != http.StatusOK || post.Header().Get("X-Clip-Seq") != strconv.FormatUint(uint64(clip.SequenceNumber()), 10) {
t.Fatalf("POST after host copied: %d %v", post.Code, post.Header())
}
if got, _ := clip.ReadText(); got != "new guest" {
t.Fatalf("host clipboard: %q", got)
}
})
}
}
type clipboardReadFailure struct {
*memClipboard
writeBase *uint32
writeErr error
}
func (c *clipboardReadFailure) readClipboard(bool) (ClipPayload, uint32, error) {
return ClipPayload{}, 0, errors.New("OpenClipboard failed")
}
func (c *clipboardReadFailure) writeClipboard(payload ClipPayload, baseSeq *uint32) (uint32, error) {
c.writeBase = baseSeq
if c.writeErr != nil {
return c.SequenceNumber(), c.writeErr
}
err := c.WriteText(string(payload.Data))
return c.SequenceNumber(), err
}
func TestClipboardPOSTUsesAtomicWriteAfterReadFailure(t *testing.T) {
for _, tc := range []struct {
name string
writeErr error
wantStatus int
wantSeq string
wantErrors uint64
}{
{"write succeeds", nil, http.StatusOK, "8", 0},
{"write also fails", errors.New("OpenClipboard failed on write"), http.StatusInternalServerError, "", 1},
{"wrapped conflict", errors.Join(errClipboardConflict, errors.New("CloseClipboard failed")), http.StatusConflict, "7", 0},
} {
t.Run(tc.name, func(t *testing.T) {
clip := &clipboardReadFailure{memClipboard: &memClipboard{seq: 7}, writeErr: tc.writeErr}
srv := newClipboardTestServer(clip)
post := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", "7", []byte("guest"))
if post.Code != tc.wantStatus || post.Header().Get("X-Clip-Seq") != tc.wantSeq {
t.Fatalf("POST: got %d %v %q, want status %d and seq %q", post.Code, post.Header(), post.Body, tc.wantStatus, tc.wantSeq)
}
if clip.writeBase == nil || *clip.writeBase != 7 {
t.Fatalf("atomic write did not receive base 7")
}
if got := srv.ClipboardDiagnostics().ErrorCount; got != tc.wantErrors {
t.Fatalf("clipboard errors: got %d, want %d", got, tc.wantErrors)
}
})
}
}
type clipboardReadHook struct {
*memClipboard
once sync.Once
afterRead func()
}
func (c *clipboardReadHook) Read() (ClipPayload, error) {
payload, err := c.memClipboard.Read()
c.once.Do(c.afterRead)
return payload, err
}
func TestClipboardGETDoesNotLoseWakeup(t *testing.T) {
clip := &clipboardReadHook{memClipboard: &memClipboard{kind: ClipText, data: []byte("old"), seq: 1}}
srv := newClipboardTestServer(clip)
clip.afterRead = func() {
_ = clip.WriteText("new")
srv.NotifyClipboardChanged()
}
start := time.Now()
resp := clipboardRequest(t, srv, http.MethodGet, "?wait=5&since="+textHash("old"), "", "", nil)
if resp.Code != http.StatusOK || resp.Body.String() != "new" || resp.Header().Get("X-Clip-Seq") != "2" {
t.Fatalf("GET got %d %v %q", resp.Code, resp.Header(), resp.Body)
}
if elapsed := time.Since(start); elapsed >= 4*time.Second {
t.Fatalf("GET returned only after waiting %s", elapsed)
}
}
func TestClipboardGETRechecksPolicyAfterWake(t *testing.T) {
png := makeSamplePNG(t, 1, 2, 3)
payload := ClipPayload{Kind: ClipPNG, Data: png}
clip := &clipboardReadHook{memClipboard: &memClipboard{kind: payload.Kind, data: payload.Data}}
srv := newClipboardTestServer(clip)
clip.afterRead = func() {
policy := DefaultClipboardPolicy()
policy.Direction = ClipboardGuestToHost
srv.SetGlobalClipboardPolicy(policy)
_ = clip.WritePNG(makeSamplePNG(t, 4, 5, 6))
}
resp := clipboardRequest(t, srv, http.MethodGet, "?accept=image&wait=1&since="+payloadHash(payload), "", "", nil)
if resp.Code != http.StatusNoContent {
t.Fatalf("GET after switching direction: %d, body %q", resp.Code, resp.Body)
}
}
func TestClipboardGETSkipsUnavailablePayloads(t *testing.T) {
png := makeSamplePNG(t, 1, 2, 3)
for i, tc := range []struct {
name string
kind ClipKind
query string
syncImages bool
maxBytes int
}{
{"too large", ClipPNG, "?accept=image", true, len(png) - 1},
{"images disabled", ClipPNG, "?accept=image", false, len(png)},
{"legacy text request", ClipPNG, "", true, len(png)},
{"unsupported", ClipEmpty, "?accept=image", true, len(png)},
} {
t.Run(tc.name, func(t *testing.T) {
clip := &memClipboard{kind: tc.kind, seq: uint32(i)}
if tc.kind == ClipPNG {
clip.data = png
}
srv := newClipboardTestServer(clip)
policy := DefaultClipboardPolicy()
policy.SyncImages = tc.syncImages
policy.MaxImageBytes = tc.maxBytes
srv.SetGlobalClipboardPolicy(policy)
resp := clipboardRequest(t, srv, http.MethodGet, tc.query, "", "", nil)
if resp.Code != http.StatusNotModified || resp.Body.Len() != 0 || resp.Header().Get("X-Clip-Seq") != strconv.Itoa(i) {
t.Fatalf("skipped GET: %d %v, %d bytes", resp.Code, resp.Header(), resp.Body.Len())
}
_ = clip.WriteText("next item")
resp = clipboardRequest(t, srv, http.MethodGet, tc.query, "", "", nil)
if resp.Code != http.StatusOK || resp.Body.String() != "next item" {
t.Fatalf("subsequent GET: %d %q", resp.Code, resp.Body)
}
})
}
}
func TestClipboardPOSTTextLimitAndEmptyOverwrite(t *testing.T) {
png := makeSamplePNG(t, 1, 2, 3)
clip := &memClipboard{kind: ClipPNG, data: png}
srv := newClipboardTestServer(clip)
policy := DefaultClipboardPolicy()
policy.MaxImageBytes = 16
srv.SetGlobalClipboardPolicy(policy)
img := clipboardRequest(t, srv, http.MethodPost, "", "image/png", "", png)
if img.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized PNG POST: got %d", img.Code)
}
for _, value := range []string{"", strings.Repeat("文本", 100)} {
resp := clipboardRequest(t, srv, http.MethodPost, "", "text/plain", "", []byte(value))
got, _ := clip.Read()
if resp.Code != http.StatusOK || got.Kind != ClipText || string(got.Data) != value {
t.Fatalf("text POST (%d bytes): got status %d and payload %+v", len(value), resp.Code, got)
}
}
}
+334 -180
View File
@@ -3,7 +3,9 @@
package guesttools
import (
"errors"
"fmt"
"runtime"
"strings"
"sync"
"syscall"
@@ -14,6 +16,11 @@ import (
var (
user32 = syscall.NewLazyDLL("user32.dll")
procCreateWindowExW = user32.NewProc("CreateWindowExW")
procDestroyWindow = user32.NewProc("DestroyWindow")
procGetMessageW = user32.NewProc("GetMessageW")
procDispatchMessageW = user32.NewProc("DispatchMessageW")
procPostMessageW = user32.NewProc("PostMessageW")
procOpenClipboard = user32.NewProc("OpenClipboard")
procCloseClipboard = user32.NewProc("CloseClipboard")
procEmptyClipboard = user32.NewProc("EmptyClipboard")
@@ -33,26 +40,122 @@ var (
pngFormatOnce sync.Once
pngFormatID uintptr
pngFormatErr error
clipboardWorkerOnce sync.Once
clipOwnerHWND uintptr
clipboardJobs = make(chan func(uintptr))
clipboardWorkerDone = make(chan struct{})
clipboardWorkerErr error
)
const (
cfDIB = 8
cfUnicodeText = 13
gmemMoveable = 0x0002
hwndMessage = ^uintptr(2)
wmClipJob = 0x8000 // WM_APP
maxDIBBytes = 128 << 20
)
type OSClipboard struct{}
func registerPNGFormat() uintptr {
pngFormatOnce.Do(func() {
p, err := syscall.UTF16PtrFromString("PNG")
if err != nil {
type clipboardWindowMessage struct {
hwnd uintptr
message uint32
wParam uintptr
lParam uintptr
time uint32
x, y int32
lPrivate uint32
}
func runClipboardWorker(ready chan<- struct{}) {
runtime.LockOSThread()
defer close(clipboardWorkerDone)
class := [...]uint16{'S', 'T', 'A', 'T', 'I', 'C', 0}
hwnd, _, err := procCreateWindowExW.Call(0, uintptr(unsafe.Pointer(&class[0])), 0, 0,
0, 0, 0, 0, hwndMessage, 0, 0, 0)
clipOwnerHWND = hwnd
close(ready)
if hwnd == 0 {
clipboardWorkerErr = fmt.Errorf("CreateWindowExW: %w", err)
return
}
defer procDestroyWindow.Call(hwnd)
// Keep dispatching messages such as WM_DESTROYCLIPBOARD while idle.
for {
var msg clipboardWindowMessage
result, _, err := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
switch int32(result) {
case -1:
clipboardWorkerErr = fmt.Errorf("GetMessageW: %w", err)
return
case 0:
clipboardWorkerErr = errors.New("clipboard worker window quit")
return
}
id, _, _ := procRegisterClipboardFormatW.Call(uintptr(unsafe.Pointer(p)))
pngFormatID = id
if msg.hwnd == hwnd && msg.message == wmClipJob {
job := <-clipboardJobs
job(hwnd)
} else {
procDispatchMessageW.Call(uintptr(unsafe.Pointer(&msg)))
}
}
}
func onClipboardThread(job func(uintptr) error) error {
clipboardWorkerOnce.Do(func() {
ready := make(chan struct{})
go runClipboardWorker(ready)
<-ready
})
return pngFormatID
if clipOwnerHWND == 0 {
<-clipboardWorkerDone
return clipboardWorkerErr
}
if ok, _, err := procPostMessageW.Call(clipOwnerHWND, wmClipJob, 0, 0); ok == 0 {
return fmt.Errorf("PostMessageW: %w", err)
}
result := make(chan error, 1)
select {
case clipboardJobs <- func(hwnd uintptr) { result <- job(hwnd) }:
return <-result
case <-clipboardWorkerDone:
return clipboardWorkerErr
}
}
func withOpenClipboard(hwnd uintptr, job func() error) (err error) {
for attempt := 0; ; attempt++ {
ok, _, openErr := procOpenClipboard.Call(hwnd)
if ok != 0 {
break
}
if attempt == 4 {
return fmt.Errorf("OpenClipboard: %w", openErr)
}
time.Sleep(15 * time.Millisecond)
}
defer func() {
if ok, _, closeErr := procCloseClipboard.Call(); ok == 0 {
err = errors.Join(err, fmt.Errorf("CloseClipboard: %w", closeErr))
}
}()
return job()
}
func registerPNGFormat() (uintptr, error) {
pngFormatOnce.Do(func() {
name := [...]uint16{'P', 'N', 'G', 0}
id, _, err := procRegisterClipboardFormatW.Call(uintptr(unsafe.Pointer(&name[0])))
pngFormatID = id
if id == 0 {
pngFormatErr = fmt.Errorf("RegisterClipboardFormatW: %w", err)
}
})
return pngFormatID, pngFormatErr
}
func (OSClipboard) SequenceNumber() uint32 {
@@ -60,213 +163,264 @@ func (OSClipboard) SequenceNumber() uint32 {
return uint32(r)
}
func openClipboardWithRetry() error {
var lastErr error
for i := 0; i < 5; i++ {
r, _, err := procOpenClipboard.Call(0)
if r != 0 {
return nil
}
lastErr = err
time.Sleep(15 * time.Millisecond)
func unlockClipboardMem(h uintptr) error {
// A zero return with no error means the last lock was released.
if ok, _, err := procGlobalUnlock.Call(h); ok == 0 && err != syscall.Errno(0) {
return fmt.Errorf("GlobalUnlock: %w", err)
}
return fmt.Errorf("OpenClipboard: %w", lastErr)
return nil
}
func readClipboardRawLocked(format uintptr, maxBytes int) ([]byte, error) {
h, _, err := procGetClipboardData.Call(format)
func readClipboardImageLocked(format uintptr, maxBytes int) ([]byte, error) {
h, _, _ := procGetClipboardData.Call(format)
if h == 0 {
return nil, fmt.Errorf("GetClipboardData(%d): %w", format, err)
}
sz, _, _ := procGlobalSize.Call(h)
if sz == 0 {
return nil, nil
}
if int(sz) > maxBytes {
return nil, fmt.Errorf("clipboard data (%d bytes) exceeds limit", sz)
size, _, _ := procGlobalSize.Call(h)
if size == 0 || size > uintptr(maxBytes) {
return nil, nil
}
ptr, _, _ := procGlobalLock.Call(h)
if ptr == 0 {
return nil, nil
}
buf := make([]byte, int(size))
procRtlMoveMem.Call(uintptr(unsafe.Pointer(&buf[0])), ptr, size)
return buf, unlockClipboardMem(h)
}
func readUnicodeTextLocked() ([]uint16, error) {
h, _, err := procGetClipboardData.Call(cfUnicodeText)
if h == 0 {
return nil, fmt.Errorf("GetClipboardData: %w", err)
}
size, _, _ := procGlobalSize.Call(h)
if size < 2 {
return nil, nil
}
ptr, _, err := procGlobalLock.Call(h)
if ptr == 0 {
return nil, fmt.Errorf("GlobalLock: %w", err)
}
defer procGlobalUnlock.Call(h)
buf := make([]byte, int(sz))
procRtlMoveMem.Call(uintptr(unsafe.Pointer(&buf[0])), ptr, sz)
return buf, nil
// UTF-16 CRLF takes up to four bytes per normalized UTF-8 byte.
words := make([]uint16, min(size/2, MaxClipboardBytes*2+1))
procRtlMoveMem.Call(uintptr(unsafe.Pointer(&words[0])), ptr, uintptr(len(words)*2))
return words, unlockClipboardMem(h)
}
func setClipboardRawLocked(format uintptr, data []byte) error {
if len(data) == 0 {
return nil
}
hMem, _, err := procGlobalAlloc.Call(gmemMoveable, uintptr(len(data)))
if hMem == 0 {
return fmt.Errorf("GlobalAlloc: %w", err)
}
ptr, _, err := procGlobalLock.Call(hMem)
if ptr == 0 {
procGlobalFree.Call(hMem)
return fmt.Errorf("GlobalLock: %w", err)
}
procRtlMoveMem.Call(ptr, uintptr(unsafe.Pointer(&data[0])), uintptr(len(data)))
procGlobalUnlock.Call(hMem)
if r, _, err := procSetClipboardData.Call(format, hMem); r == 0 {
procGlobalFree.Call(hMem)
return fmt.Errorf("SetClipboardData(%d): %w", format, err)
}
return nil
}
// ReadText reads UTF-8 text from the Windows clipboard, normalizing CRLF to LF
// for macOS guests. Returns ("", nil) when the clipboard has no text.
func (OSClipboard) ReadText() (string, error) {
avail, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText)
if avail == 0 {
return "", nil
}
if err := openClipboardWithRetry(); err != nil {
return "", err
}
defer procCloseClipboard.Call()
return readUnicodeTextLocked()
}
func readUnicodeTextLocked() (string, error) {
h, _, err := procGetClipboardData.Call(cfUnicodeText)
if h == 0 {
return "", fmt.Errorf("GetClipboardData: %w", err)
}
sz, _, _ := procGlobalSize.Call(h)
if sz < 2 {
return "", nil
}
ptr, _, err := procGlobalLock.Call(h)
if ptr == 0 {
return "", fmt.Errorf("GlobalLock: %w", err)
}
defer procGlobalUnlock.Call(h)
maxWords := int(sz / 2)
if maxWords > MaxClipboardBytes/2 {
maxWords = MaxClipboardBytes / 2
}
words := make([]uint16, maxWords)
procRtlMoveMem.Call(uintptr(unsafe.Pointer(&words[0])), ptr, uintptr(maxWords*2))
func decodeClipboardText(words []uint16) string {
n := 0
for n < len(words) && words[n] != 0 {
n++
}
s := string(utf16.Decode(words[:n]))
return strings.ReplaceAll(s, "\r\n", "\n"), nil
return strings.ReplaceAll(string(utf16.Decode(words[:n])), "\r\n", "\n")
}
// Read inspects the Windows clipboard and returns either UTF-8 text or a PNG image.
func (OSClipboard) Read() (ClipPayload, error) {
hasText, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText)
pngFmt := registerPNGFormat()
var hasPNG uintptr
if pngFmt != 0 {
hasPNG, _, _ = procIsClipboardFormatAvail.Call(pngFmt)
// ReadText reads UTF-8 text from the Windows clipboard, normalizing CRLF to LF.
func (OSClipboard) ReadText() (string, error) {
var words []uint16
err := onClipboardThread(func(hwnd uintptr) error {
return withOpenClipboard(hwnd, func() error {
if avail, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText); avail == 0 {
return nil
}
var err error
words, err = readUnicodeTextLocked()
return err
})
})
if err != nil {
return "", err
}
hasDIB, _, _ := procIsClipboardFormatAvail.Call(cfDIB)
if hasText == 0 && hasPNG == 0 && hasDIB == 0 {
return ClipPayload{Kind: ClipEmpty}, nil
}
if err := openClipboardWithRetry(); err != nil {
return ClipPayload{}, err
}
defer procCloseClipboard.Call()
if hasText != 0 {
text, err := readUnicodeTextLocked()
if err != nil {
return ClipPayload{}, err
}
return ClipPayload{Kind: ClipText, Data: []byte(text)}, nil
}
if hasPNG != 0 {
if raw, err := readClipboardRawLocked(pngFmt, MaxClipboardBytes); err == nil && IsPNG(raw) {
return ClipPayload{Kind: ClipPNG, Data: raw}, nil
}
}
if hasDIB != 0 {
raw, err := readClipboardRawLocked(cfDIB, MaxClipboardBytes*4)
if err != nil {
return ClipPayload{}, err
}
pngBytes, err := DecodeDIBToPNG(raw)
if err != nil {
return ClipPayload{}, err
}
if len(pngBytes) > MaxClipboardBytes {
return ClipPayload{}, fmt.Errorf("encoded PNG (%d bytes) exceeds clipboard limit", len(pngBytes))
}
return ClipPayload{Kind: ClipPNG, Data: pngBytes}, nil
}
return ClipPayload{Kind: ClipEmpty}, nil
return decodeClipboardText(words), nil
}
// WriteText writes UTF-8 text to the Windows clipboard as CF_UNICODETEXT
// (normalizing bare LF to CRLF for Windows apps).
func (OSClipboard) WriteText(text string) error {
if len(text) > MaxClipboardBytes {
return fmt.Errorf("clipboard payload exceeds %d bytes", MaxClipboardBytes)
}
norm := strings.ReplaceAll(strings.ReplaceAll(text, "\r\n", "\n"), "\n", "\r\n")
u16 := utf16.Encode([]rune(norm))
u16 = append(u16, 0)
byteLen := uintptr(len(u16) * 2)
type clipboardSnapshot struct {
text []uint16
png []byte
dib []byte
kind ClipKind
}
if err := openClipboardWithRetry(); err != nil {
return err
func (snap clipboardSnapshot) payload() ClipPayload {
if snap.kind == ClipText && len(snap.text) > 0 && snap.text[0] != 0 {
return ClipPayload{Kind: ClipText, Data: []byte(decodeClipboardText(snap.text))}
}
defer procCloseClipboard.Call()
if data, ok := TrimPNG(snap.png); ok {
return ClipPayload{Kind: ClipPNG, Data: data}
}
if len(snap.dib) > 0 {
if data, err := DecodeDIBToPNG(snap.dib); err == nil && len(data) <= MaxClipboardBytes {
return ClipPayload{Kind: ClipPNG, Data: data}
}
}
return ClipPayload{Kind: snap.kind}
}
if r, _, err := procEmptyClipboard.Call(); r == 0 {
return fmt.Errorf("EmptyClipboard: %w", err)
func (snap *clipboardSnapshot) readImagesLocked(wantImage bool, pngFormat uintptr, available func(uintptr) bool, readImage func(uintptr, int) ([]byte, error)) error {
if pngFormat != 0 && available(pngFormat) {
snap.kind = ClipEmpty
if !wantImage {
return nil
}
var err error
snap.png, err = readImage(pngFormat, MaxClipboardBytes)
if err != nil {
return err
}
}
hMem, _, err := procGlobalAlloc.Call(gmemMoveable, byteLen)
if hMem == 0 {
return fmt.Errorf("GlobalAlloc: %w", err)
}
ptr, _, err := procGlobalLock.Call(hMem)
if ptr == 0 {
procGlobalFree.Call(hMem)
return fmt.Errorf("GlobalLock: %w", err)
}
procRtlMoveMem.Call(ptr, uintptr(unsafe.Pointer(&u16[0])), byteLen)
procGlobalUnlock.Call(hMem)
if r, _, err := procSetClipboardData.Call(cfUnicodeText, hMem); r == 0 {
procGlobalFree.Call(hMem)
return fmt.Errorf("SetClipboardData: %w", err)
// Keep the DIB from this snapshot in case the PNG fails validation after close.
if available(cfDIB) {
snap.kind = ClipEmpty
if wantImage {
var err error
snap.dib, err = readImage(cfDIB, maxDIBBytes)
return err
}
}
return nil
}
// WritePNG writes a PNG image to the Windows clipboard in both native "PNG"
// and universal 32-bit CF_DIB formats.
func (OSClipboard) WritePNG(pngBytes []byte) error {
if len(pngBytes) == 0 || len(pngBytes) > MaxClipboardBytes {
return fmt.Errorf("clipboard PNG size %d out of bounds", len(pngBytes))
// Read inspects the Windows clipboard and returns either UTF-8 text or a PNG image.
func (c OSClipboard) Read() (ClipPayload, error) {
payload, _, err := c.readClipboard(true)
return payload, err
}
func (c OSClipboard) readClipboard(wantImage bool) (ClipPayload, uint32, error) {
pngFormat, _ := registerPNGFormat()
var snap clipboardSnapshot
var seq uint32
err := onClipboardThread(func(hwnd uintptr) error {
return withOpenClipboard(hwnd, func() error {
defer func() { seq = c.SequenceNumber() }()
if avail, _, _ := procIsClipboardFormatAvail.Call(cfUnicodeText); avail != 0 {
var err error
snap.text, err = readUnicodeTextLocked()
if err != nil {
return err
}
snap.kind = ClipText
if len(snap.text) > 0 && snap.text[0] != 0 {
return nil
}
}
return snap.readImagesLocked(wantImage, pngFormat, func(format uintptr) bool {
avail, _, _ := procIsClipboardFormatAvail.Call(format)
return avail != 0
}, readClipboardImageLocked)
})
})
if err != nil {
return ClipPayload{}, seq, err
}
return snap.payload(), seq, nil
}
type clipboardMem struct {
format uintptr
handle uintptr
}
func freeClipboardMem(h uintptr) error {
if result, _, err := procGlobalFree.Call(h); result != 0 {
return fmt.Errorf("GlobalFree: %w", err)
}
dib, err := EncodePNGToDIB(pngBytes)
if err != nil {
return err
return nil
}
func prepareClipboardMem(format, size uintptr, src unsafe.Pointer) (clipboardMem, error) {
h, _, err := procGlobalAlloc.Call(gmemMoveable, size)
if h == 0 {
return clipboardMem{}, fmt.Errorf("GlobalAlloc: %w", err)
}
ptr, _, err := procGlobalLock.Call(h)
if ptr == 0 {
return clipboardMem{}, errors.Join(fmt.Errorf("GlobalLock: %w", err), freeClipboardMem(h))
}
if err := openClipboardWithRetry(); err != nil {
return err
procRtlMoveMem.Call(ptr, uintptr(src), size)
if err := unlockClipboardMem(h); err != nil {
return clipboardMem{}, errors.Join(err, freeClipboardMem(h))
}
defer procCloseClipboard.Call()
return clipboardMem{format: format, handle: h}, nil
}
// WriteText writes UTF-8 text as CF_UNICODETEXT, with CRLF for Windows apps.
func (c OSClipboard) WriteText(text string) error {
_, err := c.writeClipboard(ClipPayload{Kind: ClipText, Data: []byte(text)}, nil)
return err
}
if r, _, err := procEmptyClipboard.Call(); r == 0 {
return fmt.Errorf("EmptyClipboard: %w", err)
// WritePNG writes an image in both native "PNG" and 32-bit CF_DIB formats.
func (c OSClipboard) WritePNG(pngBytes []byte) error {
_, err := c.writeClipboard(ClipPayload{Kind: ClipPNG, Data: pngBytes}, nil)
return err
}
func (c OSClipboard) writeClipboard(payload ClipPayload, baseSeq *uint32) (seq uint32, err error) {
var mem []clipboardMem
defer func() {
for _, item := range mem {
if item.handle != 0 {
if freeErr := freeClipboardMem(item.handle); freeErr != nil {
err = errors.Join(err, freeErr)
}
}
}
}()
if len(payload.Data) > MaxClipboardBytes {
return 0, fmt.Errorf("clipboard payload exceeds %d bytes", MaxClipboardBytes)
}
if pngFmt := registerPNGFormat(); pngFmt != 0 {
_ = setClipboardRawLocked(pngFmt, pngBytes)
if payload.Kind == ClipPNG {
dib, err := EncodePNGToDIB(payload.Data)
if err != nil {
return 0, err
}
format, err := registerPNGFormat()
if err != nil {
return 0, err
}
pngMem, err := prepareClipboardMem(format, uintptr(len(payload.Data)), unsafe.Pointer(&payload.Data[0]))
if err != nil {
return 0, err
}
mem = append(mem, pngMem)
dibMem, err := prepareClipboardMem(cfDIB, uintptr(len(dib)), unsafe.Pointer(&dib[0]))
if err != nil {
return 0, err
}
mem = append(mem, dibMem)
} else {
norm := strings.ReplaceAll(strings.ReplaceAll(string(payload.Data), "\r\n", "\n"), "\n", "\r\n")
words := append(utf16.Encode([]rune(norm)), 0)
textMem, err := prepareClipboardMem(cfUnicodeText, uintptr(len(words)*2), unsafe.Pointer(&words[0]))
if err != nil {
return 0, err
}
mem = append(mem, textMem)
}
return setClipboardRawLocked(cfDIB, dib)
err = onClipboardThread(func(hwnd uintptr) error {
return withOpenClipboard(hwnd, func() error {
seq = c.SequenceNumber()
if baseSeq != nil && seq != *baseSeq {
return errClipboardConflict
}
if ok, _, err := procEmptyClipboard.Call(); ok == 0 {
return fmt.Errorf("EmptyClipboard: %w", err)
}
var writeErr error
for i := range mem {
item := &mem[i]
if ok, _, err := procSetClipboardData.Call(item.format, item.handle); ok == 0 {
writeErr = errors.Join(writeErr, fmt.Errorf("SetClipboardData(%d): %w", item.format, err))
} else {
item.handle = 0 // The system now owns the handle.
}
}
seq = c.SequenceNumber()
return writeErr
})
})
return seq, err
}
@@ -0,0 +1,97 @@
//go:build windows
package guesttools
import (
"bytes"
"sync"
"testing"
"golang.org/x/sys/windows"
)
func TestClipboardWorkerUsesOneThreadAndWindow(t *testing.T) {
type owner struct {
thread uint32
hwnd uintptr
}
const jobs = 32
results := make(chan owner, jobs)
var wg sync.WaitGroup
for range jobs {
wg.Go(func() {
if err := onClipboardThread(func(hwnd uintptr) error {
results <- owner{windows.GetCurrentThreadId(), hwnd}
return nil
}); err != nil {
t.Errorf("clipboard worker: %v", err)
}
})
}
wg.Wait()
close(results)
want := <-results
if want.thread == 0 || want.hwnd == 0 {
t.Fatalf("expected a thread and owner window, got %+v", want)
}
for got := range results {
if got != want {
t.Errorf("clipboard job ran on %+v, want %+v", got, want)
}
}
}
func TestWindowsClipboardSnapshotFormats(t *testing.T) {
origPNG := makeSamplePNG(t, 1, 2, 3)
dib, err := EncodePNGToDIB(origPNG)
if err != nil {
t.Fatal(err)
}
dibPNG, err := DecodeDIBToPNG(dib)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
snap clipboardSnapshot
want ClipPayload
}{
{"text first", clipboardSnapshot{text: []uint16{'x', 0}, png: origPNG, kind: ClipText},
ClipPayload{Kind: ClipText, Data: []byte("x")}},
{"empty text does not hide PNG", clipboardSnapshot{text: []uint16{0}, png: append(bytes.Clone(origPNG), 0, 0)},
ClipPayload{Kind: ClipPNG, Data: origPNG}},
{"bad PNG falls back to DIB", clipboardSnapshot{png: origPNG[:len(origPNG)-2], dib: dib},
ClipPayload{Kind: ClipPNG, Data: dibPNG}},
{"empty text is representable", clipboardSnapshot{text: []uint16{0}, kind: ClipText},
ClipPayload{Kind: ClipText}},
{"unusable image is skipped", clipboardSnapshot{dib: []byte{1, 2}},
ClipPayload{Kind: ClipEmpty}},
} {
t.Run(tc.name, func(t *testing.T) {
got := tc.snap.payload()
if got.Kind != tc.want.Kind || !bytes.Equal(got.Data, tc.want.Data) {
t.Fatalf("got %s (%d bytes), want %s (%d bytes)", got.Kind, len(got.Data), tc.want.Kind, len(tc.want.Data))
}
})
}
}
func TestWindowsClipboardSnapshotSkipsDisabledImages(t *testing.T) {
const pngFormat = 0xc000
for _, format := range []uintptr{pngFormat, cfDIB} {
for _, snap := range []clipboardSnapshot{{}, {text: []uint16{0}, kind: ClipText}} {
err := snap.readImagesLocked(false, pngFormat, func(candidate uintptr) bool {
return candidate == format
}, func(uintptr, int) ([]byte, error) {
t.Fatalf("disabled image format %#x must not be copied for decoding", format)
return nil, nil
})
if err != nil {
t.Fatal(err)
}
if got := snap.payload(); got.Kind != ClipEmpty || len(got.Data) != 0 {
t.Fatalf("disabled image format %#x: got %+v, want ClipEmpty", format, got)
}
}
}
}
+74 -15
View File
@@ -9,6 +9,7 @@ import (
"image/color"
"image/draw"
"image/png"
"math/bits"
)
// pngMagic is the standard 8-byte PNG file signature.
@@ -21,6 +22,28 @@ func IsPNG(data []byte) bool {
return len(data) >= len(pngMagic) && bytes.Equal(data[:len(pngMagic)], pngMagic)
}
// TrimPNG returns the portion of raw through the end of its IEND chunk.
func TrimPNG(raw []byte) ([]byte, bool) {
if !IsPNG(raw) {
return nil, false
}
for off := len(pngMagic); len(raw)-off >= 12; {
chunk := raw[off:]
size := binary.BigEndian.Uint32(chunk[:4])
if size > 0x7fffffff || uint64(size) > uint64(len(chunk)-12) {
return nil, false
}
off += int(size) + 12
if string(chunk[4:8]) == "IEND" {
if size != 0 {
return nil, false
}
return raw[:off], true
}
}
return nil, false
}
// EncodeImageToDIB encodes an image into a standard 32-bit bottom-up Windows
// CF_DIB (BITMAPINFOHEADER + BGRA pixels) accepted by all Windows applications.
func EncodeImageToDIB(img image.Image) ([]byte, error) {
@@ -38,9 +61,9 @@ func EncodeImageToDIB(img image.Image) ([]byte, error) {
binary.LittleEndian.PutUint32(out[0:4], hdrSize)
binary.LittleEndian.PutUint32(out[4:8], uint32(w))
binary.LittleEndian.PutUint32(out[8:12], uint32(h)) // positive => bottom-up
binary.LittleEndian.PutUint16(out[12:14], 1) // planes
binary.LittleEndian.PutUint16(out[14:16], 32) // bpp
binary.LittleEndian.PutUint32(out[16:20], 0) // BI_RGB
binary.LittleEndian.PutUint16(out[12:14], 1) // planes
binary.LittleEndian.PutUint16(out[14:16], 32) // bpp
binary.LittleEndian.PutUint32(out[16:20], 0) // BI_RGB
binary.LittleEndian.PutUint32(out[20:24], uint32(pixelBytes))
for y := 0; y < h; y++ {
@@ -78,8 +101,7 @@ func EncodePNGToDIB(pngBytes []byte) ([]byte, error) {
return EncodeImageToDIB(img)
}
// DecodeDIBToPNG converts Windows CF_DIB bytes (24-bit or 32-bit BI_RGB / BI_BITFIELDS)
// into PNG bytes.
// DecodeDIBToPNG converts 24/32-bit BI_RGB or 16/32-bit BI_BITFIELDS to PNG.
func DecodeDIBToPNG(dib []byte) ([]byte, error) {
if len(dib) < 40 {
return nil, errors.New("CF_DIB too short")
@@ -107,28 +129,51 @@ func DecodeDIBToPNG(dib []byte) ([]byte, error) {
if comp != biRGB && comp != biBitfields {
return nil, fmt.Errorf("unsupported DIB compression %d", comp)
}
if bpp != 24 && bpp != 32 {
if bpp != 32 && !(comp == biRGB && bpp == 24) && !(comp == biBitfields && bpp == 16) {
return nil, fmt.Errorf("unsupported DIB bit depth %d", bpp)
}
pixelOffset := hdrSize
if comp == biBitfields && hdrSize == 40 {
// Standard BITMAPINFOHEADER + BI_BITFIELDS appends 3 DWORD color masks (12 bytes).
pixelOffset += 12
}
if clrUsed := int(binary.LittleEndian.Uint32(dib[32:36])); clrUsed > 0 && bpp <= 8 {
pixelOffset += clrUsed * 4
var masks [4]uint32
var shifts [4]int
var maxima [4]uint64
if comp == biBitfields {
switch {
case hdrSize == 40 && len(dib) >= 52:
pixelOffset += 12
case hdrSize >= 56:
masks[3] = binary.LittleEndian.Uint32(dib[52:56])
default:
return nil, errors.New("CF_DIB color masks truncated")
}
used := uint32(0)
for i := range masks {
if i < 3 {
masks[i] = binary.LittleEndian.Uint32(dib[40+i*4:])
} else if masks[i] == 0 {
continue
}
shifts[i] = bits.TrailingZeros32(masks[i])
field := masks[i] >> shifts[i]
if field == 0 || field&(field+1) != 0 || masks[i]&used != 0 || bits.Len32(masks[i]) > bpp {
return nil, errors.New("invalid CF_DIB color masks")
}
used |= masks[i]
maxima[i] = uint64(field)
}
}
tableBytes := uint64(binary.LittleEndian.Uint32(dib[32:36])) * 4
rowStride := ((w*bpp + 31) / 32) * 4
if pixelOffset+rowStride*h > len(dib) {
if uint64(pixelOffset)+tableBytes+uint64(rowStride)*uint64(h) > uint64(len(dib)) {
return nil, errors.New("CF_DIB pixel data truncated")
}
pixelOffset += int(tableBytes)
img := image.NewNRGBA(image.Rect(0, 0, w, h))
// Track whether any 32-bit pixel carries non-zero alpha; many Windows apps
// leave the 4th byte of BI_RGB 32-bit DIBs as 0 (opaque XRGB).
hasAlpha := false
if bpp == 32 {
if comp == biRGB && bpp == 32 {
for y := 0; y < h && !hasAlpha; y++ {
row := dib[pixelOffset+y*rowStride:]
for x := 0; x < w; x++ {
@@ -147,7 +192,21 @@ func DecodeDIBToPNG(dib []byte) ([]byte, error) {
}
row := dib[pixelOffset+srcY*rowStride:]
for x := 0; x < w; x++ {
if bpp == 32 {
if comp == biBitfields {
pixel := row[x*(bpp/8):]
value := uint32(binary.LittleEndian.Uint16(pixel))
if bpp == 32 {
value = binary.LittleEndian.Uint32(pixel)
}
channels := [4]uint8{0, 0, 0, 255}
for i, mask := range masks {
if mask != 0 {
level := uint64((value & mask) >> shifts[i])
channels[i] = uint8((level*255 + maxima[i]/2) / maxima[i])
}
}
img.SetNRGBA(x, y, color.NRGBA{R: channels[0], G: channels[1], B: channels[2], A: channels[3]})
} else if bpp == 32 {
off := x * 4
a := row[off+3]
if !hasAlpha {
+137
View File
@@ -0,0 +1,137 @@
package guesttools
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
func TestGuestAgentDriveMount(t *testing.T) {
shBin, err := exec.LookPath("sh")
if err != nil {
shBin = filepath.Join(os.Getenv("ProgramFiles"), "Git", "bin", "sh.exe")
if _, err := os.Stat(shBin); err != nil {
t.Skip("POSIX shell is unavailable")
}
}
dir := t.TempDir()
helper := `#!/usr/bin/perl
use strict;
use warnings;
die "Unexpected mount options" unless @ARGV == 9 && "@ARGV[0..5]" eq "-a 3 -S -o rdonly -v";
my ($drive) = $ARGV[6] =~ /^Windows ([A-Z])$/;
my ($url, $target) = @ARGV[7..8];
die "Unexpected WebDAV URL" unless $url eq "http://10.0.2.2:19847/dav/mac%20test/drives/$drive/";
die "Unexpected mount point" unless $target eq "$ENV{DRIVE_MOUNT_ROOT}/$drive";
open(my $auth, "<&=3") or die "Missing credential descriptor: $!";
seek($auth, 0, 0) or die "Credential descriptor is not seekable: $!";
binmode($auth);
local $/;
die "Invalid credential payload" unless <$auth> eq pack("Na5Na64NNN", 5, "reims", 64, "a" x 64, 0, 0, 0);
if ($drive eq "O" && -f $ENV{FAIL_O}) {
print STDERR "Authentication failed\n";
exit 22;
}
open(my $mounts, ">>", $ENV{MOUNT_STATE}) or die "Could not record mount: $!";
print $mounts "$url on $target (webdav, read-only)\n";
`
if err := os.WriteFile(filepath.Join(dir, "mount_webdav"), []byte(helper), 0o755); err != nil {
t.Fatal(err)
}
script := string(GuestAgentScript())
harness := `set -eu
PATH="$PWD:/usr/bin:/bin:$PATH"
command -v perl >/dev/null 2>&1 || exit 77
HOME="$PWD/home with spaces"
DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives"
TMP_DIR="$PWD/tmp"
MOUNT_STATE="$PWD/mounts"
FAIL_O="$PWD/fail-O"
export DRIVE_MOUNT_ROOT MOUNT_STATE FAIL_O
REIMS_HOST_URL="http://10.0.2.2:19847/"
REIMS_VM="mac test"
REIMS_TOKEN="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
mkdir -p "$DRIVE_MOUNT_ROOT" "$HOME/Desktop" "$TMP_DIR"
: >"$MOUNT_STATE"
: >"$FAIL_O"
mount() { cat "$MOUNT_STATE"; }
umount() {
[ ! -f "$PWD/busy-${1##*/}" ] || return 1
awk -v point="$1" 'index($0, " on " point " (webdav") == 0' "$MOUNT_STATE" >"$MOUNT_STATE.next"
mv "$MOUNT_STATE.next" "$MOUNT_STATE"
}
` + scriptSection(t, script, "urlencode() {", "\nhash_file() {") +
scriptSection(t, script, "\ndrive_mount_failures=", "\napply_host_config() {") + `
sync_drive_mounts '{"shared_drives":["F","O","P"]}'
sync_drive_mounts '{"shared_drives":["F","O","P"]}'
test "$(wc -l <"$MOUNT_STATE")" -eq 2
test "$(readlink "$HOME/Desktop/Windows F")" = "$DRIVE_MOUNT_ROOT/F"
test ! -L "$HOME/Desktop/Windows O"
rm "$FAIL_O"
sync_drive_mounts '{"shared_drives":["O","P"]}'
test "$(wc -l <"$MOUNT_STATE")" -eq 2
test "$(readlink "$HOME/Desktop/Windows O")" = "$DRIVE_MOUNT_ROOT/O"
test ! -e "$DRIVE_MOUNT_ROOT/F"
test ! -L "$HOME/Desktop/Windows F"
test -z "$(ls -A "$TMP_DIR")"
ln -s "$TMP_DIR" "$DRIVE_MOUNT_ROOT/F"
sync_drive_mounts '{"shared_drives":["F","O","P"]}'
sync_drive_mounts '{"shared_drives":["O","P"]}'
test -L "$DRIVE_MOUNT_ROOT/F"
test "$(wc -l <"$MOUNT_STATE")" -eq 2
: >"$PWD/busy-P"
sync_drive_mounts '{"shared_drives":["O"]}'
test -L "$HOME/Desktop/Windows P"
test "$(wc -l <"$MOUNT_STATE")" -eq 2
rm "$PWD/busy-P"
mkdir "$DRIVE_MOUNT_ROOT/Q"
printf '/dev/disk2 on %s (apfs, local)\n' "$DRIVE_MOUNT_ROOT/Q" >>"$MOUNT_STATE"
sync_drive_mounts '{"shared_drives":["O","Q"]}'
test ! -e "$DRIVE_MOUNT_ROOT/P"
test ! -L "$HOME/Desktop/Windows P"
test ! -e "$HOME/Desktop/Windows Q"
unmount_unused_drives ""
test -d "$DRIVE_MOUNT_ROOT/Q"
test "$(wc -l <"$MOUNT_STATE")" -eq 1
`
if err := os.WriteFile(filepath.Join(dir, "test.sh"), []byte(harness), 0o644); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, shBin, "test.sh")
cmd.Dir = dir
cmd.Env = append(os.Environ(), "LC_ALL=C", "MSYS=winsymlinks:lnk")
out, err := cmd.CombinedOutput()
if exit, ok := err.(*exec.ExitError); ok && exit.ExitCode() == 77 {
t.Skip("Perl is unavailable for reading the seekable credential descriptor")
}
const wantLog = "Windows drive O: mount failed (exit 22)\nAuthentication failed\n" +
"Windows drive F: mount failed (exit 1)\nMount point is a symbolic link: "
lines := strings.Split(strings.TrimSuffix(string(out), "\n"), "\n")
if err != nil || len(lines) != 4 || !strings.HasPrefix(string(out), wantLog) ||
!strings.HasSuffix(lines[3], "/home with spaces/ReimsWindowsDrives/F") {
t.Fatalf("guest drive mount failed: %v\n%s", err, out)
}
}
func scriptSection(t *testing.T, script, start, end string) string {
t.Helper()
startAt := strings.Index(script, start)
if startAt < 0 {
t.Fatalf("missing script section %q", start)
}
section, _, ok := strings.Cut(script[startAt:], end)
if !ok {
t.Fatalf("missing end of script section %q", start)
}
return section + "\n"
}
+2 -2
View File
@@ -12,8 +12,8 @@ import (
"golang.org/x/net/webdav"
)
// DriveShareAgentVersion is the first macOS agent that applies dynamic drive mounts.
const DriveShareAgentVersion = 4
// DriveShareAgentVersion is the minimum agent version recommended for drive sharing.
const DriveShareAgentVersion = 7
// NormalizeDriveLetter accepts C, C:, or C:\ and returns the canonical letter C.
func NormalizeDriveLetter(raw string) (string, bool) {
+434
View File
@@ -0,0 +1,434 @@
package guesttools
import (
"crypto/rand"
"crypto/sha256"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
)
const (
syncScopeHeader = "X-Reims-Sync-Scope"
syncDigestHeader = "X-Reims-File-SHA256"
)
func syncFileScope(token string, root *os.Root) (string, error) {
// A replacement directory at the same path must start fresh sync history.
dir, err := root.Open(".")
if err != nil {
return "", err
}
defer dir.Close()
id, err := sharedDirectoryID(dir)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", sha256.Sum256([]byte(token+"\n"+root.Name()+"\n"+id))), nil
}
func openSharedRoot(dir string) (*os.Root, error) {
info, err := os.Lstat(dir)
if err != nil {
return nil, err
}
if !info.IsDir() {
return nil, fs.ErrInvalid
}
root, err := os.OpenRoot(dir)
if err != nil {
return nil, err
}
opened, err := root.Stat(".")
if err != nil || !os.SameFile(info, opened) {
_ = root.Close()
return nil, errors.New("shared directory changed")
}
return root, nil
}
func syncFileTag(info fs.FileInfo) string {
return fmt.Sprintf("\"%d-%d\"", info.ModTime().UnixNano(), info.Size())
}
func isIgnoredSharedName(name string) bool {
return name == "" || strings.HasPrefix(name, ".")
}
func validSyncFileName(name string) bool {
return strings.TrimSpace(name) == name && !strings.ContainsAny(name, "\t\r\n")
}
// sharedFilePath returns the one relative path used by both the legacy copy
// endpoints and the versioned sync operations.
func sharedFilePath(name string) (string, error) {
name = strings.TrimSpace(name)
parts := strings.FieldsFunc(name, func(r rune) bool { return r == '/' })
if len(parts) == 0 || len(parts) > MaxSharedDepth || strings.HasPrefix(name, "/") {
return "", errors.New("invalid relative path")
}
for _, part := range parts {
if isIgnoredSharedName(part) || strings.ContainsAny(part, "\x00:\\<>|\"?*") {
return "", errors.New("invalid path segment")
}
}
rel := strings.Join(parts, "/")
if !filepath.IsLocal(filepath.FromSlash(rel)) {
return "", errors.New("invalid relative path")
}
return rel, nil
}
func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
versioned := r.URL.Query().Get("sync") == "1"
if vm.sharedDir == "" {
if versioned {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
}
return
}
dir, err := filepath.Abs(vm.sharedDir)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusInternalServerError)
return
}
if !versioned {
if err := os.MkdirAll(dir, 0o755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
root, err := openSharedRoot(dir)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
return
}
defer root.Close()
var scope string
if versioned {
scope, err = syncFileScope(vm.token, root)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
return
}
}
type entry struct {
name string
info fs.FileInfo
}
var files []entry
err = fs.WalkDir(root.FS(), ".", func(name string, d fs.DirEntry, err error) error {
if name == "." {
return err
}
if err != nil {
return nil
}
if isIgnoredSharedName(d.Name()) || d.Type()&os.ModeSymlink != 0 {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if strings.Count(name, "/")+1 > MaxSharedDepth {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if d.IsDir() || (versioned && !validSyncFileName(name)) {
return nil
}
info, err := d.Info()
if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes {
return nil
}
if len(files) == MaxSharedFiles {
return fs.SkipAll
}
files = append(files, entry{name, info})
return nil
})
if versioned {
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
return
}
w.Header().Set(syncScopeHeader, scope)
}
sort.Slice(files, func(i, j int) bool { return files[i].name < files[j].name })
w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8")
for _, file := range files {
_, _ = fmt.Fprintf(w, "%d\t%d\t", file.info.ModTime().Unix(), file.info.Size())
if versioned {
_, _ = fmt.Fprintf(w, "%s\t", syncFileTag(file.info))
}
_, _ = fmt.Fprintln(w, file.name)
}
}
func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
rawName := r.URL.Query().Get("path")
name, err := sharedFilePath(rawName)
if err != nil || vm.sharedDir == "" {
http.Error(w, "invalid shared file path", http.StatusBadRequest)
return
}
dir, err := filepath.Abs(vm.sharedDir)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusInternalServerError)
return
}
scope := r.Header.Get(syncScopeHeader)
writing := r.Method == http.MethodPut || r.Method == http.MethodPost
switch r.Method {
case http.MethodHead, http.MethodDelete:
if scope == "" {
http.Error(w, "sync scope required", http.StatusPreconditionRequired)
return
}
case http.MethodGet, http.MethodPut, http.MethodPost:
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if scope == "" && writing {
if err := os.MkdirAll(dir, 0o755); err != nil {
http.Error(w, "shared directory unavailable", http.StatusInternalServerError)
return
}
}
root, err := openSharedRoot(dir)
if err != nil {
if scope == "" && !writing && errors.Is(err, fs.ErrNotExist) {
http.NotFound(w, r)
} else {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
}
return
}
defer root.Close()
if scope != "" {
current, err := syncFileScope(vm.token, root)
if err != nil {
http.Error(w, "shared directory unavailable", http.StatusServiceUnavailable)
return
}
if !validSyncFileName(rawName) || scope != current {
http.Error(w, "shared directory or file path changed", http.StatusPreconditionFailed)
return
}
}
if writing {
s.writeSharedFile(w, r, root, name, scope != "")
} else {
s.readSharedFile(w, r, root, name, scope != "")
}
}
func matchSyncFile(r *http.Request, info fs.FileInfo) bool {
if tag := r.Header.Get("If-Match"); tag != "" {
return info != nil && info.Mode().IsRegular() && syncFileTag(info) == tag
}
return r.Header.Get("If-None-Match") != "*" || info == nil
}
// A path replaced by a symlink or directory is a conflict rather than a
// missing file. Missing files are the only ones that propagate a deletion.
func statSharedFile(root *os.Root, name string) (fs.FileInfo, error) {
for i, ch := range name {
if ch != '/' {
continue
}
info, err := root.Lstat(name[:i])
if err != nil {
return nil, err
}
if !info.IsDir() {
return nil, fs.ErrInvalid
}
}
info, err := root.Lstat(name)
if err == nil && !info.Mode().IsRegular() {
return nil, fs.ErrInvalid
}
return info, err
}
func (s *Server) readSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) {
deleting := r.Method == http.MethodDelete
expectedDigest := r.Header.Get(syncDigestHeader)
if deleting && (r.Header.Get("If-Match") == "" || expectedDigest == "") {
http.Error(w, "file revision required", http.StatusPreconditionRequired)
return
}
info, err := statSharedFile(root, name)
switch {
case errors.Is(err, fs.ErrNotExist):
http.NotFound(w, r)
return
case errors.Is(err, fs.ErrInvalid):
status := http.StatusBadRequest
if versioned {
status = http.StatusConflict
}
http.Error(w, "path is not a regular file", status)
return
case err != nil:
http.Error(w, "file unavailable", http.StatusInternalServerError)
return
case versioned && !matchSyncFile(r, info):
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
tag := syncFileTag(info)
if !deleting {
w.Header().Set("ETag", tag)
}
head := r.Method == http.MethodHead
if head && r.URL.Query().Get("sha256") != "1" {
return
}
if (head || deleting) && info.Size() > MaxUploadBytes {
http.Error(w, "file exceeds sync size limit", http.StatusRequestEntityTooLarge)
return
}
file, err := root.Open(name)
if err != nil {
http.Error(w, "file unavailable", http.StatusInternalServerError)
return
}
opened, err := file.Stat()
if err != nil || !opened.Mode().IsRegular() || syncFileTag(opened) != tag {
_ = file.Close()
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
if r.Method == http.MethodGet {
defer file.Close()
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10))
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
_, _ = io.Copy(w, file)
return
}
h := sha256.New()
n, err := io.Copy(h, io.LimitReader(file, info.Size()+1))
_ = file.Close()
if err != nil || n != info.Size() {
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
digest := fmt.Sprintf("%x", h.Sum(nil))
if head {
w.Header().Set(syncDigestHeader, digest)
return
}
s.fileMu.Lock()
defer s.fileMu.Unlock()
current, err := statSharedFile(root, name)
if digest != expectedDigest || err != nil || !os.SameFile(opened, current) || !matchSyncFile(r, current) {
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
if r.Context().Err() == nil {
if err := root.Remove(name); err != nil {
http.Error(w, "file deletion failed", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
}
func (s *Server) writeSharedFile(w http.ResponseWriter, r *http.Request, root *os.Root, name string, versioned bool) {
dir := path.Dir(name)
if err := root.MkdirAll(dir, 0o755); err != nil {
http.Error(w, "upload directory unavailable", http.StatusInternalServerError)
return
}
tmpName := path.Join(dir, ".reims-upload-"+rand.Text())
tmp, err := root.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
http.Error(w, "upload file unavailable", http.StatusInternalServerError)
return
}
defer root.Remove(tmpName)
h := sha256.New()
var dst io.Writer = tmp
if versioned {
dst = io.MultiWriter(tmp, h)
}
n, copyErr := io.Copy(dst, io.LimitReader(r.Body, MaxUploadBytes+1))
closeErr := tmp.Close()
switch {
case n > MaxUploadBytes:
http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge)
return
case copyErr != nil || closeErr != nil:
http.Error(w, "write failed", http.StatusInternalServerError)
return
}
if ts, err := strconv.ParseInt(r.URL.Query().Get("mtime"), 10, 64); err == nil && ts > 0 {
t := time.Unix(ts, 0)
_ = root.Chtimes(tmpName, t, t)
}
s.fileMu.Lock()
defer s.fileMu.Unlock()
info, err := statSharedFile(root, name)
if errors.Is(err, fs.ErrInvalid) {
http.Error(w, "path is not a regular file", http.StatusConflict)
return
}
if err != nil && !errors.Is(err, fs.ErrNotExist) {
http.Error(w, "file unavailable", http.StatusInternalServerError)
return
}
var uploadedTag string
if versioned {
if !matchSyncFile(r, info) {
http.Error(w, "file changed", http.StatusPreconditionFailed)
return
}
uploaded, err := root.Stat(tmpName)
if err != nil {
http.Error(w, "uploaded file unavailable", http.StatusInternalServerError)
return
}
uploadedTag = syncFileTag(uploaded)
}
if err := root.Rename(tmpName, name); err != nil {
http.Error(w, "publish uploaded file failed", http.StatusInternalServerError)
return
}
if versioned {
w.Header().Set("ETag", uploadedTag)
w.Header().Set(syncDigestHeader, fmt.Sprintf("%x", h.Sum(nil)))
}
w.WriteHeader(http.StatusOK)
}
+219
View File
@@ -0,0 +1,219 @@
# Keep confirmed pairs scoped to the current shared directories on both sides.
sync_files() {
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
sync_guest_root=$(sync_guest_root_id) || return 0
sync_remote="$TMP_DIR/sync-remote.tsv"
sync_local="$TMP_DIR/sync-local.tsv"
sync_headers="$TMP_DIR/sync-headers"
sync_plan="$TMP_DIR/sync-plan.tsv"
sync_delta="$TMP_DIR/sync-delta.tsv"
sync_state=/dev/null
if ! sync_request -fsS -m 5 -D "$sync_headers" -o "$sync_remote" "$REIMS_HOST_URL/v1/files?sync=1" 2>/dev/null; then
return 0
fi
sync_scope=$(sync_header X-Reims-Sync-Scope)
case "$sync_scope" in
"") ;;
*[!0-9a-f]*) return 0 ;;
*) sync_state="$APP_DIR/file-sync-$sync_scope-$sync_guest_root.tsv" ;;
esac
sync_previous="$sync_state"
[ -f "$sync_state" ] || sync_previous=/dev/null
if ! find "$SHARE_SYNC"/. -name '.*' ! -name . -prune -o -type f -exec /bin/sh -c '
root=$1
tab=$2
shift 2
newline=$(printf "\nx")
newline=${newline%x}
cr=$(printf "\r")
for file do
rel=${file#"$root"/./}
case "$rel" in *"$tab"*|*"$newline"*|*"$cr"*) continue ;; esac
row=$(stat -f "%m${tab}%z${tab}%Fm:%Fc:%i:%z" "$file") || exit 1
printf "%s\t%s\n" "$row" "$rel"
done
' sh "$SHARE_SYNC" "$TAB" {} + > "$sync_local" 2>/dev/null; then
return 0
fi
# A missing path is a deletion only after a confirmed pair has existed.
# If the remaining copy changed, preserve it using the usual copy rules.
awk -F '\t' -v extended="$sync_scope" '
BEGIN { OFS = FS }
FILENAME == ARGV[1] {
previousLocal[$4] = $1; previousRemote[$4] = $2; state[$4] = $3; paths[$4] = 1
}
FILENAME == ARGV[2] {
p = extended == "" ? $3 : $4
if (p != "") {
remoteTime[p] = $1; remoteSize[p] = $2; remote[p] = extended == "" ? "-" : $3; paths[p] = 1
}
}
FILENAME == ARGV[3] && $4 != "" {
localTime[$4] = $1; localSize[$4] = $2; local[$4] = $3; paths[$4] = 1
}
END {
for (p in paths) {
l = p in local; r = p in remote
paired = state[p] != "" && state[p] != "different"
op = ""
if (l && r) {
if (remoteTime[p] + 0 > localTime[p] + 2) op = "download"
else if (localTime[p] + 0 > remoteTime[p] + 2 && localSize[p] <= 268435456) op = "upload"
else if (extended != "" && localTime[p] == remoteTime[p] && localSize[p] == remoteSize[p] &&
(local[p] != previousLocal[p] || remote[p] != previousRemote[p])) op = "verify"
} else if (r) {
op = paired && remote[p] == previousRemote[p] ? "delete-host" : "download"
} else if (l) {
if (paired && local[p] == previousLocal[p]) op = "delete-guest"
else if (localSize[p] <= 268435456) op = "upload"
} else {
op = "forget"
}
if (op != "") {
localRevision = l ? local[p] : "-"
remoteRevision = r ? remote[p] : "-"
localMtime = l ? localTime[p] : "-"
digest = state[p] != "" ? state[p] : "-"
print op, localRevision, remoteRevision, localMtime, digest, p
}
}
}
' "$sync_previous" "$sync_remote" "$sync_local" > "$sync_plan" || return 0
: > "$sync_delta" || return 0
sync_verify_left=8
while IFS="$TAB" read -r sync_op sync_guest_rev sync_host_rev sync_guest_time sync_digest sync_rel; do
sync_apply_file
done < "$sync_plan"
if [ "$sync_state" != /dev/null ]; then
awk -F '\t' '
$1 == "-" { delete rows[$4]; next }
{ rows[$4] = $0 }
END { for (p in rows) print rows[p] }
' "$sync_previous" "$sync_delta" > "$TMP_DIR/sync-state.next" &&
mv -f "$TMP_DIR/sync-state.next" "$sync_state"
fi
}
sync_request() {
curl -H "Authorization: Bearer $REIMS_TOKEN" "$@"
}
sync_header() {
awk -v name="$1:" 'tolower($1) == tolower(name) { sub(/\r$/, "", $2); print $2; exit }' "$sync_headers"
}
sync_guest_root_id() {
[ -d "$SHARE_SYNC" ] && [ ! -L "$SHARE_SYNC" ] &&
stat -f '%d-%i-%B' "$SHARE_SYNC" 2>/dev/null
}
sync_guest_revision() {
[ "$(sync_guest_root_id)" = "$sync_guest_root" ] || return 1
sync_check=$1
while [ "$sync_check" != "$SHARE_SYNC" ]; do
[ ! -L "$sync_check" ] || return 1
sync_check=${sync_check%/*}
done
if [ -f "$1" ]; then
stat -f '%Fm:%Fc:%i:%z' "$1" 2>/dev/null
elif [ ! -e "$1" ]; then
printf '%s\n' '-'
fi
}
sync_record() {
[ -n "$1" ] && [ -n "$2" ] && [ -n "$3" ] || return 0
printf '%s\t%s\t%s\t%s\n' "$1" "$2" "$3" "$sync_rel" >> "$sync_delta"
}
sync_apply_file() {
case "/$sync_rel/" in //*|*/../*|*/./*|*//*) return ;; esac
sync_target="$SHARE_SYNC/$sync_rel"
[ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0
sync_url="$REIMS_HOST_URL/v1/file?path=$(urlencode "$sync_rel")"
if [ -n "$sync_scope" ]; then
set -- -H "X-Reims-Sync-Scope: $sync_scope"
if [ "$sync_host_rev" != - ]; then
set -- "$@" -H "If-Match: $sync_host_rev"
fi
else
set --
fi
case "$sync_op" in
delete-host)
sync_status=$(sync_request -sS -m 60 "$@" -H "X-Reims-File-SHA256: $sync_digest" -X DELETE \
-o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0
case "$sync_status" in
204) sync_record - - -; return ;;
412) sync_op=download ;;
*) return 0 ;;
esac
;;
delete-guest|forget)
# A partial host listing cannot confirm that a file was deleted.
sync_status=$(sync_request -sS -m 10 "$@" -I -o /dev/null -w '%{http_code}' "$sync_url" 2>/dev/null) || return 0
[ "$sync_status" = 404 ] || return 0
if [ "$sync_op" = "forget" ]; then
sync_record - - -
return
fi
sync_actual=$(hash_file "$sync_target")
[ -n "$sync_actual" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] || return 0
if [ "$sync_actual" = "$sync_digest" ]; then
rm "$sync_target" && sync_record - - -
return
fi
sync_op=upload
;;
esac
case "$sync_op" in
download)
sync_part="$TMP_DIR/sync-download.part"
if sync_request -fsS -m 60 "$@" -D "$sync_headers" -o "$sync_part" "$sync_url" 2>/dev/null; then
sync_download_digest=""
if [ -n "$sync_scope" ]; then
sync_download_digest=$(hash_file "$sync_part")
fi
if sync_stamp=$(TZ=UTC date -r "$(sync_header X-File-Mtime)" '+%Y%m%d%H%M.%S' 2>/dev/null); then
TZ=UTC touch -t "$sync_stamp" "$sync_part" 2>/dev/null || true
fi
if [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ] &&
mkdir -p "$(dirname "$sync_target")" && mv -f "$sync_part" "$sync_target"; then
sync_record "$(sync_guest_revision "$sync_target")" "$(sync_header ETag)" "$sync_download_digest"
fi
fi
rm -f "$sync_part"
;;
upload)
if [ -n "$sync_scope" ] && [ "$sync_host_rev" = - ]; then
set -- "$@" -H 'If-None-Match: *'
fi
if sync_request -fsS -m 60 "$@" -X PUT --data-binary "@$sync_target" -D "$sync_headers" -o /dev/null \
"$sync_url&mtime=$sync_guest_time" 2>/dev/null &&
[ -n "$sync_scope" ] && [ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then
sync_record "$sync_guest_rev" "$(sync_header ETag)" "$(sync_header X-Reims-File-SHA256)"
fi
;;
verify)
# Bound initial migration work when adopting pre-existing copies.
[ "$sync_verify_left" -gt 0 ] || return 0
sync_verify_left=$((sync_verify_left - 1))
if sync_request -fsS -m 15 "$@" -I -D "$sync_headers" -o /dev/null "$sync_url&sha256=1" 2>/dev/null; then
sync_host_hash=$(sync_header X-Reims-File-SHA256)
sync_guest_hash=$(hash_file "$sync_target")
if [ -n "$sync_host_hash" ] && [ -n "$sync_guest_hash" ] &&
[ "$(sync_guest_revision "$sync_target")" = "$sync_guest_rev" ]; then
[ "$sync_host_hash" = "$sync_guest_hash" ] || sync_host_hash=different
sync_record "$sync_guest_rev" "$sync_host_rev" "$sync_host_hash"
fi
fi
;;
esac
}
@@ -0,0 +1,12 @@
//go:build !windows && !unix
package guesttools
import (
"errors"
"os"
)
func sharedDirectoryID(*os.File) (string, error) {
return "", errors.ErrUnsupported
}
@@ -0,0 +1,18 @@
//go:build unix
package guesttools
import (
"fmt"
"os"
"syscall"
)
func sharedDirectoryID(dir *os.File) (string, error) {
info, err := dir.Stat()
if err != nil {
return "", err
}
stat := info.Sys().(*syscall.Stat_t)
return fmt.Sprintf("%x:%x", stat.Dev, stat.Ino), nil
}
@@ -0,0 +1,16 @@
package guesttools
import (
"fmt"
"os"
"syscall"
)
func sharedDirectoryID(dir *os.File) (string, error) {
var info syscall.ByHandleFileInformation
if err := syscall.GetFileInformationByHandle(syscall.Handle(dir.Fd()), &info); err != nil {
return "", err
}
return fmt.Sprintf("%x:%08x%08x:%x", info.VolumeSerialNumber, info.FileIndexHigh,
info.FileIndexLow, info.CreationTime.Nanoseconds()), nil
}
+158
View File
@@ -0,0 +1,158 @@
package guesttools
import (
"context"
"crypto/sha256"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"testing"
)
func TestFileSyncRequiresConfirmedRevisionAndContent(t *testing.T) {
root := t.TempDir()
shared := filepath.Join(root, "share")
srv := NewTransportServer(&memClipboard{})
port, err := srv.Start(-1)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = srv.Close(context.Background()) })
cfg, err := LoadOrCreateVMConfig(root, "sync-test", shared, port)
if err != nil {
t.Fatal(err)
}
srv.RegisterVM(cfg)
request := func(method, path, body string, headers http.Header, want int) (http.Header, string) {
t.Helper()
req, err := http.NewRequest(method, fmt.Sprintf("http://127.0.0.1:%d%s", port, path), strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
if headers != nil {
req.Header = headers.Clone()
}
req.Header.Set("Authorization", "Bearer "+cfg.Token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil || resp.StatusCode != want {
t.Fatalf("%s %s: status=%d, want=%d, body=%q, read error=%v", method, path, resp.StatusCode, want, b, err)
}
return resp.Header, string(b)
}
const fileURL = "/v1/file?path=entry.txt"
const contents = "original"
digest := fmt.Sprintf("%x", sha256.Sum256([]byte(contents)))
list, _ := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK)
scope := list.Get(syncScopeHeader)
if scope == "" {
t.Fatal("missing sync scope")
}
conditions := make(http.Header)
conditions.Set(syncScopeHeader, scope)
conditions.Set("If-None-Match", "*")
created, _ := request(http.MethodPut, fileURL+"&mtime=1700000000", contents, conditions, http.StatusOK)
tag := created.Get("ETag")
if tag == "" || created.Get(syncDigestHeader) != digest {
t.Fatalf("upload revision or digest missing: %v", created)
}
_, legacyList := request(http.MethodGet, "/v1/files", "", nil, http.StatusOK)
_, versionedList := request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK)
if legacyList != "1700000000\t8\tentry.txt\n" ||
versionedList != "1700000000\t8\t"+tag+"\tentry.txt\n" {
t.Fatalf("unexpected file listings: legacy=%q, versioned=%q", legacyList, versionedList)
}
request(http.MethodPut, fileURL, "overwritten", conditions, http.StatusPreconditionFailed)
conditions.Del("If-None-Match")
conditions.Set("If-Match", tag)
probed, _ := request(http.MethodHead, fileURL+"&sha256=1", "", conditions, http.StatusOK)
if probed.Get(syncDigestHeader) != digest {
t.Fatalf("unexpected digest: %v", probed)
}
request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionRequired)
conditions.Set(syncDigestHeader, digest)
conditions.Set("If-Match", "\"stale-revision\"")
request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed)
conditions.Set("If-Match", tag)
request(http.MethodPut, fileURL+"&mtime=1700000000", "modified", nil, http.StatusOK)
request(http.MethodDelete, fileURL, "", conditions, http.StatusPreconditionFailed)
_, got := request(http.MethodGet, fileURL, "", nil, http.StatusOK)
if got != "modified" {
t.Fatalf("modified copy was lost: %q", got)
}
conditions.Set(syncDigestHeader, fmt.Sprintf("%x", sha256.Sum256([]byte(got))))
request(http.MethodDelete, fileURL, "", conditions, http.StatusNoContent)
request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound)
if err := os.Rename(shared, filepath.Join(root, "old-share")); err != nil {
t.Fatal(err)
}
request(http.MethodGet, "/v1/files?sync=1", "", conditions, http.StatusServiceUnavailable)
request(http.MethodHead, fileURL, "", conditions, http.StatusServiceUnavailable)
srv.RegisterVM(cfg)
list, _ = request(http.MethodGet, "/v1/files?sync=1", "", nil, http.StatusOK)
newScope := list.Get(syncScopeHeader)
if newScope == "" || newScope == scope {
t.Fatalf("recreated share must have a new scope: %q", newScope)
}
request(http.MethodHead, fileURL, "", conditions, http.StatusPreconditionFailed)
request(http.MethodPut, fileURL, "stale upload", conditions, http.StatusPreconditionFailed)
conditions = http.Header{syncScopeHeader: {newScope}}
request(http.MethodHead, fileURL, "", conditions, http.StatusNotFound)
request(http.MethodPut, "/v1/file?path=nested/file.txt", contents, conditions, http.StatusOK)
_, got = request(http.MethodGet, "/v1/file?path=nested/file.txt", "", conditions, http.StatusOK)
if got != contents {
t.Fatalf("nested file contents: %q", got)
}
}
func TestFileSyncConfinesUploadToShare(t *testing.T) {
shared, outside := t.TempDir(), t.TempDir()
link := filepath.Join(shared, "linked")
if err := os.Symlink(outside, link); err != nil {
if runtime.GOOS != "windows" {
t.Skipf("directory symlink unavailable: %v", err)
}
output, err := exec.Command("cmd.exe", "/c", "mklink", "/J", link, outside).CombinedOutput()
if err != nil {
t.Fatalf("create test junction: %v: %s", err, output)
}
}
srv := NewTransportServer(&memClipboard{})
token := strings.Repeat("a", 64)
srv.RegisterVM(VMConfig{VMName: "sync-test", Token: token, SharedDir: shared})
list := httptest.NewRequest(http.MethodGet, "/v1/files?sync=1", nil)
list.Header.Set("Authorization", "Bearer "+token)
listed := httptest.NewRecorder()
srv.handleListFiles(listed, list)
scope := listed.Header().Get(syncScopeHeader)
if listed.Code != http.StatusOK || scope == "" {
t.Fatalf("listing failed: %d: %s", listed.Code, listed.Body)
}
for _, version := range []string{"", scope} {
req := httptest.NewRequest(http.MethodPut, "/v1/file?path=linked/upload.txt", strings.NewReader("test upload"))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set(syncScopeHeader, version)
res := httptest.NewRecorder()
srv.handleFile(res, req)
if res.Code < http.StatusBadRequest {
t.Fatalf("upload through an out-of-share link succeeded: %d", res.Code)
}
if _, err := os.Stat(filepath.Join(outside, "upload.txt")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("upload escaped share: %v", err)
}
}
}
+236 -197
View File
@@ -2,6 +2,7 @@ package guesttools
import (
"bytes"
_ "embed"
"fmt"
"io"
"os"
@@ -15,8 +16,11 @@ const (
InstallCommand = "sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command"
)
//go:embed file_sync.sh
var guestFileSync string
// BuildToolsDiskImage creates a small read-only HFS+ disk image ("REIMSTOOLS")
// containing the per-VM Bearer token config, Guest Tools 4 POSIX agent script
// containing the per-VM Bearer token config, Guest Tools POSIX agent script
// (text + PNG image clipboard with long-poll, WebDAV live mount with fallback
// sync, and caffeinate prevent-sleep daemon), plus install/uninstall/pmset scripts.
func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
@@ -65,7 +69,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files)
}
// GuestAgentScript returns the Guest Tools 4 stock-macOS POSIX shell daemon
// GuestAgentScript returns the Guest Tools stock-macOS POSIX shell daemon
// (no Xcode or Python required):
// - Two-way UTF-8 text + PNG screenshot clipboard with server long-polling
// - Zero-duplication WebDAV shared folder mount (~/Desktop/ReimsShare) with automatic sync fallback
@@ -73,7 +77,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
// - Live host-controlled prevent-sleep guard via `caffeinate -dims` (no sudo required)
func GuestAgentScript() []byte {
return []byte(`#!/bin/sh
# Reims Guest Tools 4: clipboard, WebDAV share, read-only Windows drives, prevent-sleep.
# Reims Guest Tools: clipboard, WebDAV share, read-only Windows drives, prevent-sleep.
set -u
# Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified
@@ -194,64 +198,67 @@ ensure_webdav_mount() {
}
sleep_active="false"
drive_mount_failures=""
previous_desired_drives=""
is_drive_mounted() {
mount 2>/dev/null | grep -F "on $1 (" >/dev/null 2>&1
}
` + guestDriveCleanup + `
update_drive_link() {
letter="$1"
mount_point="$DRIVE_MOUNT_ROOT/$letter"
link="$HOME/Desktop/Windows $letter"
if [ -L "$link" ]; then
[ "$(readlink "$link" 2>/dev/null || true)" = "$mount_point" ] && return 0
rm -f "$link" 2>/dev/null || true
elif [ -e "$link" ]; then
return 0
mount_drive_readonly() (
drive="$1"
target="$2"
if [ -L "$target" ]; then
printf 'Mount point is a symbolic link: %s\n' "$target" >&2
return 1
fi
ln -s "$mount_point" "$link" 2>/dev/null || true
}
mkdir -p "$target" || return 1
token_length=${#REIMS_TOKEN}
if [ "$token_length" -eq 0 ] || [ "$token_length" -gt 255 ]; then
printf 'Invalid WebDAV credential length\n' >&2
return 1
fi
dav_url="${REIMS_HOST_URL%/}/dav/$(urlencode "$REIMS_VM")/drives/$drive/"
remove_drive_link() {
letter="$1"
mount_point="$DRIVE_MOUNT_ROOT/$letter"
link="$HOME/Desktop/Windows $letter"
if [ -L "$link" ] && [ "$(readlink "$link" 2>/dev/null || true)" = "$mount_point" ]; then
rm -f "$link" 2>/dev/null || true
fi
}
unmount_drive() {
letter="$1"
mount_point="$DRIVE_MOUNT_ROOT/$letter"
if is_drive_mounted "$mount_point"; then
umount "$mount_point" >/dev/null 2>&1 || true
fi
remove_drive_link "$letter"
if ! is_drive_mounted "$mount_point"; then
rmdir "$mount_point" 2>/dev/null || true
fi
}
# Use the credential descriptor accepted by Apple's WebDAV NetFS helper.
# Each field has a 32-bit big-endian length: user, password, proxy
# user, proxy password, then TLS properties. The descriptor must be seekable.
auth_file=$(mktemp "$TMP_DIR/drive-auth.XXXXXX") || return 1
trap 'rm -f "$auth_file"' EXIT
{
rm -f "$auth_file" || return 1
printf '\000\000\000\005reims' >&3 || return 1
printf '\000\000\000%b%s' "\\0$(printf '%03o' "$token_length")" "$REIMS_TOKEN" >&3 || return 1
printf '\000\000\000\000\000\000\000\000\000\000\000\000' >&3 || return 1
exec mount_webdav -a 3 -S -o rdonly -v "Windows $drive" "$dav_url" "$target"
} 3<>"$auth_file"
)
mount_drive() {
letter="$1"
mount_point="$DRIVE_MOUNT_ROOT/$letter"
if is_drive_mounted "$mount_point"; then
update_drive_link "$letter"
return 0
fi
command -v mount_webdav >/dev/null 2>&1 || return 0
host_addr=${REIMS_HOST_URL#http://}
host_addr=${host_addr#https://}
host_addr=${host_addr%/}
dav_url="http://reims:${REIMS_TOKEN}@${host_addr}/dav/${REIMS_VM}/drives/${letter}/"
mkdir -p "$mount_point"
# Prefer a client read-only mount where supported; the host remains the authority.
if mount_webdav -o ro -v "Windows $letter" "$dav_url" "$mount_point" >/dev/null 2>&1 || \
mount_webdav -o ro "$dav_url" "$mount_point" >/dev/null 2>&1 || \
mount_webdav -v "Windows $letter" "$dav_url" "$mount_point" >/dev/null 2>&1 || \
mount_webdav "$dav_url" "$mount_point" >/dev/null 2>&1; then
update_drive_link "$letter"
case "$(drive_mount_type "$mount_point")" in
webdav) ;;
"")
mount_output=$(mount_drive_readonly "$letter" "$mount_point" 2>&1) || {
mount_status=$?
case "$drive_mount_failures" in
*"$letter"*) ;;
*)
printf 'Windows drive %s: mount failed (exit %s)\n' "$letter" "$mount_status" >&2
[ -z "$mount_output" ] || printf '%s\n' "$mount_output" >&2
drive_mount_failures="$drive_mount_failures$letter"
;;
esac
return 0
}
;;
*) return 0 ;;
esac
case "$drive_mount_failures" in
*"$letter"*) drive_mount_failures=$(printf '%s' "$drive_mount_failures" | tr -d "$letter") ;;
esac
link="$HOME/Desktop/Windows $letter"
if [ ! -L "$link" ] && [ ! -e "$link" ]; then
ln -s "$mount_point" "$link" 2>/dev/null || true
fi
}
@@ -260,14 +267,11 @@ sync_drive_mounts() {
desired=$(printf '%s\n' "$cfg_json" | \
sed -n 's/.*"shared_drives"[[:space:]]*:[[:space:]]*\[\([^]]*\)\].*/\1/p' | \
tr ',' '\n' | sed -n 's/^[[:space:]]*"\([A-Z]\)"[[:space:]]*$/\1/p' | tr '\n' ' ')
for mount_point in "$DRIVE_MOUNT_ROOT"/*; do
[ -d "$mount_point" ] || continue
letter=${mount_point##*/}
case " $desired " in
*" $letter "*) ;;
*) unmount_drive "$letter" ;;
esac
done
if [ "$desired" != "$previous_desired_drives" ]; then
previous_desired_drives="$desired"
drive_mount_failures=""
fi
unmount_unused_drives "$desired"
for letter in $desired; do
mount_drive "$letter"
done
@@ -309,57 +313,79 @@ report_status() {
curl -fsS -m 3 -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
-H "Content-Type: application/json" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":5}" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":7}" \
"$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true
}
read_local_clipboard() {
out_file="$1"
# Fast path: inspect macOS clipboard types via osascript to detect screenshots/images.
cinfo=$(osascript -e 'clipboard info' 2>/dev/null || true)
has_text=0
case "$cinfo" in
*utf8*|*"Unicode text"*|*string*) has_text=1 ;;
*utf8*|*"Unicode text"*|*string*)
if pbpaste >"$out_file" 2>/dev/null && [ -s "$out_file" ]; then
echo "text"
return 0
fi
;;
esac
if [ "$has_text" -eq 0 ]; then
case "$cinfo" in
*PNGf*)
rm -f "$out_file"
if osascript -e "set fp to open for access POSIX file \"$out_file\" with write permission" \
-e "set eof fp to 0" \
-e "write (the clipboard as «class PNGf») to fp" \
-e "close access fp" >/dev/null 2>&1 && [ -s "$out_file" ]; then
echo "png"
return 0
fi
;;
*TIFF*)
tiff_tmp="$TMP_DIR/clip_in.tiff"
rm -f "$tiff_tmp" "$out_file"
if osascript -e "set fp to open for access POSIX file \"$tiff_tmp\" with write permission" \
-e "set eof fp to 0" \
-e "write (the clipboard as TIFF picture) to fp" \
-e "close access fp" >/dev/null 2>&1 && [ -s "$tiff_tmp" ]; then
if sips -s format png "$tiff_tmp" --out "$out_file" >/dev/null 2>&1 && [ -s "$out_file" ]; then
rm -f "$tiff_tmp"
echo "png"
return 0
fi
fi
case "$cinfo" in
*PNGf*)
rm -f "$out_file"
if osascript -e "set fp to open for access POSIX file \"$out_file\" with write permission" \
-e "set eof fp to 0" \
-e "write (the clipboard as «class PNGf») to fp" \
-e "close access fp" >/dev/null 2>&1 && [ -s "$out_file" ]; then
echo "png"
return 0
fi
;;
esac
case "$cinfo" in
*TIFF*)
tiff_tmp="$TMP_DIR/clip_in.tiff"
rm -f "$tiff_tmp" "$out_file"
if osascript -e "set fp to open for access POSIX file \"$tiff_tmp\" with write permission" \
-e "set eof fp to 0" \
-e "write (the clipboard as TIFF picture) to fp" \
-e "close access fp" >/dev/null 2>&1 && [ -s "$tiff_tmp" ] &&
sips -s format png "$tiff_tmp" --out "$out_file" >/dev/null 2>&1 && [ -s "$out_file" ]; then
rm -f "$tiff_tmp"
;;
esac
fi
pbpaste >"$out_file" 2>/dev/null || : >"$out_file"
echo "text"
echo "png"
return 0
fi
rm -f "$tiff_tmp"
;;
esac
case "$cinfo" in
*PNGf*|*TIFF*)
echo "empty"
;;
*)
pbpaste >"$out_file" 2>/dev/null || : >"$out_file"
echo "text"
;;
esac
}
write_local_png() {
in_file="$1"
osascript -e "set the clipboard to (read (POSIX file \"$in_file\") as «class PNGf»)" >/dev/null 2>&1 || true
osascript -e "set the clipboard to (read (POSIX file \"$1\") as «class PNGf»)" >/dev/null 2>&1
}
last_clip_hash=""
local_clip_hash() {
case "$1" in
png) hash_png_file "$2" ;;
text) hash_file "$2" ;;
empty) echo "empty" ;;
esac
}
clip_header() {
awk -v name="$1:" 'tolower($1)==name {gsub(/\r/,"",$2); print $2; exit}' "$hdr_out"
}
last_local_hash=""
last_server_hash=""
last_server_seq=""
clip_enabled="1"
tick=0
TAB=$(printf '\t')
@@ -375,108 +401,94 @@ sync_clipboard() {
hdr_out="$TMP_DIR/clip_hdr"
local_kind=$(read_local_clipboard "$clip_in")
if [ "$local_kind" = "png" ]; then
cur_hash=$(hash_png_file "$clip_in")
else
cur_hash=$(hash_file "$clip_in")
fi
cur_hash=$(local_clip_hash "$local_kind" "$clip_in")
post_conflict=0
if [ -n "$last_clip_hash" ] && [ "$cur_hash" != "$last_clip_hash" ]; then
if [ "$local_kind" != "empty" ] && [ -n "$last_local_hash" ] && [ "$cur_hash" != "$last_local_hash" ]; then
ct="text/plain; charset=utf-8"
[ "$local_kind" = "png" ] && ct="image/png"
if curl -fsS -m 5 -X POST \
-H "Authorization: Bearer $REIMS_TOKEN" \
-H "Content-Type: $ct" \
--data-binary "@$clip_in" \
"$REIMS_HOST_URL/v1/clipboard" >/dev/null 2>&1; then
last_clip_hash="$cur_hash"
set --
if [ -n "$last_server_seq" ]; then
set -- -H "X-Clip-Base-Seq: $last_server_seq"
fi
return 0
code=$(curl -sS -m 5 -X POST -D "$hdr_out" -o /dev/null -w '%{http_code}' \
-H "Authorization: Bearer $REIMS_TOKEN" \
-H "Content-Type: $ct" ${1+"$@"} \
--data-binary "@$clip_in" \
"$REIMS_HOST_URL/v1/clipboard" 2>/dev/null) || code=000
case "$code" in
200)
last_local_hash="$cur_hash"
last_server_hash=$(clip_header x-clip-hash)
last_server_seq=$(clip_header x-clip-seq)
return 0
;;
204|413)
last_local_hash="$cur_hash"
;;
409)
post_conflict=1
;;
esac
fi
# Long-poll up to 2s: host changes return immediately (~150ms), idle stays quiet.
code=$(curl -sS -m 5 -D "$hdr_out" -o "$clip_out" -w '%{http_code}' \
-H "Authorization: Bearer $REIMS_TOKEN" \
"$REIMS_HOST_URL/v1/clipboard?since=$last_clip_hash&wait=2&accept=image" 2>/dev/null || echo "000")
if [ "$code" = "200" ]; then
new_hash=$(awk 'tolower($1)=="x-clip-hash:" {gsub(/\r/,"",$2); print $2; exit}' "$hdr_out")
new_kind=$(awk 'tolower($1)=="x-clip-kind:" {gsub(/\r/,"",$2); print tolower($2); exit}' "$hdr_out")
if [ -n "$new_hash" ] && [ "$new_hash" != "$cur_hash" ]; then
if [ "$new_kind" = "png" ]; then
write_local_png "$clip_out"
else
pbcopy <"$clip_out" 2>/dev/null || true
"$REIMS_HOST_URL/v1/clipboard?since=$last_server_hash&wait=2&accept=image" 2>/dev/null) || code=000
case "$code" in
200)
new_hash=$(clip_header x-clip-hash)
[ -n "$new_hash" ] || return 0
new_kind=$(clip_header x-clip-kind)
new_seq=$(clip_header x-clip-seq)
post_get_kind=$(read_local_clipboard "$clip_in")
post_get_hash=$(local_clip_hash "$post_get_kind" "$clip_in")
if [ "$post_get_hash" != "$cur_hash" ]; then
last_server_seq="$new_seq"
return 0
fi
last_clip_hash="$new_hash"
elif [ -n "$new_hash" ]; then
last_clip_hash="$new_hash"
fi
elif [ "$code" = "503" ]; then
# Feature disabled on host: back off instead of busy-looping osascript + curl (M11).
sleep 5
elif [ "$code" = "304" ] && [ -z "$last_clip_hash" ]; then
last_clip_hash="$cur_hash"
elif [ "$code" = "000" ]; then
sleep 2
fi
if [ "$new_hash" != "$cur_hash" ]; then
if [ "$new_kind" = "png" ]; then
write_local_png "$clip_out" || return 0
else
pbcopy <"$clip_out" 2>/dev/null || return 0
fi
post_get_kind=$(read_local_clipboard "$clip_in")
post_get_hash=$(local_clip_hash "$post_get_kind" "$clip_in")
fi
last_local_hash="$post_get_hash"
last_server_hash="$new_hash"
last_server_seq="$new_seq"
;;
204|304)
if [ -z "$last_local_hash" ]; then
last_local_hash="$cur_hash"
fi
if [ "$code" = 204 ]; then
last_server_seq=""
else
new_seq=$(clip_header x-clip-seq)
if [ -n "$new_seq" ]; then
last_server_seq="$new_seq"
fi
new_hash=$(clip_header x-clip-hash)
if [ "$post_conflict" = 1 ] && [ -z "$new_hash" ]; then
last_local_hash="$cur_hash"
fi
fi
;;
503)
# Feature disabled on host: back off instead of busy-looping osascript + curl (M11).
sleep 5
;;
000)
sleep 2
;;
esac
}
sync_files() {
[ "$mount_mode" = "webdav" ] && return 0
[ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0
remote_list="$TMP_DIR/remote_files.tsv"
if ! curl -fsS -m 5 \
-H "Authorization: Bearer $REIMS_TOKEN" \
"$REIMS_HOST_URL/v1/files" -o "$remote_list" 2>/dev/null; then
return 0
fi
# 1. Host -> Guest (download new or strictly newer files)
while IFS="$TAB" read -r rmtime rsize rrel; do
[ -n "$rrel" ] || continue
local_path="$SHARE_SYNC/$rrel"
need_dl=0
if [ ! -f "$local_path" ]; then
need_dl=1
else
lmtime=$(stat -f '%m' "$local_path" 2>/dev/null || echo 0)
if [ "$rmtime" -gt $((lmtime + 2)) ]; then
need_dl=1
fi
fi
if [ "$need_dl" -eq 1 ]; then
mkdir -p "$(dirname "$local_path")"
enc=$(urlencode "$rrel")
dl_tmp="$TMP_DIR/dl.part"
if curl -fsS -m 60 \
-H "Authorization: Bearer $REIMS_TOKEN" \
"$REIMS_HOST_URL/v1/file?path=$enc" -o "$dl_tmp" 2>/dev/null; then
mv -f "$dl_tmp" "$local_path"
touch -d "@$rmtime" "$local_path" 2>/dev/null || true
else
rm -f "$dl_tmp"
fi
fi
done <"$remote_list"
# 2. Guest -> Host (upload new or strictly newer files)
find "$SHARE_SYNC" -type f ! -name '.*' ! -path '*/.*' 2>/dev/null | while IFS= read -r fpath; do
rel=${fpath#"$SHARE_SYNC/"}
[ -n "$rel" ] || continue
lmtime=$(stat -f '%m' "$fpath" 2>/dev/null || echo 0)
lsize=$(stat -f '%z' "$fpath" 2>/dev/null || echo 0)
[ "$lsize" -le 268435456 ] || continue
rmtime=$(awk -F '\t' -v p="$rel" '$3==p {print $1; exit}' "$remote_list")
[ -n "$rmtime" ] || rmtime=0
if [ "$lmtime" -gt $((rmtime + 2)) ]; then
enc=$(urlencode "$rel")
curl -fsS -m 60 -X PUT \
-H "Authorization: Bearer $REIMS_TOKEN" \
--data-binary "@$fpath" \
"$REIMS_HOST_URL/v1/file?path=$enc&mtime=$lmtime" >/dev/null 2>&1 || true
fi
done
}
` + guestFileSync + `
text_input_loop() {
hdr="$TMP_DIR/txt_hdr"
@@ -605,12 +617,12 @@ launchctl bootstrap "gui/$uid" "$PLIST" 2>/dev/null || launchctl load -w "$PLIST
# Verify host bridge connectivity immediately.
. "$APP_DIR/config"
if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/ping" >/dev/null 2>&1; then
echo "Reims Guest Tools 4 installed and connected!"
echo "Reims Guest Tools installed and connected!"
echo "Clipboard: UTF-8 text + PNG screenshots (two-way)"
echo "Shared folder: ~/Desktop/ReimsShare (WebDAV live mount, auto-fallback to sync)"
echo "Prevent-sleep: controlled live from Reims-Go host UI"
else
echo "Reims Guest Tools 4 installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
echo "Reims Guest Tools installed (waiting for Windows host bridge at $REIMS_HOST_URL)..."
fi
`)
}
@@ -626,19 +638,46 @@ DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives"
uid=$(id -u)
launchctl bootout "gui/$uid" "$PLIST" 2>/dev/null || launchctl unload "$PLIST" 2>/dev/null || true
umount "$SHARE_MOUNT" 2>/dev/null || true
for mount_point in "$DRIVE_MOUNT_ROOT"/*; do
[ -d "$mount_point" ] || continue
letter=${mount_point##*/}
umount "$mount_point" 2>/dev/null || true
link="$HOME/Desktop/Windows $letter"
[ -L "$link" ] && rm -f "$link" 2>/dev/null || true
done
` + guestDriveCleanup + `
unmount_unused_drives ""
rm -f "$PLIST"
rm -rf "$APP_DIR"
echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept."
`)
}
const guestDriveCleanup = `
drive_mount_type() {
[ ! -L "$1" ] || return 0
mount 2>/dev/null | awk -v target=" on $1 (" '
pos = index($0, target) {
split(substr($0, pos + length(target)), options, /[,)]/)
print options[1]
exit
}
'
}
unmount_unused_drives() {
for drive_path in "$DRIVE_MOUNT_ROOT"/*; do
[ -d "$drive_path" ] && [ ! -L "$drive_path" ] || continue
drive_letter=${drive_path##*/}
case "$drive_letter" in [A-Z]) ;; *) continue ;; esac
case " $1 " in *" $drive_letter "*) continue ;; esac
case "$(drive_mount_type "$drive_path")" in
webdav) umount "$drive_path" >/dev/null 2>&1 || continue ;;
"") ;;
*) continue ;;
esac
drive_link="$HOME/Desktop/Windows $drive_letter"
if [ -L "$drive_link" ] && [ "$(readlink "$drive_link")" = "$drive_path" ]; then
rm -f "$drive_link" 2>/dev/null || true
fi
rmdir "$drive_path" 2>/dev/null || true
done
}
`
// GuestPmsetScript offers an optional system-wide pmset configuration command
// for users who want persistent no-sleep settings even before login.
func GuestPmsetScript() []byte {
+196 -361
View File
@@ -1,6 +1,7 @@
package guesttools
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
@@ -10,13 +11,10 @@ import (
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
@@ -40,6 +38,8 @@ const (
ConfigFileName = ".reims-go-tools.json"
)
const bridgeProtocolVersion = 4
// ErrGuestToolsNotConnected is returned when a guest-assisted operation
// requires a live Guest Tools agent inside macOS.
var ErrGuestToolsNotConnected = errors.New("guest tools not connected")
@@ -201,6 +201,8 @@ type registeredVM struct {
// (reachable from QEMU SLIRP guests as http://10.0.2.2:<port>).
type Server struct {
mu sync.RWMutex
fileMu sync.Mutex
clipWriteMu sync.Mutex
clip Clipboard
vms map[string]*registeredVM // keyed by driver.VMRef.Key()
davHandlers map[string]*webdav.Handler
@@ -712,7 +714,7 @@ func (s *Server) handlePing(w http.ResponseWriter, r *http.Request) {
_ = json.NewEncoder(w).Encode(map[string]any{
"ok": true,
"vm": vm.name,
"version": DriveShareAgentVersion,
"version": bridgeProtocolVersion,
"capabilities": caps,
})
}
@@ -779,15 +781,21 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func (s *Server) readClipboardPayload(acceptImage bool) (ClipPayload, error) {
if acceptImage {
return s.clip.Read()
func (s *Server) readClipboardState(wantImage bool) (ClipPayload, uint32, error) {
if clip, ok := s.clip.(interface {
readClipboard(bool) (ClipPayload, uint32, error)
}); ok {
return clip.readClipboard(wantImage)
}
text, err := s.clip.ReadText()
if err != nil {
return ClipPayload{}, err
}
return ClipPayload{Kind: ClipText, Data: []byte(text)}, nil
// A clipboard without atomic snapshots can return a newer payload with
// this sequence, which is safe for a subsequent conditional write.
seq := s.clip.SequenceNumber()
payload, err := s.clip.Read()
return payload, seq, err
}
func setClipboardSeq(w http.ResponseWriter, seq uint32) {
w.Header().Set("X-Clip-Seq", strconv.FormatUint(uint64(seq), 10))
}
func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
@@ -796,53 +804,42 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
policy := s.EffectiveClipboardPolicy(vm.key)
if !policy.Enabled {
writeFeatureDisabled(w, "clipboard")
return
}
switch r.Method {
case http.MethodGet:
waitSec := 0
if rawWait := r.URL.Query().Get("wait"); rawWait != "" {
if n, err := strconv.Atoi(rawWait); err == nil && n > 0 {
if n > MaxLongPollSec {
n = MaxLongPollSec
}
waitSec = n
}
}
if policy.Direction == ClipboardGuestToHost {
// Hold the long-poll instead of returning 204 immediately so the
// guest agent loop does not busy-spin CPU in guest-to-host mode (M11).
if waitSec > 0 {
ch := s.clipNotifyChan()
timer := time.NewTimer(time.Duration(waitSec) * time.Second)
select {
case <-ch:
timer.Stop()
case <-timer.C:
case <-r.Context().Done():
timer.Stop()
return
}
}
w.WriteHeader(http.StatusNoContent)
s.getClipboard(w, r, vm.key)
case http.MethodPost, http.MethodPut:
s.postClipboard(w, r, vm.key)
default:
if !s.EffectiveClipboardPolicy(vm.key).Enabled {
writeFeatureDisabled(w, "clipboard")
return
}
acceptImage := policy.SyncImages && (strings.EqualFold(r.URL.Query().Get("accept"), "image") ||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png"))
since := r.URL.Query().Get("since")
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
deadline := time.Now().Add(time.Duration(waitSec) * time.Second)
for {
if !s.EffectiveClipboardPolicy(vm.key).Enabled {
writeFeatureDisabled(w, "clipboard")
return
}
if ov := s.takeClipOverride(vm.key); ov != nil {
s.touchLastSeen(vm.name)
func (s *Server) getClipboard(w http.ResponseWriter, r *http.Request, vmKey string) {
waitSec, err := strconv.Atoi(r.URL.Query().Get("wait"))
if err != nil {
waitSec = 0
}
deadline := time.Now().Add(time.Duration(max(0, min(waitSec, MaxLongPollSec))) * time.Second)
wantsImage := strings.EqualFold(r.URL.Query().Get("accept"), "image") ||
strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")
since := r.URL.Query().Get("since")
for {
ch := s.clipNotifyChan()
policy := s.EffectiveClipboardPolicy(vmKey)
if !policy.Enabled {
writeFeatureDisabled(w, "clipboard")
return
}
if policy.Direction != ClipboardGuestToHost {
if ov := s.takeClipOverride(vmKey); ov != nil {
s.touchLastSeen(vmKey)
atomic.AddUint64(&s.clipStatsH2G, 1)
setClipboardSeq(w, s.clip.SequenceNumber())
w.Header().Set("X-Clip-Hash", ov.hash)
w.Header().Set("X-Clip-Kind", string(ClipText))
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
@@ -850,128 +847,171 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) {
close(ov.servedCh)
return
}
payload, err := s.readClipboardPayload(acceptImage)
wantImage := wantsImage && policy.SyncImages
payload, seq, err := s.readClipboardState(wantImage)
if err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if payload.Kind == ClipPNG && len(payload.Data) > policy.MaxImageBytes {
payload = ClipPayload{Kind: ClipText, Data: nil}
}
h := payloadHash(payload)
if since == "" || since != h {
s.touchLastSeen(vm.name)
atomic.AddUint64(&s.clipStatsH2G, 1)
w.Header().Set("X-Clip-Hash", h)
if payload.Kind == ClipPNG {
w.Header().Set("X-Clip-Kind", string(ClipPNG))
w.Header().Set("Content-Type", "image/png")
_, _ = w.Write(payload.Data)
} else {
w.Header().Set("X-Clip-Kind", string(ClipText))
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
syncable := payload.Kind == ClipText || (payload.Kind == ClipPNG &&
wantImage && len(payload.Data) <= policy.MaxImageBytes)
if syncable {
h := payloadHash(payload)
if since != h || time.Until(deadline) <= 0 {
setClipboardSeq(w, seq)
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
s.touchLastSeen(vmKey)
if since == h {
w.WriteHeader(http.StatusNotModified)
return
}
atomic.AddUint64(&s.clipStatsH2G, 1)
if payload.Kind == ClipPNG {
w.Header().Set("Content-Type", "image/png")
} else {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
}
_, _ = w.Write(payload.Data)
return
}
return
}
if waitSec <= 0 {
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
} else if time.Until(deadline) <= 0 {
s.touchLastSeen(vmKey)
setClipboardSeq(w, seq)
w.WriteHeader(http.StatusNotModified)
return
}
rem := time.Until(deadline)
if rem <= 0 {
s.touchLastSeen(vm.name)
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
w.WriteHeader(http.StatusNotModified)
return
}
ch := s.clipNotifyChan()
timer := time.NewTimer(rem)
select {
case <-ch:
timer.Stop()
case <-timer.C:
s.touchLastSeen(vm.name)
w.Header().Set("X-Clip-Hash", h)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
w.WriteHeader(http.StatusNotModified)
return
case <-r.Context().Done():
timer.Stop()
return
}
}
case http.MethodPost, http.MethodPut:
if policy.Direction == ClipboardHostToGuest {
} else if time.Until(deadline) <= 0 {
// Keep guest-to-host-only agents from busy-looping.
w.WriteHeader(http.StatusNoContent)
return
}
limit := policy.MaxImageBytes
if limit <= 0 || limit > MaxClipboardBytes {
limit = MaxClipboardBytes
}
body, err := io.ReadAll(io.LimitReader(r.Body, int64(limit)+1))
if err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(body) > limit {
http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge)
return
}
ct := strings.ToLower(r.Header.Get("Content-Type"))
if strings.Contains(ct, "image/png") {
if !policy.SyncImages {
w.WriteHeader(http.StatusNoContent)
return
}
if !IsPNG(body) {
http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest)
return
}
h := payloadHash(ClipPayload{Kind: ClipPNG, Data: body})
if cur, err := s.clip.Read(); err != nil || payloadHash(cur) != h {
if err := s.clip.WritePNG(body); err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
atomic.AddUint64(&s.clipStatsG2H, 1)
s.broadcastClipChange()
}
w.Header().Set("X-Clip-Kind", string(ClipPNG))
w.Header().Set("X-Clip-Hash", h)
w.WriteHeader(http.StatusOK)
return
}
timer := time.NewTimer(time.Until(deadline))
select {
case <-ch:
timer.Stop()
case <-timer.C:
// Re-read after the timeout in case the watcher has yet to notify us.
case <-r.Context().Done():
timer.Stop()
return
}
}
}
var errClipboardConflict = errors.New("host clipboard changed")
func (s *Server) postClipboard(w http.ResponseWriter, r *http.Request, vmName string) {
policy := s.EffectiveClipboardPolicy(vmName)
if !policy.Enabled {
writeFeatureDisabled(w, "clipboard")
return
}
isImage := strings.Contains(strings.ToLower(r.Header.Get("Content-Type")), "image/png")
if policy.Direction == ClipboardHostToGuest || (isImage && !policy.SyncImages) {
w.WriteHeader(http.StatusNoContent)
return
}
var baseSeq *uint32
if raw := r.Header.Get("X-Clip-Base-Seq"); policy.Direction != ClipboardGuestToHost && raw != "" {
n, err := strconv.ParseUint(raw, 10, 32)
if err != nil {
http.Error(w, "invalid X-Clip-Base-Seq", http.StatusBadRequest)
return
}
base := uint32(n)
baseSeq = &base
}
limit := MaxClipboardBytes
if isImage {
limit = policy.MaxImageBytes
}
body, err := io.ReadAll(io.LimitReader(r.Body, int64(limit)+1))
if err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if len(body) > limit {
http.Error(w, "clipboard too large", http.StatusRequestEntityTooLarge)
return
}
payload := ClipPayload{Kind: ClipText, Data: body}
if isImage {
if !IsPNG(body) {
http.Error(w, "clipboard payload must be a valid PNG", http.StatusBadRequest)
return
}
payload.Kind = ClipPNG
} else {
if !utf8.Valid(body) {
http.Error(w, "clipboard payload must be valid UTF-8", http.StatusBadRequest)
return
}
text := strings.ReplaceAll(string(body), "\r\n", "\n")
h := textHash(text)
if cur, err := s.clip.ReadText(); err != nil || textHash(cur) != h {
if err := s.clip.WriteText(text); err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
atomic.AddUint64(&s.clipStatsG2H, 1)
s.broadcastClipChange()
}
w.Header().Set("X-Clip-Kind", string(ClipText))
w.Header().Set("X-Clip-Hash", h)
w.WriteHeader(http.StatusOK)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
payload.Data = []byte(strings.ReplaceAll(string(body), "\r\n", "\n"))
}
h := payloadHash(payload)
seq, err := s.applyClipboardPost(payload, baseSeq)
if errors.Is(err, errClipboardConflict) {
setClipboardSeq(w, seq)
http.Error(w, errClipboardConflict.Error(), http.StatusConflict)
return
}
if err != nil {
atomic.AddUint64(&s.clipStatsErr, 1)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
setClipboardSeq(w, seq)
w.Header().Set("X-Clip-Kind", string(payload.Kind))
w.Header().Set("X-Clip-Hash", h)
w.WriteHeader(http.StatusOK)
}
func (s *Server) applyClipboardPost(payload ClipPayload, baseSeq *uint32) (uint32, error) {
s.clipWriteMu.Lock()
defer s.clipWriteMu.Unlock()
seq := s.clip.SequenceNumber()
if baseSeq != nil && seq != *baseSeq {
return seq, errClipboardConflict
}
current, seq, err := s.readClipboardState(true)
if err == nil {
if baseSeq != nil && seq != *baseSeq {
return seq, errClipboardConflict
}
if current.Kind == payload.Kind && bytes.Equal(current.Data, payload.Data) {
return seq, nil
}
}
if clip, ok := s.clip.(interface {
writeClipboard(ClipPayload, *uint32) (uint32, error)
}); ok {
seq, err = clip.writeClipboard(payload, baseSeq)
} else {
seq = s.clip.SequenceNumber()
if baseSeq != nil && seq != *baseSeq {
return seq, errClipboardConflict
}
if payload.Kind == ClipPNG {
err = s.clip.WritePNG(payload.Data)
} else {
err = s.clip.WriteText(string(payload.Data))
}
seq = s.clip.SequenceNumber()
}
if err == nil {
atomic.AddUint64(&s.clipStatsG2H, 1)
s.broadcastClipChange()
}
return seq, err
}
func (s *Server) takeClipOverride(vmName string) *pendingClipOverride {
@@ -1143,208 +1183,3 @@ func (s *Server) handleHostText(w http.ResponseWriter, r *http.Request) {
}
w.WriteHeader(http.StatusAccepted)
}
func isIgnoredSharedName(name string) bool {
return name == "" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "._")
}
// resolveSharedPath validates a relative slash path and ensures the resulting
// path stays strictly inside rootDir (no .., absolute paths, drive letters, or
// symlink escapes).
func resolveSharedPath(rootDir, rel string) (string, error) {
if rootDir == "" {
return "", errors.New("shared directory not configured")
}
if strings.ContainsRune(rel, 0) || strings.Contains(rel, `\`) {
return "", errors.New("invalid path")
}
trimmed := strings.TrimSpace(rel)
if trimmed == "" || strings.HasPrefix(trimmed, "/") {
return "", errors.New("invalid relative path")
}
for _, rawSeg := range strings.Split(trimmed, "/") {
if rawSeg == ".." || rawSeg == "." {
return "", errors.New("path traversal not allowed")
}
}
clean := path.Clean("/" + trimmed)
clean = strings.TrimPrefix(clean, "/")
if clean == "" || clean == "." || strings.HasPrefix(clean, "..") {
return "", errors.New("invalid relative path")
}
parts := strings.Split(clean, "/")
if len(parts) > MaxSharedDepth {
return "", errors.New("path too deep")
}
for _, seg := range parts {
if seg == "" || seg == "." || seg == ".." || strings.ContainsAny(seg, `:\<>|"?*`) || isIgnoredSharedName(seg) {
return "", errors.New("invalid path segment")
}
}
rootAbs, err := filepath.Abs(rootDir)
if err != nil {
return "", err
}
full := filepath.Join(append([]string{rootAbs}, parts...)...)
relBack, err := filepath.Rel(rootAbs, full)
if err != nil || relBack == "." || strings.HasPrefix(relBack, "..") || filepath.IsAbs(relBack) {
return "", errors.New("path escapes shared root")
}
return full, nil
}
func (s *Server) handleListFiles(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if vm.sharedDir == "" {
w.WriteHeader(http.StatusOK)
return
}
if err := os.MkdirAll(vm.sharedDir, 0o755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
rootAbs, err := filepath.Abs(vm.sharedDir)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
type entry struct {
mtime int64
size int64
rel string
}
var list []entry
_ = filepath.WalkDir(rootAbs, func(p string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if p == rootAbs {
return nil
}
name := d.Name()
if isIgnoredSharedName(name) {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if d.Type()&os.ModeSymlink != 0 {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
rel, err := filepath.Rel(rootAbs, p)
if err != nil {
return nil
}
slash := filepath.ToSlash(rel)
if strings.Count(slash, "/")+1 > MaxSharedDepth {
if d.IsDir() {
return filepath.SkipDir
}
return nil
}
if d.IsDir() {
return nil
}
info, err := d.Info()
if err != nil || !info.Mode().IsRegular() || info.Size() > MaxUploadBytes {
return nil
}
if len(list) >= MaxSharedFiles {
return fs.SkipAll
}
list = append(list, entry{mtime: info.ModTime().Unix(), size: info.Size(), rel: slash})
return nil
})
sort.Slice(list, func(i, j int) bool { return list[i].rel < list[j].rel })
w.Header().Set("Content-Type", "text/tab-separated-values; charset=utf-8")
for _, e := range list {
_, _ = fmt.Fprintf(w, "%d\t%d\t%s\n", e.mtime, e.size, e.rel)
}
}
func (s *Server) handleFile(w http.ResponseWriter, r *http.Request) {
vm := s.authenticate(r)
if vm == nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
rel := r.URL.Query().Get("path")
full, err := resolveSharedPath(vm.sharedDir, rel)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
switch r.Method {
case http.MethodGet:
info, err := os.Lstat(full)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !info.Mode().IsRegular() {
http.Error(w, "not a regular file", http.StatusBadRequest)
return
}
f, err := os.Open(full)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
w.Header().Set("X-File-Mtime", strconv.FormatInt(info.ModTime().Unix(), 10))
w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))
w.Header().Set("Content-Type", "application/octet-stream")
_, _ = io.Copy(w, f)
case http.MethodPut, http.MethodPost:
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmp, err := os.CreateTemp(filepath.Dir(full), ".reims-upload-*")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
tmpName := tmp.Name()
n, copyErr := io.Copy(tmp, io.LimitReader(r.Body, MaxUploadBytes+1))
closeErr := tmp.Close()
if copyErr != nil || closeErr != nil || n > MaxUploadBytes {
_ = os.Remove(tmpName)
if n > MaxUploadBytes {
http.Error(w, "file exceeds 256 MiB limit", http.StatusRequestEntityTooLarge)
return
}
http.Error(w, "write failed", http.StatusInternalServerError)
return
}
if mtimeStr := r.URL.Query().Get("mtime"); mtimeStr != "" {
if ts, perr := strconv.ParseInt(mtimeStr, 10, 64); perr == nil && ts > 0 {
t := time.Unix(ts, 0)
_ = os.Chtimes(tmpName, t, t)
}
}
if err := os.Rename(tmpName, full); err != nil {
_ = os.Remove(tmpName)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
+22
View File
@@ -0,0 +1,22 @@
//go:build !windows
package host
import (
"context"
"errors"
"github.com/Nwflower/reims-go/internal/i18n"
)
type VMCloseChoice uint8
const (
VMCloseCancel VMCloseChoice = iota
VMCloseShutdown
VMCloseSuspend
)
func ConfirmVMClose(context.Context, uintptr, string, i18n.Locale, string, bool) (VMCloseChoice, error) {
return VMCloseCancel, errors.ErrUnsupported
}
+604
View File
@@ -0,0 +1,604 @@
//go:build windows
package host
import (
"context"
"fmt"
"runtime"
"strings"
"sync"
"syscall"
"unicode/utf16"
"unsafe"
"golang.org/x/sys/windows/registry"
"github.com/Nwflower/reims-go/internal/i18n"
)
type VMCloseChoice uint8
const (
VMCloseCancel VMCloseChoice = iota
VMCloseShutdown
VMCloseSuspend
)
const (
vcIDTitle = 100
vcIDBody = 101
vcIDLeft = 111
vcIDRight = 112
vcIDCancel = 2 // IDCANCEL, including Escape in the dialog message loop.
vcWMAction = 0x8001
)
var (
vcGDI = syscall.NewLazyDLL("gdi32.dll")
vcDWM = syscall.NewLazyDLL("dwmapi.dll")
vcKernel = syscall.NewLazyDLL("kernel32.dll")
vcCreateDialog = user32.NewProc("CreateDialogIndirectParamW")
vcDestroyWindow = user32.NewProc("DestroyWindow")
vcSetTimer = user32.NewProc("SetTimer")
vcKillTimer = user32.NewProc("KillTimer")
vcSendMessage = user32.NewProc("SendMessageW")
vcPostMessage = user32.NewProc("PostMessageW")
vcGetDlgItem = user32.NewProc("GetDlgItem")
vcSetFocus = user32.NewProc("SetFocus")
vcIsDialogMessage = user32.NewProc("IsDialogMessageW")
vcTranslateMsg = user32.NewProc("TranslateMessage")
vcDispatchMsg = user32.NewProc("DispatchMessageW")
vcClientToScreen = user32.NewProc("ClientToScreen")
vcDrawText = user32.NewProc("DrawTextW")
vcFillRect = user32.NewProc("FillRect")
vcGetWindowTextW = user32.NewProc("GetWindowTextW")
vcInvalidateRect = user32.NewProc("InvalidateRect")
vcSetLayeredAttr = user32.NewProc("SetLayeredWindowAttributes")
vcSetWindowRgn = user32.NewProc("SetWindowRgn")
vcBeginPaint = user32.NewProc("BeginPaint")
vcEndPaint = user32.NewProc("EndPaint")
vcIsWindowEnabled = user32.NewProc("IsWindowEnabled")
vcMoveWindow = user32.NewProc("MoveWindow")
vcGetParent = user32.NewProc("GetParent")
vcSelectObj = vcGDI.NewProc("SelectObject")
vcStockObj = vcGDI.NewProc("GetStockObject")
vcDeleteObj = vcGDI.NewProc("DeleteObject")
vcSetDCBrushColor = vcGDI.NewProc("SetDCBrushColor")
vcSetDCPenColor = vcGDI.NewProc("SetDCPenColor")
vcSetTextColor = vcGDI.NewProc("SetTextColor")
vcSetBkMode = vcGDI.NewProc("SetBkMode")
vcCreateFontW = vcGDI.NewProc("CreateFontIndirectW")
vcCreateRoundRect = vcGDI.NewProc("CreateRoundRectRgn")
vcRoundRect = vcGDI.NewProc("RoundRect")
vcDwmSetWindowAttr = vcDWM.NewProc("DwmSetWindowAttribute")
vcRtlMoveMemory = vcKernel.NewProc("RtlMoveMemory")
)
type vcRect struct{ left, top, right, bottom int32 }
type vcMessage struct {
hwnd uintptr
id uint32
wp, lp uintptr
time uint32
pt point
}
type vcPaintStruct struct {
hdc uintptr
erase int32
rcPaint vcRect
restore int32
incUpdate int32
rgbReserve [32]byte
}
type vcDrawItem struct {
ctlType uint32
ctlID uint32
itemID uint32
itemAction uint32
itemState uint32
hwndItem uintptr
hdc uintptr
rcItem vcRect
itemData uintptr
}
type vcLogFont struct {
height, width, escapement, orientation, weight int32
italic, underline, strikeOut, charSet byte
outPrecision, clipPrecision, quality, pitch byte
faceName [32]uint16
}
type vcPalette struct {
surface, border, divider uintptr
text, text2, textDisabled uintptr
accent, accentPress uintptr
btnFill, btnPress, btnBorder uintptr
dangerText uintptr
}
func vcRGB(r, g, b uint8) uintptr {
return uintptr(r) | uintptr(g)<<8 | uintptr(b)<<16
}
var (
vcLightPalette = vcPalette{
surface: vcRGB(255, 255, 255),
border: vcRGB(224, 228, 234),
divider: vcRGB(235, 237, 240),
text: vcRGB(29, 29, 31),
text2: vcRGB(66, 66, 71),
textDisabled: vcRGB(154, 154, 160),
accent: vcRGB(0, 122, 255),
accentPress: vcRGB(0, 94, 196),
btnFill: vcRGB(246, 247, 249),
btnPress: vcRGB(235, 237, 240),
btnBorder: vcRGB(218, 221, 227),
dangerText: vcRGB(215, 0, 21),
}
vcDarkPalette = vcPalette{
surface: vcRGB(36, 37, 43),
border: vcRGB(56, 57, 65),
divider: vcRGB(52, 53, 61),
text: vcRGB(245, 245, 247),
text2: vcRGB(194, 194, 202),
textDisabled: vcRGB(110, 110, 118),
accent: vcRGB(10, 132, 255),
accentPress: vcRGB(0, 107, 230),
btnFill: vcRGB(48, 49, 57),
btnPress: vcRGB(60, 61, 70),
btnBorder: vcRGB(68, 70, 80),
dangerText: vcRGB(255, 69, 58),
}
)
type vcDialogState struct {
dark bool
fontTitle uintptr
fontBody uintptr
fontBtn uintptr
titleText string
bodyText string
}
var (
vcStatesMu sync.Mutex
vcStates = map[uintptr]*vcDialogState{}
)
func vcResolveDark(theme string) bool {
switch strings.ToLower(strings.TrimSpace(theme)) {
case "dark":
return true
case "light":
return false
}
k, err := registry.OpenKey(registry.CURRENT_USER, `Software\Microsoft\Windows\CurrentVersion\Themes\Personalize`, registry.QUERY_VALUE)
if err != nil {
return false
}
defer k.Close()
v, _, err := k.GetIntegerValue("AppsUseLightTheme")
return err == nil && v == 0
}
func vcFontFace(loc i18n.Locale) string {
if strings.HasPrefix(strings.ToLower(string(loc)), "zh") {
return "Microsoft YaHei UI"
}
return "Segoe UI"
}
func vcCreateFont(px int32, weight int32, face string) uintptr {
var lf vcLogFont
lf.height = -px
lf.weight = weight
lf.charSet = 1 // DEFAULT_CHARSET
lf.quality = 5 // CLEARTYPE_QUALITY
u := utf16.Encode([]rune(face))
for i := 0; i < len(u) && i < len(lf.faceName)-1; i++ {
lf.faceName[i] = u[i]
}
h, _, _ := vcCreateFontW.Call(uintptr(unsafe.Pointer(&lf)))
return h
}
func vcScale(px int32, dpi uint32) int32 {
if dpi == 0 {
dpi = 96
}
return (px*int32(dpi) + 48) / 96
}
func vcPaletteFor(dark bool) vcPalette {
if dark {
return vcDarkPalette
}
return vcLightPalette
}
// ConfirmVMClose shows a native Win32 confirmation card owned by the VM
// display window, offering Shutdown, Suspend (when supported), and Cancel.
func ConfirmVMClose(ctx context.Context, owner uintptr, name string, loc i18n.Locale, theme string, canSuspend bool) (VMCloseChoice, error) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
desc := "window.close.description"
if !canSuspend {
desc = "window.close.description_no_suspend"
}
title := i18n.M(loc, "window.close.title", i18n.Vars{"name": name})
body := i18n.T(loc, desc)
left := i18n.T(loc, "stop")
right := i18n.T(loc, "window.close.suspend")
cancelText := i18n.T(loc, "cancel")
template := vcBuildDialogTemplate(title, body, left, right, cancelText, !canSuspend, loc)
var flags uintptr
if vcResolveDark(theme) {
flags |= 1
}
if strings.HasPrefix(strings.ToLower(string(loc)), "zh") {
flags |= 2
}
hwnd, _, err := vcCreateDialog.Call(0, uintptr(unsafe.Pointer(&template[0])), owner, vcDialogProc, flags)
if hwnd == 0 {
return VMCloseCancel, fmt.Errorf("create VM close confirmation: %w", err)
}
defer vcDestroyWindow.Call(hwnd)
timer, _, err := vcSetTimer.Call(0, 0, 200, 0)
if timer == 0 {
return VMCloseCancel, fmt.Errorf("track VM window: %w", err)
}
defer vcKillTimer.Call(0, timer)
centerVMCloseDialog(hwnd, owner)
vcSendMessage.Call(hwnd, 0x0401, vcIDCancel, 0) // DM_SETDEFID
procShowWindow.Call(hwnd, 4) // SW_SHOWNOACTIVATE
vcSetLayeredAttr.Call(hwnd, 0, 244, 2) // LWA_ALPHA
if foreground, _, _ := procGetForegroundWindow.Call(); foreground == owner {
if active, _, _ := procSetForegroundWin.Call(hwnd); active != 0 {
cancelBtn, _, _ := vcGetDlgItem.Call(hwnd, vcIDCancel)
vcSetFocus.Call(cancelBtn)
}
}
for ctx.Err() == nil {
var msg vcMessage
ret, _, err := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(ret) == -1 {
return VMCloseCancel, err
}
if ret == 0 {
break
}
if currentOwner, _, _ := procGetWindow.Call(hwnd, 4); currentOwner != owner { // GW_OWNER
break
}
if msg.id == 0x0113 && msg.hwnd == 0 { // WM_TIMER
centerVMCloseDialog(hwnd, owner)
continue
}
if msg.id == vcWMAction && msg.hwnd == hwnd {
switch msg.wp {
case vcIDLeft:
return VMCloseShutdown, nil
case vcIDRight:
if canSuspend {
return VMCloseSuspend, nil
}
case vcIDCancel:
return VMCloseCancel, nil
}
}
if handled, _, _ := vcIsDialogMessage.Call(hwnd, uintptr(unsafe.Pointer(&msg))); handled == 0 {
vcTranslateMsg.Call(uintptr(unsafe.Pointer(&msg)))
vcDispatchMsg.Call(uintptr(unsafe.Pointer(&msg)))
}
}
return VMCloseCancel, nil
}
func vcBuildDialogTemplate(title, body, left, right, cancel string, disableRight bool, loc i18n.Locale) []uint16 {
const (
clsButton = 0x80
clsStatic = 0x82
)
// WS_POPUP | WS_CLIPCHILDREN | DS_SETFONT, WS_EX_TOOLWINDOW | WS_EX_LAYERED.
data := []uint16{0x40, 0x8200, 0x80, 8, 0, 0, 0, 220, 80, 0, 0}
addStr := func(s string) {
data = append(data, utf16.Encode([]rune(s))...)
data = append(data, 0)
}
addStr(title)
data = append(data, 9)
addStr(vcFontFace(loc))
addItem := func(class, id uint16, caption string, disabled bool) {
if len(data)%2 != 0 {
data = append(data, 0)
}
style := uint16(0x5000) // WS_CHILD | WS_VISIBLE
var ctlStyle uint16
if class == clsButton {
style |= 1 // WS_TABSTOP
ctlStyle = 0x0b // BS_OWNERDRAW
if disabled {
style |= 0x0800 // WS_DISABLED
}
} else {
ctlStyle = 0x0d // SS_OWNERDRAW
}
data = append(data, ctlStyle, style, 0, 0, 0, 0, 10, 10, id, 0xffff, class)
addStr(caption)
data = append(data, 0)
data[4]++
}
addItem(clsStatic, vcIDTitle, title, false)
addItem(clsStatic, vcIDBody, body, false)
addItem(clsButton, vcIDLeft, left, false)
addItem(clsButton, vcIDRight, right, disableRight)
addItem(clsButton, vcIDCancel, cancel, false)
return data
}
func vcGetText(hwnd uintptr) string {
var buf [512]uint16
n, _, _ := vcGetWindowTextW.Call(hwnd, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)))
return syscall.UTF16ToString(buf[:n])
}
func vcMeasureHeight(hdc, font uintptr, text string, width int32) int32 {
if text == "" {
return 0
}
old, _, _ := vcSelectObj.Call(hdc, font)
defer vcSelectObj.Call(hdc, old)
u := utf16.Encode([]rune(text))
r := vcRect{right: width}
// DT_CALCRECT | DT_WORDBREAK | DT_NOPREFIX
vcDrawText.Call(hdc, uintptr(unsafe.Pointer(&u[0])), uintptr(len(u)), uintptr(unsafe.Pointer(&r)), 0x0c10)
return r.bottom - r.top
}
func vcLayout(hwnd uintptr, st *vcDialogState) {
dpiRaw, _, _ := procGetDpiForWindow.Call(hwnd)
dpi := uint32(dpiRaw)
if dpi == 0 {
dpi = 96
}
s := func(px int32) int32 { return vcScale(px, dpi) }
pad := s(20)
width := s(380)
innerW := width - pad*2
hdc, _, _ := procGetDC.Call(hwnd)
titleH := vcMeasureHeight(hdc, st.fontTitle, st.titleText, innerW)
if titleH < s(22) {
titleH = s(22)
}
bodyH := vcMeasureHeight(hdc, st.fontBody, st.bodyText, innerW)
if bodyH < s(34) {
bodyH = s(34)
}
procReleaseDC.Call(hwnd, hdc)
y := pad
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDTitle); h != 0 {
vcMoveWindow.Call(h, uintptr(pad), uintptr(y), uintptr(innerW), uintptr(titleH), 0)
}
y += titleH + s(8)
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDBody); h != 0 {
vcMoveWindow.Call(h, uintptr(pad), uintptr(y), uintptr(innerW), uintptr(bodyH), 0)
}
y += bodyH + s(18)
btnH := s(32)
gap := s(8)
btnW := (innerW - gap*2) / 3
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDCancel); h != 0 {
vcMoveWindow.Call(h, uintptr(pad), uintptr(y), uintptr(btnW), uintptr(btnH), 0)
}
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDLeft); h != 0 {
vcMoveWindow.Call(h, uintptr(pad+btnW+gap), uintptr(y), uintptr(btnW), uintptr(btnH), 0)
}
if h, _, _ := vcGetDlgItem.Call(hwnd, vcIDRight); h != 0 {
vcMoveWindow.Call(h, uintptr(pad+(btnW+gap)*2), uintptr(y), uintptr(innerW-(btnW+gap)*2), uintptr(btnH), 0)
}
height := y + btnH + pad
procSetWindowPos.Call(hwnd, 0, 0, 0, uintptr(width), uintptr(height), 0x0016) // SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE
r := s(12)
rgn, _, _ := vcCreateRoundRect.Call(0, 0, uintptr(width+1), uintptr(height+1), uintptr(r*2), uintptr(r*2))
if rgn != 0 {
vcSetWindowRgn.Call(hwnd, rgn, 1)
}
// DWMWA_WINDOW_CORNER_PREFERENCE = 33, DWMWCP_ROUND = 2
pref := uint32(2)
vcDwmSetWindowAttr.Call(hwnd, 33, uintptr(unsafe.Pointer(&pref)), unsafe.Sizeof(pref))
}
var vcDialogProc = syscall.NewCallback(func(hwnd, msg, wp, lp uintptr) uintptr {
switch msg {
case 0x0110: // WM_INITDIALOG
dark := lp&1 != 0
face := "Segoe UI"
if lp&2 != 0 {
face = "Microsoft YaHei UI"
}
dpiRaw, _, _ := procGetDpiForWindow.Call(hwnd)
dpi := uint32(dpiRaw)
if dpi == 0 {
dpi = 96
}
titleH, _, _ := vcGetDlgItem.Call(hwnd, vcIDTitle)
bodyH, _, _ := vcGetDlgItem.Call(hwnd, vcIDBody)
st := &vcDialogState{
dark: dark,
fontTitle: vcCreateFont(vcScale(15, dpi), 600, face),
fontBody: vcCreateFont(vcScale(13, dpi), 400, face),
fontBtn: vcCreateFont(vcScale(13, dpi), 500, face),
titleText: vcGetText(titleH),
bodyText: vcGetText(bodyH),
}
vcStatesMu.Lock()
vcStates[hwnd] = st
vcStatesMu.Unlock()
vcLayout(hwnd, st)
return 0
case 0x000f: // WM_PAINT
var ps vcPaintStruct
hdc, _, _ := vcBeginPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
vcStatesMu.Lock()
st := vcStates[hwnd]
vcStatesMu.Unlock()
pal := vcPaletteFor(st != nil && st.dark)
var rc vcRect
procGetClientRect.Call(hwnd, uintptr(unsafe.Pointer(&rc)))
brush, _, _ := vcStockObj.Call(18) // DC_BRUSH
pen, _, _ := vcStockObj.Call(19) // DC_PEN
vcSetDCBrushColor.Call(hdc, pal.surface)
vcSetDCPenColor.Call(hdc, pal.border)
oldB, _, _ := vcSelectObj.Call(hdc, brush)
oldP, _, _ := vcSelectObj.Call(hdc, pen)
dpiRaw, _, _ := procGetDpiForWindow.Call(hwnd)
r := vcScale(12, uint32(dpiRaw))
vcRoundRect.Call(hdc, uintptr(rc.left), uintptr(rc.top), uintptr(rc.right), uintptr(rc.bottom), uintptr(r*2), uintptr(r*2))
vcSelectObj.Call(hdc, oldB)
vcSelectObj.Call(hdc, oldP)
vcEndPaint.Call(hwnd, uintptr(unsafe.Pointer(&ps)))
return 1
case 0x0014: // WM_ERASEBKGND
return 1
case 0x002b: // WM_DRAWITEM
if lp != 0 {
var it vcDrawItem
vcRtlMoveMemory.Call(uintptr(unsafe.Pointer(&it)), lp, unsafe.Sizeof(it))
vcPaintItem(hwnd, &it)
return 1
}
case 0x0111: // WM_COMMAND
id := wp & 0xffff
if wp>>16 == 0 && (id == vcIDLeft || id == vcIDRight || id == vcIDCancel) {
vcPostMessage.Call(hwnd, vcWMAction, id, 0)
return 1
}
case 0x0010: // WM_CLOSE
vcPostMessage.Call(hwnd, vcWMAction, vcIDCancel, 0)
return 1
case 0x0082: // WM_NCDESTROY
vcStatesMu.Lock()
st := vcStates[hwnd]
delete(vcStates, hwnd)
vcStatesMu.Unlock()
if st != nil {
for _, f := range []uintptr{st.fontTitle, st.fontBody, st.fontBtn} {
if f != 0 {
vcDeleteObj.Call(f)
}
}
}
}
return 0
})
func vcPaintItem(dlg uintptr, it *vcDrawItem) {
vcStatesMu.Lock()
st := vcStates[dlg]
vcStatesMu.Unlock()
if st == nil {
return
}
pal := vcPaletteFor(st.dark)
brush, _, _ := vcStockObj.Call(18) // DC_BRUSH
pen, _, _ := vcStockObj.Call(19) // DC_PEN
vcSetBkMode.Call(it.hdc, 1) // TRANSPARENT
text := vcGetText(it.hwndItem)
u := utf16.Encode([]rune(text))
if it.ctlID == vcIDTitle || it.ctlID == vcIDBody {
vcSetDCBrushColor.Call(it.hdc, pal.surface)
vcFillRect.Call(it.hdc, uintptr(unsafe.Pointer(&it.rcItem)), brush)
if it.ctlID == vcIDTitle {
vcSelectObj.Call(it.hdc, st.fontTitle)
vcSetTextColor.Call(it.hdc, pal.text)
} else {
vcSelectObj.Call(it.hdc, st.fontBody)
vcSetTextColor.Call(it.hdc, pal.text2)
}
if len(u) > 0 {
vcDrawText.Call(it.hdc, uintptr(unsafe.Pointer(&u[0])), uintptr(len(u)), uintptr(unsafe.Pointer(&it.rcItem)), 0x0810) // DT_WORDBREAK | DT_NOPREFIX
}
return
}
// Owner-drawn buttons: Cancel, Left (Shutdown), Right (Suspend).
disabled := it.itemState&0x0004 != 0 // ODS_DISABLED
selected := it.itemState&0x0001 != 0 // ODS_SELECTED
fill, border, fg := pal.btnFill, pal.btnBorder, pal.text
if selected {
fill = pal.btnPress
}
switch it.ctlID {
case vcIDRight:
if !disabled {
fill, border, fg = pal.accent, pal.accent, vcRGB(255, 255, 255)
if selected {
fill, border = pal.accentPress, pal.accentPress
}
} else {
fg = pal.textDisabled
}
case vcIDLeft:
fg = pal.dangerText
}
vcSetDCBrushColor.Call(it.hdc, pal.surface)
vcFillRect.Call(it.hdc, uintptr(unsafe.Pointer(&it.rcItem)), brush)
vcSetDCBrushColor.Call(it.hdc, fill)
vcSetDCPenColor.Call(it.hdc, border)
oldB, _, _ := vcSelectObj.Call(it.hdc, brush)
oldP, _, _ := vcSelectObj.Call(it.hdc, pen)
dpiRaw, _, _ := procGetDpiForWindow.Call(dlg)
r := vcScale(7, uint32(dpiRaw))
vcRoundRect.Call(it.hdc, uintptr(it.rcItem.left), uintptr(it.rcItem.top), uintptr(it.rcItem.right), uintptr(it.rcItem.bottom), uintptr(r*2), uintptr(r*2))
vcSelectObj.Call(it.hdc, oldB)
vcSelectObj.Call(it.hdc, oldP)
vcSelectObj.Call(it.hdc, st.fontBtn)
vcSetTextColor.Call(it.hdc, fg)
if len(u) > 0 {
// DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOPREFIX
vcDrawText.Call(it.hdc, uintptr(unsafe.Pointer(&u[0])), uintptr(len(u)), uintptr(unsafe.Pointer(&it.rcItem)), 0x0825)
}
}
func centerVMCloseDialog(hwnd, owner uintptr) {
if iconic, _, _ := procIsIconic.Call(owner); iconic != 0 {
return
}
var client, bounds vcRect
var origin point
if ok, _, _ := procGetClientRect.Call(owner, uintptr(unsafe.Pointer(&client))); ok == 0 {
return
}
if ok, _, _ := vcClientToScreen.Call(owner, uintptr(unsafe.Pointer(&origin))); ok == 0 {
return
}
procGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&bounds)))
x := origin.X + (client.right-(bounds.right-bounds.left))/2
y := origin.Y + (client.bottom-(bounds.bottom-bounds.top))/2
if x != bounds.left || y != bounds.top {
// SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER
procSetWindowPos.Call(hwnd, 0, uintptr(x), uintptr(y), 0, 0, 0x0215)
}
}
var _ = vcGetParent
var _ = vcInvalidateRect
+135
View File
@@ -0,0 +1,135 @@
//go:build windows
package host
import (
"bufio"
"context"
"fmt"
"os"
"os/exec"
"runtime"
"syscall"
"testing"
"time"
"unsafe"
"github.com/Nwflower/reims-go/internal/i18n"
)
func TestVMCloseConfirmation(t *testing.T) {
const ownerEnv = "REIMS_GO_TEST_CLOSE_DIALOG_OWNER"
if os.Getenv(ownerEnv) != "" {
runCloseDialogOwner(t)
return
}
ownerCtx, stopOwner := context.WithTimeout(context.Background(), 25*time.Second)
defer stopOwner()
proc := exec.CommandContext(ownerCtx, os.Args[0], "-test.run=^TestVMCloseConfirmation$")
proc.Env = append(os.Environ(), ownerEnv+"=1")
proc.Stderr = os.Stderr
stdout, err := proc.StdoutPipe()
if err != nil {
t.Fatal(err)
}
if err := proc.Start(); err != nil {
t.Fatal(err)
}
defer func() {
stopOwner()
_ = proc.Wait()
}()
var owner uintptr
if _, err := fmt.Fscan(bufio.NewReader(stdout), &owner); err != nil || owner == 0 {
t.Fatalf("read test display HWND: %v", err)
}
for _, tc := range []struct {
name string
canSuspend bool
button uintptr
want VMCloseChoice
}{
{"shutdown", true, vcIDLeft, VMCloseShutdown},
{"suspend", true, vcIDRight, VMCloseSuspend},
{"escape", true, vcIDCancel, VMCloseCancel},
{"unsupported", false, vcIDCancel, VMCloseCancel},
} {
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
result := make(chan error, 1)
go func() {
result <- exerciseVMCloseDialog(ctx, owner, tc.name, tc.button, tc.canSuspend)
}()
choice, err := ConfirmVMClose(ctx, owner, tc.name, i18n.ZhCN, "dark", tc.canSuspend)
deadline := ctx.Err()
cancel()
if probeErr := <-result; probeErr != nil || err != nil || choice != tc.want || deadline != nil {
t.Fatalf("%s: choice %v, want %v, dialog error %v, probe error %v, deadline %v", tc.name, choice, tc.want, err, probeErr, deadline)
}
}
}
func runCloseDialogOwner(t *testing.T) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
class, _ := syscall.UTF16PtrFromString("STATIC")
offscreen := int32(-16000)
owner, _, err := user32.NewProc("CreateWindowExW").Call(0x80, uintptr(unsafe.Pointer(class)), 0, 0x80000000,
uintptr(offscreen), uintptr(offscreen), 1280, 720, 0, 0, 0, 0)
if owner == 0 {
t.Fatal(err)
}
defer vcDestroyWindow.Call(owner)
fmt.Fprintln(os.Stdout, owner)
for {
var msg vcMessage
ret, _, _ := procGetMessageW.Call(uintptr(unsafe.Pointer(&msg)), 0, 0, 0)
if int32(ret) <= 0 {
return
}
vcDispatchMsg.Call(uintptr(unsafe.Pointer(&msg)))
}
}
func exerciseVMCloseDialog(ctx context.Context, owner uintptr, name string, button uintptr, canSuspend bool) error {
findWindowW := user32.NewProc("FindWindowW")
title, _ := syscall.UTF16PtrFromString("关闭「" + name + "」?")
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
for ctx.Err() == nil {
hwnd, _, _ := findWindowW.Call(0, uintptr(unsafe.Pointer(title)))
if visible, _, _ := procIsWindowVisible.Call(hwnd); visible != 0 {
actualOwner, _, _ := procGetWindow.Call(hwnd, 4) // GW_OWNER
if actualOwner != owner {
return fmt.Errorf("dialog owner %#x, want %#x", actualOwner, owner)
}
var guest, dialog vcRect
procGetWindowRect.Call(owner, uintptr(unsafe.Pointer(&guest)))
procGetWindowRect.Call(hwnd, uintptr(unsafe.Pointer(&dialog)))
dx := guest.left + guest.right - dialog.left - dialog.right
dy := guest.top + guest.bottom - dialog.top - dialog.bottom
if dx > 1 || dx < -1 || dy > 1 || dy < -1 {
return fmt.Errorf("dialog %+v is not centered over %+v", dialog, guest)
}
suspend, _, _ := vcGetDlgItem.Call(hwnd, vcIDRight)
if enabled, _, _ := vcIsWindowEnabled.Call(suspend); suspend == 0 || (enabled != 0) != canSuspend {
return fmt.Errorf("suspend button availability differs from %t", canSuspend)
}
control, _, _ := vcGetDlgItem.Call(hwnd, button)
if control == 0 {
return fmt.Errorf("missing button %d", button)
}
if button == vcIDCancel {
vcPostMessage.Call(control, 0x0100, 0x1b, 0) // WM_KEYDOWN, VK_ESCAPE
} else {
vcPostMessage.Call(control, 0x00f5, 0, 0) // BM_CLICK
}
return nil
}
select {
case <-ctx.Done():
case <-ticker.C:
}
}
return fmt.Errorf("waiting for confirmation window: %w", ctx.Err())
}
+4 -3
View File
@@ -118,7 +118,8 @@ func hasDisplayClientArea(hwnd uintptr) bool {
(placement.Normal.Bottom-placement.Normal.Top)-(client.Bottom-client.Top) >= 300
}
func findDisplayWindow(pid uint32) uintptr {
// ProcessDisplayWindow finds the VM's display window, preferring the foreground display.
func ProcessDisplayWindow(pid uint32) uintptr {
if pid == 0 {
return 0
}
@@ -149,7 +150,7 @@ func liveWindowPID(hwnd uintptr) uint32 {
// IsProcessWindowFullscreen reports whether the selected display window fills its monitor without a frame.
func IsProcessWindowFullscreen(pid uint32) bool {
fullscreenState.prune(liveWindowPID)
hwnd := findDisplayWindow(pid)
hwnd := ProcessDisplayWindow(pid)
if hwnd == 0 {
return false
}
@@ -176,7 +177,7 @@ func IsProcessWindowFullscreen(pid uint32) bool {
// borderless fullscreen and windowed mode.
func ToggleProcessWindowFullscreen(pid uint32) (bool, error) {
fullscreenState.prune(liveWindowPID)
hwnd := findDisplayWindow(pid)
hwnd := ProcessDisplayWindow(pid)
if hwnd == 0 {
return false, fmt.Errorf("%w for pid %d", ErrDisplayWindowNotFound, pid)
}
+63
View File
@@ -45,11 +45,14 @@ var catalog = map[Locale]map[string]string{
"cli.usage.cmd_version": " version 查看当前版本",
"cli.usage.cmd_vm_compact": " vm compact <name> 停机回收 .qcow2 磁盘未用空间",
"cli.usage.cmd_vm_create": " vm create [options] <name> 创建 macOS 虚拟机(可指定目录/核数/内存/硬盘/显卡)",
"cli.usage.cmd_vm_discard_suspend": " vm discard-suspend <name> 放弃已保存的挂起状态并回到关机状态",
"cli.usage.cmd_vm_list": " vm list 列出已创建的虚拟机",
"cli.usage.cmd_vm_resize": " vm resize <name> <大小> 停机扩容虚拟磁盘(如 256G 或 +64G)",
"cli.usage.cmd_vm_resume": " vm resume <name> 从磁盘挂起状态恢复虚拟机",
"cli.usage.cmd_vm_set": " vm set [options] <name> 修改虚拟机配置(下次启动生效)",
"cli.usage.cmd_vm_start": " vm start <name> 启动虚拟机:交给界面进程(未运行则在托盘拉起),带剪贴板与共享目录;指定 --data-root 时在本进程内启动",
"cli.usage.cmd_vm_stop": " vm stop|eject <name> 停止 / 弹出安装盘",
"cli.usage.cmd_vm_suspend": " vm suspend <name> 挂起运行中的虚拟机至磁盘(退出后或重启宿主可秒级恢复)",
"cli.usage.cmd_vm_type": " vm type <name> [文本] 把文本按美式键盘敲进运行中的虚拟机(不给文本则读标准输入)",
"cli.usage.header": "reims-go - Windows 一站式免编译 reims-vgpu 启动器",
"cli.usage.line_cmd": " reims-go [--lang <BCP-47|auto|en-XA>] [--data-root DIR] <命令> [参数]",
@@ -147,6 +150,14 @@ var catalog = map[Locale]map[string]string{
"err.snapshot.qcow2_only": "恢复点仅支持 .qcow2 格式磁盘",
"err.snapshot.qemu_img_failed": "恢复点操作未完成({snap})",
"err.snapshot.vm_running": "请先停止「{name}」再创建、回滚或删除恢复点",
"err.suspend.action_blocked": "虚拟机「{name}」当前处于挂起状态,请先恢复并关机,或放弃挂起状态后再执行此操作",
"err.suspend.busy": "虚拟机「{name}」正在执行状态切换,请稍后再试",
"err.suspend.discard_running": "虚拟机「{name}」正在运行,无法放弃挂起状态",
"err.suspend.disk_space": "磁盘可用空间不足以保存挂起文件(需要约 {need} GB,当前可用 {avail} GB)",
"err.suspend.incompatible": "虚拟机硬件或运行时版本与挂起时不一致({diffs})。请恢复原配置/运行时,或放弃挂起状态后重新启动",
"err.suspend.not_found": "未找到「{name}」的完整挂起状态文件",
"err.suspend.not_running": "虚拟机「{name}」未在运行,无法挂起",
"err.suspend.unsupported_runtime": "当前激活的便携运行时尚未包含虚拟机挂起/恢复支持,请更新至包含挂起补丁的运行时版本",
"err.update_changed": "已下载的更新文件被改动过,请重新下载",
"err.update_dev_build": "开发版本不支持应用内更新",
"err.update_no_asset": "这个版本没有提供 Windows 程序文件,请到发布页手动下载",
@@ -442,35 +453,45 @@ var catalog = map[Locale]map[string]string{
"toastSSHUserSaved": "已保存 SSH 用户名",
"toastSaved": "已保存",
"toastSavedNextStart": "已保存,下次启动生效",
"tray.menu.discard_suspend": "放弃挂起状态…(&X)",
"tray.menu.force_stop": "强制关机(&F)",
"tray.menu.new_vm": "新建虚拟机(&N)…",
"tray.menu.open_in_app": "在 Reims-Go 中查看(&V)",
"tray.menu.quit": "退出 Reims-Go(&Q)",
"tray.menu.restart": "重启(&R)",
"tray.menu.resume": "恢复(&U)",
"tray.menu.resume_unavailable": "恢复(当前内核不支持挂起)",
"tray.menu.screenshot": "复制屏幕截图(&C)",
"tray.menu.shared_folder": "打开共享文件夹(&H)",
"tray.menu.show": "显示 Reims-Go(&O)",
"tray.menu.show_window": "显示窗口(&W)",
"tray.menu.start": "启动(&S)",
"tray.menu.stop": "关机(&D)",
"tray.menu.suspend": "挂起(&P)",
"tray.menu.toggle_fullscreen": "切换全屏",
"tray.notify.discard_suspend_fail": "无法放弃 {name} 的挂起状态",
"tray.notify.focus_fail": "找不到 {name} 的窗口",
"tray.notify.force_stop_fail": "无法强制关机 {name}",
"tray.notify.fullscreen_fail": "无法切换 {name} 全屏",
"tray.notify.restart_fail": "无法重启 {name}",
"tray.notify.resume_fail": "无法恢复 {name}",
"tray.notify.screenshot_fail": "截图失败:{name}",
"tray.notify.screenshot_ok": "已复制屏幕截图",
"tray.notify.shared_fail": "无法打开共享文件夹",
"tray.notify.start_fail": "无法启动 {name}",
"tray.notify.stop_fail": "无法关机 {name}",
"tray.notify.suspend_fail": "无法挂起 {name}",
"tray.running": "{count, plural, =1 {Reims-Go — 1 台虚拟机运行中} other {Reims-Go — # 台虚拟机运行中}}",
"tray.running.many": "Reims-Go — {count} 台虚拟机运行中",
"tray.running.one": "Reims-Go — 1 台虚拟机运行中",
"tray.state.broken": "配置损坏",
"tray.state.resuming": "正在恢复…",
"tray.state.running": "运行中",
"tray.state.starting": "启动中…",
"tray.state.stopped": "已停止",
"tray.state.stopping": "正在关机…",
"tray.state.suspended": "已挂起",
"tray.state.suspending": "正在挂起…",
"tray.state.unknown": "未知",
"updateCancel": "取消下载",
"updateCapsuleAvailable": "{v} 可用",
@@ -511,6 +532,7 @@ var catalog = map[Locale]map[string]string{
"validate.missing_name": "虚拟机名称不能为空",
"validate.missing_release": "请选择要离线安装的 macOS 版本",
"validate.name_taken": "已存在名为 {name} 的虚拟机",
"validate.vm_suspended": "虚拟机当前处于挂起状态,请先恢复或放弃挂起状态后再修改配置",
"viewLogs": "查看日志",
"vm.already_running": "{name} 已在运行中",
"vm.compact.done": "{name}:磁盘已瘦身 {before, number, .2} GB -> {after, number, .2} GB(回收 {saved, number, .2} GB)",
@@ -527,6 +549,10 @@ var catalog = map[Locale]map[string]string{
"vmstart.pin.non_lpe": "[CPU] 虚拟机配置了 {vcpus} vCPU(超过 {pthreads} 个 P 核线程),已自动将 QEMU (PID {pid}) 绑定到 P+E 核({cores} 核 / {threads} 线程,掩码 {mask};仅排除 {lpe} 个慢速 LP-E 核)",
"vmstart.pin.pcores": "[CPU] 已将 QEMU (PID {pid}) 绑定到 {cores} 个 P 核({threads} 个逻辑线程,掩码 {mask};未占用 {excluded} 个 E 核)",
"vmstart.pin.skipped": "[CPU] 跳过绑核:虚拟机配置了 {vcpus} vCPU,超过可用安全绑定线程上限(P 核仅 {pthreads} 线程),已使用全部核心避免超售卡顿",
"window.close.description": "关机将请求系统关闭。挂起会保存当前会话。",
"window.close.description_no_suspend": "当前运行时不支持挂起。关机将请求系统关闭。",
"window.close.suspend": "挂起",
"window.close.title": "关闭「{name}」?",
},
EnUS: {
"affinity.applied.all": "[CPU] Set QEMU (PID {pid}) affinity to all CPUs ({count} logical CPUs, mask {mask}{eco})",
@@ -570,11 +596,14 @@ var catalog = map[Locale]map[string]string{
"cli.usage.cmd_version": " version Show current version",
"cli.usage.cmd_vm_compact": " vm compact <name> Compact stopped .qcow2 disk to reclaim unused space",
"cli.usage.cmd_vm_create": " vm create [options] <name> Create a macOS VM (custom dir, CPUs, RAM, disk size, GPU)",
"cli.usage.cmd_vm_discard_suspend": " vm discard-suspend <name> Discard a saved suspend state and return the VM to powered off",
"cli.usage.cmd_vm_list": " vm list List virtual machines",
"cli.usage.cmd_vm_resize": " vm resize <name> <size> Expand stopped VM disk (e.g. 256G or +64G)",
"cli.usage.cmd_vm_resume": " vm resume <name> Resume a suspended VM from disk",
"cli.usage.cmd_vm_set": " vm set [options] <name> Update VM settings (applies on next start)",
"cli.usage.cmd_vm_start": " vm start <name> Start a VM in the Reims-Go window process (launched in the tray if needed),\n with clipboard and shared folders; with --data-root it starts in this process",
"cli.usage.cmd_vm_stop": " vm stop|eject <name> Stop / eject installer",
"cli.usage.cmd_vm_suspend": " vm suspend <name> Suspend a running VM to disk for fast resume across restarts",
"cli.usage.cmd_vm_type": " vm type <name> [text] Type text into a running VM as US-keyboard keys (stdin if no text)",
"cli.usage.header": "reims-go - Portable one-stop reims-vgpu launcher for Windows",
"cli.usage.line_cmd": " reims-go [--lang <BCP-47|auto|en-XA>] [--data-root DIR] <command> [args]",
@@ -672,6 +701,14 @@ var catalog = map[Locale]map[string]string{
"err.snapshot.qcow2_only": "Restore points are only supported on .qcow2 disks",
"err.snapshot.qemu_img_failed": "Restore point operation could not finish ({snap})",
"err.snapshot.vm_running": "Stop “{name}” before creating, restoring or deleting a restore point",
"err.suspend.action_blocked": "VM “{name}” is suspended; resume and shut it down or discard its saved state before doing this",
"err.suspend.busy": "VM “{name}” is busy transitioning; try again in a moment",
"err.suspend.discard_running": "VM “{name}” is currently running; suspend state cannot be discarded",
"err.suspend.disk_space": "Not enough free disk space to save the suspend file (need about {need} GB, {avail} GB available)",
"err.suspend.incompatible": "VM hardware or runtime differs from when it was suspended ({diffs}). Restore the previous configuration/runtime or discard the saved state",
"err.suspend.not_found": "No complete suspend state found for “{name}”",
"err.suspend.not_running": "VM “{name}” is not running and cannot be suspended",
"err.suspend.unsupported_runtime": "The active portable runtime does not support VM suspend/resume; update to a runtime built with suspend support",
"err.update_changed": "The downloaded update changed on disk; download it again",
"err.update_dev_build": "In-app update is disabled in development builds",
"err.update_no_asset": "This release has no Windows executable; download it from the release page",
@@ -967,35 +1004,45 @@ var catalog = map[Locale]map[string]string{
"toastSSHUserSaved": "Saved SSH username",
"toastSaved": "Saved",
"toastSavedNextStart": "Saved — applies on next start",
"tray.menu.discard_suspend": "Discard Saved Stat&e…",
"tray.menu.force_stop": "&Force Shut Down",
"tray.menu.new_vm": "&New Virtual Machine…",
"tray.menu.open_in_app": "Show in &Reims-Go",
"tray.menu.quit": "&Quit Reims-Go",
"tray.menu.restart": "&Restart",
"tray.menu.resume": "Res&ume",
"tray.menu.resume_unavailable": "Resume (runtime lacks suspend support)",
"tray.menu.screenshot": "&Copy Screenshot",
"tray.menu.shared_folder": "Open S&hared Folder",
"tray.menu.show": "&Show Reims-Go",
"tray.menu.show_window": "Show &Window",
"tray.menu.start": "&Start",
"tray.menu.stop": "Shut &Down",
"tray.menu.suspend": "Sus&pend",
"tray.menu.toggle_fullscreen": "Toggle full screen",
"tray.notify.discard_suspend_fail": "Couldn't discard saved state for {name}",
"tray.notify.focus_fail": "Couldn't find the window of {name}",
"tray.notify.force_stop_fail": "Couldn't force shut down {name}",
"tray.notify.fullscreen_fail": "Couldn’t toggle full screen for {name}",
"tray.notify.restart_fail": "Couldn't restart {name}",
"tray.notify.resume_fail": "Couldn't resume {name}",
"tray.notify.screenshot_fail": "Screenshot failed: {name}",
"tray.notify.screenshot_ok": "Screenshot copied",
"tray.notify.shared_fail": "Couldn't open the shared folder",
"tray.notify.start_fail": "Couldn't start {name}",
"tray.notify.stop_fail": "Couldn't shut down {name}",
"tray.notify.suspend_fail": "Couldn't suspend {name}",
"tray.running": "{count, plural, one {Reims-Go — # VM running} other {Reims-Go — # VMs running}}",
"tray.running.many": "Reims-Go — {count} VMs running",
"tray.running.one": "Reims-Go — 1 VM running",
"tray.state.broken": "Broken",
"tray.state.resuming": "Resuming…",
"tray.state.running": "Running",
"tray.state.starting": "Starting…",
"tray.state.stopped": "Stopped",
"tray.state.stopping": "Shutting down…",
"tray.state.suspended": "Suspended",
"tray.state.suspending": "Suspending…",
"tray.state.unknown": "Unknown",
"updateCancel": "Cancel download",
"updateCapsuleAvailable": "{v} available",
@@ -1036,6 +1083,7 @@ var catalog = map[Locale]map[string]string{
"validate.missing_name": "VM name is required",
"validate.missing_release": "Choose the macOS release to install offline",
"validate.name_taken": "A VM named {name} already exists",
"validate.vm_suspended": "Resume or discard the VM's suspended state before changing its settings",
"viewLogs": "View logs",
"vm.already_running": "{name} is already running",
"vm.compact.done": "{name}: compacted disk {before, number, .2} GB -> {after, number, .2} GB (reclaimed {saved, number, .2} GB)",
@@ -1052,6 +1100,10 @@ var catalog = map[Locale]map[string]string{
"vmstart.pin.non_lpe": "[CPU] VM has {vcpus} vCPUs (exceeds {pthreads} P-core threads); pinned QEMU (PID {pid}) to P+E cores ({cores} cores / {threads} logical CPUs, mask {mask}; {lpe} slow LP-E cores excluded)",
"vmstart.pin.pcores": "[CPU] Pinned QEMU (PID {pid}) to {cores} P-cores ({threads} logical CPUs, mask {mask}; {excluded} E/LP-E cores excluded)",
"vmstart.pin.skipped": "[CPU] Skipped CPU pinning: VM has {vcpus} vCPUs, exceeding safe headroom (only {pthreads} P-core threads); using all host CPUs to avoid spinlock stall",
"window.close.description": "Shut down asks macOS to shut down. Suspend saves the session.",
"window.close.description_no_suspend": "The current runtime does not support suspend. Shut down asks macOS to shut down.",
"window.close.suspend": "Suspend",
"window.close.title": "Close “{name}”?",
},
}
@@ -1104,6 +1156,13 @@ var paramOrder = map[string][]string{
"err.plugin.system_locked": {"id"},
"err.snapshot.qemu_img_failed": {"snap"},
"err.snapshot.vm_running": {"name"},
"err.suspend.action_blocked": {"name"},
"err.suspend.busy": {"name"},
"err.suspend.discard_running": {"name"},
"err.suspend.disk_space": {"need", "avail"},
"err.suspend.incompatible": {"diffs"},
"err.suspend.not_found": {"name"},
"err.suspend.not_running": {"name"},
"err.update_not_writable": {"dir"},
"err.vm_not_running": {"name"},
"err.vm_window_not_found": {"name"},
@@ -1175,13 +1234,16 @@ var paramOrder = map[string][]string{
"toastInstallerReady": {"v"},
"toastRuntimeReady": {"v"},
"toastSSHConfigWritten": {"alias"},
"tray.notify.discard_suspend_fail": {"name"},
"tray.notify.focus_fail": {"name"},
"tray.notify.force_stop_fail": {"name"},
"tray.notify.fullscreen_fail": {"name"},
"tray.notify.restart_fail": {"name"},
"tray.notify.resume_fail": {"name"},
"tray.notify.screenshot_fail": {"name"},
"tray.notify.start_fail": {"name"},
"tray.notify.stop_fail": {"name"},
"tray.notify.suspend_fail": {"name"},
"tray.running": {"count"},
"tray.running.many": {"count"},
"updateCapsuleAvailable": {"v"},
@@ -1209,4 +1271,5 @@ var paramOrder = map[string][]string{
"vmstart.pin.non_lpe": {"vcpus", "pthreads", "pid", "cores", "threads", "mask", "lpe"},
"vmstart.pin.pcores": {"pid", "cores", "threads", "mask", "excluded"},
"vmstart.pin.skipped": {"vcpus", "pthreads"},
"window.close.title": {"name"},
}
+62
View File
@@ -151,3 +151,65 @@ func (s *Service) Stop(ctx context.Context, ref driver.VMRef, force bool, stdout
}
return nil
}
func (s *Service) Suspend(ctx context.Context, ref driver.VMRef, progress func(driver.SuspendProgress), stdout, stderr io.Writer) (driver.SuspendResult, error) {
d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name)
if err != nil {
return driver.SuspendResult{}, err
}
sd, ok := d.(driver.SuspendDriver)
if !ok {
return driver.SuspendResult{}, fmt.Errorf("driver %q does not support suspend", d.ID())
}
ref = vm.Ref()
ev := plugin.VMEventPayload{VMName: ref.Name, VMDir: vm.Directory, DriverID: ref.DriverID}
if s.reg != nil {
s.reg.Hooks().DispatchObserve(plugin.EventVMBeforeStop, ev)
}
res, err := sd.Suspend(ctx, driver.SuspendRequest{Ref: ref, Progress: progress, Stdout: stdout, Stderr: stderr})
if err != nil {
return driver.SuspendResult{}, err
}
if s.reg != nil {
s.reg.Hooks().DispatchObserve(plugin.EventVMAfterStop, ev)
}
return res, nil
}
func (s *Service) Resume(ctx context.Context, ref driver.VMRef, extraEnv []string, stdout, stderr io.Writer) (driver.StartResult, error) {
d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name)
if err != nil {
return driver.StartResult{}, err
}
sd, ok := d.(driver.SuspendDriver)
if !ok {
return driver.StartResult{}, fmt.Errorf("driver %q does not support resume", d.ID())
}
ref = vm.Ref()
result, err := sd.Resume(ctx, driver.ResumeRequest{Ref: ref, ExtraEnv: extraEnv, Stdout: stdout, Stderr: stderr})
if err != nil {
return driver.StartResult{}, err
}
if s.reg != nil {
ev := plugin.VMEventPayload{VMName: ref.Name, VMDir: vm.Directory, DriverID: ref.DriverID}
for _, action := range result.PostStart {
if action.Kind == "qmp.watch_cold_reboot" {
ev.QMPAddr, _ = action.Params["qmp_addr"].(string)
}
}
s.reg.Hooks().DispatchObserve(plugin.EventVMAfterStart, ev)
}
return result, nil
}
func (s *Service) DiscardSuspend(ctx context.Context, ref driver.VMRef) error {
d, vm, err := s.Resolve(ctx, ref.DriverID, ref.Name)
if err != nil {
return err
}
sd, ok := d.(driver.SuspendDriver)
if !ok {
return fmt.Errorf("driver %q does not support suspend", d.ID())
}
return sd.DiscardSuspend(ctx, vm.Name)
}
+102 -4
View File
@@ -7,16 +7,19 @@ import (
"path/filepath"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/plugin"
)
type testDriver struct {
id string
vms []driver.VMInfo
starts, stops, sets int
storageCalls []string
id string
vms []driver.VMInfo
starts, stops, sets int
suspends, resumes, discardSuspends int
lastResumeEnv []string
storageCalls []string
}
func (d *testDriver) ID() string { return d.id }
@@ -58,6 +61,30 @@ func (d *testDriver) Stop(context.Context, string, bool, io.Writer, io.Writer) e
}
func (d *testDriver) Delete(context.Context, string, bool, io.Writer, io.Writer) error { return nil }
func (d *testDriver) Suspend(_ context.Context, req driver.SuspendRequest) (driver.SuspendResult, error) {
d.suspends++
if req.Progress != nil {
req.Progress(driver.SuspendProgress{Status: "completed", Total: 100})
}
return driver.SuspendResult{VMStateSize: 1024}, nil
}
func (d *testDriver) Resume(_ context.Context, req driver.ResumeRequest) (driver.StartResult, error) {
d.resumes++
d.lastResumeEnv = append([]string(nil), req.ExtraEnv...)
return driver.StartResult{
PostStart: []plugin.PostStartAction{{
Kind: "qmp.watch_cold_reboot",
Params: map[string]any{"qmp_addr": "unix:/tmp/reboot.sock"},
}},
}, nil
}
func (d *testDriver) DiscardSuspend(_ context.Context, _ string) error {
d.discardSuspends++
return nil
}
func (d *testDriver) InvokeAction(_ context.Context, _ string, action string, _ map[string]any) (any, error) {
return action, nil
}
@@ -155,3 +182,74 @@ func TestVetoLeavesVMFilesUntouched(t *testing.T) {
}
}
}
func TestSuspendResumeDiscardRouting(t *testing.T) {
reg := plugin.NewRegistry(nil)
drv := &testDriver{id: "test.driver.macos", vms: []driver.VMInfo{{Name: "mac", DriverID: "test.driver.macos", Directory: t.TempDir(), State: "running"}}}
registerTestDriver(t, reg, drv)
type obs struct {
ev string
qmp string
}
obsCh := make(chan obs, 4)
if err := reg.Register(plugin.PluginDef{
Manifest: plugin.Manifest{ID: "vendor.observer", Version: "1.0.0"}, Desired: true,
Activate: func(_ context.Context, sc *plugin.Scope) error {
for _, ev := range []string{plugin.EventVMBeforeStop, plugin.EventVMAfterStop, plugin.EventVMAfterStart} {
evName := ev
sc.Registry().Hooks().Subscribe(sc, plugin.HookRegistration{Event: evName, Handler: func(_ context.Context, payload any) (any, error) {
var qmpAddr string
if p, ok := payload.(plugin.VMEventPayload); ok {
qmpAddr = p.QMPAddr
}
obsCh <- obs{ev: evName, qmp: qmpAddr}
return nil, nil
}})
}
return nil
},
}); err != nil {
t.Fatal(err)
}
reg.Reconcile(context.Background())
svc := New(reg, driver.NewRouter(reg, nil), nil)
ref := driver.NewVMRef(drv.id, "mac")
gotProgress := false
res, err := svc.Suspend(context.Background(), ref, func(p driver.SuspendProgress) {
if p.Status == "completed" {
gotProgress = true
}
}, io.Discard, io.Discard)
if err != nil || res.VMStateSize != 1024 || !gotProgress || drv.suspends != 1 {
t.Fatalf("Suspend = %+v, err=%v, progress=%t, count=%d", res, err, gotProgress, drv.suspends)
}
startRes, err := svc.Resume(context.Background(), ref, []string{"K=V"}, io.Discard, io.Discard)
if err != nil || len(startRes.PostStart) != 1 || drv.resumes != 1 || len(drv.lastResumeEnv) != 1 || drv.lastResumeEnv[0] != "K=V" {
t.Fatalf("Resume = %+v, err=%v, count=%d, env=%v", startRes, err, drv.resumes, drv.lastResumeEnv)
}
if err := svc.DiscardSuspend(context.Background(), ref); err != nil || drv.discardSuspends != 1 {
t.Fatalf("DiscardSuspend err=%v, count=%d", err, drv.discardSuspends)
}
seen := map[string]bool{}
var seenQMP string
deadline := time.After(2 * time.Second)
for len(seen) < 3 {
select {
case o := <-obsCh:
seen[o.ev] = true
if o.qmp != "" {
seenQMP = o.qmp
}
case <-deadline:
t.Fatalf("timed out waiting for observe events: got %v", seen)
}
}
if !seen[plugin.EventVMBeforeStop] || !seen[plugin.EventVMAfterStop] || !seen[plugin.EventVMAfterStart] || seenQMP != "unix:/tmp/reboot.sock" {
t.Fatalf("events=%v qmp=%q", seen, seenQMP)
}
}
@@ -572,7 +572,7 @@ func stylePanel(hwnd, flags uintptr) {
roundPanel(hwnd)
}
for _, id := range []uintptr{idFold, idLeft, idRight, idExtra, idJump} {
for _, id := range []uintptr{idFold, idLeft, idRight, idExtra, idJump, idCancel} {
if ctrl, _, _ := getDlgItem.Call(hwnd, id); ctrl != 0 {
setWindowSubclass.Call(ctrl, btnSubclassProc, id, 0)
}
@@ -785,6 +785,7 @@ func layoutPanel(hwnd uintptr) {
leftCtrl, _, _ := getDlgItem.Call(hwnd, idLeft)
extraCtrl, _, _ := getDlgItem.Call(hwnd, idExtra)
rightCtrl, _, _ := getDlgItem.Call(hwnd, idRight)
cancelCtrl, _, _ := getDlgItem.Call(hwnd, idCancel)
jumpCtrl, _, _ := getDlgItem.Call(hwnd, idJump)
// Adaptively widen cardW up to maxCardW when single-line controls (footer strip,
@@ -911,6 +912,27 @@ func layoutPanel(hwnd uintptr) {
if extraCtrl != 0 {
needInline += extraW + gap
}
if cancelCtrl != 0 {
setCtrlFont(cancelCtrl, fonts.btn)
cancelW := min(innerW, max(dp(dpi, 60), measureLineWidth(dc, fonts.btn, controlText(cancelCtrl))+btnPadX*2))
y += dp(dpi, 16)
if leftW+rightW+cancelW+gap*2 <= innerW {
x := cardW - padX - cancelW
moveControl(cancelCtrl, x, y, cancelW, btnH)
x -= gap + rightW
moveControl(rightCtrl, x, y, rightW, btnH)
moveControl(leftCtrl, x-gap-leftW, y, leftW, btnH)
y += btnH
} else {
for _, ctrl := range []uintptr{leftCtrl, rightCtrl, cancelCtrl} {
moveControl(ctrl, padX, y, innerW, btnH)
y += btnH + gap
}
y -= gap
}
setWindowPos.Call(hwnd, 0, 0, 0, uintptr(cardW), uintptr(y+dp(dpi, 16)), 0x16)
return
}
if extraCtrl != 0 && needInline > innerW {
st.extraStacked = true
setCtrlFont(extraCtrl, fonts.smallMed)
@@ -1187,6 +1209,11 @@ func paintItem(it *drawItem) {
flags = 0x8824
case idRight:
selectGDI.Call(dc, fonts.btnBold)
if it.state&0x0004 != 0 { // ODS_DISABLED
paintRoundedBox(dc, r, btnR, pal.surface, pal.btnFill, pal.btnBorder, true, rgb{}, false)
fg = pal.text3
break
}
fill := pal.accent
if pressed {
fill = pal.accentPress
@@ -1195,7 +1222,7 @@ func paintItem(it *drawItem) {
}
paintRoundedBox(dc, r, btnR, pal.surface, fill, rgb{}, false, pal.accentHighlight, !pressed)
fg = rgb{255, 255, 255}
case idLeft:
case idLeft, idCancel:
selectGDI.Call(dc, fonts.btn)
fill := pal.btnFill
if pressed {
@@ -19,6 +19,7 @@ const (
idRight = 112
idExtra = 113
idJump = 114
idCancel = 2 // IDCANCEL, including Escape in the dialog message loop.
wmAction = 0x8001
)
@@ -50,6 +51,9 @@ func dialogTemplate(p page, c content, locale i18n.Locale) []uint16 {
if class == button {
style |= 1 // WS_TABSTOP
controlStyle = 0x0b // BS_OWNERDRAW
if id == idRight && c.disableRight {
style |= 0x0800 // WS_DISABLED
}
} else {
controlStyle = 0x0d // SS_OWNERDRAW
}
@@ -89,6 +93,9 @@ func dialogTemplate(p page, c content, locale i18n.Locale) []uint16 {
if c.right != "" {
item(button, idRight, c.right)
}
if c.cancel != "" {
item(button, idCancel, c.cancel)
}
if c.jump != "" {
item(button, idJump, c.jump)
}
@@ -127,12 +134,12 @@ var dialogProc = syscall.NewCallback(func(hwnd, msg, wp, lp uintptr) uintptr {
}
case 0x0111: // WM_COMMAND
id := wp & 0xffff
if wp>>16 == 0 && (id == idFold || id == idLeft || id == idRight || id == idExtra || id == idJump || id == 2) {
if wp>>16 == 0 && (id == idFold || id == idLeft || id == idRight || id == idExtra || id == idJump || id == idCancel) {
postMessage.Call(hwnd, wmAction, id, 0)
return 1
}
case 0x0010: // WM_CLOSE: leave a way to reopen the guide.
postMessage.Call(hwnd, wmAction, 2, 0)
postMessage.Call(hwnd, wmAction, idCancel, 0)
return 1
case 0x0082: // WM_NCDESTROY
cleanupPanelState(hwnd)
+17 -15
View File
@@ -94,21 +94,23 @@ const (
)
type content struct {
stage string
stageTone tone
title string
body string
code string
left string
right string
extra string
jump string
fold string
inputHint string
prev page
next page
alt page
isConfirm bool
stage string
stageTone tone
title string
body string
code string
left string
right string
extra string
jump string
fold string
inputHint string
prev page
next page
alt page
isConfirm bool
cancel string
disableRight bool
}
func (g Guide) preferences() (i18n.Locale, Theme) {
+5 -1
View File
@@ -6,6 +6,8 @@ import (
"os"
"path/filepath"
"strings"
"github.com/Nwflower/reims-go/internal/config"
)
const progressFile = ".reims-go-install-guide.json"
@@ -55,7 +57,9 @@ func (g *Guide) Resume(dir, media string, recovery bool) bool {
return recovery
}
if recovery {
if cp.Kind == g.Kind && strings.EqualFold(cp.Media, media) && cp.Step.recoveryStep(g.Kind) {
// Older checkpoints may contain the abbreviated installer path from show.
sameMedia := strings.EqualFold(config.ExpandHomePath(cp.Media), media)
if cp.Kind == g.Kind && sameMedia && cp.Step.recoveryStep(g.Kind) {
g.initial = cp.Step
}
return true
@@ -2,6 +2,7 @@ package installguide
import (
"errors"
"path/filepath"
"testing"
"time"
)
@@ -148,3 +149,17 @@ func TestGuideKeepsMediaAndVMProgressSeparate(t *testing.T) {
t.Fatal("clone inherited source disk preparation")
}
}
func TestGuideResumesWithExpandedInstallerPath(t *testing.T) {
home := t.TempDir()
t.Setenv("USERPROFILE", home)
dir := t.TempDir()
g := Guide{Name: "macos-15", Kind: Offline, PID: 33}
g.Resume(dir, `~\macOS-15-offline-installer.img`, true)
if err := g.save(command, 0); err != nil {
t.Fatal(err)
}
if !g.Resume(dir, filepath.Join(home, "macOS-15-offline-installer.img"), true) || g.initial != command {
t.Fatalf("guide resumed at %s, want %s", g.initial, command)
}
}
+6 -1
View File
@@ -10,6 +10,7 @@ import (
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
rt "github.com/Nwflower/reims-go/internal/runtime"
@@ -47,13 +48,17 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
if strings.EqualFold(sourceName, cloneName) {
return fmt.Errorf("clone name must differ from source")
}
src, err := c.Show(ctx, sourceName)
src, release, err := startprep.LockVM(ctx, c, sourceName)
if err != nil {
return err
}
defer release()
if vmRunning(ctx, c, sourceName, src) {
return fmt.Errorf("stop %s before cloning it", sourceName)
}
if reims.HasSuspendState(src.Directory) {
return i18n.NewCodedError(c.Locale, "E_VM_CLONE_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": sourceName}, nil)
}
if src.HasInstaller {
return fmt.Errorf("exit recovery mode before cloning %s", sourceName)
}
+30 -7
View File
@@ -93,7 +93,7 @@ func (d *ReimsMacOSDriver) startClient() (*reims.Client, rt.Installed, error) {
}
func (d *ReimsMacOSDriver) List(ctx context.Context) ([]driver.VMInfo, error) {
c, err := d.client()
c, active, err := d.startClient()
if err != nil {
return nil, err
}
@@ -101,23 +101,28 @@ func (d *ReimsMacOSDriver) List(ctx context.Context) ([]driver.VMInfo, error) {
if err != nil {
return nil, err
}
caps := d.vmCapabilities(active, "")
out := make([]driver.VMInfo, 0, len(items))
for _, it := range items {
state := it.State
if state == "stopped" && reims.HasSuspendState(it.Dir) {
state = "suspended"
}
out = append(out, driver.VMInfo{
Name: it.Name,
DriverID: d.ID(),
Directory: it.Dir,
DriverName: "macOS (Reims vGPU)",
State: it.State,
State: state,
PID: it.PID,
Capabilities: d.Capabilities(),
Capabilities: append([]string(nil), caps...),
})
}
return out, nil
}
func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (driver.VMInfo, error) {
c, err := d.client()
c, active, err := d.startClient()
if err != nil {
return driver.VMInfo{}, err
}
@@ -125,6 +130,7 @@ func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (driver.VMInfo
if err != nil {
return driver.VMInfo{}, err
}
enrichSuspendDetail(&det)
rawBytes, _ := json.Marshal(det)
var data map[string]any
_ = json.Unmarshal(rawBytes, &data)
@@ -140,7 +146,7 @@ func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (driver.VMInfo
Directory: det.Directory,
Network: det.Network,
SSHPort: det.SSHPort,
Capabilities: d.Capabilities(),
Capabilities: d.vmCapabilities(active, det.Kind),
DriverData: data,
}, nil
}
@@ -227,10 +233,11 @@ func (d *ReimsMacOSDriver) Set(ctx context.Context, req driver.SetRequest, stdou
return err
}
opts.Name = req.Name
cur, err := c.Show(ctx, req.Name)
cur, release, err := startprep.LockMutableVM(ctx, c, req.Name)
if err != nil {
return err
}
defer release()
if reims.HasCtlSetChanges(opts) {
if err := c.Set(ctx, opts, stdout, stderr); err != nil {
return err
@@ -259,6 +266,11 @@ func (d *ReimsMacOSDriver) Stop(ctx context.Context, name string, force bool, st
if err != nil {
return err
}
release, err := startprep.LockVMForStop(ctx, c, name, force)
if err != nil {
return err
}
defer release()
if force {
return c.StopForce(ctx, name, stdout, stderr)
}
@@ -280,22 +292,33 @@ func (d *ReimsMacOSDriver) InvokeAction(ctx context.Context, vmName, action stri
}
switch action {
case "eject":
_, release, err := startprep.LockMutableVM(ctx, c, vmName)
if err != nil {
return nil, err
}
defer release()
return nil, c.Eject(ctx, vmName, io.Discard, io.Discard)
case "insert":
path, _ := params["path"].(string)
if path == "" {
return nil, fmt.Errorf("insert requires a non-empty path")
}
_, release, err := startprep.LockMutableVM(ctx, c, vmName)
if err != nil {
return nil, err
}
defer release()
return nil, c.Insert(ctx, vmName, path, io.Discard, io.Discard)
case "enter_recovery":
return d.enterRecovery(ctx, vmName)
case "finish_install":
return d.finishInstall(ctx, vmName)
case "upgrade_nvme":
det, err := c.Show(ctx, vmName)
det, release, err := startprep.LockMutableVM(ctx, c, vmName)
if err != nil {
return nil, err
}
defer release()
if det.HasInstaller {
return nil, fmt.Errorf("exit recovery mode before switching disk controller")
}
+15 -1
View File
@@ -53,10 +53,20 @@ func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (
if err != nil {
return driver.StartResult{}, err
}
cur, err := c.Show(ctx, ref.Name)
cur, release, err := startprep.LockVM(ctx, c, ref.Name)
if err != nil {
return driver.StartResult{}, err
}
defer release()
if cur.State == "stopped" && reims.HasSuspendState(cur.Directory) {
var intentEnv []string
for _, in := range req.Intents {
for k, v := range in.Env {
intentEnv = append(intentEnv, k+"="+v)
}
}
return d.resumeLocked(ctx, c, active, cur, intentEnv, stdout, stderr)
}
cfg := d.getConfig()
if cur.State == "running" {
return driver.StartResult{}, errors.New(i18n.T(cfg.Locale, "vm.already_running", ref.Name))
@@ -96,6 +106,9 @@ func (d *ReimsMacOSDriver) Start(ctx context.Context, req driver.StartRequest) (
if active.Manifest.HasCapability("display-fixed-mode") && host.ShouldUseFixedGuestMode(cur.Borderless, cur.Resolution, rep.PrimaryDisplay) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
if active.Manifest.HasCapability("client-window-close") {
c.Env = append(c.Env, vmstart.CloseRequestEnv(ref.Name)...)
}
if reconciled.Changed {
if err := c.Set(ctx, reims.SetOpts{Name: ref.Name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil {
return driver.StartResult{}, fmt.Errorf("apply reconciled start arguments: %w", err)
@@ -221,5 +234,6 @@ func stripLegacyManagedExtraArgs(extraArgs string) string {
s := reims.StripGuestToolsArgs(extraArgs)
s = reims.StripOfflineHelperArgs(s)
s = qmp.StripLegacyWin10RebootArgs(s)
s = reims.StripIncomingDeferArgs(s)
return strings.TrimSpace(s)
}
+4 -2
View File
@@ -15,10 +15,11 @@ func (d *ReimsMacOSDriver) enterRecovery(ctx context.Context, name string) (map[
if err != nil {
return nil, err
}
det, err := c.Show(ctx, name)
det, release, err := startprep.LockMutableVM(ctx, c, name)
if err != nil {
return nil, err
}
defer release()
running := det.State == "running"
if running {
scheduled := startprep.ReadRecoveryMarker(det.Directory) != "on"
@@ -42,10 +43,11 @@ func (d *ReimsMacOSDriver) finishInstall(ctx context.Context, name string) (map[
if err != nil {
return nil, err
}
det, err := c.Show(ctx, name)
det, release, err := startprep.LockMutableVM(ctx, c, name)
if err != nil {
return nil, err
}
defer release()
if det.HasInstaller {
if err := c.Eject(ctx, name, io.Discard, io.Discard); err != nil {
return nil, err
+17 -3
View File
@@ -9,7 +9,9 @@ import (
"strings"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
@@ -88,13 +90,17 @@ func (d *ReimsMacOSDriver) RunSnapshot(ctx context.Context, name, operation, sna
if err != nil {
return err
}
det, err := c.Show(ctx, name)
det, release, err := startprep.LockVM(ctx, c, name)
if err != nil {
return err
}
defer release()
if vmRunning(ctx, c, name, det) {
return fmt.Errorf("stop %s before changing restore points", name)
}
if reims.HasSuspendState(det.Directory) {
return i18n.NewCodedError(c.Locale, "E_SNAPSHOT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
diskPath := resolveVMDiskPath(det)
if diskPath == "" {
return fmt.Errorf("VM %s has no disk path", name)
@@ -111,13 +117,17 @@ func (d *ReimsMacOSDriver) ResizeDisk(ctx context.Context, name, newSize string,
if err != nil {
return driver.DiskResizeResult{}, err
}
det, err := c.Show(ctx, name)
det, release, err := startprep.LockVM(ctx, c, name)
if err != nil {
return driver.DiskResizeResult{}, err
}
defer release()
if vmRunning(ctx, c, name, det) {
return driver.DiskResizeResult{}, fmt.Errorf("stop %s before resizing its disk", name)
}
if reims.HasSuspendState(det.Directory) {
return driver.DiskResizeResult{}, i18n.NewCodedError(c.Locale, "E_RESIZE_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
diskPath := resolveVMDiskPath(det)
if diskPath == "" {
return driver.DiskResizeResult{}, fmt.Errorf("VM %s has no disk path", name)
@@ -135,13 +145,17 @@ func (d *ReimsMacOSDriver) CompactDisk(ctx context.Context, name string, stdout,
if err != nil {
return driver.DiskCompactResult{}, err
}
det, err := c.Show(ctx, name)
det, release, err := startprep.LockVM(ctx, c, name)
if err != nil {
return driver.DiskCompactResult{}, err
}
defer release()
if vmRunning(ctx, c, name, det) {
return driver.DiskCompactResult{}, fmt.Errorf("stop %s before reclaiming disk space", name)
}
if reims.HasSuspendState(det.Directory) {
return driver.DiskCompactResult{}, i18n.NewCodedError(c.Locale, "E_COMPACT_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
diskPath := resolveVMDiskPath(det)
if diskPath == "" {
return driver.DiskCompactResult{}, fmt.Errorf("VM %s has no disk path", name)
+151
View File
@@ -0,0 +1,151 @@
package macosdriver
import (
"context"
"fmt"
"io"
"os"
"strings"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/macos/startprep"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/internal/qmp"
rt "github.com/Nwflower/reims-go/internal/runtime"
"github.com/Nwflower/reims-go/internal/vmstart"
)
var _ driver.SuspendDriver = (*ReimsMacOSDriver)(nil)
func (d *ReimsMacOSDriver) vmCapabilities(active rt.Installed, kind string) []string {
caps := d.Capabilities()
low := strings.ToLower(kind)
if active.Manifest.HasCapability("vm-suspend") && !strings.Contains(low, "arm64") && !strings.Contains(low, "aarch64") {
caps = append(caps, driver.CapSuspend)
}
return caps
}
func enrichSuspendDetail(det *reims.VMDetail) {
if det != nil && det.State == "stopped" && reims.HasSuspendState(det.Directory) {
det.State = "suspended"
if info, err := reims.ReadSuspendInfo(det.Directory); err == nil {
det.SuspendInfo = info
}
}
}
func (d *ReimsMacOSDriver) Suspend(ctx context.Context, req driver.SuspendRequest) (driver.SuspendResult, error) {
c, active, err := d.startClient()
if err != nil {
return driver.SuspendResult{}, err
}
cur, release, err := startprep.LockVM(ctx, c, req.Ref.Name)
if err != nil {
return driver.SuspendResult{}, err
}
defer release()
stdout := req.Stdout
if stdout == nil {
stdout = io.Discard
}
prep, err := startprep.New(d.getConfig(), func(line string) { startLog(stdout, line) })
if err != nil {
return driver.SuspendResult{}, err
}
prep.Client, prep.Runtime = c, active
var prog func(qmp.MigrateProgress)
if req.Progress != nil {
prog = func(p qmp.MigrateProgress) {
req.Progress(driver.SuspendProgress{
Status: p.Status,
Transferred: p.Transferred,
Remaining: p.Remaining,
Total: p.Total,
})
}
}
info, err := prep.SuspendSnapshot(ctx, cur, prog)
if err != nil {
return driver.SuspendResult{}, err
}
return driver.SuspendResult{
VMStateSize: info.VMStateSize,
SavedAt: info.CreatedAt,
}, nil
}
func (d *ReimsMacOSDriver) Resume(ctx context.Context, req driver.ResumeRequest) (driver.StartResult, error) {
c, active, err := d.startClient()
if err != nil {
return driver.StartResult{}, err
}
cur, release, err := startprep.LockVM(ctx, c, req.Ref.Name)
if err != nil {
return driver.StartResult{}, err
}
defer release()
return d.resumeLocked(ctx, c, active, cur, req.ExtraEnv, req.Stdout, req.Stderr)
}
func (d *ReimsMacOSDriver) resumeLocked(ctx context.Context, c *reims.Client, active rt.Installed, cur reims.VMDetail, extraEnv []string, stdout, stderr io.Writer) (driver.StartResult, error) {
if stdout == nil {
stdout = io.Discard
}
if stderr == nil {
stderr = io.Discard
}
cfg := d.getConfig()
rep := host.Inspect(cfg.DataRoot)
var qmpAddr string
if cur.State == "stopped" && reims.HasSuspendState(cur.Directory) && rep.NeedsColdRebootWorkaround {
sockPath := qmp.RebootSocketPath(cur.Directory, cfg.TempDir(), cur.Name)
if qmp.HasWin10RebootUnixArgs(cur.ExtraArgs, sockPath) {
if err := os.Remove(sockPath); err != nil && !os.IsNotExist(err) {
return driver.StartResult{}, fmt.Errorf("remove stale reboot socket: %w", err)
}
qmpAddr = "unix:" + sockPath
}
}
if len(extraEnv) > 0 {
c.Env = append(c.Env, extraEnv...)
}
if active.Manifest.HasCapability("display-fixed-mode") && host.ShouldUseFixedGuestMode(cur.Borderless, cur.Resolution, rep.PrimaryDisplay) {
c.Env = append(c.Env, "REIMS_VGPU_WINDOW_FIXED_MODE=1")
}
if active.Manifest.HasCapability("client-window-close") {
c.Env = append(c.Env, vmstart.CloseRequestEnv(cur.Name)...)
}
prep, err := startprep.New(cfg, func(line string) { startLog(stdout, line) })
if err != nil {
return driver.StartResult{}, err
}
prep.Client, prep.Runtime = c, active
if err := prep.ResumeSnapshot(ctx, cur, rep, stdout, stderr); err != nil {
return driver.StartResult{}, err
}
var res driver.StartResult
if qmpAddr != "" {
res.PostStart = append(res.PostStart, plugin.PostStartAction{
PluginID: d.opts.OwnerID,
Kind: "qmp.watch_cold_reboot",
Params: map[string]any{"qmp_addr": qmpAddr},
})
}
return res, nil
}
func (d *ReimsMacOSDriver) DiscardSuspend(ctx context.Context, name string) error {
c, err := d.client()
if err != nil {
return err
}
cur, release, err := startprep.LockVM(ctx, c, name)
if err != nil {
return err
}
defer release()
return startprep.DiscardSnapshot(c.Locale, cur)
}
+10 -4
View File
@@ -84,8 +84,9 @@ type VMDetail struct {
GuestToolsAgentVersion int `json:"guest_tools_agent_version,omitempty"`
// GuestToolsDisabled is set when the Guest Tools plugin is switched off.
GuestToolsDisabled bool `json:"guest_tools_disabled,omitempty"`
SharedDir string `json:"shared_dir,omitempty"`
GuestLang string `json:"guest_lang,omitempty"`
SharedDir string `json:"shared_dir,omitempty"`
GuestLang string `json:"guest_lang,omitempty"`
SuspendInfo *SuspendInfo `json:"suspend_info,omitempty"`
}
type ValidationIssue struct {
@@ -254,6 +255,10 @@ func ValidateSetLocalized(o SetOpts, current VMDetail, rep host.Report, loc i18n
if strings.TrimSpace(o.Name) == "" {
issues = append(issues, ValidationIssue{Field: "name", Code: "missing_name", Message: i18n.T(loc, "validate.missing_name")})
}
if current.State == "suspended" {
issues = append(issues, ValidationIssue{Field: "state", Code: "vm_suspended", Message: i18n.T(loc, "validate.vm_suspended")})
return issues
}
if o.CPUs != 0 && (o.CPUs < 1 || (rep.LogicalCPUs > 0 && o.CPUs > rep.LogicalCPUs)) {
issues = append(issues, ValidationIssue{Field: "cpus", Code: "invalid_cpus", Message: i18n.T(loc, "validate.invalid_cpus", max(rep.LogicalCPUs, 1))})
}
@@ -544,6 +549,7 @@ func parseDisplayCount(v string) int {
}
// ParseShow parses the text output of `reims-ctl show <name>` while redacting MAC addresses.
// Paths under the user's home are abbreviated upstream (3731afd, cli.rs:1117,1189-1192).
func ParseShow(name, text string) VMDetail {
d := VMDetail{
Name: name,
@@ -573,7 +579,7 @@ func ParseShow(name, text string) VMDetail {
case "kind":
d.Kind = v
case "directory":
d.Directory = v
d.Directory = config.ExpandHomePath(v)
case "cpus":
d.CPUs, _ = strconv.Atoi(v)
case "memory":
@@ -618,7 +624,7 @@ func ParseShow(name, text string) VMDetail {
d.HasOpenCore = v != ""
case "installer":
d.HasInstaller = v != "" && !strings.EqualFold(v, "none")
d.InstallerPath = v
d.InstallerPath = config.ExpandHomePath(v)
case "cpu model":
d.CPUModel = v
case "audio":
+21
View File
@@ -1,6 +1,7 @@
package reims
import (
"path/filepath"
"reflect"
"strings"
"testing"
@@ -63,6 +64,26 @@ func TestParseShowRedactsMACAndDetectsInstaller(t *testing.T) {
}
}
func TestParseShowExpandsHomeRelativePaths(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
vm := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "vms", "macos-15")
image := filepath.Join("Documents", "MacEmu", "data", "reims-ctl", "installers", "macOS-Sequoia-15.7-offline-installer.img")
tilde := "~" + string(filepath.Separator)
d := ParseShow("macos-15", " directory "+tilde+vm+"\n installer "+tilde+image+"\n")
if want := filepath.Join(home, vm); d.Directory != want {
t.Errorf("VM directory = %q, want %q", d.Directory, want)
}
if want := filepath.Join(home, image); !d.HasInstaller || d.InstallerPath != want {
t.Errorf("installer attached = %t, path = %q, want attached at %q", d.HasInstaller, d.InstallerPath, want)
}
d = ParseShow("macos-15", " directory ~\n installer none\n")
if d.Directory != home || d.HasInstaller {
t.Errorf("VM directory = %q, want %q, installer attached = %t, want false", d.Directory, home, d.HasInstaller)
}
}
func TestOfflineCreateTurnsNetworkOff(t *testing.T) {
args, err := BuildCreateArgs(CreateOpts{Name: "m1", MacOS: "26.7.3", Offline: true})
if err != nil {
+241
View File
@@ -0,0 +1,241 @@
package reims
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"time"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
const (
// SuspendStateFileName holds the QEMU mapped-ram + device VMState snapshot.
SuspendStateFileName = "suspend.vmstate"
// SuspendMetaFileName records the hardware and runtime fingerprint used to
// create suspend.vmstate so incompatible resumes are caught before launch.
SuspendMetaFileName = "suspend.json"
// SuspendSchemaVersion is the current metadata schema version.
SuspendSchemaVersion = 2
)
// SuspendInfo describes a VM's saved suspend-to-disk state inside its VM folder.
type SuspendInfo struct {
SchemaVersion int `json:"schema_version"`
VMName string `json:"vm_name"`
CPUs int `json:"cpus"`
Memory string `json:"memory"`
Graphics string `json:"graphics"`
Displays int `json:"displays"`
Resolution string `json:"resolution"`
DiskController string `json:"disk_controller"`
CPUModel string `json:"cpu_model,omitempty"`
Audio bool `json:"audio"`
AudioBackend string `json:"audio_backend,omitempty"`
Network bool `json:"network"`
SSHPort int `json:"ssh_port"`
ExtraArgs string `json:"extra_args,omitempty"`
RuntimeCommit string `json:"runtime_commit"`
VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"`
CreatedAt string `json:"created_at"`
VMStateSize int64 `json:"vmstate_size"`
}
// SuspendStatePath returns the path to a VM's suspend snapshot file.
func SuspendStatePath(vmDir string) string {
return filepath.Join(vmDir, SuspendStateFileName)
}
// SuspendMetaPath returns the path to a VM's suspend metadata JSON file.
func SuspendMetaPath(vmDir string) string {
return filepath.Join(vmDir, SuspendMetaFileName)
}
// HasSuspendState reports whether vmDir contains a complete suspend snapshot
// (both a non-empty suspend.vmstate and its suspend.json metadata).
func HasSuspendState(vmDir string) bool {
state, _ := suspendFiles(vmDir)
return state != ""
}
func suspendFiles(vmDir string) (state, meta string) {
if strings.TrimSpace(vmDir) == "" {
return "", ""
}
state, meta = SuspendStatePath(vmDir), SuspendMetaPath(vmDir)
nonEmpty := func(path string) bool {
st, err := os.Stat(path)
return err == nil && st.Mode().IsRegular() && st.Size() > 0
}
if nonEmpty(meta) {
if nonEmpty(state) {
return state, meta
}
return "", ""
}
// A staged record is written only after the full state file was
// synced. Preserve that pair if either of the publication steps fails.
if nonEmpty(meta + ".tmp") {
if nonEmpty(state) {
return state, meta + ".tmp"
}
if nonEmpty(state + ".tmp") {
return state + ".tmp", meta + ".tmp"
}
}
return "", ""
}
// ReadSuspendInfo reads suspend.json from vmDir and refreshes VMStateSize from
// the actual suspend.vmstate file on disk.
func ReadSuspendInfo(vmDir string) (*SuspendInfo, error) {
state, meta := suspendFiles(vmDir)
if state == "" {
return nil, os.ErrNotExist
}
b, err := os.ReadFile(meta)
if err != nil {
return nil, err
}
var info SuspendInfo
if err := json.Unmarshal(b, &info); err != nil {
return nil, fmt.Errorf("parse %s: %w", SuspendMetaFileName, err)
}
if st, err := os.Stat(state); err == nil {
info.VMStateSize = st.Size()
}
return &info, nil
}
// BuildSuspendInfo snapshots a VM's hardware and runtime fingerprint for suspend.json.
func BuildSuspendInfo(d VMDetail, active rt.Installed, vmstateSize int64) SuspendInfo {
return SuspendInfo{
SchemaVersion: SuspendSchemaVersion,
VMName: d.Name,
CPUs: d.CPUs,
Memory: strings.TrimSpace(d.Memory),
Graphics: strings.TrimSpace(d.Graphics),
Displays: d.Displays,
Resolution: strings.TrimSpace(d.Resolution),
DiskController: strings.TrimSpace(d.DiskController),
CPUModel: strings.TrimSpace(d.CPUModel),
Audio: d.Audio,
AudioBackend: strings.TrimSpace(d.AudioBackend),
Network: d.Network,
SSHPort: d.SSHPort,
ExtraArgs: StripIncomingDeferArgs(d.ExtraArgs),
RuntimeCommit: strings.TrimSpace(active.Commit),
VendorQemuCommit: strings.TrimSpace(active.Manifest.VendorQemuCommit),
CreatedAt: time.Now().UTC().Format(time.RFC3339),
VMStateSize: vmstateSize,
}
}
// RemoveSuspendState deletes suspend.vmstate, suspend.json, and any partial
// temporary files inside vmDir.
func RemoveSuspendState(vmDir string) error {
if strings.TrimSpace(vmDir) == "" {
return nil
}
var firstErr error
for _, name := range []string{
SuspendMetaFileName,
SuspendMetaFileName + ".tmp",
SuspendStateFileName,
SuspendStateFileName + ".tmp",
} {
if err := os.Remove(filepath.Join(vmDir, name)); err != nil && !os.IsNotExist(err) && firstErr == nil {
firstErr = err
}
}
return firstErr
}
// ValidateSuspendCompatibility checks that the VM hardware and runtime match
// the fingerprint stored when the VM was suspended. Returns human-readable
// mismatch descriptions; an empty slice means compatible.
func ValidateSuspendCompatibility(meta SuspendInfo, cur VMDetail, active rt.Installed) []string {
var diffs []string
if meta.CPUs > 0 && cur.CPUs > 0 && meta.CPUs != cur.CPUs {
diffs = append(diffs, fmt.Sprintf("CPUs (%d -> %d)", meta.CPUs, cur.CPUs))
}
if meta.Memory != "" && cur.Memory != "" && !strings.EqualFold(strings.TrimSpace(meta.Memory), strings.TrimSpace(cur.Memory)) {
diffs = append(diffs, fmt.Sprintf("Memory (%s -> %s)", meta.Memory, cur.Memory))
}
if meta.Graphics != "" && cur.Graphics != "" && !strings.EqualFold(strings.TrimSpace(meta.Graphics), strings.TrimSpace(cur.Graphics)) {
diffs = append(diffs, fmt.Sprintf("Graphics (%s -> %s)", meta.Graphics, cur.Graphics))
}
if meta.Displays > 0 && cur.Displays > 0 && meta.Displays != cur.Displays {
diffs = append(diffs, fmt.Sprintf("Displays (%d -> %d)", meta.Displays, cur.Displays))
}
if meta.DiskController != "" && cur.DiskController != "" && !strings.EqualFold(strings.TrimSpace(meta.DiskController), strings.TrimSpace(cur.DiskController)) {
diffs = append(diffs, fmt.Sprintf("Disk controller (%s -> %s)", meta.DiskController, cur.DiskController))
}
if meta.Audio != cur.Audio {
diffs = append(diffs, fmt.Sprintf("Audio (%v -> %v)", meta.Audio, cur.Audio))
}
if meta.Network != cur.Network {
diffs = append(diffs, fmt.Sprintf("Network (%v -> %v)", meta.Network, cur.Network))
}
if meta.VendorQemuCommit != "" && active.Manifest.VendorQemuCommit != "" &&
!strings.EqualFold(strings.TrimSpace(meta.VendorQemuCommit), strings.TrimSpace(active.Manifest.VendorQemuCommit)) {
diffs = append(diffs, fmt.Sprintf("QEMU commit (%s -> %s)", shortRev(meta.VendorQemuCommit), shortRev(active.Manifest.VendorQemuCommit)))
} else if meta.RuntimeCommit != "" && active.Commit != "" &&
!strings.EqualFold(strings.TrimSpace(meta.RuntimeCommit), strings.TrimSpace(active.Commit)) {
diffs = append(diffs, fmt.Sprintf("Runtime (%s -> %s)", meta.RuntimeCommit, active.Commit))
}
return diffs
}
func shortRev(rev string) string {
rev = strings.TrimSpace(rev)
if len(rev) > 8 {
return rev[:8]
}
return rev
}
// HasIncomingDeferArg reports whether extraArgs contains `-incoming defer`.
func HasIncomingDeferArg(extraArgs string) bool {
tokens := splitShellTokens(extraArgs)
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" {
return true
}
if tok == "-incoming=defer" {
return true
}
}
return false
}
// StripIncomingDeferArgs removes any `-incoming defer` / `-incoming=defer`
// arguments from QEMU extra-args while leaving all other arguments intact.
func StripIncomingDeferArgs(existing string) string {
tokens := splitShellTokens(existing)
cleaned := make([]string, 0, len(tokens))
for i := 0; i < len(tokens); i++ {
tok := tokens[i]
if tok == "-incoming" && i+1 < len(tokens) && tokens[i+1] == "defer" {
i++
continue
}
if tok == "-incoming=defer" {
continue
}
cleaned = append(cleaned, tok)
}
return strings.Join(cleaned, " ")
}
// MergeIncomingDeferArgs idempotently appends `-incoming defer` to extra-args.
func MergeIncomingDeferArgs(existing string) string {
base := StripIncomingDeferArgs(existing)
if base == "" {
return "-incoming defer"
}
return base + " -incoming defer"
}
@@ -0,0 +1,26 @@
//go:build !windows
package reims
import (
"errors"
"fmt"
"os"
"syscall"
)
func lockVMFile(f *os.File) error {
err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
if errors.Is(err, syscall.EWOULDBLOCK) {
return ErrVMOperationBusy
}
return err
}
func mediaFileID(path string, info os.FileInfo) (uint64, uint64, error) {
st, ok := info.Sys().(*syscall.Stat_t)
if !ok {
return 0, 0, fmt.Errorf("file identity unavailable for %s", path)
}
return uint64(st.Dev), uint64(st.Ino), nil
}
@@ -0,0 +1,39 @@
//go:build windows
package reims
import (
"errors"
"os"
"golang.org/x/sys/windows"
)
func lockVMFile(f *os.File) error {
err := windows.LockFileEx(windows.Handle(f.Fd()),
windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,
0, 1, 0, new(windows.Overlapped))
if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {
return ErrVMOperationBusy
}
return err
}
func mediaFileID(path string, _ os.FileInfo) (uint64, uint64, error) {
name, err := windows.UTF16PtrFromString(path)
if err != nil {
return 0, 0, err
}
handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES,
windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil,
windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, 0)
if err != nil {
return 0, 0, err
}
defer windows.CloseHandle(handle)
var info windows.ByHandleFileInformation
if err := windows.GetFileInformationByHandle(handle, &info); err != nil {
return 0, 0, err
}
return uint64(info.VolumeSerialNumber), uint64(info.FileIndexHigh)<<32 | uint64(info.FileIndexLow), nil
}
+121
View File
@@ -0,0 +1,121 @@
package reims
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestSuspendStateLifecycle(t *testing.T) {
dir := t.TempDir()
if HasSuspendState(dir) {
t.Fatal("empty dir should not have suspend state")
}
// Only vmstate without meta -> incomplete.
if err := os.WriteFile(SuspendStatePath(dir)+".tmp", []byte("vmstate-bytes"), 0o644); err != nil {
t.Fatal(err)
}
if HasSuspendState(dir) {
t.Fatal("vmstate without suspend.json should not count as complete suspend state")
}
active := rt.Installed{
Commit: "3731afd-p9",
Manifest: rt.Manifest{
VendorQemuCommit: "4571bc5fecb039e8cfd6837e077810fbe074e11b",
},
}
detail := VMDetail{
Name: "tahoe",
Directory: dir,
CPUs: 8,
Memory: "8G",
Graphics: "reims-vgpu",
Displays: 1,
Resolution: "1920x1080",
DiskController: "nvme",
Audio: true,
Network: true,
ExtraArgs: "-machine kernel-irqchip=on -incoming defer",
}
media := filepath.Join(dir, "disk.qcow2")
for _, path := range []string{media, filepath.Join(dir, "vm.toml")} {
if err := os.WriteFile(path, []byte("state"), 0o600); err != nil {
t.Fatal(err)
}
}
if _, err := SealSuspend(detail, active, []string{media}); err != nil {
t.Fatalf("SealSuspend: %v", err)
}
if !HasSuspendState(dir) {
t.Fatal("expected HasSuspendState=true after writing both files")
}
got, err := ReadSuspendInfo(dir)
if err != nil {
t.Fatalf("ReadSuspendInfo: %v", err)
}
if got.VMStateSize != 13 || got.CPUs != 8 || got.ExtraArgs != "-machine kernel-irqchip=on" {
t.Fatalf("unexpected suspend info: %+v", got)
}
// Compatible check passes.
if diffs := ValidateSuspendCompatibility(*got, detail, active); len(diffs) != 0 {
t.Fatalf("expected compatible, got %v", diffs)
}
// Hardware and runtime mismatch checks trigger.
changedDetail := detail
changedDetail.CPUs = 12
changedDetail.Memory = "16G"
changedRT := active
changedRT.Manifest.VendorQemuCommit = "deadbeef00000000000000000000000000000000"
diffs := ValidateSuspendCompatibility(*got, changedDetail, changedRT)
if len(diffs) != 3 {
t.Fatalf("expected 3 diffs, got %v", diffs)
}
if err := RemoveSuspendState(dir); err != nil {
t.Fatalf("RemoveSuspendState: %v", err)
}
if HasSuspendState(dir) {
t.Fatal("expected HasSuspendState=false after RemoveSuspendState")
}
}
func TestIncomingDeferArgsIdempotent(t *testing.T) {
if HasIncomingDeferArg("") || HasIncomingDeferArg("-machine q35") {
t.Fatal("unexpected HasIncomingDeferArg=true")
}
m := MergeIncomingDeferArgs(`-drive "id=x,file=C:/a b/c.img"`)
if !HasIncomingDeferArg(m) {
t.Fatalf("expected -incoming defer in %q", m)
}
if m2 := MergeIncomingDeferArgs(m); m2 != m {
t.Fatalf("MergeIncomingDeferArgs not idempotent: %q vs %q", m2, m)
}
if s := StripIncomingDeferArgs(m + " -incoming=defer"); s != `-drive "id=x,file=C:/a b/c.img"` {
t.Fatalf("StripIncomingDeferArgs = %q", s)
}
}
func TestValidateSetRejectsSuspendedVM(t *testing.T) {
issues := ValidateSetLocalized(
SetOpts{Name: "tahoe", CPUs: 6},
VMDetail{Name: "tahoe", State: "suspended", CPUs: 8, Memory: "8G"},
host.Report{LogicalCPUs: 16, TotalRAMGB: 32},
i18n.EnUS,
)
if len(issues) == 0 || issues[0].Code != "vm_suspended" {
t.Fatalf("expected vm_suspended validation issue, got %+v", issues)
}
if !strings.Contains(strings.ToLower(issues[0].Message), "suspend") {
t.Fatalf("unexpected message: %q", issues[0].Message)
}
}
+185
View File
@@ -0,0 +1,185 @@
package reims
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
var ErrVMOperationBusy = errors.New("another operation holds the VM lock")
// LockVMOperation serializes GUI and CLI operations on the same VM directory.
// The lock file stays in place so contenders always lock the same inode.
func LockVMOperation(vmDir string) (func(), error) {
if strings.TrimSpace(vmDir) == "" {
return nil, fmt.Errorf("VM directory is required")
}
f, err := os.OpenFile(filepath.Join(vmDir, ".reims-go-vm-operation.lock"), os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return nil, err
}
if err := lockVMFile(f); err != nil {
_ = f.Close()
return nil, err
}
return func() { _ = f.Close() }, nil
}
type mediaFingerprint struct {
Path string `json:"path"`
Volume uint64 `json:"volume"`
FileID uint64 `json:"file_id"`
Size int64 `json:"size"`
MTime int64 `json:"mtime_ns"`
}
type suspendRecord struct {
SuspendInfo
ConfigHash string `json:"config_sha256"`
Media []mediaFingerprint `json:"media"`
}
func fingerprintMedia(path string) (mediaFingerprint, error) {
st, err := os.Stat(path)
if err != nil {
return mediaFingerprint{}, err
}
if !st.Mode().IsRegular() {
return mediaFingerprint{}, fmt.Errorf("attached path is not a regular file: %s", path)
}
volume, id, err := mediaFileID(path, st)
if err != nil {
return mediaFingerprint{}, err
}
return mediaFingerprint{Path: path, Volume: volume, FileID: id, Size: st.Size(), MTime: st.ModTime().UnixNano()}, nil
}
func suspendConfigHash(vmDir string) (string, error) {
data, err := os.ReadFile(filepath.Join(vmDir, "vm.toml"))
if err != nil {
return "", err
}
sum := sha256.Sum256(data)
return hex.EncodeToString(sum[:]), nil
}
// SealSuspend publishes a completed migration as the only usable snapshot.
// Every failure leaves the migration file available and the sender still alive.
func SealSuspend(d VMDetail, active rt.Installed, paths []string) (SuspendInfo, error) {
if len(paths) == 0 {
return SuspendInfo{}, fmt.Errorf("cannot seal a snapshot without attached media")
}
dir := d.Directory
tmp := SuspendStatePath(dir) + ".tmp"
state, err := os.OpenFile(tmp, os.O_RDWR, 0)
if err != nil {
return SuspendInfo{}, err
}
st, err := state.Stat()
if err == nil && (!st.Mode().IsRegular() || st.Size() == 0) {
err = fmt.Errorf("suspend snapshot is empty or is not a regular file")
}
if err == nil {
err = state.Sync()
}
if err := errors.Join(err, state.Close()); err != nil {
return SuspendInfo{}, err
}
configHash, err := suspendConfigHash(dir)
if err != nil {
return SuspendInfo{}, err
}
record := suspendRecord{
SuspendInfo: BuildSuspendInfo(d, active, st.Size()),
ConfigHash: configHash,
Media: make([]mediaFingerprint, 0, len(paths)),
}
for _, path := range paths {
item, err := fingerprintMedia(path)
if err != nil {
return SuspendInfo{}, fmt.Errorf("fingerprint attached media: %w", err)
}
record.Media = append(record.Media, item)
}
metaTmp := SuspendMetaPath(dir) + ".tmp"
if err := stageSuspendRecord(metaTmp, record); err != nil {
return SuspendInfo{}, err
}
if err := os.Rename(tmp, SuspendStatePath(dir)); err != nil {
return SuspendInfo{}, err
}
if err := os.Rename(metaTmp, SuspendMetaPath(dir)); err != nil {
return SuspendInfo{}, err
}
return record.SuspendInfo, nil
}
func stageSuspendRecord(path string, record suspendRecord) error {
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
if err != nil {
return err
}
enc := json.NewEncoder(f)
enc.SetIndent("", " ")
err = enc.Encode(record)
if err == nil {
err = f.Sync()
}
return errors.Join(err, f.Close())
}
// ValidateSuspendFiles checks contents and identities before starting incoming
// QEMU and returns the expected media paths for validation before load.
func ValidateSuspendFiles(d VMDetail, active rt.Installed) (string, []string, error) {
state, meta := suspendFiles(d.Directory)
if state == "" {
return "", nil, os.ErrNotExist
}
data, err := os.ReadFile(meta)
if err != nil {
return "", nil, err
}
var record suspendRecord
if err := json.Unmarshal(data, &record); err != nil {
return "", nil, err
}
if record.SchemaVersion != SuspendSchemaVersion || record.ConfigHash == "" || len(record.Media) == 0 {
return "", nil, fmt.Errorf("snapshot has no supported VM and media fingerprint")
}
st, err := os.Stat(state)
if err != nil {
return "", nil, err
}
if !st.Mode().IsRegular() || st.Size() <= 0 || st.Size() != record.VMStateSize {
return "", nil, fmt.Errorf("snapshot file size changed")
}
diffs := ValidateSuspendCompatibility(record.SuspendInfo, d, active)
configHash, err := suspendConfigHash(d.Directory)
if err != nil {
return "", nil, err
}
if configHash != record.ConfigHash {
diffs = append(diffs, "VM configuration changed")
}
paths := make([]string, 0, len(record.Media))
for _, expected := range record.Media {
current, err := fingerprintMedia(expected.Path)
if err != nil || current != expected {
diffs = append(diffs, fmt.Sprintf("attached media changed (%s)", expected.Path))
}
paths = append(paths, expected.Path)
}
if len(diffs) > 0 {
return "", nil, errors.New(strings.Join(diffs, ", "))
}
slices.Sort(paths)
return state, paths, nil
}
@@ -0,0 +1,89 @@
package reims
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
rt "github.com/Nwflower/reims-go/internal/runtime"
)
func TestVMOperationLockExcludesAnotherHandle(t *testing.T) {
dir := t.TempDir()
release, err := LockVMOperation(dir)
if err != nil {
t.Fatal(err)
}
if _, err = LockVMOperation(dir); !errors.Is(err, ErrVMOperationBusy) {
t.Fatalf("second lock = %v, want busy", err)
}
release()
release, err = LockVMOperation(dir)
if err != nil {
t.Fatal(err)
}
release()
}
func TestSuspendTransactionRejectsChangedBackingFile(t *testing.T) {
dir := t.TempDir()
top := filepath.Join(dir, "disk.qcow2")
base := filepath.Join(dir, "base.qcow2")
for _, path := range []string{top, base, filepath.Join(dir, "vm.toml"), SuspendStatePath(dir) + ".tmp"} {
if err := os.WriteFile(path, []byte("test data"), 0o600); err != nil {
t.Fatal(err)
}
}
d := VMDetail{Name: "test", Directory: dir, CPUs: 2, Memory: "4G"}
runtime := rt.Installed{Commit: "test"}
if _, err := SealSuspend(d, runtime, []string{top, base}); err != nil {
t.Fatal(err)
}
if _, _, err := ValidateSuspendFiles(d, runtime); err != nil {
t.Fatal(err)
}
st, err := os.Stat(base)
if err != nil {
t.Fatal(err)
}
if err := os.Rename(base, base+".old"); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(base, []byte("test data"), 0o600); err != nil {
t.Fatal(err)
}
if err := os.Chtimes(base, st.ModTime(), st.ModTime()); err != nil {
t.Fatal(err)
}
if _, _, err := ValidateSuspendFiles(d, runtime); err == nil || !strings.Contains(err.Error(), "base.qcow2") {
t.Fatalf("replaced backing file not detected: %v", err)
}
}
func TestSuspendTransactionKeepsSealedFilesWhenPublicationFails(t *testing.T) {
dir := t.TempDir()
media := filepath.Join(dir, "OVMF_VARS.fd")
stagedState := SuspendStatePath(dir) + ".tmp"
for _, path := range []string{media, filepath.Join(dir, "vm.toml"), stagedState} {
if err := os.WriteFile(path, []byte("test state"), 0o600); err != nil {
t.Fatal(err)
}
}
if err := os.Mkdir(SuspendMetaPath(dir), 0o700); err != nil {
t.Fatal(err)
}
d := VMDetail{Name: "test", Directory: dir}
runtime := rt.Installed{Commit: "test"}
if _, err := SealSuspend(d, runtime, []string{media}); err == nil {
t.Fatal("expected publication to fail")
}
if !HasSuspendState(dir) {
t.Fatal("published state and staged metadata should be recoverable")
}
state, paths, err := ValidateSuspendFiles(d, runtime)
if err != nil || state != SuspendStatePath(dir) || len(paths) != 1 || paths[0] != media {
t.Fatalf("recoverable snapshot = %q, %v, %v", state, paths, err)
}
}
+5
View File
@@ -87,6 +87,11 @@ func (p *Prep) CheckMemory(memory string, rep host.Report) error {
// language preset and the WHPX nested-virtualization fallback. cur is updated
// to match what was written through `reims-ctl set`.
func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) {
if stripped := reims.StripIncomingDeferArgs(cur.ExtraArgs); stripped != cur.ExtraArgs {
if err := p.setExtraArgs(ctx, name, stripped); err == nil {
cur.ExtraArgs = stripped
}
}
p.syncOfflineHelper(ctx, name, cur)
p.syncRecoveryBootPicker(ctx, name, cur)
p.ReplayGuestLang(ctx, cur.Directory)
+231
View File
@@ -0,0 +1,231 @@
package startprep
import (
"context"
"errors"
"fmt"
"io"
"os"
"slices"
"strings"
"time"
"github.com/Nwflower/reims-go/internal/host"
"github.com/Nwflower/reims-go/internal/i18n"
"github.com/Nwflower/reims-go/internal/macos/reims"
"github.com/Nwflower/reims-go/internal/qmp"
)
// LockVM reads the VM again after locking its directory so that another
// process cannot change the state between inspection and operation.
func LockVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) {
d, err := c.Show(ctx, name)
if err != nil {
return d, nil, err
}
release, err := reims.LockVMOperation(d.Directory)
if errors.Is(err, reims.ErrVMOperationBusy) {
return d, nil, i18n.NewCodedError(c.Locale, "E_SUSPEND_BUSY", "err.suspend.busy", i18n.Vars{"name": name}, nil)
}
if err != nil {
return d, nil, err
}
cur, err := c.Show(ctx, name)
if err == nil && cur.Directory != d.Directory {
err = fmt.Errorf("VM directory changed while waiting to operate on %s", name)
}
if err != nil {
release()
return cur, nil, err
}
return cur, release, nil
}
// LockMutableVM protects configuration and media updates and rejects updates
// while a published suspend state depends on the current configuration.
func LockMutableVM(ctx context.Context, c *reims.Client, name string) (reims.VMDetail, func(), error) {
d, release, err := LockVM(ctx, c, name)
if err != nil {
return d, nil, err
}
if reims.HasSuspendState(d.Directory) {
release()
return d, nil, i18n.NewCodedError(c.Locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil)
}
return d, release, nil
}
// LockVMForStop serializes graceful shutdown. Emergency shutdown is also
// the escape path for a stalled operation that already holds the lock.
func LockVMForStop(ctx context.Context, c *reims.Client, name string, force bool) (func(), error) {
if force {
return func() {}, nil
}
_, release, err := LockVM(ctx, c, name)
return release, err
}
func (p *Prep) checkSuspendRuntime(d reims.VMDetail) error {
kind := strings.ToLower(d.Kind)
if !p.Runtime.Manifest.HasCapability("vm-suspend") || strings.Contains(kind, "arm64") || strings.Contains(kind, "aarch64") {
return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_UNSUPPORTED_RUNTIME", "err.suspend.unsupported_runtime", nil, nil)
}
return nil
}
// SuspendSnapshot saves and publishes a VM snapshot while the caller holds
// LockVM. The source exits only after the snapshot and metadata are durable.
func (p *Prep) SuspendSnapshot(ctx context.Context, d reims.VMDetail, progress func(qmp.MigrateProgress)) (reims.SuspendInfo, error) {
var info reims.SuspendInfo
if err := p.checkSuspendRuntime(d); err != nil {
return info, err
}
pid, err := vmPID(ctx, p.Client, d.Name)
if err != nil {
return info, err
}
if pid == 0 {
return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_RUNNING", "err.suspend.not_running", i18n.Vars{"name": d.Name}, nil)
}
if memGB, ok := reims.ParseSizeGB(d.Memory); ok {
if avail := host.Inspect(d.Directory).FreeDiskGB; avail > 0 && avail < memGB+1 {
return info, i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_DISK_SPACE", "err.suspend.disk_space", i18n.Vars{
"need": fmt.Sprintf("%.1f", memGB+1), "avail": fmt.Sprintf("%.1f", avail),
}, nil)
}
}
state := reims.SuspendStatePath(d.Directory)
tmp := state + ".tmp"
meta := reims.SuspendMetaPath(d.Directory)
for _, path := range []string{state, tmp, meta, meta + ".tmp"} {
if _, err := os.Lstat(path); !os.IsNotExist(err) {
if err != nil {
return info, err
}
return info, fmt.Errorf("previous suspend data still exists: %s", path)
}
}
err = qmp.SuspendToFile(ctx, d.Directory, tmp, progress, func(paths []string) error {
var err error
info, err = reims.SealSuspend(d, p.Runtime, paths)
return err
})
if err != nil {
return info, cleanupSuspendAttempt(tmp, err)
}
waitCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
defer cancel()
if err := host.WaitProcessExit(waitCtx, uint32(pid), "qemu-system-x86_64.exe"); err != nil {
if !errors.Is(err, errors.ErrUnsupported) {
return info, err
}
for {
cur, err := vmPID(waitCtx, p.Client, d.Name)
if err != nil || cur == 0 {
return info, err
}
select {
case <-waitCtx.Done():
return info, waitCtx.Err()
case <-time.After(100 * time.Millisecond):
}
}
}
return info, nil
}
func cleanupSuspendAttempt(tmp string, err error) error {
if errors.Is(err, qmp.ErrIncompleteSuspend) {
if removeErr := os.Remove(tmp); removeErr != nil && !os.IsNotExist(removeErr) {
return errors.Join(err, fmt.Errorf("remove incomplete snapshot: %w", removeErr))
}
}
return err
}
// ResumeSnapshot owns the incoming launch and snapshot consumption while
// the caller holds LockVM. The original configuration must be restored
// before guest execution can continue.
func (p *Prep) ResumeSnapshot(ctx context.Context, d reims.VMDetail, rep host.Report, out, stderr io.Writer) error {
if err := p.checkSuspendRuntime(d); err != nil {
return err
}
if d.State == "running" {
return fmt.Errorf("%s", i18n.T(p.Client.Locale, "vm.already_running", d.Name))
}
if !reims.HasSuspendState(d.Directory) {
return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_NOT_FOUND", "err.suspend.not_found", i18n.Vars{"name": d.Name}, nil)
}
state, paths, err := reims.ValidateSuspendFiles(d, p.Runtime)
if err != nil {
return i18n.NewCodedError(p.Client.Locale, "E_SUSPEND_INCOMPATIBLE", "err.suspend.incompatible", i18n.Vars{"diffs": err.Error()}, err)
}
if err := p.CheckWHPX(rep); err != nil {
return err
}
if err := p.CheckMemory(d.Memory, rep); err != nil {
return err
}
c := p.Client
incoming := reims.MergeIncomingDeferArgs(d.ExtraArgs)
if err := c.Set(ctx, reims.SetOpts{Name: d.Name, ExtraArgs: &incoming}, out, stderr); err != nil {
return err
}
startErr := c.Start(ctx, d.Name, out, stderr)
restoreCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second)
restoreErr := c.Set(restoreCtx, reims.SetOpts{Name: d.Name, ExtraArgs: &d.ExtraArgs}, out, stderr)
cancel()
if restoreErr != nil {
restoreErr = fmt.Errorf("restore original VM start arguments: %w", restoreErr)
}
if err := errors.Join(startErr, restoreErr); err != nil {
p.stopFailedIncoming(ctx, d)
return err
}
err = qmp.ResumeFromFile(ctx, d.Directory, state, nil, func(conn *qmp.Conn) error {
attached, err := conn.AttachedFiles(d.Directory)
if err != nil {
return err
}
if !slices.Equal(paths, attached) {
return fmt.Errorf("incoming QEMU opened different media from the saved VM")
}
return nil
})
if err != nil {
p.stopFailedIncoming(ctx, d)
return err
}
if err := reims.RemoveSuspendState(d.Directory); err != nil {
p.log("Warning: could not remove consumed suspend files: " + err.Error())
}
return nil
}
func (p *Prep) stopFailedIncoming(ctx context.Context, d reims.VMDetail) {
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 20*time.Second)
defer cancel()
if err := qmp.QuitVM(cleanup, d.Directory); err != nil {
_ = p.Client.StopForce(cleanup, d.Name, io.Discard, io.Discard)
}
}
func DiscardSnapshot(loc i18n.Locale, d reims.VMDetail) error {
if d.State == "running" {
return i18n.NewCodedError(loc, "E_SUSPEND_DISCARD_RUNNING", "err.suspend.discard_running", i18n.Vars{"name": d.Name}, nil)
}
return reims.RemoveSuspendState(d.Directory)
}
func vmPID(ctx context.Context, c *reims.Client, name string) (int, error) {
vms, err := c.List(ctx)
if err != nil {
return 0, err
}
for _, vm := range vms {
if vm.Name == name && vm.State == "running" && vm.PID != nil {
return *vm.PID, nil
}
}
return 0, nil
}
+48
View File
@@ -0,0 +1,48 @@
package startprep
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"testing"
"github.com/Nwflower/reims-go/internal/qmp"
)
func TestForceStopDoesNotWaitForVMInspectionOrLock(t *testing.T) {
// A forced stop must not ask reims-ctl to show the VM before it can
// invoke stop --force. A stalled owner may also be holding its lock.
release, err := LockVMForStop(context.Background(), nil, "stalled", true)
if err != nil {
t.Fatal(err)
}
release()
}
func TestCleanupSuspendAttempt(t *testing.T) {
for _, tt := range []struct {
name string
err error
keep bool
}{
{"migration failed", fmt.Errorf("%w: disk full", qmp.ErrIncompleteSuspend), false},
{"seal failed", errors.New("could not publish suspend metadata"), true},
{"unknown outcome", errors.New("connection closed"), true},
} {
t.Run(tt.name, func(t *testing.T) {
tmp := filepath.Join(t.TempDir(), "suspend.vmstate.tmp")
if err := os.WriteFile(tmp, []byte("snapshot data"), 0o600); err != nil {
t.Fatal(err)
}
if err := cleanupSuspendAttempt(tmp, tt.err); !errors.Is(err, tt.err) {
t.Fatalf("cleanup lost the save error: %v", err)
}
_, err := os.Stat(tmp)
if tt.keep && err != nil || !tt.keep && !os.IsNotExist(err) {
t.Fatalf("stat after cleanup = %v, want keep=%t", err, tt.keep)
}
})
}
}
+31 -9
View File
@@ -45,15 +45,26 @@ func (c *Conn) Close() error { return c.nc.Close() }
type qmpReply struct {
Return json.RawMessage `json:"return"`
Error *struct {
Class string `json:"class"`
Desc string `json:"desc"`
} `json:"error"`
Event string `json:"event"`
Error *commandError `json:"error"`
Event string `json:"event"`
}
// Query runs one command and waits for its JSON return value, skipping async events.
type commandError struct {
Class string `json:"class"`
Desc string `json:"desc"`
}
func (e *commandError) Error() string { return e.Class + ": " + e.Desc }
// Query runs one command with the default 5-second timeout and waits for its
// JSON return value, skipping async events.
func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
return c.QueryWithTimeout(command, args, 5*time.Second)
}
// QueryWithTimeout runs one command and waits up to timeout for its JSON return
// value, skipping async events.
func (c *Conn) QueryWithTimeout(command string, args any, timeout time.Duration) (json.RawMessage, error) {
req := map[string]any{"execute": command}
if args != nil {
req["arguments"] = args
@@ -62,7 +73,10 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
if err != nil {
return nil, err
}
_ = c.nc.SetDeadline(time.Now().Add(5 * time.Second))
if timeout <= 0 {
timeout = 5 * time.Second
}
_ = c.nc.SetDeadline(time.Now().Add(timeout))
if _, err := c.nc.Write(append(b, '\n')); err != nil {
return nil, fmt.Errorf("QMP %s: %w", command, err)
}
@@ -72,7 +86,7 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
continue
}
if r.Error != nil {
return nil, fmt.Errorf("QMP %s: %s: %s", command, r.Error.Class, r.Error.Desc)
return nil, fmt.Errorf("QMP %s: %w", command, r.Error)
}
if r.Return != nil {
return append(json.RawMessage(nil), r.Return...), nil
@@ -84,8 +98,16 @@ func (c *Conn) Query(command string, args any) (json.RawMessage, error) {
return nil, fmt.Errorf("QMP %s: connection closed", command)
}
// Execute runs one command and waits for its reply, skipping async events.
// Execute runs one command with the default timeout and waits for its reply,
// skipping async events.
func (c *Conn) Execute(command string, args any) error {
_, err := c.Query(command, args)
return err
}
// ExecuteWithTimeout runs one command and waits up to timeout for its reply,
// skipping async events.
func (c *Conn) ExecuteWithTimeout(command string, args any, timeout time.Duration) error {
_, err := c.QueryWithTimeout(command, args, timeout)
return err
}
+59
View File
@@ -0,0 +1,59 @@
package qmp
import (
"encoding/json"
"fmt"
"path/filepath"
"slices"
"strings"
)
// AttachedFiles lists the inserted image and backing files for each block
// device. QEMU's resolved image names include the real pflash and CD drives.
func (c *Conn) AttachedFiles(vmDir string) ([]string, error) {
raw, err := c.Query("query-block", nil)
if err != nil {
return nil, err
}
type image struct {
Filename string `json:"filename"`
Backing *image `json:"backing-image"`
}
var devices []struct {
Device string `json:"device"`
Inserted *struct {
Image *image `json:"image"`
Backing string `json:"backing_file"`
} `json:"inserted"`
}
if err := json.Unmarshal(raw, &devices); err != nil {
return nil, fmt.Errorf("decode query-block: %w", err)
}
var paths []string
for _, d := range devices {
if d.Inserted == nil {
continue
}
if d.Inserted.Image == nil || (d.Inserted.Backing != "" && d.Inserted.Image.Backing == nil) {
return nil, fmt.Errorf("cannot identify the complete attached disk or backing chain")
}
for img := d.Inserted.Image; img != nil; img = img.Backing {
if img.Filename == "" {
return nil, fmt.Errorf("block device has no filename")
}
name := img.Filename
if strings.HasPrefix(name, "json:") {
return nil, fmt.Errorf("block device %s uses a non-persistent or unresolvable image; eject it before suspending", d.Device)
}
if !filepath.IsAbs(name) {
name = filepath.Join(vmDir, name)
}
paths = append(paths, filepath.Clean(name))
}
}
if len(paths) == 0 {
return nil, fmt.Errorf("no attached media reported by QEMU")
}
slices.Sort(paths)
return slices.Compact(paths), nil
}
+410
View File
@@ -0,0 +1,410 @@
package qmp
import (
"context"
"encoding/json"
"errors"
"fmt"
"path/filepath"
"strings"
"time"
)
const (
// DefaultMultifdChannels is the parallel I/O channel count used for
// mapped-ram file snapshots on Windows.
DefaultMultifdChannels = 8
// UnlimitedMigrationBandwidth disables QEMU's default 128 MiB/s throttle
// (RATE_LIMIT_DISABLED = 0 in migration/migration-stats.h) for paused
// local snapshot writes.
UnlimitedMigrationBandwidth = 0
migratePollInterval = 100 * time.Millisecond
migrateCmdTimeout = 2 * time.Minute
migrateTotalTimeout = 15 * time.Minute
)
// MigrateProgress carries the latest snapshot save/load progress from QMP
// `query-migrate`.
type MigrateProgress struct {
Status string `json:"status"`
Transferred int64 `json:"transferred"`
Remaining int64 `json:"remaining"`
Total int64 `json:"total"`
TotalTimeMs int64 `json:"total_time_ms"`
}
type migrateInfo struct {
Status string `json:"status"`
ErrorDesc string `json:"error-desc"`
TotalTimeMs int64 `json:"total-time"`
RAM *struct {
Transferred int64 `json:"transferred"`
Remaining int64 `json:"remaining"`
Total int64 `json:"total"`
} `json:"ram"`
}
type vmStatusReply struct {
Running bool `json:"running"`
Status string `json:"status"`
}
// ErrIncompleteSuspend marks a save that QEMU rejected, failed, or cancelled.
// The caller may remove its staging file once QEMU no longer writes to it.
var ErrIncompleteSuspend = errors.New("incomplete suspend snapshot")
type migrationFailure struct {
status string
desc string
}
func (e *migrationFailure) Error() string {
if e.desc != "" {
return fmt.Sprintf("migration %s: %s", e.status, e.desc)
}
return "migration " + e.status
}
// A timeout or a dropped connection can hide a completed migration.
type unknownSuspendOutcome struct{ error }
func (e *unknownSuspendOutcome) Unwrap() error { return e.error }
// SuspendToFile pauses a running Intel VM via QMP, writes a mapped-ram +
// multifd file snapshot to vmstatePath, waits for completion, and shuts down
// QEMU cleanly via `quit`.
//
// If migration fails before reaching completion while the VM is merely paused
// (not postmigrate), SuspendToFile attempts to resume the guest with `cont` so
// the running VM is not left frozen.
func SuspendToFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), seal func([]string) error) error {
if seal == nil {
return errors.New("suspend snapshot requires a seal callback")
}
addr := SocketPath(vmDir)
c, err := Dial(ctx, "unix", addr)
if err != nil {
return err
}
defer c.Close()
paths, err := c.AttachedFiles(vmDir)
if err != nil {
return err
}
err = suspendToFileConn(ctx, c, vmstatePath, onProgress, func(*Conn) error { return seal(paths) })
var unknown *unknownSuspendOutcome
if errors.As(err, &unknown) {
_ = c.Close()
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 8*time.Second)
defer cancel()
fresh, dialErr := dialMigrateConnWithRetry(cleanup, "unix", addr, 3*time.Second)
if dialErr == nil {
defer fresh.Close()
if cancelIncompleteSuspend(cleanup, fresh) {
return fmt.Errorf("%w: %w", ErrIncompleteSuspend, err)
}
}
}
return err
}
func suspendToFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress), seal func(*Conn) error) error {
if err := c.ExecuteWithTimeout("stop", nil, 30*time.Second); err != nil {
return fmt.Errorf("pause VM before suspend: %w", err)
}
st, err := queryVMStatus(c)
if err != nil {
tryResumePaused(c)
return fmt.Errorf("verify paused state: %w", err)
}
if st.Running {
return fmt.Errorf("VM remained running after stop (status=%s)", st.Status)
}
directIO, err := configureMappedRAM(c, true)
if err != nil {
tryResumePaused(c)
return err
}
args := map[string]any{
"channels": fileChannels(vmstatePath),
}
err = runSuspendMigration(ctx, c, args, onProgress)
if directIO && errors.Is(err, ErrIncompleteSuspend) && isDirectIOErr(err) {
// Fall back to buffered file I/O if the target volume rejects Win32
// direct I/O (e.g., compressed directory or unsupported filesystem).
if st, stErr := queryVMStatus(c); stErr == nil && !st.Running && st.Status == "paused" {
if disableErr := c.ExecuteWithTimeout("migrate-set-parameters", map[string]any{"direct-io": false}, 15*time.Second); disableErr == nil {
err = runSuspendMigration(ctx, c, args, onProgress)
}
}
}
if err != nil {
if errors.Is(err, ErrIncompleteSuspend) {
tryResumePaused(c)
}
return err
}
if seal != nil {
if err := seal(c); err != nil {
// The source still owns the session. Leave it paused and retain
// the completed file if publishing the save failed.
return fmt.Errorf("seal snapshot before exiting QEMU: %w", err)
}
}
// Migration completed (RUN_STATE_POSTMIGRATE): never send `cont` here;
// exit QEMU cleanly so the disk and WHPX partition close.
if err := c.ExecuteWithTimeout("quit", nil, 15*time.Second); err != nil {
// QEMU may close the QMP socket immediately upon receiving `quit`.
if !isConnClosedErr(err) {
return fmt.Errorf("quit QEMU after suspend: %w", err)
}
}
return nil
}
// ResumeFromFile connects to a QEMU process started with `-incoming defer`,
// loads the mapped-ram + multifd file snapshot from vmstatePath, waits for
// completion, and resumes execution with `cont`.
//
// On any error, vmstatePath is left untouched so the caller can retry.
func ResumeFromFile(ctx context.Context, vmDir, vmstatePath string, onProgress func(MigrateProgress), checkMedia func(*Conn) error) error {
c, err := dialMigrateConnWithRetry(ctx, "unix", SocketPath(vmDir), 10*time.Second)
if err != nil {
return err
}
defer c.Close()
if checkMedia != nil {
if err := checkMedia(c); err != nil {
return err
}
}
return resumeFromFileConn(ctx, c, vmstatePath, onProgress)
}
func resumeFromFileConn(ctx context.Context, c *Conn, vmstatePath string, onProgress func(MigrateProgress)) error {
// Keep direct-io disabled on incoming resume so OS read-ahead accelerates
// sparse mapped-ram bitmap reads.
if _, err := configureMappedRAM(c, false); err != nil {
return err
}
args := map[string]any{
"channels": fileChannels(vmstatePath),
"exit-on-error": false,
}
if err := c.ExecuteWithTimeout("migrate-incoming", args, migrateCmdTimeout); err != nil {
return fmt.Errorf("start snapshot restore: %w", err)
}
if err := waitMigrateDone(ctx, c, onProgress); err != nil {
return fmt.Errorf("restore snapshot: %w", err)
}
if err := c.ExecuteWithTimeout("cont", nil, 30*time.Second); err != nil {
return fmt.Errorf("resume VM execution after restore: %w", err)
}
return nil
}
// QuitVM sends QMP `quit` to the VM's QMP socket (best-effort cleanup for a
// failed incoming-resume QEMU process).
func QuitVM(ctx context.Context, vmDir string) error {
c, err := Dial(ctx, "unix", SocketPath(vmDir))
if err != nil {
return err
}
defer c.Close()
if err := c.ExecuteWithTimeout("quit", nil, 10*time.Second); err != nil && !isConnClosedErr(err) {
return err
}
return nil
}
func configureMappedRAM(c *Conn, enableDirectIO bool) (bool, error) {
caps := map[string]any{
"capabilities": []map[string]any{
{"capability": "mapped-ram", "state": true},
{"capability": "multifd", "state": true},
},
}
if err := c.ExecuteWithTimeout("migrate-set-capabilities", caps, 15*time.Second); err != nil {
return false, fmt.Errorf("enable mapped-ram/multifd capabilities: %w", err)
}
params := map[string]any{
"max-bandwidth": UnlimitedMigrationBandwidth,
"multifd-channels": DefaultMultifdChannels,
}
if err := c.ExecuteWithTimeout("migrate-set-parameters", params, 15*time.Second); err != nil {
return false, fmt.Errorf("set migration parameters: %w", err)
}
if !enableDirectIO {
return false, nil
}
if err := c.ExecuteWithTimeout("migrate-set-parameters", map[string]any{"direct-io": true}, 15*time.Second); err != nil {
var rejected *commandError
if errors.As(err, &rejected) {
// Older QEMU builds without Win32 direct-io reject the parameter;
// continue with buffered multifd I/O.
return false, nil
}
return false, fmt.Errorf("enable direct-io migration parameter: %w", err)
}
return true, nil
}
func fileChannels(vmstatePath string) []map[string]any {
return []map[string]any{
{
"channel-type": "main",
"addr": map[string]any{
"transport": "file",
"filename": filepath.Clean(vmstatePath),
"offset": 0,
},
},
}
}
func queryVMStatus(c *Conn) (vmStatusReply, error) {
raw, err := c.QueryWithTimeout("query-status", nil, 15*time.Second)
if err != nil {
return vmStatusReply{}, err
}
var st vmStatusReply
if err := json.Unmarshal(raw, &st); err != nil {
return vmStatusReply{}, fmt.Errorf("parse query-status: %w", err)
}
return st, nil
}
func tryResumePaused(c *Conn) {
st, err := queryVMStatus(c)
if err != nil || st.Running {
return
}
// Only resume when QEMU is still in ordinary paused state (never postmigrate).
if st.Status == "paused" {
_ = c.ExecuteWithTimeout("cont", nil, 10*time.Second)
}
}
func cancelIncompleteSuspend(ctx context.Context, c *Conn) bool {
cancelSent := false
for ctx.Err() == nil {
info, err := queryMigration(c, 2*time.Second)
if err != nil {
return false
}
switch info.Status {
case "failed", "cancelled":
tryResumePaused(c)
return true
case "completed", "none", "":
return false
}
if !cancelSent {
// Completion can race cancellation. Check the terminal status
// even if QEMU rejects the cancel request.
_ = c.ExecuteWithTimeout("migrate_cancel", nil, 2*time.Second)
cancelSent = true
}
sleep(ctx, migratePollInterval)
}
return false
}
func queryMigration(c *Conn, timeout time.Duration) (migrateInfo, error) {
var info migrateInfo
raw, err := c.QueryWithTimeout("query-migrate", nil, timeout)
if err != nil {
return info, err
}
if err := json.Unmarshal(raw, &info); err != nil {
return info, fmt.Errorf("parse query-migrate: %w", err)
}
return info, nil
}
func waitMigrateDone(ctx context.Context, c *Conn, onProgress func(MigrateProgress)) error {
deadline := time.Now().Add(migrateTotalTimeout)
for {
if err := ctx.Err(); err != nil {
return err
}
if time.Now().After(deadline) {
return errors.New("timed out waiting for migration to finish")
}
info, err := queryMigration(c, migrateCmdTimeout)
if err != nil {
return err
}
prog := MigrateProgress{
Status: info.Status,
TotalTimeMs: info.TotalTimeMs,
}
if info.RAM != nil {
prog.Transferred = info.RAM.Transferred
prog.Remaining = info.RAM.Remaining
prog.Total = info.RAM.Total
}
if onProgress != nil {
onProgress(prog)
}
switch info.Status {
case "completed":
return nil
case "failed", "cancelled":
return &migrationFailure{status: info.Status, desc: strings.TrimSpace(info.ErrorDesc)}
}
sleep(ctx, migratePollInterval)
}
}
func dialMigrateConnWithRetry(ctx context.Context, network, addr string, timeout time.Duration) (*Conn, error) {
deadline := time.Now().Add(timeout)
var lastErr error
for {
c, err := Dial(ctx, network, addr)
if err == nil {
return c, nil
}
lastErr = err
if ctx.Err() != nil || time.Now().After(deadline) {
return nil, lastErr
}
sleep(ctx, 100*time.Millisecond)
}
}
func runSuspendMigration(ctx context.Context, c *Conn, args map[string]any, onProgress func(MigrateProgress)) error {
if err := c.ExecuteWithTimeout("migrate", args, migrateCmdTimeout); err != nil {
var rejected *commandError
if errors.As(err, &rejected) {
return fmt.Errorf("%w: start snapshot save: %w", ErrIncompleteSuspend, err)
}
return &unknownSuspendOutcome{fmt.Errorf("start snapshot save: %w", err)}
}
if err := waitMigrateDone(ctx, c, onProgress); err != nil {
var failed *migrationFailure
if errors.As(err, &failed) {
return fmt.Errorf("%w: save snapshot: %w", ErrIncompleteSuspend, err)
}
return &unknownSuspendOutcome{fmt.Errorf("save snapshot: %w", err)}
}
return nil
}
func isDirectIOErr(err error) bool {
s := strings.ToLower(err.Error())
return strings.Contains(s, "direct i/o") || strings.Contains(s, "direct-io") || strings.Contains(s, "o_direct")
}
func isConnClosedErr(err error) bool {
if err == nil {
return false
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "connection closed") || strings.Contains(s, "eof") || strings.Contains(s, "wsarecv") || strings.Contains(s, "broken pipe")
}
+536
View File
@@ -0,0 +1,536 @@
package qmp
import (
"bufio"
"context"
"encoding/json"
"errors"
"net"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"time"
)
func TestSuspendToFileRequiresSeal(t *testing.T) {
if err := SuspendToFile(context.Background(), t.TempDir(), "state", nil, nil); err == nil ||
!strings.Contains(err.Error(), "seal callback") {
t.Fatalf("suspend without a seal callback: %v", err)
}
}
func TestSuspendMigrationFailedBeforeSeal(t *testing.T) {
addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
reply := map[string]any{}
switch req.Execute {
case "query-status":
reply["status"] = "paused"
reply["running"] = false
case "query-migrate":
reply["status"] = "failed"
reply["error-desc"] = "write failed"
case "quit":
t.Error("QEMU would exit after an incomplete save")
}
return map[string]any{"return": reply}, false
})
ctx := context.Background()
c, err := Dial(ctx, "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
err = suspendToFileConn(ctx, c, "state.tmp", nil, func(*Conn) error {
t.Error("an incomplete save reached seal")
return nil
})
if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "write failed") {
t.Fatalf("incomplete save = %v", err)
}
}
func TestCancelIncompleteSuspendRechecksTerminalStatus(t *testing.T) {
for _, terminal := range []string{"cancelled", "completed"} {
t.Run(terminal, func(t *testing.T) {
cancelled := false
addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "query-migrate":
status := "active"
if cancelled {
status = terminal
}
return map[string]any{"return": map[string]any{"status": status}}, false
case "migrate_cancel":
cancelled = true
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
}
return map[string]any{"return": map[string]any{}}, false
})
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
c, err := Dial(ctx, "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
want := terminal == "cancelled"
if got := cancelIncompleteSuspend(ctx, c); got != want {
t.Fatalf("safe discard = %t, want %t", got, want)
}
cmds := recorded()
if sawCont := len(cmds) > 0 && cmds[len(cmds)-1].Execute == "cont"; sawCont != want {
t.Fatalf("unexpected rollback commands: %v", cmds)
}
})
}
}
func TestAttachedFiles(t *testing.T) {
vmDir := t.TempDir()
disk := filepath.Join(vmDir, "disk.qcow2")
parent := filepath.Join(vmDir, "base.qcow2")
addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
if req.Execute != "query-block" {
t.Errorf("unexpected command: %s", req.Execute)
}
return map[string]any{"return": []map[string]any{
{"device": "disk", "inserted": map[string]any{"image": map[string]any{
"filename": disk, "backing-image": map[string]any{"filename": parent},
}}},
{"device": "empty", "inserted": nil},
}}, false
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
got, err := c.AttachedFiles(vmDir)
if err != nil || !slices.Equal(got, []string{parent, disk}) {
t.Fatalf("attached files = %v, %v", got, err)
}
}
func TestAttachedFilesRejectsTemporaryOverlay(t *testing.T) {
addr, _ := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
return map[string]any{"return": []map[string]any{
{"device": "installer", "inserted": map[string]any{"image": map[string]any{
"filename": "json:temporary disk descriptor",
}}},
}}, false
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
if _, err := c.AttachedFiles(t.TempDir()); err == nil || !strings.Contains(err.Error(), "installer uses a non-persistent") {
t.Fatalf("temporary installer overlay = %v", err)
}
}
func TestSuspendSealFailureDoesNotQuitSource(t *testing.T) {
addr, recorded := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "completed"}}, false
case "quit":
t.Error("QEMU would exit with an unsealed snapshot")
}
return map[string]any{"return": map[string]any{}}, false
})
ctx := context.Background()
c, err := Dial(ctx, "tcp", addr)
if err != nil {
t.Fatal(err)
}
defer c.Close()
sealErr := errors.New("unable to publish state")
if err := suspendToFileConn(ctx, c, "test.vmstate", nil, func(*Conn) error { return sealErr }); !errors.Is(err, sealErr) || errors.Is(err, ErrIncompleteSuspend) {
t.Fatalf("suspend error = %v", err)
}
cmds := recorded()
if len(cmds) == 0 || cmds[len(cmds)-1].Execute != "query-migrate" {
t.Fatalf("unexpected commands: %+v", cmds)
}
}
type mockQMPReq struct {
Execute string `json:"execute"`
Arguments json.RawMessage `json:"arguments"`
}
func startMockQMP(t *testing.T, handle func(req mockQMPReq) (reply map[string]any, closeAfter bool)) (string, func() []mockQMPReq) {
t.Helper()
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen mock QMP: %v", err)
}
t.Cleanup(func() { _ = ln.Close() })
var mu sync.Mutex
var recorded []mockQMPReq
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go func(nc net.Conn) {
defer nc.Close()
_, _ = nc.Write([]byte(`{"QMP":{"version":{"qemu":{"major":9,"minor":2,"micro":0}},"capabilities":[]}}` + "\n"))
sc := bufio.NewScanner(nc)
for sc.Scan() {
var req mockQMPReq
if err := json.Unmarshal(sc.Bytes(), &req); err != nil {
return
}
if req.Execute == "qmp_capabilities" {
_, _ = nc.Write([]byte(`{"return":{}}` + "\n"))
continue
}
mu.Lock()
recorded = append(recorded, req)
mu.Unlock()
reply, closeAfter := handle(req)
if reply != nil {
b, _ := json.Marshal(reply)
_, _ = nc.Write(append(b, '\n'))
}
if closeAfter {
return
}
}
}(conn)
}
}()
return ln.Addr().String(), func() []mockQMPReq {
mu.Lock()
defer mu.Unlock()
return append([]mockQMPReq(nil), recorded...)
}
}
func TestSuspendToFileHappyPath(t *testing.T) {
polls := 0
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate-set-parameters", "migrate":
return map[string]any{"return": map[string]any{}}, false
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "query-migrate":
polls++
if polls == 1 {
return map[string]any{"return": map[string]any{
"status": "active",
"ram": map[string]any{"transferred": 1024, "remaining": 1024, "total": 2048},
}}, false
}
return map[string]any{"return": map[string]any{
"status": "completed",
"total-time": 4500,
"ram": map[string]any{"transferred": 2048, "remaining": 0, "total": 2048},
}}, false
case "quit":
return map[string]any{"return": map[string]any{}}, true
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
var progress []MigrateProgress
if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, func(p MigrateProgress) {
progress = append(progress, p)
}, nil); err != nil {
t.Fatalf("suspendToFileConn: %v", err)
}
if len(progress) != 2 || progress[1].Status != "completed" {
t.Fatalf("unexpected progress: %+v", progress)
}
got := cmds()
var names []string
var sawBandwidthZero, sawChannels, sawDirectIO bool
for _, r := range got {
names = append(names, r.Execute)
if r.Execute == "migrate-set-parameters" {
var params map[string]any
if err := json.Unmarshal(r.Arguments, &params); err != nil {
t.Fatalf("unmarshal migrate-set-parameters: %v", err)
}
if bw, ok := params["max-bandwidth"].(float64); ok && bw == UnlimitedMigrationBandwidth {
sawBandwidthZero = true
}
if ch, ok := params["multifd-channels"].(float64); ok && int(ch) == DefaultMultifdChannels {
sawChannels = true
}
if dio, ok := params["direct-io"].(bool); ok && dio {
sawDirectIO = true
}
}
}
want := "stop,query-status,migrate-set-capabilities,migrate-set-parameters,migrate-set-parameters,migrate,query-migrate,query-migrate,quit"
if strings.Join(names, ",") != want {
t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want)
}
if !sawBandwidthZero || !sawChannels || !sawDirectIO {
t.Fatalf("expected max-bandwidth=0 (%t), multifd-channels=%d (%t), direct-io=true (%t)",
sawBandwidthZero, DefaultMultifdChannels, sawChannels, sawDirectIO)
}
}
func TestSuspendToFileFallsBackWhenDirectIOUnsupported(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate":
return map[string]any{"return": map[string]any{}}, false
case "migrate-set-parameters":
if strings.Contains(string(req.Arguments), `"direct-io":true`) {
return map[string]any{"error": map[string]any{"class": "GenericError", "desc": "No build-time support for direct-io"}}, false
}
return map[string]any{"return": map[string]any{}}, false
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "completed", "total-time": 1200}}, false
case "quit":
return map[string]any{"return": map[string]any{}}, true
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
if err := suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil); err != nil {
t.Fatalf("suspendToFileConn with unsupported direct-io: %v", err)
}
var names []string
for _, r := range cmds() {
names = append(names, r.Execute)
}
want := "stop,query-status,migrate-set-capabilities,migrate-set-parameters,migrate-set-parameters,migrate,query-migrate,quit"
if strings.Join(names, ",") != want {
t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want)
}
}
func TestSuspendToFileRetriesBufferedOnlyForDirectIOFailures(t *testing.T) {
for _, tc := range []struct {
name string
reason string
retry bool
}{
{"open rejected", "Unable to open 'suspend.vmstate.tmp' with direct I/O", true},
{"write rejected", "Unable to pwritev to file with direct I/O: The parameter is incorrect", true},
{"disk full", "Unable to pwritev to file: The disk is full", false},
} {
t.Run(tc.name, func(t *testing.T) {
attempts := 0
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate-set-parameters", "cont":
return map[string]any{"return": map[string]any{}}, false
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "migrate":
attempts++
return map[string]any{"return": map[string]any{}}, false
case "query-migrate":
if attempts == 1 {
return map[string]any{"return": map[string]any{
"status": "failed", "error-desc": tc.reason,
}}, false
}
return map[string]any{"return": map[string]any{"status": "completed"}}, false
case "quit":
return map[string]any{"return": map[string]any{}}, true
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
ctx := context.Background()
c, err := Dial(ctx, "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
err = suspendToFileConn(ctx, c, `C:\VMs\mac\suspend.vmstate`, nil, nil)
wantAttempts := 1
if tc.retry {
wantAttempts = 2
if err != nil {
t.Fatalf("buffered retry failed: %v", err)
}
} else if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), tc.reason) {
t.Fatalf("expected original write error, got %v", err)
}
gotAttempts := 0
var disabledDirectIO, resumed bool
for _, req := range cmds() {
switch req.Execute {
case "migrate":
gotAttempts++
case "migrate-set-parameters":
disabledDirectIO = disabledDirectIO || strings.Contains(string(req.Arguments), `"direct-io":false`)
case "cont":
resumed = true
}
}
if gotAttempts != wantAttempts || disabledDirectIO != tc.retry || resumed == tc.retry {
t.Fatalf("attempts = %d, direct I/O disabled = %t, guest resumed = %t", gotAttempts, disabledDirectIO, resumed)
}
})
}
}
func TestSuspendToFileFailureResumesPausedVM(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "stop", "migrate-set-capabilities", "migrate-set-parameters", "cont":
return map[string]any{"return": map[string]any{}}, false
case "query-status":
return map[string]any{"return": map[string]any{"running": false, "status": "paused"}}, false
case "migrate":
return map[string]any{"error": map[string]any{"class": "GenericError", "desc": "disk full"}}, false
default:
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
err = suspendToFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil, nil)
if !errors.Is(err, ErrIncompleteSuspend) || !strings.Contains(err.Error(), "disk full") {
t.Fatalf("expected disk full error, got %v", err)
}
var sawCont bool
for _, r := range cmds() {
if r.Execute == "cont" {
sawCont = true
}
if r.Execute == "quit" {
t.Fatal("must not quit QEMU when migrate fails")
}
}
if !sawCont {
t.Fatal("expected cont rollback when migrate fails while paused")
}
}
func TestResumeFromFileHappyPath(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming", "cont":
return map[string]any{"return": map[string]any{}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "completed", "total-time": 1900}}, false
default:
t.Errorf("unexpected QMP command: %s", req.Execute)
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
if err := resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil); err != nil {
t.Fatalf("resumeFromFileConn: %v", err)
}
got := cmds()
var names []string
var sawExitOnErrorFalse, sawBandwidthZero, sawChannels, sawDirectIO bool
for _, r := range got {
names = append(names, r.Execute)
if r.Execute == "migrate-incoming" && strings.Contains(string(r.Arguments), `"exit-on-error":false`) {
sawExitOnErrorFalse = true
}
if r.Execute == "migrate-set-parameters" {
var params map[string]any
if err := json.Unmarshal(r.Arguments, &params); err != nil {
t.Fatalf("unmarshal migrate-set-parameters: %v", err)
}
if bw, ok := params["max-bandwidth"].(float64); ok && bw == UnlimitedMigrationBandwidth {
sawBandwidthZero = true
}
if ch, ok := params["multifd-channels"].(float64); ok && int(ch) == DefaultMultifdChannels {
sawChannels = true
}
if _, ok := params["direct-io"]; ok {
sawDirectIO = true
}
}
}
want := "migrate-set-capabilities,migrate-set-parameters,migrate-incoming,query-migrate,cont"
if strings.Join(names, ",") != want {
t.Fatalf("commands = %q, want %q", strings.Join(names, ","), want)
}
if !sawExitOnErrorFalse {
t.Fatal("expected migrate-incoming to pass exit-on-error:false")
}
if !sawBandwidthZero || !sawChannels {
t.Fatalf("expected resume max-bandwidth=0 (%t) and multifd-channels=%d (%t)",
sawBandwidthZero, DefaultMultifdChannels, sawChannels)
}
if sawDirectIO {
t.Fatal("resume must keep direct-io disabled to preserve OS read-ahead")
}
}
func TestResumeFromFileFailedDoesNotCont(t *testing.T) {
addr, cmds := startMockQMP(t, func(req mockQMPReq) (map[string]any, bool) {
switch req.Execute {
case "migrate-set-capabilities", "migrate-set-parameters", "migrate-incoming":
return map[string]any{"return": map[string]any{}}, false
case "query-migrate":
return map[string]any{"return": map[string]any{"status": "failed", "error-desc": "corrupt RVGSNAP1 snapshot"}}, false
default:
return map[string]any{"return": map[string]any{}}, false
}
})
c, err := Dial(context.Background(), "tcp", addr)
if err != nil {
t.Fatalf("Dial: %v", err)
}
defer c.Close()
err = resumeFromFileConn(context.Background(), c, `C:\VMs\mac\suspend.vmstate`, nil)
if err == nil || !strings.Contains(err.Error(), "corrupt RVGSNAP1 snapshot") {
t.Fatalf("expected corrupt snapshot error, got %v", err)
}
for _, r := range cmds() {
if r.Execute == "cont" {
t.Fatal("must not issue cont when restore failed")
}
}
}
+24 -3
View File
@@ -89,9 +89,7 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string {
}
cleaned = append(cleaned, tok)
}
escaped := strings.ReplaceAll(sockPath, ",", ",,")
escaped = strings.ReplaceAll(escaped, `\`, `/`)
qmpVal := fmt.Sprintf("unix:%s,server=on,wait=off", escaped)
qmpVal := win10RebootUnixTarget(sockPath)
if strings.ContainsAny(qmpVal, " \t") {
qmpVal = `"` + strings.ReplaceAll(qmpVal, `"`, `\"`) + `"`
}
@@ -99,6 +97,29 @@ func MergeWin10RebootUnixArgs(existing, sockPath string) string {
return strings.Join(cleaned, " ")
}
func win10RebootUnixTarget(sockPath string) string {
escaped := strings.ReplaceAll(sockPath, ",", ",,")
escaped = strings.ReplaceAll(escaped, "\\", "/")
return "unix:" + escaped + ",server=on,wait=off"
}
// HasWin10RebootUnixArgs checks for the private socket Reims-Go configured,
// without accepting other monitors declared in extra-args.
func HasWin10RebootUnixArgs(extraArgs, sockPath string) bool {
tokens := splitShellTokens(extraArgs)
want := win10RebootUnixTarget(sockPath)
var noReboot, socket bool
for i, token := range tokens {
if token == "-no-reboot" {
noReboot = true
}
if token == "-qmp" && i+1 < len(tokens) && strings.Trim(tokens[i+1], "'\"") == want {
socket = true
}
}
return noReboot && socket
}
func isManagedQMPTarget(arg string) bool {
arg = strings.Trim(arg, "'\"")
if !strings.HasSuffix(arg, ",server=on,wait=off") {
+17
View File
@@ -10,6 +10,23 @@ import (
"time"
)
func TestHasWin10RebootUnixArgs(t *testing.T) {
sock := "D:\\VM data\\group,1\\reims-go-reboot.sock"
args := MergeWin10RebootUnixArgs("-machine q35", sock)
if !HasWin10RebootUnixArgs(args, sock) {
t.Fatal("saved socket with escaped comma and quoted path was not recognized")
}
if HasWin10RebootUnixArgs(strings.ReplaceAll(args, "-no-reboot", ""), sock) {
t.Fatal("recognized a monitor without the cold-reboot flag")
}
if HasWin10RebootUnixArgs(args, "D:/other/reims-go-reboot.sock") {
t.Fatal("recognized a different monitor")
}
if HasWin10RebootUnixArgs("-no-reboot -qmp tcp:127.0.0.1:45555,server=on,wait=off", sock) {
t.Fatal("recognized a legacy TCP monitor")
}
}
func TestMergeWin10RebootUnixArgs(t *testing.T) {
got := MergeWin10RebootUnixArgs("", `D:\Data\reims-go\vms\m0\reims-go-reboot.sock`)
want := "-no-reboot -qmp unix:D:/Data/reims-go/vms/m0/reims-go-reboot.sock,server=on,wait=off"
+13 -3
View File
@@ -162,14 +162,15 @@ func (m Manifest) EffectiveCapabilities() []string {
const buggyWin32UnicodeInputPatchSHA256 = "0b34f7c0ebdf3ca537c7f4523af97967a06924aedba7058dbc978870f561b366"
// legacyCapabilities declares capabilities for built-in packages whose
// manifest.json predates the "capabilities" field. It mirrors the mapping in
// scripts/pack-runtime.ps1 and runs once when the manifest is read, so callers
// only ever see declared capabilities. Other kinds must declare their own.
// manifest.json predates the "capabilities" field. It runs once when the
// manifest is read, so callers only ever see declared capabilities. Other kinds
// must declare their own.
func legacyCapabilities(m Manifest) []string {
if m.EffectiveKind() != DefaultKind {
return nil
}
var out []string
var hasWin32MappedRAM, hasIntelWHPXSuspend, hasVGPUSnapshotReplay bool
for _, p := range m.Patches {
low := strings.ToLower(p.Name)
var c string
@@ -188,11 +189,20 @@ func legacyCapabilities(m Manifest) []string {
}
case strings.Contains(low, "display-fixed-mode"):
c = "display-fixed-mode"
case strings.Contains(low, "win32-mapped-ram-io"):
hasWin32MappedRAM = true
case strings.Contains(low, "intel-whpx-suspend"):
hasIntelWHPXSuspend = true
case strings.Contains(low, "reims-vgpu-snapshot-replay"):
hasVGPUSnapshotReplay = true
}
if c != "" && !slices.Contains(out, c) {
out = append(out, c)
}
}
if hasWin32MappedRAM && hasIntelWHPXSuspend && hasVGPUSnapshotReplay && !slices.Contains(out, "vm-suspend") {
out = append(out, "vm-suspend")
}
return out
}
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff. Show more