From 938fc8193ac01e16a40e019b70623e630f6dc98c Mon Sep 17 00:00:00 2001 From: ssdsl0126 <35905829+ssdsl0126@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:24:38 +0800 Subject: [PATCH 01/47] feat(network): add Npcap bridging and live per-VM uplink switching --- docs/architecture.md | 1 + docs/design-guidelines.md | 2 +- docs/networking.md | 48 +++ docs/roadmap.md | 3 +- frontend/scripts/test-i18n.mjs | 4 + frontend/src/App.tsx | 21 +- frontend/src/components/CreateWizard.tsx | 68 +++- .../src/components/NetworkErrorNotice.tsx | 15 + frontend/src/components/NpcapDependency.tsx | 39 ++ frontend/src/components/SettingsModal.tsx | 12 +- frontend/src/components/VMNetworkSettings.tsx | 138 ++++++++ frontend/src/components/VMPage.tsx | 4 +- frontend/src/i18n/domains/settings.gen.ts | 58 +++ frontend/src/i18n/domains/vm.gen.ts | 8 + frontend/src/i18n/keys.gen.ts | 33 ++ frontend/src/lib/format.ts | 4 + frontend/src/lib/useNetworkPlan.ts | 62 ++++ frontend/src/styles/app.css | 8 + frontend/src/types.ts | 4 + frontend/src/wails.ts | 7 +- frontend/wailsjs/go/app/App.d.ts | 20 +- frontend/wailsjs/go/app/App.js | 36 +- frontend/wailsjs/go/models.ts | 86 +++++ internal/app/app.go | 39 ++ internal/app/clone_flow.go | 2 +- internal/app/create_flow.go | 41 ++- internal/app/create_network.go | 35 ++ internal/app/guesttools_flow.go | 42 ++- internal/app/install_flow.go | 4 +- internal/app/network_dependencies.go | 75 ++++ internal/app/network_flow.go | 299 ++++++++++++++++ internal/app/network_i18n.go | 7 + internal/app/network_lock.go | 76 ++++ internal/app/network_policy.go | 94 +++++ internal/app/network_transaction.go | 44 +++ internal/app/packet_network.go | 326 +++++++++++++++++ internal/app/suspend_flow.go | 7 + internal/driver/reims/guest_network.go | 44 +++ internal/driver/reims/network.go | 335 ++++++++++++++++++ internal/driver/reims/reims.go | 15 +- internal/guesttools/management.go | 220 ++++++++++++ internal/guesttools/server.go | 13 + internal/i18n/catalog_gen.go | 172 +++++++++ internal/networkmsg/messages.go | 60 ++++ internal/packetbridge/adapters.go | 11 + internal/packetbridge/adapters_other.go | 7 + internal/packetbridge/adapters_windows.go | 93 +++++ internal/packetbridge/bridge.go | 277 +++++++++++++++ internal/packetbridge/frame.go | 186 ++++++++++ internal/packetbridge/installation_windows.go | 67 ++++ internal/packetbridge/installer.go | 54 +++ internal/packetbridge/installer_other.go | 8 + internal/packetbridge/installer_windows.go | 86 +++++ internal/packetbridge/pcap_other.go | 14 + internal/packetbridge/pcap_windows.go | 201 +++++++++++ internal/plugin/builtin/builtin.go | 40 ++- internal/qmp/network.go | 38 ++ locales/en-US/native.json | 82 +++++ locales/en-US/settings.json | 29 ++ locales/en-US/vm.json | 4 + locales/zh-CN/native.json | 82 +++++ locales/zh-CN/settings.json | 29 ++ locales/zh-CN/vm.json | 4 + 63 files changed, 3878 insertions(+), 65 deletions(-) create mode 100644 docs/networking.md create mode 100644 frontend/src/components/NetworkErrorNotice.tsx create mode 100644 frontend/src/components/NpcapDependency.tsx create mode 100644 frontend/src/components/VMNetworkSettings.tsx create mode 100644 frontend/src/lib/useNetworkPlan.ts create mode 100644 internal/app/create_network.go create mode 100644 internal/app/network_dependencies.go create mode 100644 internal/app/network_flow.go create mode 100644 internal/app/network_i18n.go create mode 100644 internal/app/network_lock.go create mode 100644 internal/app/network_policy.go create mode 100644 internal/app/network_transaction.go create mode 100644 internal/app/packet_network.go create mode 100644 internal/driver/reims/guest_network.go create mode 100644 internal/driver/reims/network.go create mode 100644 internal/guesttools/management.go create mode 100644 internal/networkmsg/messages.go create mode 100644 internal/packetbridge/adapters.go create mode 100644 internal/packetbridge/adapters_other.go create mode 100644 internal/packetbridge/adapters_windows.go create mode 100644 internal/packetbridge/bridge.go create mode 100644 internal/packetbridge/frame.go create mode 100644 internal/packetbridge/installation_windows.go create mode 100644 internal/packetbridge/installer.go create mode 100644 internal/packetbridge/installer_other.go create mode 100644 internal/packetbridge/installer_windows.go create mode 100644 internal/packetbridge/pcap_other.go create mode 100644 internal/packetbridge/pcap_windows.go create mode 100644 internal/qmp/network.go diff --git a/docs/architecture.md b/docs/architecture.md index 43b92a1..38e8fbd 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -57,6 +57,7 @@ flowchart TB | `internal/vmstart` | GUI 与 CLI 共用的启动前准备:提交内存预检、离线辅助盘、恢复模式引导、客体语言重放、WHPX 兼容处理、启动后 CPU 绑核 | | `internal/cli` | 命令行子命令实现、单实例参数解析与向界面进程交接 `vm start` | | `internal/host` | 宿主机体检与硬件调优:WHPX 检测与 UAC 启用、提交内存预检、Vulkan ICD 扫描、三层大小核拓扑与实时绑核、显示器 HiDPI 推荐、音频与磁盘总线探测、窗口置前、IME 文本钩子 | +| `internal/packetbridge`、`internal/networkmsg` | 基于 Npcap 的独立有线/WLAN 出口、运行中更换出口及虚拟机网络事务恢复,以及复用 i18n 词条、参数和 CodedError 的网络提示;行为、依赖和验收边界见 [网络管理](networking.md) | | `internal/runtime` | 便携运行时拉取(GitHub Releases)、原子解压、多版本切换与子进程环境变量构造 | | `internal/fetch` | 发布附件下载:HTTP `Range` 续传与按发布页 `SHA256SUMS.txt` 强制校验,运行时安装与应用内更新共用 | | `internal/selfupdate` | 应用内更新:把已校验的新版 `reims-go.exe` 换入运行中程序的位置、重新拉起与残留清理 | diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index 481e3fb..49ab496 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -36,7 +36,7 @@ Reims-Go 的桌面外壳遵循「**macOS 的结构与词表,Windows 的平台 | **CPU** | 核心数、CPU 亲和性策略(自动/全部/性能核/避开低功耗核/自定义) | 核心数下次启动;亲和性立即生效 | 亲和性由 Reims-Go 在宿主机侧实时绑定 | | **内存** | 客体内存大小 | 下次启动 | 按宿主机可用提交内存推荐安全档位,启动前拦截超额配置 | | **存储** | 磁盘控制器(NVMe / VirtIO / SATA)、停机扩容、空间回收、恢复点 | 停机时 / 下次启动 | 切换控制器前须先弹出安装盘;扩容与空间回收仅在停机状态执行 | -| **网络** | 网络开关、SSH 端口转发、MAC 地址 | 下次启动 | MAC 属于敏感字段,默认隐藏 | +| **网络** | 关闭 / NAT / 桥接、出口网卡、SSH 端口转发、MAC 地址 | 模式关机后单独应用;Npcap 桥接出口可运行中更换;SSH 下次启动 | 每台虚拟机独立选择物理出口,使用 Npcap 转发;MAC 属于敏感字段,默认隐藏,见 [网络管理](networking.md) | | **图形与显示器** | 显卡后端、显示器数量(1–4)、分辨率 / HiDPI / 全屏、宿主 GPU | 下次启动(改后端需停机) | GPU 列表自动过滤虚拟显示适配器;按主屏分辨率与 DPI 推荐清晰 HiDPI 档位 | | **音频** | 音频开关、音频后端 | 下次启动 | 展示宿主播放/录音设备可用状态 | | **键盘与指针** | 点击窗口捕获键鼠 | 下次启动 | 按实际图形后端展示准确的快捷键提示 | diff --git a/docs/networking.md b/docs/networking.md new file mode 100644 index 0000000..b14d773 --- /dev/null +++ b/docs/networking.md @@ -0,0 +1,48 @@ +# 网络管理 + +新建向导与设置提供关闭、NAT 和桥接。桥接统一使用 Npcap,每台虚拟机独立选择有线或 WLAN 出口,不创建宿主网桥或虚拟出口网卡,不修改宿主的 IP、DNS、路由及协议绑定。 + +## 模式与出口 + +- NAT 使用运行时生成的用户态网络,支持本机回环 SSH 端口转发。 +- 桥接为每台虚拟机提供独立的本地帧通道,通过所选物理网卡收发。多台虚拟机可使用同一出口,也可选择不同出口,无需统一迁移其他虚拟机。 +- 同一出口的虚拟机通过本地转发互通,不向其他出口传播广播。这不阻断上游局域网本来就能互通的流量,同一 DHCP 服务器可以给不同出口上的虚拟机分别分配租约。 +- 更改关闭、NAT、桥接三种模式时要求目标虚拟机关机。已运行的 Npcap 桥接虚拟机可更换出口,其他虚拟机无需关机;更换出口不修改 QEMU 设备、MAC、PCI 布局或运行时参数。 + +运行中更换出口会关闭该虚拟机的原转发通道并在原本地端口重新打开。等待 QEMU 重连后,通过 QMP `set_link` 让主联网网卡断开两秒再接通,通知客体重新检查链路和 DHCP,期间会短暂断流;专用管理网卡不参与重连,无需更新 Guest Tools。客体使用静态地址时需自行调整。应用不宣称跨网段切换能保留现有 TCP 会话。 + +当前运行时 QEMU commit `c67660108a968231d2b4eb95128e59d73d028256` 的 [net/net.c:1590](https://github.com/yxc0915/qemu-reims-vgpu/blob/c67660108a968231d2b4eb95128e59d73d028256/net/net.c#L1590) 会把主通道链路变化传递给相连的 NIC,[hw/net/e1000.c:1509](https://github.com/yxc0915/qemu-reims-vgpu/blob/c67660108a968231d2b4eb95128e59d73d028256/hw/net/e1000.c#L1509) 注册链路变化处理。命令本身不代表 DHCP 已完成,macOS 实际续租仍需真实客体验收。 + +配置通过 `reims-ctl set` 保存。网络模式转换只替换主网络,保留设备身份及其他用户参数;切回 NAT 后恢复运行时生成的主网络。生成命令只在内存中检查,不记录完整命令。自定义主网络、重复设备或不明确的布局会停止自动修改,需由用户处理。 + +上游参数核验基线为 `steelbrain/reims-vgpu` commit `3731afd9b13416a24f74ec27a90b3913aef2dcc0`:[追加参数](https://github.com/steelbrain/reims-vgpu/blob/3731afd9b13416a24f74ec27a90b3913aef2dcc0/crates/reims-ctl/src/qemu.rs#L202)、[生成主网卡](https://github.com/steelbrain/reims-vgpu/blob/3731afd9b13416a24f74ec27a90b3913aef2dcc0/crates/reims-ctl/src/qemu.rs#L426)、[解析额外参数](https://github.com/steelbrain/reims-vgpu/blob/3731afd9b13416a24f74ec27a90b3913aef2dcc0/crates/reims-ctl/src/cli.rs#L1418)。其他版本以实际生成命令校验。 + +## 依赖安装 + +新建向导与网络设置显示 Npcap 安装状态和「下载并安装」入口。缺少 Npcap 时,应用网络或新建桥接虚拟机会先从 [Npcap 官网](https://npcap.com/#download) 下载固定版本的官方安装程序到数据目录缓存,校验 SHA-256 与 Authenticode 签名,再打开官方图形向导。许可、安装选项和 UAC 由用户确认;不使用仅 OEM 提供的静默安装,不随应用重新分发 Npcap 二进制。使用限制以 [Npcap 官方许可与安装说明](https://npcap.com/guide/npcap-users-guide.html) 为准。 + +只有安装或修复驱动时要求全部虚拟机关机,避免安装程序重载正在使用的驱动;已经安装 Npcap 时,选择多个出口没有整组关机限制。安装程序要求重启时提示用户处理,不自动重启 Windows。 + +安装状态每次检查实际 DLL、驱动文件及只读服务状态,查询本身不加载 DLL,不因已加载的句柄而忽略卸载。服务删除、停止中、被禁用或文件不完整时不视为完整安装;正常按需启动的已停止服务不等同于未安装。界面定时刷新安装状态,返回窗口时立即重查。 + +创建桥接虚拟机前先准备依赖并打开、激活所选出口,此检查不发送报文。准备失败时尚未分配虚拟机,可修正问题后以原名称重试。虚拟机已创建而网络应用失败时保留虚拟机及磁盘,不自动启动,提示进入网络设置继续处理。 + +## 事务与恢复 + +每台虚拟机的网络操作使用 GUI、CLI 共用的跨进程锁。模式切换先准备转发通道,再保存并校验虚拟机配置;失败时恢复原配置及原通道。运行中更换出口只保存本地出口记录,不调用 `reims-ctl set`;等待通道重连和主网卡通知成功后才提交新出口。取消和失败时仍尝试把主网卡恢复为接通,无法恢复时保留未完成标记。 + +虚拟机目录中的 `.reims-go-network.json` 保存出口、本地端口及未完成事务。未完成恢复会阻止启动和普通配置修改,要求关闭该虚拟机后通过「检查并修复」重试。记录可能包含本机设备身份,不得提交仓库或原文公开。 + +网络错误与依赖安装进度接入现有 i18n,使用 `network.*` 词条、命名参数及 `CodedError`,提供稳定的 `E_NETWORK_*` 错误码。内置中英文,其他语言沿用语言包及回退规则;系统原始诊断按原文脱敏保留。 + +## 兼容性与边界 + +Npcap 转发使用系统目录中的官方库,支持 ARP、IPv4、IPv6,保留客体 IP 与 DHCP 身份并转换链路地址。WLAN 使用普通以太网兼容模式,不要求监听模式。此方式不宣称支持 VLAN 干线、任意非 IP 二层协议或禁止同一物理 MAC 使用多个 IP 的上游网络。 + +管理器须保持运行;重新启动后恢复运行中虚拟机的通道,QEMU 自动重连。接口断开后尝试重新打开捕获句柄,不重置物理网卡。代理、VPN、无线驱动、Hyper-V 外部交换机及上游网络策略仍可能影响捕获或转发;不自动更改其配置。不同无线 AP、Hyper-V 占用出口、静态地址及客体实际跨网段续租需要真实环境验收。 + +## Guest Tools 管理通道 + +桥接虚拟机启动时自动加入专用管理网卡,沿用 Guest Tools 的认证地址与令牌。该通道用于剪贴板等宿主通信,DHCP 仅提供本地子网地址,移除默认网关、DNS、搜索域和代理选项,并关闭 IPv6。联网继续使用主网卡所选出口,更换出口不停止管理通道。 + +关闭或 NAT 模式不添加管理网卡。已有可用 Guest Tools 无需重装,已有虚拟机无需手动编辑。管理器重新启动时复用保存的端口,QEMU 自动重连。挂起恢复时重开原有转发与管理通道,保持封存的设备参数;Guest Tools 插件关闭时跳过管理通道恢复。 diff --git a/docs/roadmap.md b/docs/roadmap.md index 1a1f177..8404f12 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -52,6 +52,7 @@ ## 下一步计划(P1) ### 开发者网络与工作流增强 +- NAT 与 Npcap 桥接已接入新建向导与网络设置,每台虚拟机独立选择有线/WLAN 出口,桥接出口可在运行中更换。继续验证不同无线 AP、多虚拟机并行和桥接专用 Guest Tools 管理通道;实现与验收边界见 [网络管理](networking.md)。 - 支持自定义多条宿客 TCP 端口转发(含端口冲突检测),无需手写 `--extra-args`。 - 在 Guest Tools 中提供可选的宿主机代理快捷开关(显式开启、一键清除),方便客体内的 Homebrew / Xcode / npm 下载。 @@ -71,6 +72,6 @@ - **不长期维护上游 fork**:对 `reims-vgpu` / QEMU 的改动只走临时补丁队列,上游合入即退役。 - **不向默认用户分发未验证的上游最新提交**:CI 产物先进入 `alpha` 预发布,经真机冒烟并人工确认后才升级为 `stable`。 -- **暂不做 TAP / 虚拟网卡驱动安装器**:维护与驱动签名成本高,优先做好用户态网络、端口转发与 Guest Tools。 +- **不自行开发或分发未签名网络驱动**:桥接按需获取并校验 Npcap 官方安装程序,不维护自有内核驱动。 - **暂不做运行中内存热快照(`savevm`)**:在 `reims-vgpu` 显存与设备状态序列化未获上游验证前,以停机恢复点和 CoW 派生为准。 - **不兼容已淘汰的旧图形栈**:不引入 `apple-gfx` 等旧后端,不为堆砌参数列表而增加复杂界面。 diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index 6539187..1c26d7d 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -59,6 +59,10 @@ test('Static Guard (CRITICAL-1): lazy i18n domain keys are always backed by doma const lazyEntryBasenames = new Set([ 'CreateWizard.tsx', 'SettingsModal.tsx', + // 网络设置仅随延迟加载的 SettingsModal 进入,使用同一语言域。 + 'VMNetworkSettings.tsx', + // 由新建向导和网络设置两个延迟入口共用。 + 'NpcapDependency.tsx', 'AffinityDialog.tsx', 'Setup.tsx', 'RuntimeOnline.tsx', diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 11d5d38..3a61998 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -810,7 +810,8 @@ export const App: React.FC = () => { borderless: false, capture: false, audio: true, - network: !isOffline, + network: true, + network_mode: 'nat', ssh_port: 0, logs: true, guest_lang: defaultGuestLang(locale), @@ -835,6 +836,23 @@ export const App: React.FC = () => { }) .catch((e) => { void refresh() + const parsed = parseAppError(e) + if (parsed.code === 'E_NETWORK_CREATE_BRIDGE_PENDING') { + setSelected(name) + toasts.push({ + kind: 'error', + title: tr('toastCreated', { name }), + description: parsed.summary, + errorCode: parsed.code, + rawDetail: parsed.rawDetail, + detailsLabel: tr('errRawDetailsToggle'), + copyDetailsLabel: tr('errCopyDetails'), + action: { label: tr('settings'), onClick: () => { + api.GetVMDetail(name).then((d) => { setDetail(d); setSelected(name); setShowSettings(true) }).catch((err) => fail(tr('failGeneric'), err)) + } }, + }) + return + } if (/\bcontext canceled\b/i.test(errText(e))) { toasts.push({ kind: 'ok', @@ -844,7 +862,6 @@ export const App: React.FC = () => { }) return } - const parsed = parseAppError(e) toasts.push({ kind: 'error', title: tr('failCreate', { name }), diff --git a/frontend/src/components/CreateWizard.tsx b/frontend/src/components/CreateWizard.tsx index 7a210c6..d950b6e 100644 --- a/frontend/src/components/CreateWizard.tsx +++ b/frontend/src/components/CreateWizard.tsx @@ -1,5 +1,9 @@ import { Check, ChevronRight, CircleAlert, CircleCheck, CloudDownload, Copy, Disc3, HardDrive, LucideIcon, Package } from 'lucide-react' import React, { Suspense, lazy, useEffect, useState } from 'react' +import { useNetworkPlan } from '../lib/useNetworkPlan' +import { NpcapDependency } from './NpcapDependency' +import { NetworkErrorNotice } from './NetworkErrorNotice' +import type { ParsedAppError } from '../i18n' import '../i18n/domains/wizard.gen' import '../i18n/domains/settings.gen' import { I18nKey, locText, parseAppError, t } from '../i18n' @@ -30,7 +34,7 @@ import { splitLangLabel, sshCommand, } from '../lib/format' -import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue } from '../types' +import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types' import { findActiveOfflineTask, taskInstallerPhase } from '../lib/tasks' import { Button, IconButton } from '../ui/controls' import { NumberField, PopupSelect, RangeField, Segmented, SetGroup, SetRow, Switch } from '../ui/settings' @@ -64,6 +68,7 @@ const STEP_OF_FIELD: Record = { cpus: 2, memory: 2, disk_size: 3, disk_controller: 3, graphics: 4, gpu: 4, resolution: 4, displays: 4, ssh_port: 4, + network_mode: 4, uplink_guid: 4, } const stepOfIssue = (i: ValidationIssue) => STEP_OF_FIELD[i.field] ?? REVIEW_STEP @@ -88,6 +93,8 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, const [driverID, setDriverID] = useState(BUILTIN_MACOS_DRIVER) const [driverOpts, setDriverOpts] = useState>({}) const [driverCreating, setDriverCreating] = useState(false) + const [dependencyBusy, setDependencyBusy] = useState(false) + const [dependencyRefresh, setDependencyRefresh] = useState(0) useEffect(() => { let live = true @@ -100,8 +107,7 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, const [opts, setOpts] = useState(draft?.opts ?? { name: 'macos-tahoe', dir: '', - // Offline by default: one exact release that installs with no network - // (roadmap M2.3; `reims-ctl create --help`, upstream 3731afd). + // 安装源与网络模式独立,离线安装也可按需选择 NAT、桥接或关闭网络。 source_mode: 'offline', macos: '', offline: true, @@ -121,13 +127,31 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, borderless: false, capture: false, audio: true, - network: false, + network: true, + network_mode: 'nat', ssh_port: 0, logs: true, guest_lang: defaultGuestLang(locale), start: true, }) const set = (patch: Partial) => setOpts((o) => ({ ...o, ...patch })) + const networkMode = opts.network_mode ?? (opts.network ? 'nat' : 'off') + const [networkAdapters, setNetworkAdapters] = useState(null) + const [networkError, setNetworkError] = useState(null) + const { plan: networkPlan, planning: networkPlanning, planError: networkPlanError } = useNetworkPlan(opts.name.trim(), networkMode, opts.uplink_guid ?? '', step >= 4 && networkMode === 'bridge', `${dependencyRefresh}:${locale}`) + const networkBlocked = networkMode === 'bridge' && (networkPlanning || !!networkPlanError || !networkPlan || !opts.uplink_guid) + useEffect(() => { + if (step !== 4 || networkMode !== 'bridge') return + let active = true + setNetworkError(null) + api.ListNetworkAdapters().then((list) => { + if (!active) return + setNetworkAdapters(list ?? []) + const connected = (list ?? []).filter((adapter) => adapter.status === 'Up') + if (connected.length === 1) setOpts((current) => current.uplink_guid ? current : { ...current, uplink_guid: connected[0].guid }) + }).catch((error) => { if (active) setNetworkError(parseAppError(error)) }) + return () => { active = false } + }, [step, networkMode, locale]) const buildPayload = (): CreateOpts => { const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' } @@ -206,7 +230,10 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, if (f) set({ [field]: f }) } - const handleCreate = () => onSubmit(buildPayload(), { opts, step: REVIEW_STEP }) + const handleCreate = () => { + if (dependencyBusy || networkBlocked) return + onSubmit(buildPayload(), { opts, step: REVIEW_STEP }) + } const issueSteps = new Set(reviewed ? issues.map(stepOfIssue) : []) const realGPUs = (host.gpus ?? []).filter((g) => g.kind !== 'virtual') @@ -300,7 +327,6 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, checked={on} onChange={() => set({ source_mode: s.mode, - network: s.mode !== 'offline', ...(s.mode === 'apple' ? { macos: 'tahoe' } : {}), ...(s.mode === 'offline' ? { macos: releases?.[0]?.version ?? '' } : {}), })} @@ -592,14 +618,25 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, set({ network })} />} + desc={tr('bridgeModeDesc')} + control={ set({ network_mode: mode, network: mode !== 'off', ssh_port: mode === 'nat' ? opts.ssh_port : 0 })} options={[{ value: 'off', label: tr('off') }, { value: 'nat', label: tr('networkNAT') }, { value: 'bridge', label: tr('networkBridge') }]} />} /> + {networkMode === 'bridge' && + + {networkAdapters === null && !networkError && {tr('bridgeLoading')}} + {networkAdapters?.map((adapter) => )} + {networkAdapters?.length === 0 && {tr('bridgeNoAdapters')}} + } />} + {networkMode === 'bridge' && <> + setDependencyRefresh((value) => value + 1)} /> + {networkPlanning &&
{tr('bridgePlanPending')}
} + + } 0 ? {sshCommand(opts.ssh_port ?? 0)} : tr('sshOffDesc')} - disabled={!opts.network} - reason={tr('sshNeedsNetwork')} + disabled={networkMode !== 'nat'} + reason={tr(networkMode === 'bridge' ? 'sshNeedsNAT' : 'sshNeedsNetwork')} control={
{(opts.ssh_port ?? 0) > 0 && ( @@ -647,6 +684,7 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, locale={locale} host={host} opts={opts} + networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name} issues={issues} checking={checking} command={cmdPreview} @@ -688,11 +726,11 @@ export const CreateWizard: React.FC = ({ locale, host, tasks = [], draft, {tr('createNow')} ) : step < REVIEW_STEP ? ( - + ) : ( } + /> + + +} diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 7eaee4d..988f655 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -31,6 +31,7 @@ import { Modal } from '../ui/dialog' import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings' import { api } from '../wails' import { formatAffinitySummary } from './AffinityDialog' +import { VMNetworkSettings } from './VMNetworkSettings' const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm }))) @@ -864,19 +865,14 @@ export const SettingsModal: React.FC = ({ locale, detail, stats, host, op )} - - set({ network })} />} - /> + 0} onBusy={setBusy} onSaved={onSaved} /> + {sshCommand(form.ssh_port ?? 0)} : tr('sshOffDesc')} disabled={!form.network} - reason={tr('sshNeedsNetwork')} + reason={tr(detail.network_mode === 'bridge' ? 'sshNeedsNAT' : 'sshNeedsNetwork')} control={
{sshOn && ( diff --git a/frontend/src/components/VMNetworkSettings.tsx b/frontend/src/components/VMNetworkSettings.tsx new file mode 100644 index 0000000..42bc654 --- /dev/null +++ b/frontend/src/components/VMNetworkSettings.tsx @@ -0,0 +1,138 @@ +import React, { useEffect, useState } from 'react' +import '../i18n/domains/settings.gen' +import { parseAppError, t } from '../i18n' +import type { I18nKey, ParsedAppError } from '../i18n' +import type { Locale, VMNetworkSettings as NetworkState } from '../types' +import { useNetworkPlan } from '../lib/useNetworkPlan' +import { NpcapDependency } from './NpcapDependency' +import { NetworkErrorNotice } from './NetworkErrorNotice' +import { Button } from '../ui/controls' +import { Segmented, SetGroup, SetRow, SetValue } from '../ui/settings' +import { api } from '../wails' + +type Mode = 'off' | 'nat' | 'bridge' + +export function VMNetworkSettings({ name, locale, running, disabled, stagedDirty, onBusy, onSaved }: { + name: string + locale: Locale + running: boolean + disabled: boolean + stagedDirty: boolean + onBusy: (busy: boolean) => void + onSaved: () => void +}) { + const tr = (key: I18nKey, vars?: Record) => t(locale, key, vars) + const [state, setState] = useState(null) + const [mode, setMode] = useState('nat') + const [uplink, setUplink] = useState('') + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + const [dependencyRefresh, setDependencyRefresh] = useState(0) + const { plan, planning, planError } = useNetworkPlan(name, mode, uplink, !!state, `${dependencyRefresh}:${locale}`) + + useEffect(() => { + let active = true + setState(null) + setError(null) + api.GetVMNetworkSettings(name).then((next) => { + if (!active) return + setState(next) + setDependencyRefresh((value) => value + 1) + if (next.mode !== 'custom') setMode(next.mode as Mode) + setUplink(next.uplink_guid) + }).catch((err) => { if (active) setError(parseAppError(err)) }) + return () => { active = false } + }, [name, running, locale]) + + + const apply = async () => { + if (!state || busy || disabled || stagedDirty || planning || planError || (active && !canSwitchUplink)) return + setBusy(true) + onBusy(true) + setError(null) + try { + const next = await api.ApplyVMNetwork(name, mode, uplink) + setState(next) + setDependencyRefresh((value) => value + 1) + setUplink(next.uplink_guid) + onSaved() + } catch (err) { + setError(parseAppError(err)) + // 失败后读取实际状态;回滚未完成时保留修复入口。 + try { setState(await api.GetVMNetworkSettings(name)) } catch { /* 保留首个错误 */ } + } finally { + setBusy(false) + onBusy(false) + } + } + + const locked = disabled || busy || !state + const active = running || !!state?.running + const canSwitchUplink = state?.mode === 'bridge' && mode === 'bridge' && !state.recovery_pending + const changed = state && (mode !== state.mode || (mode === 'bridge' && uplink !== state.uplink_guid)) + const canRepair = state && (state.mode === 'bridge' || state.recovery_pending) + const adapters = state?.adapters ?? [] + const status = !state ? tr('bridgeLoading') + : state.mode === 'bridge' + ? state.ready ? tr('bridgeReady') : tr('bridgeNeedsRepair') + : state.mode === 'nat' ? tr('networkNAT') : state.mode === 'off' ? tr('off') : tr('bridgeCustom') + + return ( + + + + } + /> + {mode === 'bridge' && ( + + {adapters.map((adapter) => ( + + ))} + {adapters.length === 0 && {tr('bridgeNoAdapters')}} +
+ } + /> + )} + {state?.mode === 'bridge' && state.uplink_name && ( + + )} + {mode === 'bridge' && { setBusy(value); onBusy(value) }} onInstalled={() => setDependencyRefresh((value) => value + 1)} />} + {state?.recovery_pending &&
{tr('bridgeRecoveryPending')}
} + {planning &&
{tr('bridgePlanPending')}
} + + {state?.notes?.map((note) =>
{note}
)} + + + {changed ? tr('bridgeApply') : tr('bridgeRepair')} + + } + /> +
+ ) +} diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 01f16df..94b3e13 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -571,8 +571,8 @@ export const VMPage: React.FC = ({ }, { key: 'net', label: tr('fieldNetwork'), icon:
+
+
+
{tr('hostDNSModeTitle')}
+
+ {tr(dnsMode === 'doh' ? 'hostDNSModeDoHSub' : 'hostDNSModeSystemSub')} +
+
+
+ + label={tr('hostDNSModeTitle')} + value={dnsMode} + onChange={handleDNSModeChange} + options={[ + { value: 'system', label: tr('hostDNSModeSystem') }, + { value: 'doh', label: tr('hostDNSModeDoH') }, + ]} + /> +
+
+
+
+
+
{tr('hostDNSDoHTitle')}
+
{tr('hostDNSDoHSub')}
+
+
+ ({ + value: p.url, + label: tr(p.labelKey), + detail: p.host, + })), + { value: CUSTOM_DOH_VALUE, label: tr('hostDNSPresetCustom') }, + ]} + /> + +
+
+ {showDoHExtra && ( +
+ {dohCustom && ( +
+ { + setDohDraft(e.target.value) + setDnsValidationErr('') + setDnsSavedHint(false) + setDnsTestResult(null) + }} + onBlur={() => commitCustomDoH(false)} + onKeyDown={(e) => { + if (e.key === 'Enter') { + e.preventDefault() + commitCustomDoH(true) + } + }} + /> + +
+ )} + {dnsValidationErr && ( +
+
+ )} + {!dnsValidationErr && dnsSavedHint && ( +
+
+ )} + {dnsTestResult && ( +
+ {dnsTestResult.ok ?
+ )} +
+ )} +
{tr('forceQuitAppTitle')}
diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 6b6b2f4..4f4f598 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -43,7 +43,7 @@ import { UserRound, } from 'lucide-react' import React, { useEffect, useId, useRef, useState } from 'react' -import { I18nKey, localeDir, locText, t } from '../i18n' +import { I18nKey, localeDir, locText, parseAppError, t } from '../i18n' import { controllerLabel, formatBytes, formatDiskUsage, formatMemory, formatUptime, graphicsLabel, parseMemoryGB, pendingChangeText, resolveGuestLang, sshCommand, @@ -86,6 +86,9 @@ export type VMAction = // macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`. const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh' const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command' +const HOST_DNS_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Host-DNS.command' +const HOST_DNS_DISABLE_CMD = 'sh /Volumes/REIMSTOOLS/Disable-Host-DNS.command' +const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos' export const PRIMARY_SHORTCUT = 'Ctrl+Enter' interface Props { @@ -186,9 +189,95 @@ export const VMPage: React.FC = ({ const guestToolsHintId = useId() const installing = !!detail && (detail.has_installer || detail.recovery_mode) const transitioning = state === 'starting' || state === 'stopping' || state === 'suspending' || state === 'resuming' + const isMacOSDriver = !driverID || driverID === BUILTIN_MACOS_DRIVER + const canUseHostDNS = !!detail && !installing && !detail.guest_tools_disabled && isMacOSDriver && state !== 'broken' // Polled here rather than in App so each tick re-renders only this page. const stats = useVMStats(driverID, name, running) + // Per-VM Host DNS proxy state (host_dns_flow.go). + const [hostDNS, setHostDNS] = useState<{ + host_dns_enabled: boolean + host_dns_active: boolean + host_dns_config_stale: boolean + host_dns_reported: boolean + } | null>(null) + const [hostDNSLoadErr, setHostDNSLoadErr] = useState('') + const [hostDNSBusy, setHostDNSBusy] = useState(false) + const hostDNSWriteSeq = useRef(0) + useEffect(() => { + hostDNSWriteSeq.current += 1 + setHostDNS(null) + setHostDNSLoadErr('') + setHostDNSBusy(false) + }, [driverID, name]) + useEffect(() => { + if (!canUseHostDNS) { + setHostDNS(null) + setHostDNSLoadErr('') + return + } + let live = true + const pull = (force = false) => { + if (!force && document.hidden) return + const seq = hostDNSWriteSeq.current + api.GetGuestToolsHostDNS(name) + .then((s) => { + if (live && seq === hostDNSWriteSeq.current) { + setHostDNS(s) + setHostDNSLoadErr('') + } + }) + .catch((e) => { + console.warn('[vm] GetGuestToolsHostDNS failed:', e) + if (live && seq === hostDNSWriteSeq.current) { + setHostDNSLoadErr(parseAppError(e).summary) + } + }) + } + pull(true) + const onVisible = () => { + if (!document.hidden) pull(true) + } + document.addEventListener('visibilitychange', onVisible) + const timer = running ? window.setInterval(() => pull(false), 5000) : undefined + return () => { + live = false + document.removeEventListener('visibilitychange', onVisible) + if (timer) window.clearInterval(timer) + } + }, [driverID, name, canUseHostDNS, running, state, detail?.guest_tools_connected, detail?.guest_tools_attached]) + + const handleToggleHostDNS = async (enabled: boolean) => { + if (hostDNSBusy || guestToolsLocked || !canUseHostDNS || hostDNS === null) return + const writeSeq = ++hostDNSWriteSeq.current + setHostDNSBusy(true) + try { + await api.SetGuestToolsHostDNS(name, enabled) + onToast(tr(enabled ? 'toastHostDNSOn' : 'toastHostDNSOff')) + try { + const next = await api.GetGuestToolsHostDNS(name) + if (writeSeq === hostDNSWriteSeq.current) { + setHostDNS(next) + setHostDNSLoadErr('') + } + } catch (e) { + console.warn('[vm] GetGuestToolsHostDNS after toggle failed:', e) + if (writeSeq === hostDNSWriteSeq.current) { + setHostDNS((prev) => ({ + host_dns_enabled: enabled, + host_dns_active: prev?.host_dns_active ?? false, + host_dns_config_stale: prev?.host_dns_config_stale ?? false, + host_dns_reported: prev?.host_dns_reported ?? false, + })) + } + } + } catch (e) { + onError(tr('failGuestTools'), e) + } finally { + if (writeSeq === hostDNSWriteSeq.current) setHostDNSBusy(false) + } + } + // Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM // runs, otherwise the last frame saved. Skipped while this window is hidden; // the backend also skips it while the VM's own window is in front. @@ -1154,6 +1243,119 @@ export const VMPage: React.FC = ({
)} + {canUseHostDNS && (() => { + const dnsEnabled = hostDNS?.host_dns_enabled ?? false + const dnsActive = hostDNS?.host_dns_active ?? false + const dnsStale = hostDNS?.host_dns_config_stale ?? false + const dnsReported = hostDNS?.host_dns_reported ?? false + const toolsAttached = !!detail.guest_tools_attached + const disableCmd = toolsAttached + ? HOST_DNS_DISABLE_CMD + : 'sh "/Library/Application Support/ReimsGuestTools/Disable-Host-DNS.command"' + const showApplySub = dnsEnabled && (dnsStale || !dnsActive || !dnsReported) + const showDisableSub = !dnsEnabled && (dnsActive || (running && !dnsReported)) + + let dnsStatus: React.ReactNode + if (hostDNSLoadErr && hostDNS === null) { + dnsStatus = {hostDNSLoadErr} + } else if (dnsEnabled && dnsReported && dnsStale) { + dnsStatus = ( + + + ) + } else if (dnsEnabled && dnsReported && dnsActive) { + dnsStatus = ( + + + ) + } else if (dnsEnabled) { + dnsStatus = ( + + + ) + } else if (dnsReported && dnsActive) { + dnsStatus = ( + + + ) + } else { + dnsStatus = ( + + {tr('hostDNSOffHint')} + + ) + } + + return ( + <> +
+
+ {tr('guestToolsHostDNS')} + {dnsStatus} +
+
+ void handleToggleHostDNS(checked)} + /> +
+
+ {showApplySub && ( +
+
+
+ + {tr(dnsStale ? 'hostDNSStaleHint' : 'hostDNSApplyHint')} + +
+ {toolsAttached && ( +
+
+ {HOST_DNS_APPLY_CMD} + } onClick={() => onCopy(HOST_DNS_APPLY_CMD)} /> + {running && ( + } busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(HOST_DNS_APPLY_CMD)} /> + )} +
+
+ )} +
+ {!dnsStale && ( +
+ {tr('hostDNSDisableHint', { cmd: disableCmd })} +
+ )} +
+ )} + {showDisableSub && ( +
+
+ {tr('hostDNSDisableCmdHint')} +
+
+
+ {disableCmd} + } onClick={() => onCopy(disableCmd)} /> + {running && ( + } busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(disableCmd)} /> + )} +
+
+
+ )} + + ) + })()} ) diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 13bc2aa..8a6f8da 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -229,6 +229,25 @@ export const settingsZh: Record = { "hostAudioOutput": "Windows 播放设备", "hostCPU": "处理器", "hostCoresThreads": "{c} 核 · {t} 线程", + "hostDNSCustomPlaceholder": "https://dns.example.com/dns-query", + "hostDNSDoHSub": "DoH 模式下处理全部查询,系统模式下用于非常规记录回退", + "hostDNSDoHTitle": "DoH 上游地址", + "hostDNSInvalidURL": "需要以 https:// 开头的有效地址", + "hostDNSModeDoH": "DoH 加密上游", + "hostDNSModeDoHSub": "全部经 DoH 上游解析,并继承宿主机代理", + "hostDNSModeSystem": "宿主机系统解析", + "hostDNSModeSystemSub": "优先走 Windows 系统解析与本地网络,非常规记录回退 DoH", + "hostDNSModeTitle": "虚拟机 DNS 代理模式", + "hostDNSPresetAliDNS": "阿里云 DNS", + "hostDNSPresetCloudflare": "Cloudflare", + "hostDNSPresetCustom": "自定义", + "hostDNSPresetDNSPod": "腾讯 DNSPod", + "hostDNSPresetGoogle": "Google", + "hostDNSSaved": "已保存配置", + "hostDNSTest": "测试解析", + "hostDNSTestFailed": "解析失败:{reason}", + "hostDNSTestOK": "{domain} → {ips} · {ms} ms", + "hostDNSTesting": "测试中…", "hostDataRoot": "数据目录", "hostDisk": "可用空间", "hostDisplayPrimary": "主屏", @@ -664,6 +683,25 @@ export const settingsEn: Record = { "hostAudioOutput": "Windows playback", "hostCPU": "CPU", "hostCoresThreads": "{c} cores · {t} threads", + "hostDNSCustomPlaceholder": "https://dns.example.com/dns-query", + "hostDNSDoHSub": "Handles all queries in DoH mode and fallback record types in system mode", + "hostDNSDoHTitle": "DoH upstream URL", + "hostDNSInvalidURL": "Must be a valid https:// URL", + "hostDNSModeDoH": "DoH encrypted upstream", + "hostDNSModeDoHSub": "Resolves all queries via the DoH upstream and inherits host proxy settings", + "hostDNSModeSystem": "Host system resolver", + "hostDNSModeSystemSub": "Uses Windows system DNS and local networks first; falls back to DoH for unsupported record types", + "hostDNSModeTitle": "VM DNS proxy mode", + "hostDNSPresetAliDNS": "AliDNS", + "hostDNSPresetCloudflare": "Cloudflare", + "hostDNSPresetCustom": "Custom", + "hostDNSPresetDNSPod": "DNSPod", + "hostDNSPresetGoogle": "Google", + "hostDNSSaved": "Settings saved", + "hostDNSTest": "Test lookup", + "hostDNSTestFailed": "Lookup failed: {reason}", + "hostDNSTestOK": "{domain} → {ips} · {ms} ms", + "hostDNSTesting": "Testing…", "hostDataRoot": "Data folder", "hostDisk": "Free space", "hostDisplayPrimary": "Primary", diff --git a/frontend/src/i18n/domains/vm.gen.ts b/frontend/src/i18n/domains/vm.gen.ts index 1a97e4e..47430bd 100644 --- a/frontend/src/i18n/domains/vm.gen.ts +++ b/frontend/src/i18n/domains/vm.gen.ts @@ -87,6 +87,7 @@ export const vmZh: Record = { "gtStatusWaiting": "未连接", "gtStatusWaitingTip": "在 macOS 里运行安装命令后会自动连接", "gtUpdate": "更新…", + "guestToolsHostDNS": "宿主机 DNS 代理", "guestToolsModeSync": "文件同步模式", "guestToolsModeWebDAV": "WebDAV 挂载", "guestToolsPreventSleep": "防止 macOS 睡眠", @@ -107,6 +108,15 @@ export const vmZh: Record = { "guideStep2": "回到恢复主界面,选「Reinstall macOS Tahoe」,装到刚抹好的磁盘,中途会重启几次", "guideStep3": "看到「设置助理」后,点「退出恢复模式」弹出安装盘", "guideTitle": "恢复模式", + "hostDNSApplyHint": "在 macOS 终端运行以启用", + "hostDNSDisableCmdHint": "在 macOS 终端运行以移除代理", + "hostDNSDisableHint": "关闭时运行 {cmd} 还原默认 DNS", + "hostDNSOffHint": "上游过滤 UDP/53 导致虚拟机无网络时开启", + "hostDNSStaleHint": "宿主机端口已变更,重新运行以刷新", + "hostDNSStatusActive": "运行中", + "hostDNSStatusPending": "待应用", + "hostDNSStatusStale": "配置已过期", + "hostDNSStatusStillActive": "macOS 代理未移除", "netOff": "无网络", "netShared": "共享网络", "onlineRecoveryConfirm": "拉取并挂载(约 1 GB)", @@ -192,6 +202,8 @@ export const vmZh: Record = { "toastGuestToolsAttachedNextStart": "已挂载 Guest Tools 工具盘,重启虚拟机后在访达中可见", "toastGuestToolsDetached": "已弹出工具盘", "toastGuestToolsDetachedNextStart": "已弹出工具盘,下次启动生效", + "toastHostDNSOff": "已关闭宿主机 DNS 代理", + "toastHostDNSOn": "已开启宿主机 DNS 代理", "toastInstallFinished": "已退出恢复模式", "toastInstallerAttached": "已挂载离线镜像:{name}", "toastInstallerAttachedNextStart": "已挂载离线镜像(重启后生效):{name}", @@ -303,6 +315,7 @@ export const vmEn: Record = { "gtStatusWaiting": "Not connected", "gtStatusWaitingTip": "Connects once the install command has run in macOS", "gtUpdate": "Update…", + "guestToolsHostDNS": "Host DNS proxy", "guestToolsModeSync": "Folder sync", "guestToolsModeWebDAV": "WebDAV mount", "guestToolsPreventSleep": "Prevent macOS sleep", @@ -323,6 +336,15 @@ export const vmEn: Record = { "guideStep2": "Back in Recovery, choose “Reinstall macOS Tahoe” and install to the disk you erased. It restarts a few times", "guideStep3": "When Setup Assistant appears, click “Exit recovery mode” to eject the installer", "guideTitle": "Recovery mode", + "hostDNSApplyHint": "Run in macOS Terminal to apply", + "hostDNSDisableCmdHint": "Run in macOS Terminal to remove", + "hostDNSDisableHint": "When disabling, run {cmd} to restore default DNS", + "hostDNSOffHint": "Enable when upstream blocks UDP/53 and the VM loses network", + "hostDNSStaleHint": "Host port changed; rerun to refresh", + "hostDNSStatusActive": "Active", + "hostDNSStatusPending": "Not applied", + "hostDNSStatusStale": "Config outdated", + "hostDNSStatusStillActive": "Still active in macOS", "netOff": "No network", "netShared": "Shared network", "onlineRecoveryConfirm": "Download \u0026 attach (~1 GB)", @@ -408,6 +430,8 @@ export const vmEn: Record = { "toastGuestToolsAttachedNextStart": "Guest Tools disk attached — restart VM to mount in Finder", "toastGuestToolsDetached": "Tools disk ejected", "toastGuestToolsDetachedNextStart": "Tools disk ejected; applies on next start", + "toastHostDNSOff": "Host DNS proxy disabled", + "toastHostDNSOn": "Host DNS proxy enabled", "toastInstallFinished": "Exited recovery mode", "toastInstallerAttached": "Offline image attached: {name}", "toastInstallerAttachedNextStart": "Offline image attached (applies on restart): {name}", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index c96c1aa..f76a2ae 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -369,6 +369,7 @@ export type I18nKey = | "guestLangZhHantUS" | "guestMemory" | "guestToolsConnected" + | "guestToolsHostDNS" | "guestToolsModeSync" | "guestToolsModeWebDAV" | "guestToolsPreventSleep" @@ -406,6 +407,34 @@ export type I18nKey = | "hostAudioOutput" | "hostCPU" | "hostCoresThreads" + | "hostDNSApplyHint" + | "hostDNSCustomPlaceholder" + | "hostDNSDisableCmdHint" + | "hostDNSDisableHint" + | "hostDNSDoHSub" + | "hostDNSDoHTitle" + | "hostDNSInvalidURL" + | "hostDNSModeDoH" + | "hostDNSModeDoHSub" + | "hostDNSModeSystem" + | "hostDNSModeSystemSub" + | "hostDNSModeTitle" + | "hostDNSOffHint" + | "hostDNSPresetAliDNS" + | "hostDNSPresetCloudflare" + | "hostDNSPresetCustom" + | "hostDNSPresetDNSPod" + | "hostDNSPresetGoogle" + | "hostDNSSaved" + | "hostDNSStaleHint" + | "hostDNSStatusActive" + | "hostDNSStatusPending" + | "hostDNSStatusStale" + | "hostDNSStatusStillActive" + | "hostDNSTest" + | "hostDNSTestFailed" + | "hostDNSTestOK" + | "hostDNSTesting" | "hostDataRoot" | "hostDisk" | "hostDisplayHint" @@ -961,6 +990,8 @@ export type I18nKey = | "toastGuestToolsAttachedNextStart" | "toastGuestToolsDetached" | "toastGuestToolsDetachedNextStart" + | "toastHostDNSOff" + | "toastHostDNSOn" | "toastInstallFinished" | "toastInstallerAttached" | "toastInstallerAttachedNextStart" diff --git a/frontend/src/styles/app.css b/frontend/src/styles/app.css index 11080ff..05c12c3 100644 --- a/frontend/src/styles/app.css +++ b/frontend/src/styles/app.css @@ -458,6 +458,9 @@ h1, h2, h3, p { margin: 0; } .conn-row.conn-sub { min-height: 40px; padding-top: 0; padding-left: 28px; } .conn-row.conn-sub::before { display: none; } .conn-row.conn-sub .conn-main { flex: 0 0 auto; } +.conn-row.conn-sub.conn-sub-stack { flex-direction: column; align-items: stretch; gap: var(--sp-1); padding-bottom: 10px; } +.conn-sub-line { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-3); min-width: 0; } +.conn-sub-note { font-size: var(--fs-12); color: var(--text-3); overflow-wrap: anywhere; user-select: text; } .conn-ctrl { display: flex; align-items: center; gap: 6px; flex-shrink: 0; } .conn-ctrl-grow { flex: 1; flex-shrink: 1; min-width: 0; justify-content: flex-end; } .conn-ctrl .btn { height: 28px; padding: 0 11px; font-size: 12.5px; } @@ -640,11 +643,18 @@ h1, h2, h3, p { margin: 0; } /* ── Grouped list (host page, settings) ────────────────── */ .list { background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg); overflow: hidden; box-shadow: var(--shadow-card); } .row { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); padding: 11px 16px; position: relative; } +.row.row-stack { flex-direction: column; align-items: stretch; gap: var(--sp-2); } +.row-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); width: 100%; } .row + .row::before { content: ""; position: absolute; top: 0; left: 16px; right: 16px; height: 1px; background: var(--border); } .row-main { min-width: 0; flex: 1; display: flex; flex-direction: column; gap: 2px; } .row-title { font-size: 13.5px; display: flex; align-items: center; gap: var(--sp-2); flex-wrap: wrap; color: var(--text); font-variant-numeric: tabular-nums; } .row-sub { font-size: var(--fs-12); color: var(--text-3); overflow-wrap: anywhere; font-variant-numeric: tabular-nums; } .row-right { display: flex; align-items: center; gap: var(--sp-2); flex-shrink: 0; } +.host-dns-extra { display: flex; flex-direction: column; gap: var(--sp-2); } +.host-dns-custom { display: flex; align-items: center; gap: var(--sp-2); } +.host-dns-custom > .input { flex: 1; min-width: 0; } +.host-dns-feedback { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-12); line-height: 1.45; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; } +.host-dns-feedback > svg { flex-shrink: 0; } .badge { display: inline-flex; align-items: center; height: 20px; padding: 0 8px; border-radius: 999px; font-size: 11.5px; font-weight: var(--fw-medium); white-space: nowrap; flex-shrink: 0; background: var(--surface-active); color: var(--text-2); } .badge-accent { background: var(--accent-soft); color: var(--accent-soft-text); } @@ -1154,6 +1164,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .srow-kv .srow-value { min-width: 0; text-align: right; font-size: var(--fs-13); color: var(--text-2); overflow-wrap: anywhere; user-select: text; font-variant-numeric: tabular-nums; } .dirty-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--accent); flex-shrink: 0; } .warn-text { color: var(--warn-text); } +.danger-text { color: var(--danger-text); } .inline-code { font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); background: var(--surface-active); padding: 2px 7px; border-radius: 5px; user-select: text; } .folder-path { display: block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .stack-1 { display: flex; flex-direction: column; gap: var(--sp-1); } @@ -2011,7 +2022,7 @@ button.status-issue + .status-metric { margin-left: 6px; } } @container (max-width: 520px) { - .row, .srow-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } + .row, .row-head, .srow-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } .row-main, .srow-text { flex: 1 1 220px; } .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; } } @@ -2021,7 +2032,7 @@ button.status-issue + .status-metric { margin-left: 6px; } .review-group:last-child .review-rows { grid-template-columns: max-content 1fr; } .vm-spec-card { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 14px; } .affinity-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); } - .conn-row, .srow-head, .row, .page-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } + .conn-row, .conn-sub-line, .srow-head, .row, .row-head, .page-head { flex-wrap: wrap; gap: var(--sp-2) var(--sp-4); } .row-main, .srow-text { flex: 1 1 220px; } .conn-ctrl, .row-right, .srow-ctrl { flex-wrap: wrap; max-width: 100%; min-width: 0; } .plugin-search-wrap, .plugin-search { width: 100%; } diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index ab52fd2..40beb1c 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -10,6 +10,7 @@ import {installer} from '../models'; import {http} from '../models'; import {dataroot} from '../models'; import {opencore} from '../models'; +import {guesttools} from '../models'; export function AddVMSharedFolder(arg1:string,arg2:string):Promise; @@ -121,6 +122,10 @@ export function GenerateVMSMBIOS(arg1:string):Promise; export function GetActiveTheme():Promise; +export function GetGuestToolsHostDNS(arg1:string):Promise; + +export function GetHostDNSConfig():Promise; + export function GetLicenseTexts():Promise; export function GetPluginSettings(arg1:string,arg2:string):Promise>; @@ -279,6 +284,10 @@ export function SetDataRoot(arg1:string):Promise; export function SetGuestPreventSleep(arg1:string,arg2:boolean):Promise; +export function SetGuestToolsHostDNS(arg1:string,arg2:boolean):Promise; + +export function SetHostDNSConfig(arg1:guesttools.HostDNSConfig):Promise; + export function SetLocale(arg1:string):Promise; export function SetMinimizeToTray(arg1:boolean):Promise; @@ -325,6 +334,8 @@ export function SuspendVM(arg1:string):Promise; export function SuspendVMWithDriver(arg1:string,arg2:string):Promise; +export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise; + export function ToggleBorderless(arg1:string,arg2:boolean):Promise; export function ToggleVMFullscreen(arg1:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 9c6cb94..40c5c37 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -222,6 +222,14 @@ export function GetActiveTheme() { return window['go']['app']['App']['GetActiveTheme'](); } +export function GetGuestToolsHostDNS(arg1) { + return window['go']['app']['App']['GetGuestToolsHostDNS'](arg1); +} + +export function GetHostDNSConfig() { + return window['go']['app']['App']['GetHostDNSConfig'](); +} + export function GetLicenseTexts() { return window['go']['app']['App']['GetLicenseTexts'](); } @@ -538,6 +546,14 @@ export function SetGuestPreventSleep(arg1, arg2) { return window['go']['app']['App']['SetGuestPreventSleep'](arg1, arg2); } +export function SetGuestToolsHostDNS(arg1, arg2) { + return window['go']['app']['App']['SetGuestToolsHostDNS'](arg1, arg2); +} + +export function SetHostDNSConfig(arg1) { + return window['go']['app']['App']['SetHostDNSConfig'](arg1); +} + export function SetLocale(arg1) { return window['go']['app']['App']['SetLocale'](arg1); } @@ -630,6 +646,10 @@ export function SuspendVMWithDriver(arg1, arg2) { return window['go']['app']['App']['SuspendVMWithDriver'](arg1, arg2); } +export function TestHostDNS(arg1) { + return window['go']['app']['App']['TestHostDNS'](arg1); +} + export function ToggleBorderless(arg1, arg2) { return window['go']['app']['App']['ToggleBorderless'](arg1, arg2); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 99c768e..851cb54 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -213,6 +213,25 @@ export namespace app { return a; } } + export class GuestToolsHostDNSStatus { + host_dns_enabled: boolean; + host_dns_active: boolean; + host_dns_reported: boolean; + host_dns_config_stale: boolean; + + static createFrom(source: any = {}) { + return new GuestToolsHostDNSStatus(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.host_dns_enabled = source["host_dns_enabled"]; + this.host_dns_active = source["host_dns_active"]; + this.host_dns_reported = source["host_dns_reported"]; + this.host_dns_config_stale = source["host_dns_config_stale"]; + } + } + export class LicenseTexts { license: string; notice: string; @@ -621,6 +640,8 @@ export namespace config { app_update_channel?: string; minimize_to_tray?: boolean; sync_host_memory_smbios?: boolean; + host_dns_mode?: string; + host_dns_doh_url?: string; static createFrom(source: any = {}) { return new Config(source); @@ -637,6 +658,8 @@ export namespace config { this.app_update_channel = source["app_update_channel"]; this.minimize_to_tray = source["minimize_to_tray"]; this.sync_host_memory_smbios = source["sync_host_memory_smbios"]; + this.host_dns_mode = source["host_dns_mode"]; + this.host_dns_doh_url = source["host_dns_doh_url"]; } } @@ -854,6 +877,40 @@ export namespace driver { } +export namespace guesttools { + export class HostDNSConfig { + mode: string; + doh_url: string; + + static createFrom(source: any = {}) { + return new HostDNSConfig(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.mode = source["mode"]; + this.doh_url = source["doh_url"]; + } + } + + export class HostDNSTestResult { + domain: string; + addresses: string[]; + elapsed_ms: number; + + static createFrom(source: any = {}) { + return new HostDNSTestResult(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.domain = source["domain"]; + this.addresses = source["addresses"]; + this.elapsed_ms = source["elapsed_ms"]; + } + } +} + export namespace host { export class AudioInfo { diff --git a/internal/app/app.go b/internal/app/app.go index b4e794a..320e621 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -971,6 +971,7 @@ func (a *App) SetDataRoot(dir string) error { curAppUpdateChannel := a.cfg.AppUpdateChannel curMinToTray := a.cfg.MinimizeToTray curSyncHostMemSMBIOS := a.cfg.SyncHostMemorySMBIOS + curHostDNS := a.hostDNSConfigLocked() for _, v := range a.lastVMs { if v.State == "running" || v.State == "starting" || v.State == "stopping" || v.State == "suspending" || v.State == "resuming" { a.mu.Unlock() @@ -1016,6 +1017,7 @@ func (a *App) SetDataRoot(dir string) error { nextCfg.AppUpdateChannel = curAppUpdateChannel nextCfg.MinimizeToTray = curMinToTray nextCfg.SyncHostMemorySMBIOS = curSyncHostMemSMBIOS + nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = curHostDNS.Mode, curHostDNS.DoHURL } if err := nextCfg.EnsureDirs(); err != nil { return err @@ -1035,6 +1037,9 @@ func (a *App) SetDataRoot(dir string) error { a.mu.Lock() wasReadOnly := a.root.ReadOnly a.cfg = nextCfg + if a.guestTools != nil { + a.guestTools.SetHostDNSConfig(a.hostDNSConfigLocked()) + } a.root = st a.mu.Unlock() a.logDataRoot(st) diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index c667e56..00f6da0 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -116,6 +116,7 @@ func (a *App) startGuestToolsServer() (srv *guesttools.Server, port int, created a.injectRemoteTextRef(vmKey, vmName, "", text) }) a.guestTools = srv + srv.SetHostDNSConfig(a.hostDNSConfigLocked()) srv.SetStatusChangeHandler(func(string) { a.syncKeymapRules() }) created = true } diff --git a/internal/app/host_dns_flow.go b/internal/app/host_dns_flow.go new file mode 100644 index 0000000..abc8c98 --- /dev/null +++ b/internal/app/host_dns_flow.go @@ -0,0 +1,120 @@ +package app + +import ( + "fmt" + "os" + "time" + + "github.com/Nwflower/reims-go/internal/guesttools" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +func (a *App) hostDNSConfigLocked() guesttools.HostDNSConfig { + return guesttools.HostDNSConfig{Mode: a.cfg.HostDNSMode, DoHURL: a.cfg.HostDNSDoHURL} +} + +func (a *App) GetHostDNSConfig() guesttools.HostDNSConfig { + a.mu.Lock() + defer a.mu.Unlock() + return a.hostDNSConfigLocked().WithDefaults() +} + +func (a *App) SetHostDNSConfig(cfg guesttools.HostDNSConfig) error { + if err := cfg.Validate(); err != nil { + return err + } + a.mu.Lock() + defer a.mu.Unlock() + prev := a.hostDNSConfigLocked() + a.cfg.HostDNSMode, a.cfg.HostDNSDoHURL = cfg.Mode, cfg.DoHURL + if err := a.saveConfigLocked(); err != nil { + a.cfg.HostDNSMode, a.cfg.HostDNSDoHURL = prev.Mode, prev.DoHURL + return err + } + if a.guestTools != nil { + a.guestTools.SetHostDNSConfig(cfg) + } + return nil +} + +func (a *App) TestHostDNS(cfg guesttools.HostDNSConfig) (guesttools.HostDNSTestResult, error) { + if err := cfg.Validate(); err != nil { + return guesttools.HostDNSTestResult{}, err + } + return guesttools.TestHostDNSProxy(a.baseCtx(), cfg, "example.com") +} + +type GuestToolsHostDNSStatus struct { + HostDNSEnabled bool `json:"host_dns_enabled"` + HostDNSActive bool `json:"host_dns_active"` + HostDNSReported bool `json:"host_dns_reported"` + HostDNSConfigStale bool `json:"host_dns_config_stale"` +} + +func (a *App) GetGuestToolsHostDNS(name string) (GuestToolsHostDNSStatus, error) { + epoch := a.vmDeleteEpoch(name) + d, err := a.getVMDetail(name, epoch) + if err != nil { + return GuestToolsHostDNSStatus{}, err + } + unlock := a.lockGuestToolsVM(d.Name) + defer unlock() + if a.vmDeleteEpoch(d.Name) != epoch { + return GuestToolsHostDNSStatus{}, os.ErrNotExist + } + cfg, _, err := guesttools.ReadVMConfigStrict(d.Directory) + if err != nil { + return GuestToolsHostDNSStatus{}, err + } + status := GuestToolsHostDNSStatus{HostDNSEnabled: cfg.HostDNSEnabled} + srv, _, err := a.ensureGuestToolsBridge() + if err != nil { + return GuestToolsHostDNSStatus{}, err + } + live := srv.Status(d.Name, 45*time.Second) + status.HostDNSActive = live.HostDNSActive + status.HostDNSReported = live.HostDNSReported + status.HostDNSConfigStale = live.HostDNSConfigStale + return status, nil +} + +func (a *App) SetGuestToolsHostDNS(name string, enabled bool) error { + if err := a.requireWritableDataRoot(); err != nil { + return err + } + epoch := a.vmDeleteEpoch(name) + d, err := a.getVMDetail(name, epoch) + if err != nil { + return err + } + if d.Directory == "" { + return fmt.Errorf("VM %s has no directory", name) + } + srv, port, err := a.ensureGuestToolsBridge() + if err != nil { + return err + } + unlock := a.lockGuestToolsVM(d.Name) + defer unlock() + if a.vmDeleteEpoch(d.Name) != epoch { + return os.ErrNotExist + } + if err := requireGuestToolsVM(d.Directory); err != nil { + return err + } + cfg, err := guesttools.LoadOrCreateVMConfig(d.Directory, d.Name, a.vmSharedDir(d.Name), port) + if err != nil { + return err + } + cfg.HostDNSEnabled = enabled + if err := guesttools.SaveVMConfig(d.Directory, cfg); err != nil { + return err + } + if err := a.registerGuestToolsConfig(srv, d.Directory, cfg); err != nil { + return err + } + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "reims:state-changed", true) + } + return nil +} diff --git a/internal/app/host_dns_flow_test.go b/internal/app/host_dns_flow_test.go new file mode 100644 index 0000000..777a2ae --- /dev/null +++ b/internal/app/host_dns_flow_test.go @@ -0,0 +1,153 @@ +package app + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/Nwflower/reims-go/internal/config" + "github.com/Nwflower/reims-go/internal/dataroot" + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/guesttools" + vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" + "github.com/Nwflower/reims-go/internal/plugin" +) + +func TestAppHostDNSConfig(t *testing.T) { + a := &App{cfg: &config.Config{DataRoot: t.TempDir()}} + if got := a.GetHostDNSConfig(); got.Mode != "system" || got.DoHURL != guesttools.DefaultHostDNSDoHURL { + t.Fatalf("default host DNS = %+v", got) + } + valid := guesttools.HostDNSConfig{Mode: "doh", DoHURL: "https://resolver.example.test/custom"} + if err := a.SetHostDNSConfig(valid); err != nil { + t.Fatal(err) + } + for _, bad := range []guesttools.HostDNSConfig{ + {Mode: "auto"}, {Mode: "doh", DoHURL: "http://resolver.example.test"}, + {Mode: "doh", DoHURL: "https:///dns-query"}, + } { + if err := a.SetHostDNSConfig(bad); err == nil { + t.Fatalf("accepted invalid config %+v", bad) + } + if _, err := a.TestHostDNS(bad); err == nil { + t.Fatalf("tested invalid config %+v", bad) + } + } + if got := a.GetHostDNSConfig(); got != valid { + t.Fatalf("host DNS = %+v, want %+v", got, valid) + } + persisted, err := config.Load(filepath.Join(a.cfg.DataRoot, "reims-go.json")) + if err != nil || persisted.HostDNSMode != valid.Mode || persisted.HostDNSDoHURL != valid.DoHURL { + t.Fatalf("persisted host DNS = %+v, %v", persisted, err) + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + a.ctx = ctx + if _, err := a.TestHostDNS(valid); !errors.Is(err, context.Canceled) { + t.Fatalf("connection test should honor app context, got %v", err) + } +} + +func TestAppGuestToolsHostDNSRejectsReadOnlyDataRoot(t *testing.T) { + a := &App{ + cfg: &config.Config{DataRoot: t.TempDir()}, + root: dataroot.Status{ReadOnly: true, Reason: dataroot.ReasonNewer}, + } + if err := a.SetGuestToolsHostDNS("dns-vm", true); err == nil || !strings.Contains(err.Error(), "E_DATAROOT_NEWER") { + t.Fatalf("expected read-only data root error, got %v", err) + } +} + +func TestAppGuestToolsHostDNSToggle(t *testing.T) { + const driverID = driver.BuiltinReimsMacOSDriverID + const name = "dns-vm" + vmDir := t.TempDir() + vmConfigPath := filepath.Join(vmDir, "vm.toml") + const vmConfig = "vm config kept intact" + if err := os.WriteFile(vmConfigPath, []byte(vmConfig), 0o600); err != nil { + t.Fatal(err) + } + drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{ + {Name: name, DriverID: driverID, Directory: vmDir, State: "stopped"}, + }} + reg := plugin.NewRegistry(nil) + if err := reg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ID: "test.host-dns", Version: "1.0.0"}, + Source: plugin.SourceBuiltin, + Desired: true, + Activate: func(_ context.Context, sc *plugin.Scope) error { + reg.RegisterGuestDriver(sc, driverID, drv) + return nil + }, + }); err != nil { + t.Fatal(err) + } + reg.Reconcile(t.Context()) + + srv := guesttools.NewTransportServer(nil) + port, err := srv.Start(-1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = srv.Close(context.Background()) }) + a := &App{cfg: &config.Config{DataRoot: t.TempDir()}, guestTools: srv, + lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil)} + imagePath := a.guestToolsImagePath(name) + const imageContents = "existing REIMSTOOLS image" + var token string + for _, enabled := range []bool{true, false} { + if !enabled { + if _, err := os.Stat(imagePath); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("toggle created REIMSTOOLS image: %v", err) + } + if err := os.MkdirAll(filepath.Dir(imagePath), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(imagePath, []byte(imageContents), 0o600); err != nil { + t.Fatal(err) + } + } + if err := a.SetGuestToolsHostDNS(name, enabled); err != nil { + t.Fatal(err) + } + cfg, ok, err := guesttools.ReadVMConfigStrict(vmDir) + if err != nil || !ok || cfg.HostDNSEnabled != enabled { + t.Fatalf("VM config = %+v, exists %v, error %v", cfg, ok, err) + } + if token != "" && cfg.Token != token { + t.Fatal("toggling DNS changed the guest token") + } + token = cfg.Token + req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, + fmt.Sprintf("http://127.0.0.1:%d/v1/config", port), nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+cfg.Token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + var live GuestToolsHostDNSStatus + err = json.NewDecoder(resp.Body).Decode(&live) + resp.Body.Close() + if err != nil || resp.StatusCode != http.StatusOK || live.HostDNSEnabled != enabled { + t.Fatalf("live config = %+v, HTTP %d, error %v", live, resp.StatusCode, err) + } + if status, err := a.GetGuestToolsHostDNS(name); err != nil || status.HostDNSEnabled != enabled { + t.Fatalf("app status = %+v, %v", status, err) + } + } + if got, err := os.ReadFile(imagePath); err != nil || string(got) != imageContents { + t.Fatalf("toggle changed the existing REIMSTOOLS image: %q, %v", got, err) + } + if data, err := os.ReadFile(vmConfigPath); err != nil || string(data) != vmConfig { + t.Fatalf("vm.toml changed: %q, %v", data, err) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 2d04ae5..3e5063d 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -29,7 +29,9 @@ type Config struct { // SyncHostMemorySMBIOS overrides QEMU's default SMBIOS Type 17 memory spec // (2666 MHz DDR4) with the host's physical memory speed and generation so // macOS About This Mac reports the host's real RAM frequency. Defaults to false. - SyncHostMemorySMBIOS bool `json:"sync_host_memory_smbios,omitempty"` + SyncHostMemorySMBIOS bool `json:"sync_host_memory_smbios,omitempty"` + HostDNSMode string `json:"host_dns_mode,omitempty"` + HostDNSDoHURL string `json:"host_dns_doh_url,omitempty"` } // ShouldMinimizeToTray returns true when closing the main window should hide to tray. diff --git a/internal/guesttools/Apply-Host-DNS.command b/internal/guesttools/Apply-Host-DNS.command new file mode 100644 index 0000000..802d473 --- /dev/null +++ b/internal/guesttools/Apply-Host-DNS.command @@ -0,0 +1,119 @@ +#!/bin/sh +set -eu +export LC_ALL=C +MEDIA=/Volumes/REIMSTOOLS +APP_DIR="/Library/Application Support/ReimsGuestTools" +PLIST=/Library/LaunchDaemons/com.reimsgo.dns-proxy.plist +SERVICE=system/com.reimsgo.dns-proxy +CONF="$APP_DIR/dns-proxy.conf" +BACKUP="$APP_DIR/dns-proxy.previous-dns" + +proxy_pid() { + sudo launchctl print "$SERVICE" 2>/dev/null | awk '$1 == "pid" && $2 == "=" {print $3; exit}' +} + +dns_listener_pids() { + sudo /usr/sbin/lsof -nP -Fpn "$@" | awk ' + /^p/ {pid = substr($0, 2)} + /^n(127[.]0[.]0[.]1|\*|\[::\]):53(->|$)/ {print pid} + ' +} + +sudo -v +port=$(sudo sed -n "s/^REIMS_HOST_PORT='\([0-9][0-9]*\)'$/\1/p" "$MEDIA/config") +token=$(sudo sed -n "s/^REIMS_TOKEN='\([0-9a-f][0-9a-f]*\)'$/\1/p" "$MEDIA/config") +if ! printf '%s\n' "$port" | grep -Eq '^[0-9]{1,5}$' || + [ "$port" -lt 1 ] || [ "$port" -gt 65535 ] || + ! printf '%s\n' "$token" | grep -Eq '^[0-9a-f]{64}$'; then + echo "Invalid DNS settings on REIMSTOOLS." >&2 + exit 1 +fi +settings=$(curl -fsS -m 5 -H "Authorization: Bearer $token" "http://10.0.2.2:$port/v1/config") +if ! printf '%s\n' "$settings" | grep -q '"host_dns_enabled"[[:space:]]*:[[:space:]]*true'; then + echo "Enable Host DNS for this VM in Reims Go first." >&2 + exit 1 +fi + +pid=$(proxy_pid) +for owner in $(dns_listener_pids -iUDP:53) $(dns_listener_pids -iTCP:53 -sTCP:LISTEN); do + if [ "$owner" != "$pid" ]; then + echo "Another process (PID $owner) is using 127.0.0.1:53." >&2 + exit 1 + fi +done + +sudo install -d -o root -g wheel -m 0755 "$APP_DIR" +sudo install -o root -g wheel -m 0755 "$MEDIA/Disable-Host-DNS.command" "$APP_DIR/Disable-Host-DNS.command" +sudo install -o root -g wheel -m 0755 "$MEDIA/dns-proxy.pl" "$APP_DIR/dns-proxy.pl" +sudo install -o root -g wheel -m 0600 /dev/null "$CONF.new" +printf 'REIMS_HOST_PORT=%s\nREIMS_TOKEN=%s\n' "$port" "$token" | sudo tee "$CONF.new" >/dev/null +sudo chmod 600 "$CONF.new" +sudo mv -f "$CONF.new" "$CONF" +if sudo launchctl print "$SERVICE" >/dev/null 2>&1; then + sudo launchctl bootout "$SERVICE" +fi +token_sha256=$(printf '%s' "$token" | /usr/bin/shasum -a 256 | awk '{print $1}') +sudo install -o root -g wheel -m 0644 /dev/null "$PLIST" +sudo tee "$PLIST" >/dev/null < + + + + Labelcom.reimsgo.dns-proxy + ProgramArguments + /usr/bin/perl$APP_DIR/dns-proxy.pl + EnvironmentVariables + + REIMS_HOST_PORT$port + REIMS_TOKEN_SHA256$token_sha256 + + RunAtLoad + KeepAlive + + +EOF +if ! sudo launchctl bootstrap system "$PLIST"; then + sudo rm -f "$PLIST" + exit 1 +fi + +# Check that the responding resolver owns both sockets before changing system DNS. +addresses=$(dig @127.0.0.1 +tries=3 +time=7 +short example.com A) || addresses= +pid=$(proxy_pid) +if ! printf '%s\n' "$addresses" | grep -Eq '^[0-9]+(\.[0-9]+){3}$' || + [ -z "$pid" ] || + ! dns_listener_pids -iUDP:53 | grep -Fxq "$pid" || + ! dns_listener_pids -iTCP:53 -sTCP:LISTEN | grep -Fxq "$pid"; then + if sudo launchctl print "$SERVICE" >/dev/null 2>&1; then + sudo launchctl bootout "$SERVICE" + fi + sudo rm -f "$PLIST" + echo "The Host DNS proxy did not return an address for example.com." >&2 + exit 1 +fi +if ! sudo test -f "$BACKUP"; then + sudo install -o root -g wheel -m 0600 /dev/null "$BACKUP" +fi +snapshots=$(sudo cat "$BACKUP") +services=$(networksetup -listallnetworkservices) +printf '%s\n' "$services" | sed '1d; /^\*/d; /^$/d' | while IFS= read -r svc; do + previous=$(networksetup -getdnsservers "$svc") + already_local=0 + if [ "$previous" = 127.0.0.1 ]; then + already_local=1 + previous=Empty + elif [ "$previous" = "There aren't any DNS Servers set on $svc." ]; then + previous=Empty + fi + if ! printf '%s\n' "$snapshots" | REIMS_DNS_SERVICE="$svc" awk ' + BEGIN {RS = ""; FS = "\n"} + $1 == ENVIRON["REIMS_DNS_SERVICE"] {found = 1; exit} + END {exit !found} + '; then + printf '%s\n%s\n\n' "$svc" "$previous" | sudo tee -a "$BACKUP" >/dev/null + fi + [ "$already_local" -eq 0 ] || continue + sudo networksetup -setdnsservers "$svc" 127.0.0.1 +done +sudo dscacheutil -flushcache +echo "Host DNS is active." diff --git a/internal/guesttools/Disable-Host-DNS.command b/internal/guesttools/Disable-Host-DNS.command new file mode 100644 index 0000000..0d13c75 --- /dev/null +++ b/internal/guesttools/Disable-Host-DNS.command @@ -0,0 +1,34 @@ +#!/bin/sh +set -eu +export LC_ALL=C +APP_DIR="/Library/Application Support/ReimsGuestTools" +PLIST=/Library/LaunchDaemons/com.reimsgo.dns-proxy.plist +SERVICE=system/com.reimsgo.dns-proxy +BACKUP="$APP_DIR/dns-proxy.previous-dns" +LOCAL_DISABLE="$APP_DIR/Disable-Host-DNS.command" + +sudo -v +if [ -f "$BACKUP" ]; then + services=$(networksetup -listallnetworkservices) + snapshots=$(sudo cat "$BACKUP") + printf '%s\n\n' "$snapshots" | while IFS= read -r svc && [ -n "$svc" ]; do + set -- + while IFS= read -r value && [ -n "$value" ]; do + set -- "$@" "$value" + done + printf '%s\n' "$services" | sed '1d' | grep -Fxq -e "$svc" -e "*$svc" || continue + current=$(networksetup -getdnsservers "$svc") + [ "$current" = 127.0.0.1 ] || continue + if [ "$*" = Empty ] || [ "$*" = "There aren't any DNS Servers set on $svc." ]; then + sudo networksetup -setdnsservers "$svc" Empty + else + sudo networksetup -setdnsservers "$svc" "$@" + fi + done +fi +if sudo launchctl print "$SERVICE" >/dev/null 2>&1; then + sudo launchctl bootout "$SERVICE" +fi +sudo dscacheutil -flushcache +sudo rm -f "$PLIST" "$APP_DIR/dns-proxy.pl" "$APP_DIR/dns-proxy.conf" "$BACKUP" "$LOCAL_DISABLE" +echo "Host DNS is disabled." diff --git a/internal/guesttools/dns-proxy.pl b/internal/guesttools/dns-proxy.pl new file mode 100644 index 0000000..82ed333 --- /dev/null +++ b/internal/guesttools/dns-proxy.pl @@ -0,0 +1,157 @@ +#!/usr/bin/perl +use strict; +use warnings; +use IO::Socket::INET; +use IO::Select; + +my $config = '/Library/Application Support/ReimsGuestTools/dns-proxy.conf'; +my $host = '10.0.2.2'; +my $max_query = 4096; +my $max_reply = 65535; +my ($port, $token); +my $next_reload = 0; +$SIG{PIPE} = 'IGNORE'; +$SIG{HUP} = sub { $next_reload = 0 }; + +my $udp = IO::Socket::INET->new(LocalAddr => '127.0.0.1', LocalPort => 53, Proto => 'udp') + or die "DNS UDP listen: $!"; +my $tcp = IO::Socket::INET->new(LocalAddr => '127.0.0.1', LocalPort => 53, Proto => 'tcp', + Listen => 32, ReuseAddr => 1) or die "DNS TCP listen: $!"; +my $listeners = IO::Select->new($udp, $tcp); +my $children = 0; + +sub reload_config { + $next_reload = time + 10; + if (!open(my $fh, '<', $config)) { + warn "Read DNS proxy config: $!\n"; + return; + } else { + my %values; + while (my $line = <$fh>) { + if ($line =~ /\A(REIMS_HOST_PORT|REIMS_TOKEN)=([0-9a-f]+)\n?\z/) { + $values{$1} = $2; + } + } + close $fh; + if (($values{REIMS_HOST_PORT} // '') !~ /\A[0-9]{1,5}\z/ || + $values{REIMS_HOST_PORT} < 1 || $values{REIMS_HOST_PORT} > 65535 || + ($values{REIMS_TOKEN} // '') !~ /\A[0-9a-f]{64}\z/) { + warn "Invalid DNS proxy config\n"; + return; + } + ($port, $token) = @values{qw(REIMS_HOST_PORT REIMS_TOKEN)}; + } +} + +sub write_all { + my ($sock, $data) = @_; + my $offset = 0; + while ($offset < length $data) { + my $n = syswrite($sock, $data, length($data) - $offset, $offset); + return unless $n; + $offset += $n; + } + return 1; +} + +sub read_exact { + my ($sock, $size) = @_; + my $data = ''; + while (length($data) < $size) { + my $n = sysread($sock, $data, $size - length($data), length($data)); + return unless $n; + } + return $data; +} + +sub forward_query { + my ($query) = @_; + return unless defined $port; + my $upstream = IO::Socket::INET->new(PeerAddr => $host, PeerPort => $port, + Proto => 'tcp', Timeout => 5) or return; + my $request = "POST /v1/dns-query HTTP/1.0\r\nHost: $host:$port\r\n" . + "Authorization: Bearer $token\r\nContent-Type: application/dns-message\r\n" . + "Content-Length: " . length($query) . "\r\nConnection: close\r\n\r\n" . $query; + return unless write_all($upstream, $request); + + # HTTP/1.0 lets the host delimit the body by closing the connection. + my $response = ''; + while (1) { + my $n = sysread($upstream, $response, 8192, length($response)); + return unless defined $n; + last if $n == 0; + return if length($response) > $max_reply + 8192; + } + my ($header, $body) = split /\r\n\r\n/, $response, 2; + return unless defined $body && $header =~ /\AHTTP\/1\.[01] 200(?: |\r\n)/ && + length($body) >= 12 && length($body) <= $max_reply; + if ($header =~ /\r\nContent-Length:\s*(\d+)\r?$/im) { + return unless length($body) == $1; + } + return $body; +} + +sub udp_reply { + my ($reply) = @_; + # 512 bytes works even for clients that did not send an EDNS option. + return $reply if length($reply) <= 512; + my $end = 12; + while ($end < length($reply)) { + my $size = ord(substr($reply, $end++, 1)); + last if $size == 0; + if ($size >= 192) { + ++$end; + last; + } + $end += $size; + } + my ($id, $flags) = unpack('nn', $reply); + return pack('n6', $id, $flags | 0x0200, 1, 0, 0, 0) . substr($reply, 12, $end - 8); +} + +while (1) { + while (waitpid(-1, 1) > 0) { + --$children; + } + reload_config() if time >= $next_reload; + for my $ready ($listeners->can_read(1)) { + my ($peer, $query, $client); + if ($ready == $udp) { + $peer = recv($udp, $query, $max_query + 1, 0); + next unless defined $peer && length($query) >= 12 && length($query) <= $max_query; + } else { + $client = $tcp->accept() or next; + } + next if $children >= 32; + my $pid = fork(); + if (!defined $pid) { + warn "Fork DNS worker: $!\n"; + next; + } + if ($pid) { + ++$children; + next; + } + + close $tcp; + alarm 7; + if (defined $peer) { + my $reply = forward_query($query); + send($udp, udp_reply($reply), 0, $peer) if defined $reply; + } else { + close $udp; + while (defined(my $prefix = read_exact($client, 2))) { + my $size = unpack('n', $prefix); + last if $size < 12 || $size > $max_query; + my $packet = read_exact($client, $size); + last unless defined $packet; + alarm 7; + reload_config() if time >= $next_reload; + my $reply = forward_query($packet); + last unless defined $reply && write_all($client, pack('n', length($reply)) . $reply); + alarm 7; + } + } + exit 0; + } +} diff --git a/internal/guesttools/dns.go b/internal/guesttools/dns.go new file mode 100644 index 0000000..888a737 --- /dev/null +++ b/internal/guesttools/dns.go @@ -0,0 +1,602 @@ +package guesttools + +import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "mime" + "net" + "net/http" + "net/url" + "strings" + "time" + + "github.com/Nwflower/reims-go/internal/netproxy" +) + +const ( + DefaultHostDNSDoHURL = "https://dns.alidns.com/dns-query" + dnsMediaType = "application/dns-message" + maxDNSQuery = 4096 + maxDNSResponse = 65535 + dnsHeaderSize = 12 + dnsTimeout = 5 * time.Second + + dnsA = 1 + dnsNS = 2 + dnsCNAME = 5 + dnsPTR = 12 + dnsMX = 15 + dnsTXT = 16 + dnsAAAA = 28 + dnsSRV = 33 + dnsIN = 1 + + dnsSERVFAIL = 2 + dnsNXDOMAIN = 3 + dnsNOTIMP = 4 + dnsQR = 0x8000 + dnsOpcode = 0x7800 + dnsRD = 0x0100 + dnsRA = 0x0080 +) + +type HostDNSConfig struct { + Mode string `json:"mode"` + DoHURL string `json:"doh_url"` +} + +func (c HostDNSConfig) WithDefaults() HostDNSConfig { + if c.Mode == "" { + c.Mode = "system" + } + if c.DoHURL == "" { + c.DoHURL = DefaultHostDNSDoHURL + } + return c +} + +func (c HostDNSConfig) Validate() error { + if c.Mode != "system" && c.Mode != "doh" { + return fmt.Errorf("invalid host DNS mode %q", c.Mode) + } + if c.DoHURL == "" { + return nil + } + u, err := url.Parse(c.DoHURL) + if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" { + return errors.New("DoH URL must be an HTTPS endpoint") + } + return nil +} + +type HostDNSTestResult struct { + Domain string `json:"domain"` + Addresses []string `json:"addresses"` + ElapsedMS int64 `json:"elapsed_ms"` +} + +type dnsResolver interface { + LookupIP(context.Context, string, string) ([]net.IP, error) + LookupNS(context.Context, string) ([]*net.NS, error) + LookupCNAME(context.Context, string) (string, error) + LookupAddr(context.Context, string) ([]string, error) + LookupMX(context.Context, string) ([]*net.MX, error) + LookupTXT(context.Context, string) ([]string, error) + LookupSRV(context.Context, string, string, string) (string, []*net.SRV, error) +} + +type hostDNS struct { + resolver dnsResolver + client *http.Client +} + +func newHostDNS() hostDNS { + client := netproxy.NewClient() + client.Timeout = dnsTimeout + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return hostDNS{resolver: net.DefaultResolver, client: client} +} + +var defaultHostDNS = newHostDNS() + +type dnsQuestion struct { + id, flags, qtype, class uint16 + name string + wireName []byte +} + +// readDNSName expands a wire name while preserving label boundaries. Pointers +// refer to prior occurrences, and the expanded name is limited to 255 bytes. +func readDNSName(msg []byte, offset int) ([]byte, int, error) { + name := make([]byte, 0, 32) + end := 0 + limit := len(msg) + for { + if offset >= limit { + break + } + n := int(msg[offset]) + switch { + case n == 0: + if end == 0 { + end = offset + 1 + } + return append(name, 0), end, nil + case n <= 63 && offset+1+n <= limit && len(name)+1+n < 255: + name = append(name, msg[offset:offset+1+n]...) + offset += 1 + n + continue + case n&0xc0 == 0xc0 && offset+1 < limit: + target := (n&0x3f)<<8 | int(msg[offset+1]) + if target >= dnsHeaderSize && target < offset { + if end == 0 { + end = offset + 2 + } + limit, offset = offset, target + continue + } + } + break + } + return nil, 0, errors.New("invalid DNS name") +} + +func dnsNameForLookup(wire []byte) string { + if len(wire) == 1 { + return "." + } + var name strings.Builder + for i := 0; wire[i] != 0; { + n := int(wire[i]) + label := wire[i+1 : i+1+n] + if bytes.ContainsAny(label, ".\x00") { + return "" + } + name.Write(label) + name.WriteByte('.') + i += n + 1 + } + return name.String() +} + +type dnsRecord struct { + name []byte + rrtype uint16 + class uint16 + data []byte + dataOffset int +} + +func readDNSRecord(msg []byte, offset int) (dnsRecord, int, error) { + name, fields, err := readDNSName(msg, offset) + if err != nil || fields+10 > len(msg) { + return dnsRecord{}, 0, errors.New("invalid DNS record") + } + end := fields + 10 + int(binary.BigEndian.Uint16(msg[fields+8:])) + if end > len(msg) { + return dnsRecord{}, 0, errors.New("truncated DNS record") + } + return dnsRecord{ + name: name, rrtype: binary.BigEndian.Uint16(msg[fields:]), + class: binary.BigEndian.Uint16(msg[fields+2:]), data: msg[fields+10 : end], + dataOffset: fields + 10, + }, end, nil +} + +func readDNSMessage(msg []byte) (dnsQuestion, []dnsRecord, error) { + if len(msg) < dnsHeaderSize || binary.BigEndian.Uint16(msg[4:]) != 1 { + return dnsQuestion{}, nil, errors.New("expected a single DNS question") + } + wire, end, err := readDNSName(msg, dnsHeaderSize) + if err != nil || end+4 > len(msg) { + return dnsQuestion{}, nil, errors.New("invalid DNS question") + } + q := dnsQuestion{ + id: binary.BigEndian.Uint16(msg), flags: binary.BigEndian.Uint16(msg[2:]), + wireName: wire, name: dnsNameForLookup(wire), + qtype: binary.BigEndian.Uint16(msg[end:]), class: binary.BigEndian.Uint16(msg[end+2:]), + } + answerCount := int(binary.BigEndian.Uint16(msg[6:])) + recordCount := answerCount + int(binary.BigEndian.Uint16(msg[8:])) + int(binary.BigEndian.Uint16(msg[10:])) + offset := end + 4 + var answers []dnsRecord + for i := 0; i < recordCount; i++ { + record, next, err := readDNSRecord(msg, offset) + if err != nil { + return dnsQuestion{}, nil, err + } + if i < answerCount { + answers = append(answers, record) + } + offset = next + } + if offset != len(msg) { + return dnsQuestion{}, nil, errors.New("unexpected trailing DNS data") + } + return q, answers, nil +} + +func parseDNSQuery(msg []byte) (dnsQuestion, error) { + if len(msg) > maxDNSQuery { + return dnsQuestion{}, errors.New("DNS query exceeds 4096 bytes") + } + q, _, err := readDNSMessage(msg) + if err != nil { + return dnsQuestion{}, err + } + if q.flags&dnsQR != 0 { + return dnsQuestion{}, errors.New("expected a DNS query") + } + return q, nil +} + +func encodeDNSName(name string) ([]byte, error) { + if name == "." { + return []byte{0}, nil + } + wire := make([]byte, 0, len(name)+2) + for label := range strings.SplitSeq(strings.TrimSuffix(name, "."), ".") { + if len(label) == 0 || len(label) > 63 || len(wire)+len(label)+2 > 255 { + return nil, errors.New("invalid DNS label") + } + wire = append(wire, byte(len(label))) + wire = append(wire, label...) + } + return append(wire, 0), nil +} + +func (q dnsQuestion) message(flags uint16, answers [][]byte) []byte { + msg := make([]byte, dnsHeaderSize) + binary.BigEndian.PutUint16(msg, q.id) + binary.BigEndian.PutUint16(msg[2:], flags) + binary.BigEndian.PutUint16(msg[4:], 1) + binary.BigEndian.PutUint16(msg[6:], uint16(len(answers))) + msg = append(msg, q.wireName...) + msg = binary.BigEndian.AppendUint16(msg, q.qtype) + msg = binary.BigEndian.AppendUint16(msg, q.class) + for _, data := range answers { + msg = append(msg, 0xc0, 0x0c) + msg = binary.BigEndian.AppendUint16(msg, q.qtype) + msg = binary.BigEndian.AppendUint16(msg, q.class) + // The system resolver does not expose the upstream TTL. + msg = binary.BigEndian.AppendUint32(msg, 0) + msg = binary.BigEndian.AppendUint16(msg, uint16(len(data))) + msg = append(msg, data...) + if len(msg) > maxDNSResponse { + return q.response(dnsSERVFAIL, nil) + } + } + return msg +} + +func (q dnsQuestion) response(rcode uint16, answers [][]byte) []byte { + return q.message(dnsQR|dnsRA|q.flags&(dnsRD|dnsOpcode)|rcode, answers) +} + +func reverseDNSAddress(name string) (string, error) { + labels := strings.Split(strings.ToLower(strings.TrimSuffix(name, ".")), ".") + switch { + case len(labels) == 6 && labels[4] == "in-addr" && labels[5] == "arpa": + ip := net.ParseIP(strings.Join([]string{labels[3], labels[2], labels[1], labels[0]}, ".")) + if ip != nil { + return ip.String(), nil + } + case len(labels) == 34 && labels[32] == "ip6" && labels[33] == "arpa": + addr := make([]byte, 0, 39) + for i := 31; i >= 0; i-- { + if len(labels[i]) != 1 { + return "", errors.New("invalid PTR name") + } + addr = append(addr, labels[i][0]) + if i > 0 && i%4 == 0 { + addr = append(addr, ':') + } + } + if ip := net.ParseIP(string(addr)); ip != nil { + return ip.String(), nil + } + } + return "", errors.New("invalid PTR name") +} + +func (d hostDNS) lookup(ctx context.Context, q dnsQuestion) ([][]byte, error) { + var answers [][]byte + addName := func(prefix []byte, name string) error { + wire, err := encodeDNSName(name) + if err != nil { + return err + } + answers = append(answers, append(prefix, wire...)) + return nil + } + switch q.qtype { + case dnsA, dnsAAAA: + network := "ip4" + if q.qtype == dnsAAAA { + network = "ip6" + } + ips, err := d.resolver.LookupIP(ctx, network, q.name) + if err != nil { + return nil, err + } + for _, ip := range ips { + if q.qtype == dnsA { + answers = append(answers, ip.To4()) + } else { + answers = append(answers, ip.To16()) + } + } + case dnsNS: + records, err := d.resolver.LookupNS(ctx, q.name) + if err != nil { + return nil, err + } + for _, record := range records { + if err := addName(nil, record.Host); err != nil { + return nil, err + } + } + case dnsCNAME: + name, err := d.resolver.LookupCNAME(ctx, q.name) + if err != nil { + return nil, err + } + if !strings.EqualFold(strings.TrimSuffix(q.name, "."), strings.TrimSuffix(name, ".")) { + if err := addName(nil, name); err != nil { + return nil, err + } + } + case dnsPTR: + addr, err := reverseDNSAddress(q.name) + if err != nil { + return nil, nil + } + names, err := d.resolver.LookupAddr(ctx, addr) + if err != nil { + return nil, err + } + for _, name := range names { + if err := addName(nil, name); err != nil { + return nil, err + } + } + case dnsMX: + records, err := d.resolver.LookupMX(ctx, q.name) + if err != nil { + return nil, err + } + for _, record := range records { + prefix := binary.BigEndian.AppendUint16(nil, record.Pref) + if err := addName(prefix, record.Host); err != nil { + return nil, err + } + } + case dnsTXT: + records, err := d.resolver.LookupTXT(ctx, q.name) + if err != nil { + return nil, err + } + for _, record := range records { + var data []byte + for len(record) > 255 { + data = append(data, 255) + data = append(data, record[:255]...) + record = record[255:] + } + data = append(data, byte(len(record))) + answers = append(answers, append(data, record...)) + } + case dnsSRV: + _, records, err := d.resolver.LookupSRV(ctx, "", "", q.name) + if err != nil { + return nil, err + } + for _, record := range records { + prefix := binary.BigEndian.AppendUint16(nil, record.Priority) + prefix = binary.BigEndian.AppendUint16(prefix, record.Weight) + prefix = binary.BigEndian.AppendUint16(prefix, record.Port) + if err := addName(prefix, record.Target); err != nil { + return nil, err + } + } + } + return answers, nil +} + +func (d hostDNS) forwardDoH(ctx context.Context, endpoint string, raw []byte, q dnsQuestion) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(raw)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", dnsMediaType) + req.Header.Set("Accept", dnsMediaType) + resp, err := d.client.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return nil, fmt.Errorf("DoH upstream returned HTTP %d", resp.StatusCode) + } + mediaType, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type")) + if err != nil || mediaType != dnsMediaType { + return nil, errors.New("DoH upstream returned an invalid content type") + } + msg, err := io.ReadAll(io.LimitReader(resp.Body, maxDNSResponse+1)) + if err != nil { + return nil, err + } + if len(msg) > maxDNSResponse { + return nil, errors.New("DoH upstream response exceeds 65535 bytes") + } + reply, _, err := readDNSMessage(msg) + if err != nil || reply.flags&dnsQR == 0 || reply.flags&dnsOpcode != q.flags&dnsOpcode || + reply.id != q.id || reply.qtype != q.qtype || reply.class != q.class || + !bytes.EqualFold(reply.wireName, q.wireName) { + return nil, errors.New("DoH upstream returned an invalid DNS response") + } + return msg, nil +} + +func dnsNameNotFound(err error) bool { + var dnsErr *net.DNSError + return errors.As(err, &dnsErr) && dnsErr.IsNotFound +} + +func (d hostDNS) resolve(ctx context.Context, cfg HostDNSConfig, raw []byte, q dnsQuestion) ([]byte, error) { + cfg = cfg.WithDefaults() + if err := cfg.Validate(); err != nil { + return nil, err + } + if q.flags&dnsOpcode != 0 { + return q.response(dnsNOTIMP, nil), nil + } + ctx, cancel := context.WithTimeout(ctx, dnsTimeout) + defer cancel() + if cfg.Mode == "system" && q.class == dnsIN && q.name != "" { + switch q.qtype { + case dnsA, dnsAAAA, dnsNS, dnsCNAME, dnsPTR, dnsMX, dnsTXT, dnsSRV: + answers, err := d.lookup(ctx, q) + switch { + case err == nil: + return q.response(0, answers), nil + case !dnsNameNotFound(err): + return nil, err + } + switch q.qtype { + case dnsA, dnsAAAA: + otherNetwork := "ip6" + if q.qtype == dnsAAAA { + otherNetwork = "ip4" + } + ips, err := d.resolver.LookupIP(ctx, otherNetwork, q.name) + if err != nil && !dnsNameNotFound(err) { + return nil, err + } + if len(ips) == 0 { + return q.response(dnsNXDOMAIN, nil), nil + } + case dnsPTR: + return q.response(dnsNXDOMAIN, nil), nil + } + return q.response(0, nil), nil + } + } + return d.forwardDoH(ctx, cfg.DoHURL, raw, q) +} + +func TestHostDNSProxy(ctx context.Context, cfg HostDNSConfig, domain string) (HostDNSTestResult, error) { + return defaultHostDNS.test(ctx, cfg, domain) +} + +func (s *Server) SetHostDNSConfig(cfg HostDNSConfig) { + cfg = cfg.WithDefaults() + if err := cfg.Validate(); err != nil { + cfg = (HostDNSConfig{}).WithDefaults() + } + s.mu.Lock() + s.hostDNSConfig = cfg + s.mu.Unlock() +} + +func (s *Server) handleDNSQuery(w http.ResponseWriter, r *http.Request) { + _ = http.NewResponseController(w).SetReadDeadline(time.Now().Add(dnsTimeout)) + if !strings.HasPrefix(strings.TrimSpace(r.Header.Get("Authorization")), "Bearer ") { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + vm := s.authenticate(r) + if vm == nil { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + if !vm.hostDNSEnabled { + http.Error(w, "host DNS is disabled", http.StatusForbidden) + return + } + if r.Method != http.MethodPost { + http.Error(w, "method not allowed", http.StatusMethodNotAllowed) + return + } + raw, err := io.ReadAll(io.LimitReader(r.Body, maxDNSQuery+1)) + if err != nil { + http.Error(w, "could not read DNS query", http.StatusBadRequest) + return + } + q, err := parseDNSQuery(raw) + if err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + s.mu.RLock() + cfg := s.hostDNSConfig + s.mu.RUnlock() + reply, err := s.hostDNS.resolve(r.Context(), cfg, raw, q) + if err != nil { + reply = q.response(dnsSERVFAIL, nil) + } + w.Header().Set("Content-Type", dnsMediaType) + _, _ = w.Write(reply) +} + +func (d hostDNS) test(ctx context.Context, cfg HostDNSConfig, domain string) (HostDNSTestResult, error) { + wire, err := encodeDNSName(domain) + if err != nil { + return HostDNSTestResult{}, err + } + start := time.Now() + q := dnsQuestion{flags: dnsRD, class: dnsIN, wireName: wire, name: dnsNameForLookup(wire)} + result := HostDNSTestResult{Domain: domain} + var lookupErr error + for _, qtype := range []uint16{dnsA, dnsAAAA} { + q.qtype = qtype + msg, err := d.resolve(ctx, cfg, q.message(q.flags, nil), q) + if err != nil { + lookupErr = err + continue + } + reply, answers, err := readDNSMessage(msg) + if err != nil { + return HostDNSTestResult{}, err + } + if rcode := reply.flags & 0xf; rcode != 0 { + lookupErr = fmt.Errorf("DNS response code %d", rcode) + continue + } + aliases := make(map[string]string) + for _, record := range answers { + if record.class == q.class && record.rrtype == dnsCNAME { + target, end, err := readDNSName(msg, record.dataOffset) + if err == nil && end == record.dataOffset+len(record.data) { + aliases[strings.ToLower(dnsNameForLookup(record.name))] = strings.ToLower(dnsNameForLookup(target)) + } + } + } + names := make(map[string]bool) + for name := strings.ToLower(q.name); name != "" && !names[name]; name = aliases[name] { + names[name] = true + } + addressSize := net.IPv4len + if qtype == dnsAAAA { + addressSize = net.IPv6len + } + for _, record := range answers { + if record.class == q.class && record.rrtype == qtype && len(record.data) == addressSize && + names[strings.ToLower(dnsNameForLookup(record.name))] { + result.Addresses = append(result.Addresses, net.IP(record.data).String()) + } + } + } + if len(result.Addresses) == 0 { + if lookupErr == nil { + lookupErr = errors.New("DNS response contained no IP addresses") + } + return HostDNSTestResult{}, lookupErr + } + result.ElapsedMS = time.Since(start).Milliseconds() + return result, nil +} diff --git a/internal/guesttools/dns_test.go b/internal/guesttools/dns_test.go new file mode 100644 index 0000000..a928e01 --- /dev/null +++ b/internal/guesttools/dns_test.go @@ -0,0 +1,392 @@ +package guesttools + +import ( + "bytes" + "context" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/config" +) + +func dnsTestQuery(t *testing.T, name string, qtype uint16) []byte { + t.Helper() + wire, err := encodeDNSName(name) + if err != nil { + t.Fatal(err) + } + q := dnsQuestion{id: 0xabcd, flags: dnsRD, class: dnsIN, qtype: qtype, wireName: wire} + return q.message(q.flags, nil) +} + +func TestParseDNSQuery(t *testing.T) { + raw := dnsTestQuery(t, "www.Example.com", dnsAAAA) + got, err := parseDNSQuery(raw) + if err != nil || got.id != 0xabcd || got.flags != dnsRD || got.name != "www.Example.com." || + got.qtype != dnsAAAA || got.class != dnsIN { + t.Fatalf("parseDNSQuery = %+v, %v", got, err) + } + compressed := append(slices.Clone(raw), 0xc0, 0x0c, 0, dnsA, 0, dnsIN, 0, 0, 0, 0, 0, 4, 192, 0, 2, 1) + compressed[11] = 1 + if _, err := parseDNSQuery(compressed); err != nil { + t.Fatalf("valid compression: %v", err) + } + loop := slices.Clone(compressed) + loop[len(raw)+1] = byte(len(raw)) + labelLoop := append(slices.Clone(raw[:12]), 1, 'a', 0xc0, 0x0c, 0, 1, 0, 1) + longName := slices.Clone(raw[:12]) + for range 4 { + longName = append(longName, 63) + longName = append(longName, bytes.Repeat([]byte{'a'}, 63)...) + } + longName = append(longName, 0, 0, 1, 0, 1) + for name, msg := range map[string][]byte{ + "self-pointer": loop, "label-cycle": labelLoop, "truncated question": raw[:len(raw)-1], + "truncated record": compressed[:len(compressed)-1], "too large": make([]byte, maxDNSQuery+1), + "long name": longName, "trailing data": append(slices.Clone(raw), 0), + } { + t.Run(name, func(t *testing.T) { + if _, err := parseDNSQuery(msg); err == nil { + t.Fatal("expected query to be rejected") + } + }) + } +} + +type localDNSResolver struct{} + +func (localDNSResolver) LookupIP(_ context.Context, network, name string) ([]net.IP, error) { + switch { + case name == "missing.example.", name == "v4only.example." && network == "ip6", + name == "v6only.example." && network == "ip4": + return nil, &net.DNSError{IsNotFound: true} + case name == "unavailable.example.": + return nil, &net.DNSError{IsTemporary: true} + case network == "ip4": + return []net.IP{net.ParseIP("192.0.2.10")}, nil + case network == "ip6": + return []net.IP{net.ParseIP("2001:db8::10")}, nil + default: + return nil, errors.New("unexpected IP network") + } +} + +func (localDNSResolver) LookupCNAME(_ context.Context, name string) (string, error) { + if name == "v4only.example." { + return "V4Only.example", nil + } + return "target.example.", nil +} +func (localDNSResolver) LookupNS(context.Context, string) ([]*net.NS, error) { + return []*net.NS{{Host: "target.example."}}, nil +} +func (localDNSResolver) LookupAddr(_ context.Context, addr string) ([]string, error) { + if addr != "192.0.2.10" && addr != "2001:db8::10" { + return nil, fmt.Errorf("unexpected reverse address %s", addr) + } + return []string{"target.example."}, nil +} +func (localDNSResolver) LookupMX(context.Context, string) ([]*net.MX, error) { + return []*net.MX{{Host: "target.example.", Pref: 20}}, nil +} +func (localDNSResolver) LookupTXT(context.Context, string) ([]string, error) { + return []string{"hello", strings.Repeat("x", 256)}, nil +} +func (localDNSResolver) LookupSRV(_ context.Context, service, proto, name string) (string, []*net.SRV, error) { + if service != "" || proto != "" || name != "_service._tcp.example." { + return "", nil, errors.New("unexpected SRV resolver arguments") + } + return name, []*net.SRV{{Target: "target.example.", Port: 443, Priority: 5, Weight: 10}}, nil +} + +func TestHostDNSSystemRecords(t *testing.T) { + d := hostDNS{resolver: localDNSResolver{}} + cfg := HostDNSConfig{}.WithDefaults() + target := []byte("\x06target\x07example\x00") + for _, tc := range []struct { + qtype uint16 + name string + rcode uint16 + want [][]byte + }{ + {dnsA, "example.", 0, [][]byte{{192, 0, 2, 10}}}, + {dnsAAAA, "example.", 0, [][]byte{net.ParseIP("2001:db8::10")}}, + {dnsAAAA, "v4only.example.", 0, nil}, + {dnsA, "v6only.example.", 0, nil}, + {dnsA, "missing.example.", dnsNXDOMAIN, nil}, + {dnsAAAA, "missing.example.", dnsNXDOMAIN, nil}, + {dnsCNAME, "v4only.example.", 0, nil}, + {dnsCNAME, "alias.example.", 0, [][]byte{target}}, + {dnsNS, "example.", 0, [][]byte{target}}, + {dnsPTR, "10.2.0.192.in-addr.arpa.", 0, [][]byte{target}}, + {dnsPTR, "0.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.", 0, [][]byte{target}}, + {dnsMX, "example.", 0, [][]byte{append([]byte{0, 20}, target...)}}, + {dnsTXT, "example.", 0, [][]byte{[]byte("\x05hello"), []byte("\xff" + strings.Repeat("x", 255) + "\x01x")}}, + {dnsSRV, "_service._tcp.example.", 0, [][]byte{append([]byte{0, 5, 0, 10, 1, 187}, target...)}}, + } { + t.Run(fmt.Sprintf("%d/%s", tc.qtype, tc.name), func(t *testing.T) { + raw := dnsTestQuery(t, tc.name, tc.qtype) + q, _ := parseDNSQuery(raw) + reply, err := d.resolve(t.Context(), cfg, raw, q) + if err != nil { + t.Fatal(err) + } + got, answers, err := readDNSMessage(reply) + if err != nil || got.id != q.id || got.name != q.name || got.qtype != q.qtype || + got.flags != dnsQR|dnsRD|dnsRA|tc.rcode || len(answers) != len(tc.want) { + t.Fatalf("reply = %+v, answers = %+v, err = %v", got, answers, err) + } + for i, record := range answers { + if record.rrtype != q.qtype || record.class != dnsIN || !bytes.Equal(record.name, q.wireName) || + !bytes.Equal(record.data, tc.want[i]) { + t.Fatalf("answer %d = %+v, want data %x", i, record, tc.want[i]) + } + } + }) + } + result, err := d.test(t.Context(), cfg, "example.") + if err != nil || !slices.Equal(result.Addresses, []string{"192.0.2.10", "2001:db8::10"}) { + t.Fatalf("system test result = %+v, %v", result, err) + } +} + +func TestHostDNSRejectsInvalidDiskConfig(t *testing.T) { + for _, tc := range []struct{ name, json string }{ + {"http", `{"host_dns_mode":"doh","host_dns_doh_url":"http://resolver.example.test/dns-query"}`}, + {"mode", `{"host_dns_mode":"invalid","host_dns_doh_url":"https://resolver.example.test/dns-query"}`}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "reims-go.json") + if err := os.WriteFile(path, []byte(tc.json), 0o600); err != nil { + t.Fatal(err) + } + cfg, err := config.Load(path) + if err != nil { + t.Fatal(err) + } + srv := NewTransportServer(nil) + bad := HostDNSConfig{Mode: cfg.HostDNSMode, DoHURL: cfg.HostDNSDoHURL} + srv.SetHostDNSConfig(bad) + if got := srv.hostDNSConfig; got != (HostDNSConfig{}).WithDefaults() { + t.Fatalf("bridge config = %+v, expected safe defaults", got) + } + raw := dnsTestQuery(t, "example.org.", 65) + q, _ := parseDNSQuery(raw) + if _, err := (hostDNS{}).resolve(t.Context(), bad, raw, q); err == nil { + t.Fatal("resolver accepted invalid configuration") + } + }) + } +} + +func TestHostDNSDoH(t *testing.T) { + raw := dnsTestQuery(t, "example.org.", 65) + q, _ := parseDNSQuery(raw) + reply := q.response(dnsNXDOMAIN, nil) + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.Header.Get("Accept") != dnsMediaType || r.Header.Get("Content-Type") != dnsMediaType { + t.Error("unexpected DoH method or headers") + } + request, err := io.ReadAll(r.Body) + if r.URL.Path == "/probe" { + query, parseErr := parseDNSQuery(request) + if err != nil || parseErr != nil || query.name != "example.com." { + t.Errorf("invalid DoH test query: %x, %v, %v", request, err, parseErr) + w.WriteHeader(http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", dnsMediaType) + switch query.qtype { + case dnsA: + msg := query.response(0, nil) + addRecord := func(owner []byte, rrtype uint16, data []byte) { + msg = append(msg, owner...) + msg = binary.BigEndian.AppendUint16(msg, rrtype) + msg = binary.BigEndian.AppendUint16(msg, dnsIN) + msg = binary.BigEndian.AppendUint32(msg, 0) + msg = binary.BigEndian.AppendUint16(msg, uint16(len(data))) + msg = append(msg, data...) + } + owner := []byte{0xc0, dnsHeaderSize} + target, _ := encodeDNSName("alias.example.com.") + unrelated, _ := encodeDNSName("other.example.com.") + addRecord(unrelated, dnsA, []byte{192, 0, 2, 20}) + addRecord(owner, dnsAAAA, net.ParseIP("2001:db8::20")) + addRecord(target, dnsA, []byte{192, 0, 2, 10}) + addRecord(owner, dnsCNAME, append([]byte("\x05alias"), owner...)) + binary.BigEndian.PutUint16(msg[6:], 4) + _, _ = w.Write(msg) + case dnsAAAA: + _, _ = w.Write(query.response(0, [][]byte{net.ParseIP("2001:db8::10")})) + default: + t.Errorf("unexpected DoH test query type %d", query.qtype) + } + return + } + if err != nil || !bytes.Equal(request, raw) { + t.Errorf("unexpected DoH body: %x, %v", request, err) + } + if r.URL.Path == "/status" { + w.WriteHeader(http.StatusBadGateway) + return + } + w.Header().Set("Content-Type", dnsMediaType) + switch r.URL.Path { + case "/type": + w.Header().Set("Content-Type", "text/plain") + case "/large": + _, _ = w.Write(make([]byte, maxDNSResponse+1)) + return + case "/mismatch": + bad := slices.Clone(reply) + bad[0] ^= 1 + _, _ = w.Write(bad) + return + } + _, _ = w.Write(reply) + })) + defer srv.Close() + d := hostDNS{client: srv.Client()} + for _, mode := range []string{"doh", "system"} { + got, err := d.resolve(t.Context(), HostDNSConfig{Mode: mode, DoHURL: srv.URL}, raw, q) + if err != nil || !bytes.Equal(got, reply) { + t.Fatalf("%s DoH reply = %x, %v", mode, got, err) + } + } + for _, tc := range []struct{ path, want string }{ + {"/status", "HTTP 502"}, {"/type", "content type"}, {"/large", "exceeds"}, {"/mismatch", "invalid DNS response"}, + } { + _, err := d.resolve(t.Context(), HostDNSConfig{Mode: "doh", DoHURL: srv.URL + tc.path}, raw, q) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("%s: unexpected upstream error: %v", tc.path, err) + } + } + result, err := d.test(t.Context(), HostDNSConfig{Mode: "doh", DoHURL: srv.URL + "/probe"}, "example.com") + if err != nil || !slices.Equal(result.Addresses, []string{"192.0.2.10", "2001:db8::10"}) { + t.Fatalf("DoH test result = %+v, %v", result, err) + } +} + +func TestGuestToolsDNSRouteAndStatus(t *testing.T) { + srv := NewTransportServer(nil) + srv.hostDNS.resolver = localDNSResolver{} + port, err := srv.Start(-1) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = srv.Close(context.Background()) }) + baseURL := fmt.Sprintf("http://127.0.0.1:%d", port) + vm := VMConfig{VMName: "dns-test", Token: "dns-token", SharedDir: t.TempDir()} + srv.RegisterVM(vm) + request := func(method, path, auth string, body []byte, wantStatus int) ([]byte, http.Header) { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), method, baseURL+path, bytes.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", auth) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + got, err := io.ReadAll(resp.Body) + if err != nil || resp.StatusCode != wantStatus { + t.Fatalf("%s: HTTP %d, want %d. Body %q, err %v", path, resp.StatusCode, wantStatus, got, err) + } + return got, resp.Header + } + raw := dnsTestQuery(t, "example.org.", dnsA) + const dnsPath = "/v1/dns-query" + const bearer = "Bearer dns-token" + request(http.MethodPost, dnsPath, "", raw, 401) + request(http.MethodPost, dnsPath, "Bearer wrong", raw, 401) + request(http.MethodPost, dnsPath, "Basic cmVpbXM6ZG5zLXRva2Vu", raw, 401) + request(http.MethodPost, dnsPath, bearer, raw, 403) + for _, enabled := range []bool{false, true} { + vm.HostDNSEnabled = enabled + srv.RegisterVM(vm) + got, _ := request(http.MethodGet, "/v1/config", bearer, nil, 200) + var fields map[string]json.RawMessage + if err := json.Unmarshal(got, &fields); err != nil { + t.Fatal(err) + } + var actual bool + if err := json.Unmarshal(fields["host_dns_enabled"], &actual); err != nil || actual != enabled { + t.Fatalf("/v1/config: %s, %v", got, err) + } + } + request(http.MethodGet, dnsPath, bearer, nil, 405) + request(http.MethodPost, dnsPath, bearer, make([]byte, maxDNSQuery+1), 400) + for _, tc := range []struct { + name string + opcode, code uint16 + }{ + {"example.org.", 0, 0}, + {"missing.example.", 0, dnsNXDOMAIN}, + {"unavailable.example.", 0, dnsSERVFAIL}, + {"example.org.", 2 << 11, dnsNOTIMP}, + } { + wire := dnsTestQuery(t, tc.name, dnsA) + binary.BigEndian.PutUint16(wire[2:], tc.opcode|dnsRD) + got, header := request(http.MethodPost, dnsPath, bearer, wire, 200) + reply, records, err := readDNSMessage(got) + if err != nil || header.Get("Content-Type") != dnsMediaType || + reply.flags != dnsQR|dnsRD|dnsRA|tc.opcode|tc.code { + t.Fatalf("%s: invalid DNS reply = %+v, headers %v, error %v", tc.name, reply, header, err) + } + if tc.code == 0 && (len(records) != 1 || !bytes.Equal(records[0].data, []byte{192, 0, 2, 10})) { + t.Fatalf("unexpected answer: %+v", records) + } + } + request(http.MethodPost, "/v1/status", bearer, []byte("{\"host_dns_active\":true,\"host_dns_config_stale\":true}"), 200) + if status := srv.Status(vm.VMName, time.Minute); !status.HostDNSEnabled || !status.HostDNSReported || !status.HostDNSActive || !status.HostDNSConfigStale { + t.Fatalf("unexpected live status: %+v", status) + } + request(http.MethodPost, "/v1/status", bearer, []byte("{\"host_dns_active\":false}"), 200) + if status := srv.Status(vm.VMName, time.Minute); !status.HostDNSReported || status.HostDNSActive || status.HostDNSConfigStale { + t.Fatalf("unexpected cleared status: %+v", status) + } + request(http.MethodPost, "/v1/status", bearer, []byte(`{"agent_version":2}`), 200) + if status := srv.Status(vm.VMName, time.Minute); !status.Connected || status.HostDNSReported { + t.Fatalf("legacy status was treated as a DNS report: %+v", status) + } + request(http.MethodPost, "/v1/status", bearer, []byte(`{"host_dns_active":true}`), 200) + srv.mu.Lock() + srv.vms[vmRegistryKey(vm.DriverID, vm.VMName)].lastStatus = time.Now().Add(-2 * time.Minute) + srv.mu.Unlock() + if status := srv.Status(vm.VMName, time.Minute); !status.Connected || status.HostDNSReported || status.HostDNSActive { + t.Fatalf("expired status was treated as a live DNS report: %+v", status) + } +} + +func TestGuestDNSScriptCommands(t *testing.T) { + for _, tc := range []struct { + script []byte + want []string + }{ + {guestDNSProxy, []string{"IO::Socket::INET", "IO::Select", "LocalPort => 53, Proto => 'udp'", "LocalPort => 53, Proto => 'tcp'", "POST /v1/dns-query HTTP/1.0", "Authorization: Bearer", "pack('n', length($reply))", "SIG{PIPE}", "alarm 7", "reload_config"}}, + {guestApplyHostDNS, []string{"chmod 600", "launchctl bootstrap system", "RunAtLoad", "KeepAlive", "networksetup -getdnsservers \"$svc\"", "networksetup -setdnsservers \"$svc\" 127.0.0.1", "dig @127.0.0.1"}}, + {guestDisableHostDNS, []string{"launchctl bootout", "networksetup -setdnsservers \"$svc\" Empty"}}, + {GuestAgentScript(), []string{"host_dns_active", "host_dns_config_stale", "launchctl print system/com.reimsgo.dns-proxy"}}, + {GuestUninstallScript(), []string{"Disable-Host-DNS.command"}}, + } { + for _, want := range tc.want { + if !bytes.Contains(tc.script, []byte(want)) { + t.Errorf("guest scripts missing %q", want) + } + } + } +} diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 2129aae..963d800 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -37,6 +37,12 @@ func TestGuestAgentFolderMounts(t *testing.T) { } } agent, uninstall, install := string(GuestAgentScript()), string(GuestUninstallScript()), string(GuestInstallScript()) + dnsPaths := strings.NewReplacer( + "/Library/LaunchDaemons/com.reimsgo.dns-proxy.plist", "$PWD/dns-proxy.plist", + `"/Library/Application Support/ReimsGuestTools`, `"$PWD/system tools`, + "/Volumes/REIMSTOOLS/Disable-Host-DNS.command", "$PWD/media/Disable-Host-DNS.command", + ) + uninstall = dnsPaths.Replace(uninstall) if CurrentAgentVersion != KeymapAgentVersion { t.Fatalf("CurrentAgentVersion = %d, want keymap version %d", CurrentAgentVersion, KeymapAgentVersion) } @@ -65,6 +71,15 @@ func TestGuestAgentFolderMounts(t *testing.T) { run(t, folderShellFixture+folderUninstallSetup+ "\nrun_uninstall() {\n"+uninstall+"\n}\n"+folderUninstallBusyChecks+folderUninstallChecks, "-s", "--", "owned") }) + disableDNS := dnsPaths.Replace(strings.ReplaceAll(string(guestDisableHostDNS), "\r\n", "\n")) + for _, scenario := range []string{"local", "media", "cancelled", "restore_failed", "flush_failed"} { + t.Run("uninstall_dns_"+scenario, func(t *testing.T) { + run(t, folderShellFixture+folderUninstallSetup+ + "\nrun_uninstall() {\n"+uninstall+"\n}\n"+ + "cat > disable-dns <<'DISABLE_DNS'\n"+disableDNS+"DISABLE_DNS\n"+ + folderUninstallDNSChecks, "-s", "--", "owned", scenario) + }) + } install = strings.Replace(install, `SRC="/Volumes/REIMSTOOLS"`, `SRC="$PWD/tools"`, 1) for _, scenario := range []string{"new_vm", "new_token", "busy", "same_identity"} { t.Run("install_"+scenario, func(t *testing.T) { @@ -298,6 +313,75 @@ busy=0 run_uninstall ` +const folderUninstallDNSChecks = ` +export DNS_SCENARIO="$2" +system_tools="$PWD/system tools" +mkdir "$system_tools" media +touch dns-proxy.plist "$system_tools/dns-proxy.pl" "$system_tools/dns-proxy.conf" +printf 'Ethernet\n192.0.2.53\n\n' > "$system_tools/dns-proxy.previous-dns" +printf '127.0.0.1\n' > current-dns +disable_path="$system_tools/Disable-Host-DNS.command" +case "$DNS_SCENARIO" in + media) disable_path="$PWD/media/Disable-Host-DNS.command" ;; + local) + printf '#!/bin/sh\nexit 9\n' > media/Disable-Host-DNS.command + chmod +x media/Disable-Host-DNS.command ;; +esac +cp disable-dns "$disable_path" +chmod +x "$disable_path" +cat > sudo <<'EOF' +#!/bin/sh +if [ "$1" = -v ]; then + [ "$DNS_SCENARIO" != cancelled ] + exit $? +fi +exec "$@" +EOF +cat > networksetup <<'EOF' +#!/bin/sh +case "$1" in + -listallnetworkservices) printf 'Network services:\nEthernet\n' ;; + -getdnsservers) cat current-dns ;; + -setdnsservers) + [ "$DNS_SCENARIO" != restore_failed ] || exit 1 + printf '%s\n' "$3" > current-dns ;; + *) exit 1 ;; +esac +EOF +cat > launchctl <<'EOF' +#!/bin/sh +if [ "$1" = bootout ]; then + [ "$(cat current-dns)" = 192.0.2.53 ] || exit 1 + touch dns-stopped +fi +EOF +printf '#!/bin/sh\n[ "$DNS_SCENARIO" != flush_failed ]\n' > dscacheutil +chmod +x sudo networksetup launchctl dscacheutil +case "$DNS_SCENARIO" in + local|media) + run_uninstall + expect "$(cat current-dns)" 192.0.2.53 + [ -f dns-stopped ] + [ ! -f dns-proxy.plist ] + [ ! -d "$APP_DIR" ] + [ ! -f "$system_tools/dns-proxy.previous-dns" ] + ;; + *) + if (run_uninstall) > uninstall_stdout 2> uninstall_stderr; then + echo "uninstall succeeded after DNS cleanup failed" >&2 + exit 1 + fi + grep -Fq 'retry uninstalling' uninstall_stderr + [ -f dns-proxy.plist ] + [ -f "$APP_DIR/config" ] + [ -f "$system_tools/dns-proxy.pl" ] + [ -f "$system_tools/dns-proxy.conf" ] + [ -f "$system_tools/dns-proxy.previous-dns" ] + [ -x "$disable_path" ] + ;; +esac +` + const folderOwnershipChecks = ` mkdir -p "$FOLDER_MOUNT_ROOT/work" "$FOLDER_MOUNT_ROOT/notes" "$FOLDER_MOUNT_ROOT/foreign" "$DRIVE_MOUNT_ROOT/D" printf 'http://other:19847/dav-folders/mac/work/ on %s (webdav)\n' "$FOLDER_MOUNT_ROOT/work" > mounts diff --git a/internal/guesttools/guesttools_test.go b/internal/guesttools/guesttools_test.go index 8ee7263..5dbb97f 100644 --- a/internal/guesttools/guesttools_test.go +++ b/internal/guesttools/guesttools_test.go @@ -626,6 +626,23 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) { t.Fatalf("missing %s in REIMSTOOLS image: err=%v size=%d", name, err, sz) } } + for name, script := range map[string][]byte{ + "dns-proxy.pl": guestDNSProxy, + "Apply-Host-DNS.command": guestApplyHostDNS, + "Disable-Host-DNS.command": guestDisableHostDNS, + } { + offset, size, err := installer.FindFileInHFSPlusImage(f, name) + if err != nil { + t.Fatal(err) + } + got := make([]byte, size) + if _, err := f.ReadAt(got, offset); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, bytes.ReplaceAll(script, []byte("\r\n"), []byte("\n"))) { + t.Fatalf("unexpected content in %s on REIMSTOOLS", name) + } + } // Syntax check every generated POSIX script if sh is available. shBin, err := exec.LookPath("sh") @@ -646,6 +663,8 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) { "Install-Reims-Tools.command": GuestInstallScript(), "Uninstall-Reims-Tools.command": GuestUninstallScript(), "Apply-Prevent-Sleep-pmset.command": GuestPmsetScript(), + "Apply-Host-DNS.command": guestApplyHostDNS, + "Disable-Host-DNS.command": guestDisableHostDNS, } { p := filepath.Join(tmp, name) if err := os.WriteFile(p, content, 0o755); err != nil { diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 56ab1e4..06c1594 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -24,9 +24,18 @@ const ( //go:embed file_sync.sh var guestFileSync string +//go:embed dns-proxy.pl +var guestDNSProxy []byte + +//go:embed Apply-Host-DNS.command +var guestApplyHostDNS []byte + +//go:embed Disable-Host-DNS.command +var guestDisableHostDNS []byte + // BuildToolsDiskImage creates a read-only HFS+ disk image ("REIMSTOOLS") // containing the per-VM Bearer token config, the POSIX guest agent script, and -// install/uninstall/pmset helper scripts. +// install/uninstall/pmset/DNS helper scripts. func BuildToolsDiskImage(outPath string, cfg VMConfig) error { if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil { return err @@ -70,6 +79,23 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(pmsetBytes)), nil }, }, } + for _, script := range []struct { + name string + data []byte + }{ + {"dns-proxy.pl", guestDNSProxy}, + {"Apply-Host-DNS.command", guestApplyHostDNS}, + {"Disable-Host-DNS.command", guestDisableHostDNS}, + } { + // The Windows checkout may have CRLF line endings. + data := bytes.ReplaceAll(script.data, []byte("\r\n"), []byte("\n")) + files = append(files, installer.HFSFile{ + Name: script.name, + Mode: 0o100755, + Size: int64(len(data)), + Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil }, + }) + } return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files) } @@ -435,10 +461,26 @@ apply_host_config() { report_status() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 + host_dns_active=false + host_dns_config_stale=false + dns_plist=/Library/LaunchDaemons/com.reimsgo.dns-proxy.plist + if [ -f "$dns_plist" ]; then + if launchctl print system/com.reimsgo.dns-proxy 2>/dev/null | grep -q 'state = running'; then + host_dns_active=true + fi + dns_port=$(/usr/libexec/PlistBuddy -c 'Print :EnvironmentVariables:REIMS_HOST_PORT' "$dns_plist" 2>/dev/null || true) + dns_token_sha=$(/usr/libexec/PlistBuddy -c 'Print :EnvironmentVariables:REIMS_TOKEN_SHA256' "$dns_plist" 2>/dev/null || true) + cur_token_sha=$(printf '%s' "$REIMS_TOKEN" | /usr/bin/shasum -a 256 2>/dev/null | awk '{print $1}' || true) + if [ -n "$dns_port" ] && [ "$dns_port" != "$REIMS_HOST_PORT" ]; then + host_dns_config_stale=true + elif [ -n "$dns_token_sha" ] && [ -n "$cur_token_sha" ] && [ "$dns_token_sha" != "$cur_token_sha" ]; then + host_dns_config_stale=true + fi + fi curl -fsS -m "${1:-3}" -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":10,\"keymap_active\":$keymap_active}" \ + -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":10,\"keymap_active\":$keymap_active,\"host_dns_active\":$host_dns_active,\"host_dns_config_stale\":$host_dns_config_stale}" \ "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true } @@ -774,7 +816,7 @@ fi `) } -// GuestUninstallScript cleanly removes the LaunchAgent while preserving user files. +// GuestUninstallScript removes Guest Tools and restores DNS while preserving user files. func GuestUninstallScript() []byte { return []byte(`#!/bin/sh set -e @@ -786,6 +828,17 @@ DRIVE_MOUNT_ROOT="$HOME/ReimsWindowsDrives" FOLDER_MOUNT_ROOT="$HOME/ReimsSharedFolders" FOLDER_MODE_DIR="$APP_DIR/folder_modes" FOLDER_DESKTOP_LINK="$HOME/Desktop/ReimsSharedFolders" +DNS_PLIST=/Library/LaunchDaemons/com.reimsgo.dns-proxy.plist +if [ -f "$DNS_PLIST" ]; then + DNS_DISABLE="/Library/Application Support/ReimsGuestTools/Disable-Host-DNS.command" + if [ ! -x "$DNS_DISABLE" ]; then + DNS_DISABLE=/Volumes/REIMSTOOLS/Disable-Host-DNS.command + fi + if [ ! -x "$DNS_DISABLE" ] || ! "$DNS_DISABLE"; then + echo "Could not disable Host DNS. If needed, attach REIMSTOOLS, then retry uninstalling and approve the administrator prompt." >&2 + exit 1 + fi +fi [ ! -f "$CONF" ] || . "$CONF" ` + guestURLencode + folderMountHelpers + shareUnmountScript + ` uid=$(id -u) diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 16b1ad5..ff47da4 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -77,6 +77,7 @@ type VMConfig struct { Port int `json:"port"` SharedDir string `json:"shared_dir"` PreventSleep bool `json:"prevent_sleep"` + HostDNSEnabled bool `json:"host_dns_enabled,omitempty"` DriveSharingEnabled bool `json:"drive_sharing_enabled"` SharedDrives []string `json:"shared_drives,omitempty"` DriveVolumes map[string]string `json:"drive_volumes,omitempty"` @@ -91,13 +92,17 @@ type VMConfig struct { // GuestStatus summarizes live Guest Tools connection and capability state. type GuestStatus struct { - KeymapActive bool `json:"keymap_active"` - Connected bool `json:"connected"` - MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync" - PreventSleep bool `json:"prevent_sleep"` - SleepActive bool `json:"sleep_active"` - AgentVersion int `json:"agent_version,omitempty"` - LastSeen time.Time `json:"last_seen,omitempty"` + KeymapActive bool `json:"keymap_active"` + Connected bool `json:"connected"` + MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync" + PreventSleep bool `json:"prevent_sleep"` + SleepActive bool `json:"sleep_active"` + HostDNSEnabled bool `json:"host_dns_enabled"` + HostDNSActive bool `json:"host_dns_active"` + HostDNSReported bool `json:"host_dns_reported"` + HostDNSConfigStale bool `json:"host_dns_config_stale"` + AgentVersion int `json:"agent_version,omitempty"` + LastSeen time.Time `json:"last_seen,omitempty"` } // LoadOrCreateVMConfig loads an existing per-VM Guest Tools config or generates @@ -215,6 +220,10 @@ type registeredVM struct { sharedDir string sharedRoot sharedRoot preventSleep bool + hostDNSEnabled bool + hostDNSActive bool + hostDNSReported bool + hostDNSConfigStale bool driveSharingEnabled bool sharedDriveRoots map[string]string driveVolumeGUIDs map[string]string @@ -265,6 +274,8 @@ type Server struct { clipNotify chan struct{} onHostText func(vmKey, vmName, text string) onStatusChange func(vmName string) + hostDNSConfig HostDNSConfig + hostDNS hostDNS } // NewServer constructs a Guest Tools HTTP bridge with clipboard active by default. @@ -282,6 +293,7 @@ func NewServer(clip Clipboard) *Server { globalClipPolicy: DefaultClipboardPolicy(), vmClipPolicies: make(map[string]ClipboardPolicy), clipNotify: make(chan struct{}), + hostDNS: defaultHostDNS, } s.dynamicRoutes["/v1/clipboard"] = s.handleClipboard return s @@ -329,6 +341,7 @@ func (s *Server) Start(preferredPort int) (int, error) { mux.HandleFunc("/v1/config", s.handleConfig) mux.HandleFunc("/v1/folders", s.handleFolders) mux.HandleFunc("/v1/status", s.handleStatus) + mux.HandleFunc("/v1/dns-query", s.handleDNSQuery) mux.HandleFunc("/v1/clipboard", s.dispatchDynamicRoute("/v1/clipboard", "clipboard")) mux.HandleFunc("/v1/text-input", s.handleTextInput) mux.HandleFunc("/v1/text-input/ack", s.handleTextInputAck) @@ -508,6 +521,7 @@ func (s *Server) RegisterVM(cfg VMConfig) { cur.sharedDir = cfg.SharedDir cur.sharedRoot = root cur.preventSleep = cfg.PreventSleep + cur.hostDNSEnabled = cfg.HostDNSEnabled cur.driveSharingEnabled = cfg.DriveSharingEnabled cur.sharedDriveRoots = driveRoots cur.driveVolumeGUIDs = cloneStringMap(cfg.DriveVolumes) @@ -704,14 +718,19 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { return GuestStatus{} } connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= maxAge + dnsReported := connected && vm.hostDNSReported && time.Since(vm.lastStatus) <= maxAge return GuestStatus{ - KeymapActive: connected && vm.keymapCarrierEnabled && vm.keymapActive && time.Since(vm.lastStatus) <= maxAge, - Connected: connected, - MountMode: vm.mountMode, - PreventSleep: vm.preventSleep, - SleepActive: connected && vm.sleepActive, - AgentVersion: vm.agentVersion, - LastSeen: vm.lastSeen, + KeymapActive: connected && vm.keymapCarrierEnabled && vm.keymapActive && time.Since(vm.lastStatus) <= maxAge, + Connected: connected, + MountMode: vm.mountMode, + PreventSleep: vm.preventSleep, + SleepActive: connected && vm.sleepActive, + HostDNSEnabled: vm.hostDNSEnabled, + HostDNSActive: dnsReported && vm.hostDNSActive, + HostDNSReported: dnsReported, + HostDNSConfigStale: dnsReported && vm.hostDNSConfigStale, + AgentVersion: vm.agentVersion, + LastSeen: vm.lastSeen, } } @@ -767,6 +786,7 @@ func (s *Server) authenticate(r *http.Request) *registeredVM { sharedDir: vm.sharedDir, sharedRoot: vm.sharedRoot, preventSleep: vm.preventSleep, + hostDNSEnabled: vm.hostDNSEnabled, driveSharingEnabled: vm.driveSharingEnabled, sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots), driveVolumeGUIDs: cloneStringMap(vm.driveVolumeGUIDs), @@ -840,6 +860,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { "vm": vm.name, "keymap_carrier_enabled": vm.keymapCarrierEnabled, "prevent_sleep": vm.preventSleep, + "host_dns_enabled": vm.hostDNSEnabled, "webdav_path": "/dav/" + vm.name + "/", "shared_drives": enabledDriveLetters(vm), "shared_folders_count": len(vm.resolvedFolders), @@ -861,10 +882,12 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { return } var req struct { - KeymapActive bool `json:"keymap_active"` - MountMode string `json:"mount_mode"` - SleepActive bool `json:"sleep_active"` - AgentVersion int `json:"agent_version"` + KeymapActive bool `json:"keymap_active"` + MountMode string `json:"mount_mode"` + SleepActive bool `json:"sleep_active"` + HostDNSActive *bool `json:"host_dns_active"` + HostDNSConfigStale bool `json:"host_dns_config_stale"` + AgentVersion int `json:"agent_version"` } if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) @@ -888,6 +911,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { cur.mountMode = mode } cur.sleepActive = req.SleepActive + cur.hostDNSReported = req.HostDNSActive != nil + cur.hostDNSActive = cur.hostDNSReported && *req.HostDNSActive + cur.hostDNSConfigStale = req.HostDNSConfigStale if req.AgentVersion > 0 { cur.agentVersion = req.AgentVersion } diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index ff8b64a..bdf2041 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -443,5 +443,24 @@ "targetDisplayHint": "Target display: {name} ({w}×{h} at {scale}%)", "targetDisplayToastMoved": "Switched to {display}", "targetDisplayToastSaved": "Launch display set to {display}; applies on next start", - "targetDisplaySaveFailed": "Could not update launch display" + "targetDisplaySaveFailed": "Could not update launch display", + "hostDNSModeTitle": "VM DNS proxy mode", + "hostDNSModeSystem": "Host system resolver", + "hostDNSModeDoH": "DoH encrypted upstream", + "hostDNSModeSystemSub": "Uses Windows system DNS and local networks first; falls back to DoH for unsupported record types", + "hostDNSModeDoHSub": "Resolves all queries via the DoH upstream and inherits host proxy settings", + "hostDNSDoHTitle": "DoH upstream URL", + "hostDNSDoHSub": "Handles all queries in DoH mode and fallback record types in system mode", + "hostDNSPresetAliDNS": "AliDNS", + "hostDNSPresetDNSPod": "DNSPod", + "hostDNSPresetCloudflare": "Cloudflare", + "hostDNSPresetGoogle": "Google", + "hostDNSPresetCustom": "Custom", + "hostDNSCustomPlaceholder": "https://dns.example.com/dns-query", + "hostDNSInvalidURL": "Must be a valid https:// URL", + "hostDNSSaved": "Settings saved", + "hostDNSTest": "Test lookup", + "hostDNSTesting": "Testing…", + "hostDNSTestOK": "{domain} → {ips} · {ms} ms", + "hostDNSTestFailed": "Lookup failed: {reason}" } diff --git a/locales/en-US/vm.json b/locales/en-US/vm.json index 6f2f87e..f293ae9 100644 --- a/locales/en-US/vm.json +++ b/locales/en-US/vm.json @@ -195,6 +195,18 @@ "guestToolsUpgradeHint": "The tools in macOS are out of date; run the install command again to update", "guestToolsPreventSleep": "Prevent macOS sleep", "guestToolsSleepActive": "Keeping macOS awake", + "guestToolsHostDNS": "Host DNS proxy", + "hostDNSStatusActive": "Active", + "hostDNSStatusStale": "Config outdated", + "hostDNSStatusPending": "Not applied", + "hostDNSStatusStillActive": "Still active in macOS", + "hostDNSOffHint": "Enable when upstream blocks UDP/53 and the VM loses network", + "hostDNSApplyHint": "Run in macOS Terminal to apply", + "hostDNSStaleHint": "Host port changed; rerun to refresh", + "hostDNSDisableHint": "When disabling, run {cmd} to restore default DNS", + "hostDNSDisableCmdHint": "Run in macOS Terminal to remove", + "toastHostDNSOn": "Host DNS proxy enabled", + "toastHostDNSOff": "Host DNS proxy disabled", "toastFileDelivered": "Sent {name}", "toastPreventSleepOn": "Prevent-sleep guard enabled", "toastPreventSleepOff": "Prevent-sleep guard disabled", diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index ac31844..5588d72 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -443,5 +443,24 @@ "targetDisplayHint": "目标显示器:{name}({w}×{h},{scale}% 缩放)", "targetDisplayToastMoved": "已切换至「{display}」", "targetDisplayToastSaved": "启动显示器已设为「{display}」,下次启动生效", - "targetDisplaySaveFailed": "无法更新启动显示器" + "targetDisplaySaveFailed": "无法更新启动显示器", + "hostDNSModeTitle": "虚拟机 DNS 代理模式", + "hostDNSModeSystem": "宿主机系统解析", + "hostDNSModeDoH": "DoH 加密上游", + "hostDNSModeSystemSub": "优先走 Windows 系统解析与本地网络,非常规记录回退 DoH", + "hostDNSModeDoHSub": "全部经 DoH 上游解析,并继承宿主机代理", + "hostDNSDoHTitle": "DoH 上游地址", + "hostDNSDoHSub": "DoH 模式下处理全部查询,系统模式下用于非常规记录回退", + "hostDNSPresetAliDNS": "阿里云 DNS", + "hostDNSPresetDNSPod": "腾讯 DNSPod", + "hostDNSPresetCloudflare": "Cloudflare", + "hostDNSPresetGoogle": "Google", + "hostDNSPresetCustom": "自定义", + "hostDNSCustomPlaceholder": "https://dns.example.com/dns-query", + "hostDNSInvalidURL": "需要以 https:// 开头的有效地址", + "hostDNSSaved": "已保存配置", + "hostDNSTest": "测试解析", + "hostDNSTesting": "测试中…", + "hostDNSTestOK": "{domain} → {ips} · {ms} ms", + "hostDNSTestFailed": "解析失败:{reason}" } diff --git a/locales/zh-CN/vm.json b/locales/zh-CN/vm.json index a8ab8f3..defb14c 100644 --- a/locales/zh-CN/vm.json +++ b/locales/zh-CN/vm.json @@ -195,6 +195,18 @@ "guestToolsUpgradeHint": "macOS 里的工具是旧版,重新运行安装命令即可升级", "guestToolsPreventSleep": "防止 macOS 睡眠", "guestToolsSleepActive": "正在保持唤醒", + "guestToolsHostDNS": "宿主机 DNS 代理", + "hostDNSStatusActive": "运行中", + "hostDNSStatusStale": "配置已过期", + "hostDNSStatusPending": "待应用", + "hostDNSStatusStillActive": "macOS 代理未移除", + "hostDNSOffHint": "上游过滤 UDP/53 导致虚拟机无网络时开启", + "hostDNSApplyHint": "在 macOS 终端运行以启用", + "hostDNSStaleHint": "宿主机端口已变更,重新运行以刷新", + "hostDNSDisableHint": "关闭时运行 {cmd} 还原默认 DNS", + "hostDNSDisableCmdHint": "在 macOS 终端运行以移除代理", + "toastHostDNSOn": "已开启宿主机 DNS 代理", + "toastHostDNSOff": "已关闭宿主机 DNS 代理", "toastFileDelivered": "已发送 {name}", "toastPreventSleepOn": "已开启 macOS 防休眠守护", "toastPreventSleepOff": "已关闭 macOS 防休眠守护", From b78f4b3028f973d9afb372503a31234311d65120 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Wed, 2 Dec 2026 03:15:54 +0800 Subject: [PATCH 06/47] feat(runtime): accept suspend-compatible Alpha revisions Read the verified compatibility ID while preserving legacy and media checks. --- changes/alpha-suspend-compatibility.json | 7 +++ frontend/wailsjs/go/models.ts | 4 ++ internal/macos/reims/suspend.go | 17 +++++-- internal/macos/reims/suspend_test.go | 20 +++++++++ .../macos/reims/suspend_transaction_test.go | 44 +++++++++++++++++++ internal/runtime/remote.go | 14 ++++++ internal/runtime/runtime.go | 1 + 7 files changed, 103 insertions(+), 4 deletions(-) create mode 100644 changes/alpha-suspend-compatibility.json diff --git a/changes/alpha-suspend-compatibility.json b/changes/alpha-suspend-compatibility.json new file mode 100644 index 0000000..d1a9dfd --- /dev/null +++ b/changes/alpha-suspend-compatibility.json @@ -0,0 +1,7 @@ +{ + "group": "improvements", + "order": 0, + "authors": ["yxc0915"], + "zh": "具有相同挂起兼容标识的 Alpha 修订可恢复同一主编号下保存的虚拟机挂起状态。", + "en": "Alpha revisions with the same suspend compatibility ID can resume VM state saved under the same base version." +} diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 99c768e..35d4dc6 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -2680,6 +2680,7 @@ export namespace reims { extra_args?: string; runtime_commit: string; vendor_qemu_commit?: string; + suspend_compat_id?: string; created_at: string; vmstate_size: number; @@ -2705,6 +2706,7 @@ export namespace reims { this.extra_args = source["extra_args"]; this.runtime_commit = source["runtime_commit"]; this.vendor_qemu_commit = source["vendor_qemu_commit"]; + this.suspend_compat_id = source["suspend_compat_id"]; this.created_at = source["created_at"]; this.vmstate_size = source["vmstate_size"]; } @@ -2873,6 +2875,7 @@ export namespace runtime { raw_bytes: number; sha256: Record; vendor_qemu_commit?: string; + suspend_compat_id?: string; util_commit?: string; metal2vulkan_commit?: string; patches?: Patch[]; @@ -2905,6 +2908,7 @@ export namespace runtime { this.raw_bytes = source["raw_bytes"]; this.sha256 = source["sha256"]; this.vendor_qemu_commit = source["vendor_qemu_commit"]; + this.suspend_compat_id = source["suspend_compat_id"]; this.util_commit = source["util_commit"]; this.metal2vulkan_commit = source["metal2vulkan_commit"]; this.patches = this.convertValues(source["patches"], Patch); diff --git a/internal/macos/reims/suspend.go b/internal/macos/reims/suspend.go index 202565f..26c9f20 100644 --- a/internal/macos/reims/suspend.go +++ b/internal/macos/reims/suspend.go @@ -39,6 +39,7 @@ type SuspendInfo struct { ExtraArgs string `json:"extra_args,omitempty"` RuntimeCommit string `json:"runtime_commit"` VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"` + SuspendCompatID string `json:"suspend_compat_id,omitempty"` CreatedAt string `json:"created_at"` VMStateSize int64 `json:"vmstate_size"` } @@ -128,6 +129,7 @@ func BuildSuspendInfo(d VMDetail, active rt.Installed, vmstateSize int64) Suspen ExtraArgs: StripIncomingDeferArgs(d.ExtraArgs), RuntimeCommit: strings.TrimSpace(active.Commit), VendorQemuCommit: strings.TrimSpace(active.Manifest.VendorQemuCommit), + SuspendCompatID: rt.SuspendCompatibilityID(active.Commit, active.Manifest.SuspendCompatID), CreatedAt: time.Now().UTC().Format(time.RFC3339), VMStateSize: vmstateSize, } @@ -179,11 +181,18 @@ func ValidateSuspendCompatibility(meta SuspendInfo, cur VMDetail, active rt.Inst 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)) { + savedID := rt.SuspendCompatibilityID(meta.RuntimeCommit, meta.SuspendCompatID) + activeID := rt.SuspendCompatibilityID(active.Commit, active.Manifest.SuspendCompatID) + switch { + case savedID != "" && activeID != "": + if savedID != activeID { + diffs = append(diffs, fmt.Sprintf("Suspend compatibility (%s -> %s)", savedID, activeID)) + } + case 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)) { + case 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 diff --git a/internal/macos/reims/suspend_test.go b/internal/macos/reims/suspend_test.go index b285d49..0549c80 100644 --- a/internal/macos/reims/suspend_test.go +++ b/internal/macos/reims/suspend_test.go @@ -105,6 +105,26 @@ func TestIncomingDeferArgsIdempotent(t *testing.T) { } } +func TestSuspendLegacyRuntimeStillRequiresExactVersion(t *testing.T) { + qemu := strings.Repeat("a", 40) + state := SuspendInfo{RuntimeCommit: "a1b2c3d", VendorQemuCommit: qemu} + active := rt.Installed{Commit: "a1b2c3d", Manifest: rt.Manifest{VendorQemuCommit: qemu}} + if diffs := ValidateSuspendCompatibility(state, VMDetail{}, active); len(diffs) != 0 { + t.Fatalf("legacy exact version rejected: %v", diffs) + } + active.Commit = "a1b2c3d-p1" + active.Manifest.SuspendCompatID = "a1b2c3d" + if diffs := ValidateSuspendCompatibility(state, VMDetail{}, active); len(diffs) != 1 || !strings.Contains(diffs[0], "Runtime") { + t.Fatalf("legacy state accepted a different revision: %v", diffs) + } + + state.SuspendCompatID = "a1b2c3d" + active.Manifest.SuspendCompatID = "d4e5f6a" + if diffs := ValidateSuspendCompatibility(state, VMDetail{}, active); len(diffs) == 0 { + t.Fatal("compatibility declaration for another family was accepted") + } +} + func TestValidateSetRejectsSuspendedVM(t *testing.T) { issues := ValidateSetLocalized( SetOpts{Name: "tahoe", CPUs: 6}, diff --git a/internal/macos/reims/suspend_transaction_test.go b/internal/macos/reims/suspend_transaction_test.go index 7c9a845..77cf76b 100644 --- a/internal/macos/reims/suspend_transaction_test.go +++ b/internal/macos/reims/suspend_transaction_test.go @@ -87,3 +87,47 @@ func TestSuspendTransactionKeepsSealedFilesWhenPublicationFails(t *testing.T) { t.Fatalf("recoverable snapshot = %q, %v, %v", state, paths, err) } } + +func TestSuspendTransactionChecksRuntimeCompatibilityFamily(t *testing.T) { + dir := t.TempDir() + media := filepath.Join(dir, "disk.qcow2") + for _, path := range []string{media, filepath.Join(dir, "vm.toml"), SuspendStatePath(dir) + ".tmp"} { + if err := os.WriteFile(path, []byte("test state"), 0o600); err != nil { + t.Fatal(err) + } + } + d := VMDetail{Name: "test", Directory: dir, CPUs: 2} + saved := rt.Installed{Commit: "a1b2c3d-p1", Manifest: rt.Manifest{ + SuspendCompatID: "a1b2c3d", VendorQemuCommit: strings.Repeat("a", 40), + }} + if _, err := SealSuspend(d, saved, []string{media}); err != nil { + t.Fatal(err) + } + info, err := ReadSuspendInfo(dir) + if err != nil || info.SuspendCompatID != "a1b2c3d" { + t.Fatalf("saved suspend compatibility = %+v, %v", info, err) + } + candidate := rt.Installed{Commit: "a1b2c3d-p2", Manifest: rt.Manifest{ + SuspendCompatID: "a1b2c3d", VendorQemuCommit: strings.Repeat("b", 40), + }} + if _, _, err := ValidateSuspendFiles(d, candidate); err != nil { + t.Fatalf("compatible revision rejected: %v", err) + } + + otherFamily := candidate + otherFamily.Commit = "d4e5f6a" + otherFamily.Manifest.SuspendCompatID = "d4e5f6a" + if _, _, err := ValidateSuspendFiles(d, otherFamily); err == nil || !strings.Contains(err.Error(), "Suspend compatibility") { + t.Fatalf("different family was not rejected: %v", err) + } + if !HasSuspendState(dir) { + t.Fatal("compatibility check removed the saved state") + } + + if err := os.WriteFile(media, []byte("changed disk content"), 0o600); err != nil { + t.Fatal(err) + } + if _, _, err := ValidateSuspendFiles(d, candidate); err == nil || !strings.Contains(err.Error(), "disk.qcow2") { + t.Fatalf("compatible revision bypassed media verification: %v", err) + } +} diff --git a/internal/runtime/remote.go b/internal/runtime/remote.go index 6452895..39c4ada 100644 --- a/internal/runtime/remote.go +++ b/internal/runtime/remote.go @@ -448,6 +448,20 @@ func splitRuntimeID(id string) (base, rev string) { return id, "" } +var suspendReleaseIDPattern = regexp.MustCompile(`^[0-9a-f]{7,40}(-p[1-9][0-9]*)?$`) + +// SuspendCompatibilityID accepts a declaration only for its own release family. +// An absent declaration keeps the legacy exact-runtime checks. +func SuspendCompatibilityID(releaseID, declared string) string { + releaseID = strings.ToLower(strings.TrimSpace(releaseID)) + declared = strings.ToLower(strings.TrimSpace(declared)) + base, _ := splitRuntimeID(releaseID) + if !suspendReleaseIDPattern.MatchString(releaseID) || declared != base { + return "" + } + return declared +} + // sameRuntimeID reports whether a and b refer to the same runtime build, // allowing short/full commit prefix matching only within the same revision. func sameRuntimeID(a, b string) bool { diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index ae9c3e2..ca75be4 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -38,6 +38,7 @@ type Manifest struct { // Schema 2 provenance fields: upstream commits, applied patches, build channel, and source archive. VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"` + SuspendCompatID string `json:"suspend_compat_id,omitempty"` UtilCommit string `json:"util_commit,omitempty"` MetalCommit string `json:"metal2vulkan_commit,omitempty"` Patches []Patch `json:"patches,omitempty"` From 584db4742d9bfde382b097fef0c528dcd8c14cfd Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Wed, 2 Dec 2026 04:07:54 +0800 Subject: [PATCH 07/47] docs(runtime): codify client compatibility and AI index [ci skip] --- AGENTS.md | 12 +------- AI-DOCS.md | 30 ++++++++++++++++++++ docs/runtime-client-compatibility.md | 42 ++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 11 deletions(-) create mode 100644 AI-DOCS.md create mode 100644 docs/runtime-client-compatibility.md diff --git a/AGENTS.md b/AGENTS.md index f117e04..69f09ac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -46,14 +46,4 @@ Reims-Go 自身代码采用 [Apache-2.0](LICENSE) 协议。便携运行时以独 ## 文档导航 -| 文档 | 说明 | -| :--- | :--- | -| [English](README.md) / [简体中文](README.zh-CN.md) | 项目总览、核心特性与快速开始,默认英文 | -| [`CHANGELOG.md`](CHANGELOG.md) | 客户端版本更新日志 | -| [`docs/architecture.md`](docs/architecture.md) | 系统边界、进程通信、安全隔离与便携运行时契约 | -| [`docs/design-guidelines.md`](docs/design-guidelines.md) | 状态模型、界面层级与文案规范 | -| [`docs/plugin-architecture.md`](docs/plugin-architecture.md) | 插件隔离模型、包清单与公开契约规则 | -| [`docs/testing.md`](docs/testing.md) | 分级测试命令与并发隔离规则 | -| [`docs/pr-review-guidelines.md`](docs/pr-review-guidelines.md) | PR 跨仓归属审查与自动审核规范 | -| [`docs/changelog.md`](docs/changelog.md) | 双语变更片段格式与版本编入流程 | -| [运行时补丁与上游跟踪](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) | 外部运行时仓库源码入口与依赖补丁 | +开始处理用户任务前,先通过 [AI 文档索引](AI-DOCS.md) 定位修改目标涉及的领域,并阅读对应的规范。跨领域任务须查阅各相关规范。 diff --git a/AI-DOCS.md b/AI-DOCS.md new file mode 100644 index 0000000..6621757 --- /dev/null +++ b/AI-DOCS.md @@ -0,0 +1,30 @@ +# AI 任务文档索引 + +开始处理用户任务前,先阅读 [AGENTS.md](AGENTS.md)。根据任务的修改目标定位可能涉及的领域,阅读下表对应的规范和相关章节,再修改文件或执行验证。跨领域任务须阅读各相关规范。任务范围变化时,先补读新领域的规范。 + +## 仓库规范 + +| 涉及领域 | 文档名称 | 位置 | +| :--- | :--- | :--- | +| 任务范围、存储、调试目录、安全和合规 | 仓库协作规则 | [AGENTS.md](AGENTS.md) | +| 核心分层、跨仓归属、运行时契约和数据迁移 | 系统架构 | [docs/architecture.md](docs/architecture.md) | +| 运行时下载、安装、版本门槛和分发 | 运行时客户端版本兼容规范 | [docs/runtime-client-compatibility.md](docs/runtime-client-compatibility.md) | +| 界面、状态模型、生产文案和操作反馈 | 产品与界面设计规范 | [docs/design-guidelines.md](docs/design-guidelines.md) | +| 插件、驱动扩展接口、权限和分发 | 插件系统架构 | [docs/plugin-architecture.md](docs/plugin-architecture.md) | +| 测试选择、构建检查、冒烟和并发隔离 | 测试 | [docs/testing.md](docs/testing.md) | +| 提交、PR 描述、跨仓审查和合并检查 | PR 变更归属审查 | [docs/pr-review-guidelines.md](docs/pr-review-guidelines.md) | +| PR 验证记录和合并前核对 | PR 模板 | [.github/PULL_REQUEST_TEMPLATE.md](.github/PULL_REQUEST_TEMPLATE.md) | +| 用户可见变更、更新日志与发布说明 | 更新日志编写与发布 | [docs/changelog.md](docs/changelog.md) | +| 开源许可、依赖声明和运行时分发合规 | Apache License 2.0、Third-Party Notices | [LICENSE](LICENSE) · [NOTICE.md](NOTICE.md) | + +## 专题与关联仓库 + +| 涉及领域 | 文档名称 | 位置 | +| :--- | :--- | :--- | +| 挂起恢复所用运行时的编号和兼容判定 | Alpha 运行时编号与挂起兼容性规范 | [reims-go/reims-vgpu 的 packaging/windows-runtime/versioning.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/versioning.md) | +| 运行时源码、依赖补丁和补丁退役 | 运行时源码与依赖补丁 | [reims-go/reims-vgpu 的 packaging/windows-runtime/patches/README.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) | +| FileVault 开机输入与启动镜像 | FileVault 开机输入镜像构建 | [scripts/filevault-input/README.md](scripts/filevault-input/README.md) | +| 虚拟机系统盘性能测量 | 系统盘小文件 I/O 基准与采样工具 | [scripts/io-bench/README.md](scripts/io-bench/README.md) | +| 跨会话工单与 Agent 交接 | 调试工单模板 | [scripts/debug/work-template.md](scripts/debug/work-template.md) | + +项目总览见 [English](README.md) 和 [简体中文](README.zh-CN.md)。已发布的客户端变更见 [CHANGELOG.md](CHANGELOG.md)。新增、移动或废止规范时同步更新本索引。 diff --git a/docs/runtime-client-compatibility.md b/docs/runtime-client-compatibility.md new file mode 100644 index 0000000..9174b2d --- /dev/null +++ b/docs/runtime-client-compatibility.md @@ -0,0 +1,42 @@ +# 运行时客户端版本兼容规范 + +本规范适用于带客户端版本门槛的便携运行时。新分发源在客户端和构建流程通过本文验收后启用。 + +## 最低支持版本 + +最低客户端版本取分发协议下限与运行契约下限中的较高者。分发协议下限是能够识别新分发源并执行下载、安装校验的首个正式客户端版本。初始目标为 `v0.2.12`。该正式版实际提供上述能力并通过验收后,才能作为发布下限。 + +运行契约下限取该运行时必需能力各自首次进入正式客户端的版本中的最高值。审查以客户端和运行时的源码、对应正式发布标签,以及实际操作结果为依据。 + +| 运行时变更 | 版本判定 | +| :--- | :--- | +| QEMU 内部修复、磁盘性能优化或打包整理 | 用原最低版本验证相关操作。通过后沿用下限。 | +| 启动或运行依赖新的参数、配置、CLI 或 QMP 行为 | 找到客户端首次正确处理该契约的正式版,提高下限。 | +| 新增可选功能且原有路径可安全使用 | 验证旧客户端的降级行为后沿用下限。 | +| 旧客户端误判运行时、生成错误启动参数或跳过必要校验 | 找到具备正确处理能力的正式版,并验证修复后再发布。 | + +宿主机或驱动差异随验收环境记录。客户端版本下限以客户端缺失的必需能力为依据。运行时发版记录写明最低版本、需要的能力和验证结果。 + +## 分发和安装校验 + +- 旧客户端继续访问现有运行时分发源,获取已验证兼容的基线。带门槛的新运行时发布到独立的 GitHub Release 分发仓库。首个新源运行时使用新的发布编号。 +- 新客户端的 GUI 和 CLI 使用同一条运行时校验路径。客户端在下载运行时压缩包前读取并校验 Release 的小型兼容清单。新源缺少清单、校验失败或客户端低于门槛时,禁止拉取该包并提示所需版本。 +- 安装前再次检查包内 `manifest.json`,覆盖缓存和离线导入。新格式要求声明最低客户端版本。在线安装还要比对包内外的运行时编号和版本约束。校验通过后才替换当前运行时。 +- 最低版本包含该版本本身,按 SemVer 比较。若门槛为 `v0.2.12`,则同编号的 Dev 预发布低于该正式版。 [SemVer 版本优先级](https://semver.org/spec/v2.0.0.html#spec-item-11) + +Release 兼容清单使用 `runtime-compat.json`,至少记录 `runtime_id` 和 `min_client_version`。`runtime_id` 与包内 `manifest.json` 的 `commit` 一致,最低版本在两份清单中使用同一个值。 + +客户端版本通过后,挂起恢复仍执行运行时挂起兼容、虚拟硬件和介质完整性校验。 [挂起兼容规范](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/versioning.md) + +## 构建与发布 + +运行时源码中的 `reims-go-runtime.json` 声明 `min_client_version`。流水线从这一处生成包内最低版本字段和 Release 兼容清单,并将兼容清单纳入 `SHA256SUMS.txt`。CI 在发布前核对归档名称、包内外版本、校验和与源码来源。运行时编号和去重使用实际运行时与打包提交。 + +先发布具备全部校验能力的正式客户端,再向新分发源发布 Alpha。自动发布凭据只授予分发仓库所需的发布权限。Alpha 由流水线发布,Stable 经真机验证后人工晋升。 [构建入口](https://github.com/reims-go/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) + +## 验收 + +1. 用同一运行时包在隔离环境里验证拟定的最低客户端和上一正式版。最低客户端应完成下载、安装、启动、关机,以及此次改动涉及的操作。 +2. 声明上一正式版存在运行兼容问题时,记录同包对照中的失败步骤和源码依据。 +3. 验证旧客户端从旧源取得兼容基线。新版客户端的版本不足、清单异常、清单与包不一致时,分别确认在下载、安装阶段拦截。 +4. 验证缓存和离线安装在校验失败后保留原运行时。涉及虚拟机运行和恢复的兼容结论以真机结果为准,未完成时标记待验证。 [测试](testing.md) From e7087c7bd87b4a01b592060b44cc540e2ac6d4af Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Wed, 2 Dec 2026 04:11:02 +0800 Subject: [PATCH 08/47] docs: clarify independently maintained runtime sources [ci skip] --- AGENTS.md | 4 +++- docs/architecture.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 69f09ac..8986b6a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,9 @@ Reims-Go 是面向 Windows x86-64 的免编译 macOS 虚拟机桌面启动器与工作台,桌面窗口与命令行共用同一份 Go 核心。 -上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 提供虚拟显卡引擎、Metal 转 Vulkan 运行库与底层命令行工具。本仓库负责客户端界面、命令行外壳、硬件体检、宿客协作、恢复点与插件托管。便携运行时的编译、依赖补丁、打包与预览发布由 [Reims vGPU fork 的构建流水线](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 独立负责。 +`steelbrain/reims-vgpu` 是虚拟显卡引擎、Metal 转 Vulkan 运行库与底层命令行工具的技术上游。本仓库负责客户端界面、命令行外壳、硬件体检、宿客协作、恢复点与插件托管。 [技术上游](https://github.com/steelbrain/reims-vgpu) + +Reims-Go 发布的便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时维护仓库通过 `vendor/qemu` 固定团队 QEMU 仓库的提交,并负责编译、依赖补丁、打包和预览发布。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu) · [运行时构建流程](https://github.com/reims-go/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) ## 存储与调试目录纪律 diff --git a/docs/architecture.md b/docs/architecture.md index fdfda94..5cdebef 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -83,7 +83,7 @@ macOS 专属逻辑集中在 `internal/macos/` 与 `frontend/src/macos/`,宿主 ## 便携运行时与跨仓边界 -便携运行时由独立的 [Reims vGPU fork 流水线](https://github.com/yxc0915/reims-vgpu) 每日自动构建并发布,压缩包内包含同一上游提交产出的 `reims-ctl.exe`、`reims-util.exe`、QEMU 可执行文件、自包含运行库、`manifest.json` 溯源清单、应用的全部补丁原文及许可证全文,调试符号单独打包分发。 +便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时仓库固定 QEMU 子模块的提交,负责构建、依赖补丁、打包与 Alpha 发布。压缩包包含 `reims-ctl.exe`、`reims-util.exe`、QEMU、自包含运行库、实际应用的补丁和许可证全文。`manifest.json` 记录各组件的实际源码提交及补丁,调试符号单独打包分发。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu) 客户端下载运行时经 `SHA256SUMS.txt` 强校验后原子解压到数据目录的 `runtimes/` 下,并在调用子进程时统一将 `XDG_CONFIG_HOME`、`XDG_DATA_HOME`、`XDG_CACHE_HOME` 与 `REIMS_CTL_QEMU` 重定向到数据目录内,不污染用户主目录或系统盘。自动构建产物先作为 GitHub 预发布进入 `alpha` 通道;只有在真实 Windows 宿主机跑通环境检查、启动进入桌面、截屏与正常关机冒烟并经人工确认后,才晋升为默认提供的 `stable` 正式版。 From fe838368d76af0c9f4b79dabeca6612d3a978a63 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Wed, 2 Dec 2026 04:21:27 +0800 Subject: [PATCH 09/47] fix(guesttools): protect timezone helper and simplify status --- NOTICE.md | 47 +++++++++++++++++++++++ changes/guest-tools-timezone.json | 7 ++++ frontend/src/components/SettingsModal.tsx | 27 ++++--------- internal/guesttools/image.go | 4 -- internal/guesttools/server.go | 5 ++- internal/guesttools/timezone.go | 37 ++++++++++++------ internal/guesttools/timezone_test.go | 15 ++++---- internal/host/timezone.go | 2 +- internal/host/timezone_windows.go | 26 +------------ 9 files changed, 101 insertions(+), 69 deletions(-) create mode 100644 changes/guest-tools-timezone.json diff --git a/NOTICE.md b/NOTICE.md index ff828e8..eabcaa8 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -37,6 +37,53 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +### Unicode CLDR Windows timezone data + +The Windows timezone fallback table uses the +[CLDR 48 Windows zone mappings](https://github.com/unicode-org/cldr/blob/release-48/common/supplemental/windowsZones.xml). + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2004-2025 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +SPDX-License-Identifier: Unicode-3.0 + ## Portable runtime The portable runtime bundle (`reims-runtime-win-x64-.tar.zst`) contains diff --git a/changes/guest-tools-timezone.json b/changes/guest-tools-timezone.json new file mode 100644 index 0000000..29d9ddd --- /dev/null +++ b/changes/guest-tools-timezone.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 35, + "authors": ["reiasu2", "yxc0915"], + "zh": "在 macOS 虚拟机设置中选择跟随宿主机或固定时区。同步需要更新并授权 Guest Tools。 [#66](https://github.com/Nwflower/Reims-Go/pull/66)", + "en": "Set a fixed timezone or follow the host in macOS VM settings. Sync requires updated and authorized Guest Tools. [#66](https://github.com/Nwflower/Reims-Go/pull/66)" +} diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index ec88986..105d2ac 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -698,13 +698,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats // ── Pages ──────────────────────────────────────────────── const detectedHostTZ = tzStatus?.host_timezone || host.timezone || '' - const tzSelectedValue = tzStatus - ? tzStatus.mode === 'off' - ? 'off' - : tzStatus.mode === 'custom' && tzStatus.timezone - ? tzStatus.timezone - : 'host' - : undefined + const tzSelectedValue = tzStatus?.mode === 'custom' ? tzStatus.timezone : tzStatus?.mode const tzOptions = [ { value: 'host', label: tr('guestTimezoneHost'), detail: detectedHostTZ || undefined }, ...GUEST_TIMEZONE_PRESETS.map((p) => ({ @@ -717,37 +711,30 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats : []), { value: 'off', label: tr('guestTimezoneOff') }, ] - const tzRequiredVer = tzStatus?.required_agent_version || 11 - const tzAgentVer = tzStatus?.guest_agent_version ?? 0 - const tzRunning = tzStatus?.running ?? running - const tzConnected = tzStatus?.guest_connected ?? false - const tzHelperReady = tzStatus?.helper_ready ?? false - const tzEffective = tzStatus?.effective_timezone || '' - const tzApplied = tzStatus?.guest_applied || '' - let tzDesc: React.ReactNode = tr('guestTimezoneDesc') let tzCommand = '' if (tzStatus) { + const tzEffective = tzStatus.effective_timezone if (tzStatus.mode === 'off') { tzDesc = tr('guestTimezoneOffDesc') } else if (detail.guest_tools_disabled) { tzDesc = {tr('gtStatusOffTip')} } else if (!tzEffective) { tzDesc = {tr('guestTimezoneHostUnknown')} - } else if (tzRunning && tzConnected) { + } else if (tzStatus.running && tzStatus.guest_connected) { const tzFailure = tzStatus.timezone_error ? {tr('guestTimezoneApplyFailed', { tz: tzEffective })} : null - if (tzAgentVer < tzRequiredVer) { - tzDesc = {tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzRequiredVer })} + if (tzStatus.guest_agent_version < tzStatus.required_agent_version) { + tzDesc = {tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzStatus.required_agent_version })} if (detail.guest_tools_attached) tzCommand = GUEST_TOOLS_INSTALL_CMD - } else if (!tzHelperReady) { + } else if (!tzStatus.helper_ready) { const hint = tr(detail.guest_tools_attached ? 'guestTimezoneApplyHint' : 'guestTimezoneApplyAttachHint') tzDesc = tzFailure ?
{tzFailure}{hint}
: hint if (detail.guest_tools_attached) tzCommand = GUEST_TIMEZONE_APPLY_CMD } else if (tzFailure) { tzDesc = tzFailure - } else if (tzApplied === tzEffective) { + } else if (tzStatus.guest_applied === tzEffective) { tzDesc = } else { tzDesc = tr('guestTimezoneSyncing', { tz: tzEffective }) diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 126daba..ce3f380 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -450,10 +450,6 @@ apply_host_config() { report_status() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 timezone_applied=$(current_timezone) - timezone_helper_ready=false - if [ -x "$TIMEZONE_HELPER" ] && /usr/bin/sudo -n -l -- "$TIMEZONE_HELPER" >/dev/null 2>&1; then - timezone_helper_ready=true - fi curl -fsS -m "${1:-3}" -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index fb80b17..d1fda43 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -715,8 +715,9 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { } connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= maxAge freshStatus := connected && time.Since(vm.lastStatus) <= maxAge - timezoneError := "" + var timezone, timezoneError string if freshStatus { + timezone = vm.timezoneApplied timezoneError = vm.timezoneError } return GuestStatus{ @@ -727,7 +728,7 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { SleepActive: connected && vm.sleepActive, AgentVersion: vm.agentVersion, LastSeen: vm.lastSeen, - TimezoneApplied: vm.timezoneApplied, + TimezoneApplied: timezone, TimezoneHelperReady: freshStatus && vm.timezoneHelperReady, TimezoneError: timezoneError, } diff --git a/internal/guesttools/timezone.go b/internal/guesttools/timezone.go index a7d8529..69ae96f 100644 --- a/internal/guesttools/timezone.go +++ b/internal/guesttools/timezone.go @@ -32,8 +32,8 @@ func (s *Server) SetTimezone(vmKey, token, setting string) { } } -const guestTimezonePath = "/Library/Application Support/ReimsGuestTools/set-timezone.sh" -const guestTimezoneSudoers = "/etc/sudoers.d/reims-timezone-" +const guestTimezonePath = "/private/etc/reims-timezone/set-timezone.sh" +const guestTimezoneSudoers = "/private/etc/sudoers.d/reims-timezone-" const guestTimezoneValidation = ` valid_timezone() { @@ -47,6 +47,8 @@ valid_timezone() { const guestTimezoneAgent = ` TIMEZONE_HELPER="` + guestTimezonePath + `" timezone_error="" +timezone_helper_ready=false +timezone_check_at=0 ` + guestTimezoneValidation + ` current_timezone() ( link=$(/usr/bin/readlink /etc/localtime) || return 0 @@ -62,10 +64,23 @@ current_timezone() ( sync_timezone() { desired_timezone=$(config_timezone "$1") || desired_timezone="" timezone_error="" - if [ -n "$desired_timezone" ] && [ -x "$TIMEZONE_HELPER" ] && - [ "$desired_timezone" != "$(current_timezone)" ] && - ! /usr/bin/sudo -n -- "$TIMEZONE_HELPER" "$desired_timezone" >/dev/null 2>&1; then - timezone_error=apply_failed + if [ -z "$desired_timezone" ] || [ ! -x "$TIMEZONE_HELPER" ]; then + timezone_helper_ready=false + timezone_check_at=0 + return 0 + fi + timezone_now=$(/bin/date +%s) + if [ "$timezone_now" -ge "$timezone_check_at" ]; then + timezone_helper_ready=false + if /usr/bin/sudo -n -l -- "$TIMEZONE_HELPER" >/dev/null 2>&1; then + timezone_helper_ready=true + fi + timezone_check_at=$((timezone_now + 30)) + fi + if [ "$timezone_helper_ready" = true ] && [ "$desired_timezone" != "$(current_timezone)" ]; then + if ! /usr/bin/sudo -n -- "$TIMEZONE_HELPER" "$desired_timezone" >/dev/null 2>&1; then + timezone_error=apply_failed + fi fi } ` @@ -216,8 +231,8 @@ fi set -eu export LC_ALL=C ` + guestTimezoneSystemPaths + ` -secure_path /Library -d 002 -secure_path "${helper_dir%/*}" -d 002 +secure_path /private -d 022 +secure_path /private/etc -d 022 if [ ! -e "$sudoers_dir" ] && [ ! -L "$sudoers_dir" ]; then /usr/bin/install -d -o root -g wheel -m 0755 "$sudoers_dir" fi @@ -283,7 +298,7 @@ trap cleanup_timezone_install EXIT rule_tmp=$(/usr/bin/mktemp "$sudoers_dir/.reims-timezone.XXXXXX") # A numeric sudoers user ID avoids interpreting special characters in a username. -printf '#%s ALL=(root) NOPASSWD: /Library/Application\\ Support/ReimsGuestTools/set-timezone.sh\n' "$1" >"$rule_tmp" +printf '#%s ALL=(root) NOPASSWD: %s\n' "$1" "$helper" >"$rule_tmp" /usr/sbin/chown root:wheel "$rule_tmp" /bin/chmod 0440 "$rule_tmp" /usr/sbin/visudo -cf "$rule_tmp" @@ -314,6 +329,8 @@ if [ "$#" -eq 0 ]; then set -eu export LC_ALL=C ` + guestTimezoneSystemPaths + ` +secure_path /private -d 022 +secure_path /private/etc -d 022 if [ -e "$sudoers_dir" ] || [ -L "$sudoers_dir" ]; then secure_path "$sudoers_dir" -d 022 else @@ -328,8 +345,6 @@ for rule in "$rule_prefix"*; do fi done if [ -e "$helper" ] || [ -L "$helper" ]; then - secure_path /Library -d 002 - secure_path "${helper_dir%/*}" -d 002 secure_path "$helper_dir" -d 022 /bin/rm -f "$helper" fi diff --git a/internal/guesttools/timezone_test.go b/internal/guesttools/timezone_test.go index b35fef6..41b34db 100644 --- a/internal/guesttools/timezone_test.go +++ b/internal/guesttools/timezone_test.go @@ -15,8 +15,9 @@ import ( func testTimezoneScripts(t *testing.T, sh, rootInstall string) { t.Helper() rewrite := strings.NewReplacer( - "/Library", "system/Library", - "/etc/sudoers.d", "system/sudoers.d", + "/private/etc/sudoers.d", "system/sudoers.d", + "/private/etc", "system/etc", + "/private", "system", "/Volumes/REIMSTOOLS", "tools", "/var/db/timezone/zoneinfo", "zones", "/usr/share/zoneinfo", "missing-zones", @@ -109,7 +110,7 @@ expect_timezone_error "" {"rollback_reinstall", "seed_old; fail_visudo=1", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"}, {"rollback_failed_rule_replace", "seed_old; fail_rule_replace=1", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"}, {"rollback_first_install", "fail_visudo=1", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"}, - {"reject_world_writable_parent", "parent_mode=0777", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"}, + {"reject_group_writable_parent", "parent_mode=0775", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"}, {"reject_group_writable_helper", "seed_old; helper_mode=0775", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"}, } { t.Run(tc.name, func(t *testing.T) { @@ -166,7 +167,7 @@ expect_timezone_error "" t.Run("uninstall_failure", func(t *testing.T) { script := "seed_old\nuid=501\nfail_rm=$helper\n" + guestTimezoneUninstall + "\necho 'Uninstalled'\n" out, err := run(t, script) - if err == nil || !strings.Contains(out, "Remaining Reims timezone file: system/Library/Application Support/ReimsGuestTools/set-timezone.sh") || + if err == nil || !strings.Contains(out, "Remaining Reims timezone file: system/etc/reims-timezone/set-timezone.sh") || !strings.Contains(out, "retry") || strings.Contains(out, "Uninstalled") { t.Fatalf("timezone uninstall failure: %v\n%s", err, out) } @@ -175,9 +176,9 @@ expect_timezone_error "" const timezoneShellFixture = ` set -eu -parent_mode=0775 +parent_mode=0755 helper_mode=0755 -helper='system/Library/Application Support/ReimsGuestTools/set-timezone.sh' +helper=system/etc/reims-timezone/set-timezone.sh rule=system/sudoers.d/reims-timezone-501 mkdir -p "${helper%/*}" system/sudoers.d tools zones/Asia printf new-helper > tools/set-timezone.sh @@ -192,7 +193,7 @@ mock_stat() { echo 0 else case "$3" in - system/Library|'system/Library/Application Support') echo "$parent_mode" ;; + system|system/etc) echo "$parent_mode" ;; "$helper") echo "$helper_mode" ;; *) echo 0755 ;; esac diff --git a/internal/host/timezone.go b/internal/host/timezone.go index 388ff09..4084573 100644 --- a/internal/host/timezone.go +++ b/internal/host/timezone.go @@ -19,7 +19,7 @@ func ValidateIANATimezone(tz string) bool { } // CLDR 48 windowsZones.xml, territory 001 (global defaults). -// Copyright © 1991-2013 Unicode, Inc. https://www.unicode.org/copyright.html +// Copyright © 2004-2025 Unicode, Inc. See NOTICE.md for the Unicode license. // https://github.com/unicode-org/cldr/blob/release-48/common/supplemental/windowsZones.xml var windowsIANATimezones = map[string]string{ "Dateline Standard Time": "Etc/GMT+12", diff --git a/internal/host/timezone_windows.go b/internal/host/timezone_windows.go index 931607e..fac232b 100644 --- a/internal/host/timezone_windows.go +++ b/internal/host/timezone_windows.go @@ -1,7 +1,6 @@ package host import ( - "sync" "unsafe" "golang.org/x/sys/windows" @@ -9,17 +8,10 @@ import ( var ( icu = windows.NewLazySystemDLL("icu.dll") - icuDefaultTimezone = icu.NewProc("ucal_getDefaultTimeZone") icuTimezoneForWindowsID = icu.NewProc("ucal_getTimeZoneIDForWindowsID") getDynamicTimezone = windows.NewLazySystemDLL("kernel32.dll").NewProc("GetDynamicTimeZoneInformation") ) -var initialWindowsTimezone struct { - sync.Once - key [128]uint16 - iana string -} - type dynamicTimezoneInformation struct { Bias int32 StandardName [32]uint16 @@ -33,28 +25,14 @@ type dynamicTimezoneInformation struct { } func DetectHostTimezone() string { - var buf [65]uint16 - var status int32 - var info dynamicTimezoneInformation result, _, _ := getDynamicTimezone.Call(uintptr(unsafe.Pointer(&info))) - // ICU caches the default zone for the process. Use the live Windows key - // for lookups if the system setting has changed since the first probe. - initialWindowsTimezone.Do(func() { - initialWindowsTimezone.key = info.TimeZoneKeyName - if icuDefaultTimezone.Find() == nil { - n, _, _ := icuDefaultTimezone.Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&status))) - initialWindowsTimezone.iana = readICUTimezone(buf[:], int32(n), status) - } - }) - if initialWindowsTimezone.key == info.TimeZoneKeyName && initialWindowsTimezone.iana != "" { - return initialWindowsTimezone.iana - } if uint32(result) == 0xffffffff { return "" } if icuTimezoneForWindowsID.Find() == nil { - status = 0 + var buf [65]uint16 + var status int32 n, _, _ := icuTimezoneForWindowsID.Call(uintptr(unsafe.Pointer(&info.TimeZoneKeyName[0])), uintptr(^uint32(0)), 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&status))) if tz := readICUTimezone(buf[:], int32(n), status); tz != "" { From 0fb9a4606eb124dfff7bb821dbdb23077a8cb1f8 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Wed, 2 Dec 2026 04:31:02 +0800 Subject: [PATCH 10/47] fix(vm): gate nested virtualization on WHPX VMX support --- changes/vm-nested-virtualization.json | 7 +++ docs/design-guidelines.md | 2 + frontend/src/components/SettingsModal.tsx | 6 ++- frontend/src/i18n/domains/settings.gen.ts | 8 ++- frontend/src/i18n/keys.gen.ts | 2 + frontend/wailsjs/go/models.ts | 4 ++ internal/app/macos_detail.go | 16 ++---- internal/app/macos_lifecycle_native.go | 28 +++++++++-- internal/app/macos_settings.go | 7 ++- internal/host/host.go | 1 + internal/host/whpx_probe_windows.go | 4 ++ internal/i18n/catalog_gen.go | 4 ++ internal/macos/macosdriver/prepare.go | 34 ++++++------- internal/macos/macosdriver/prepare_test.go | 42 ++++++++-------- internal/macos/reims/nested_virt_args.go | 40 --------------- internal/macos/reims/nested_virt_args_test.go | 49 ------------------- internal/macos/reims/reims.go | 9 ++-- internal/macos/startprep/startprep.go | 28 +---------- locales/en-US/native.json | 2 + locales/en-US/settings.json | 4 +- locales/zh-CN/native.json | 2 + locales/zh-CN/settings.json | 4 +- 22 files changed, 121 insertions(+), 182 deletions(-) create mode 100644 changes/vm-nested-virtualization.json delete mode 100644 internal/macos/reims/nested_virt_args.go delete mode 100644 internal/macos/reims/nested_virt_args_test.go diff --git a/changes/vm-nested-virtualization.json b/changes/vm-nested-virtualization.json new file mode 100644 index 0000000..22e8707 --- /dev/null +++ b/changes/vm-nested-virtualization.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 68, + "authors": ["zhongruan0522", "yxc0915"], + "zh": "支持 VMX 的 Windows 宿主机可为单台 macOS 虚拟机启用嵌套虚拟化。默认关闭,冷启动后生效。 [#72](https://github.com/Nwflower/Reims-Go/pull/72)", + "en": "Enable nested virtualization per macOS VM on Windows hosts with WHPX VMX support. Off by default, applied on cold start. [#72](https://github.com/Nwflower/Reims-Go/pull/72)" +} diff --git a/docs/design-guidelines.md b/docs/design-guidelines.md index ed4b134..cc423ba 100644 --- a/docs/design-guidelines.md +++ b/docs/design-guidelines.md @@ -4,6 +4,8 @@ ## 设计定位与配置原语 +嵌套虚拟化由客户端按虚拟机保存,默认关闭,冷启动时按宿主机的 WHPX 能力生成驱动参数。界面只显示用户手动添加的额外参数。 + 桌面界面采用贴近 macOS 系统设置的侧栏加详情结构和硬件分类词表,同时遵循 Windows 窗口控制、字体渲染与多档缩放习惯。宿主机全局能力(虚拟化平台、处理器调度、显卡驱动、运行时版本与数据目录)集中在「内核」与「设置」页,不混入单台虚拟机的设置表单。 1. 每台虚拟机对应一份声明式配置,界面只编辑结构化选项,不要求用户手工拼接底层启动命令行。 diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 58553cd..5cfd705 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -309,6 +309,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats const resBad = customRes && !RES_RE.test(form.resolution ?? '') const sshOn = (form.ssh_port ?? 0) > 0 const localBlock = resBad + const nestedVirtAvailable = host.whpx === 'ready' && host.whpx_caps?.nested_vmx && !host.needs_cold_reboot_workaround const rowProps = (f: Field) => ({ field: f, @@ -823,8 +824,9 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats set({ nested_virt })} />} + desc={tr(nestedVirtAvailable ? 'nestedVirtDesc' : 'nestedVirtUnavailable')} + error={detail.nested_virt_invalid && !dirty('nested_virt') ? tr('nestedVirtInvalid') : issueOf('nested_virt')} + control={ set({ nested_virt })} />} /> = { "minimizeToTraySub": "关闭窗口后剪贴板和共享文件夹继续工作,可从托盘启停虚拟机", "multiDisplayHint": "{n, plural, other {检测到 # 块显示器,排列方式在 macOS「系统设置 › 显示器」里调整}}", "navHasIssue": "这一页有需要修改的项", - "nestedVirtDesc": "在 macOS 里再运行虚拟机(如 Docker Desktop),部分电脑不支持,可能无法启用", + "nestedVirtDesc": "允许 macOS 运行自己的虚拟机,完全关机后再次启动时生效。", + "nestedVirtInvalid": "保存的设置无法读取,虚拟机将按默认 CPU 设置启动。", "nestedVirtLabel": "嵌套虚拟化", + "nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。", "networkDesc": "通过 Windows 的网络连接上网", "networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网", "networkTitle": "网络", @@ -750,8 +752,10 @@ export const settingsEn: Record = { "minimizeToTraySub": "Clipboard and shared folders keep working; start and stop VMs from the tray", "multiDisplayHint": "{n, plural, one {# display detected; arrange displays inside macOS System Settings › Displays} other {# displays detected; arrange them inside macOS System Settings › Displays}}", "navHasIssue": "This page has settings to fix", - "nestedVirtDesc": "Lets macOS run VMs of its own, such as Docker Desktop; some PCs cannot enable it", + "nestedVirtDesc": "Lets macOS run its own virtual machines. Applies on a full restart.", + "nestedVirtInvalid": "The saved setting could not be read. The VM starts with the default CPU settings.", "nestedVirtLabel": "Nested virtualization", + "nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.", "networkDesc": "Uses the Windows network connection", "networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking", "networkTitle": "Network", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index afda943..51792de 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -529,7 +529,9 @@ export type I18nKey = | "multiDisplayHint" | "navHasIssue" | "nestedVirtDesc" + | "nestedVirtInvalid" | "nestedVirtLabel" + | "nestedVirtUnavailable" | "netOff" | "netShared" | "networkDesc" diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 53ffdf5..48c6d5c 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -1029,6 +1029,7 @@ export namespace host { apic_emulation: boolean; kernel_irqchip_available: boolean; nested_virt_property: boolean; + nested_vmx: boolean; nested_virt_probe_error?: string; static createFrom(source: any = {}) { @@ -1041,6 +1042,7 @@ export namespace host { this.apic_emulation = source["apic_emulation"]; this.kernel_irqchip_available = source["kernel_irqchip_available"]; this.nested_virt_property = source["nested_virt_property"]; + this.nested_vmx = source["nested_vmx"]; this.nested_virt_probe_error = source["nested_virt_probe_error"]; } } @@ -2755,6 +2757,7 @@ export namespace reims { shared_dir?: string; guest_lang?: string; nested_virt: boolean; + nested_virt_invalid?: boolean; suspend_info?: SuspendInfo; static createFrom(source: any = {}) { @@ -2804,6 +2807,7 @@ export namespace reims { this.shared_dir = source["shared_dir"]; this.guest_lang = source["guest_lang"]; this.nested_virt = source["nested_virt"]; + this.nested_virt_invalid = source["nested_virt_invalid"]; this.suspend_info = this.convertValues(source["suspend_info"], SuspendInfo); } diff --git a/internal/app/macos_detail.go b/internal/app/macos_detail.go index 28d87e2..12034e0 100644 --- a/internal/app/macos_detail.go +++ b/internal/app/macos_detail.go @@ -3,7 +3,6 @@ package app import ( "context" "encoding/json" - "fmt" "path/filepath" "strings" @@ -65,9 +64,7 @@ func (a *App) getVMDetailLegacy(name string, epoch uint64) (reims.VMDetail, erro a.populateGuestToolsDetail(&d, epoch) a.populateGuestLangDetail(&d) populateSuspendDetail(&d) - if err := populateNestedVirtDetail(&d); err != nil { - return reims.VMDetail{}, err - } + populateNestedVirtDetail(&d) return d, nil } @@ -101,21 +98,16 @@ func (a *App) getVMDetail(name string, epoch uint64) (reims.VMDetail, error) { a.populateGuestToolsDetail(&d, epoch) a.populateGuestLangDetail(&d) populateSuspendDetail(&d) - if err := populateNestedVirtDetail(&d); err != nil { - return reims.VMDetail{}, err - } + populateNestedVirtDetail(&d) return d, nil } // populateNestedVirtDetail reads the VM's nested-virtualization switch, which Reims-Go keeps // in the VM directory rather than in the configuration reims-ctl manages. -func populateNestedVirtDetail(d *reims.VMDetail) error { +func populateNestedVirtDetail(d *reims.VMDetail) { cfg, err := vmstart.ReadVMNestedVirt(d.Directory) - if err != nil { - return fmt.Errorf("read nested virtualization switch: %w", err) - } + d.NestedVirtInvalid = err != nil d.NestedVirt = cfg.Enabled - return nil } func populateSuspendDetail(d *reims.VMDetail) { diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index 4c2d923..15f81fd 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -203,6 +203,7 @@ func (a *App) startVMLegacy(name string) error { a.mu.Lock() root := a.cfg.DataRoot tmpDir := a.cfg.TempDir() + locale := a.cfg.Locale a.mu.Unlock() rep := host.Inspect(root) if err := prep.CheckWHPX(rep); err != nil { @@ -253,7 +254,9 @@ func (a *App) startVMLegacy(name string) error { // Strip pre-ledger or out-of-band managed fragments so upgrading existing // VMs never duplicates QEMU device IDs. baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs) - reconciled := plugin.ReconcileStartIntents(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), intents) + nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS} + macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(baseExtraArgs, ledger), rep) + reconciled := plugin.ReconcileStartIntentsForDriver(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), nested.PluginID, append(intents, nested)) reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs for _, warn := range reconciled.Warnings { a.emitVMLog(name, "[plugin] "+warn) @@ -285,9 +288,7 @@ func (a *App) startVMLegacy(name string) error { c.Env = append(c.Env, env...) } } - if err := prep.Prepare(context.Background(), name, rep, &curDetail); err != nil { - return err - } + prep.Prepare(context.Background(), name, rep, &curDetail) if rep.NeedsColdRebootWorkaround { sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name) _ = os.MkdirAll(filepath.Dir(sockPath), 0o755) @@ -300,6 +301,25 @@ func (a *App) startVMLegacy(name string) error { curDetail.ExtraArgs = merged } } + ledger, err := plugin.LoadArgLedger(curDetail.Directory) + if err != nil { + return err + } + nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS} + macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(curDetail.ExtraArgs, ledger), rep) + reconciled := plugin.ReconcileStartIntentsForDriver(curDetail.ExtraArgs, ledger, nil, nested.PluginID, []plugin.StartIntent{nested}) + for _, warning := range reconciled.Warnings { + a.emitVMLog(name, warning) + } + if reconciled.Changed { + if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil { + return err + } + if err := plugin.SaveArgLedger(curDetail.Directory, ledger); err != nil { + return err + } + curDetail.ExtraArgs = reconciled.ExtraArgs + } } if prep.Runtime.Manifest.HasCapability("display-fixed-mode") && diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index ba2eba3..3e6d710 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -63,6 +63,9 @@ func (a *App) ValidateSet(opts reims.SetOpts) ([]reims.ValidationIssue, error) { } func (a *App) ApplyVMSettings(opts reims.SetOpts) error { + if err := a.requireWritableDataRoot(); err != nil { + return err + } cur, err := a.GetVMDetail(opts.Name) if err != nil { return err @@ -92,7 +95,7 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error { if err != nil { return err } - _, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name) + locked, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name) if err != nil { return err } @@ -104,7 +107,7 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) error { } } if opts.NestedVirt != nil { - if err := vmstart.SaveVMNestedVirt(cur.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil { + if err := vmstart.SaveVMNestedVirt(locked.Directory, vmstart.VMNestedVirtConfig{Enabled: *opts.NestedVirt}); err != nil { return err } } diff --git a/internal/host/host.go b/internal/host/host.go index 9605b4e..83a2df2 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -47,6 +47,7 @@ type WHPXCapabilities struct { APICEmulation bool `json:"apic_emulation"` KernelIrqchipAvailable bool `json:"kernel_irqchip_available"` NestedVirtProperty bool `json:"nested_virt_property"` + NestedVMX bool `json:"nested_vmx"` NestedVirtProbeError string `json:"nested_virt_probe_error,omitempty"` } diff --git a/internal/host/whpx_probe_windows.go b/internal/host/whpx_probe_windows.go index 3528e00..dc19f38 100644 --- a/internal/host/whpx_probe_windows.go +++ b/internal/host/whpx_probe_windows.go @@ -13,6 +13,7 @@ const ( // WinHvPlatformDefs.h capability & partition property codes. whvCapFeatures = 0x00000001 whvCapProcessorPerfmon = 0x00001009 + whvCapVmxBasic = 0x00002000 whvPropNestedVirtualization = 0x00000004 whvPropLocalApicEmulationMode = 0x00001005 whvPropProcessorCount = 0x00001fff @@ -90,6 +91,9 @@ func probeWHPXCapabilities() WHPXCapabilities { hr, _, _ = setProp.Call(part, uintptr(whvPropNestedVirtualization), uintptr(unsafe.Pointer(&nestedBuf[0])), uintptr(len(nestedBuf))) if int32(hr) >= 0 { caps.NestedVirtProperty = true + var vmxBasic uint64 + hr, _, _ = getCap.Call(whvCapVmxBasic, uintptr(unsafe.Pointer(&vmxBasic)), unsafe.Sizeof(vmxBasic), uintptr(unsafe.Pointer(&written))) + caps.NestedVMX = caps.KernelIrqchipAvailable && int32(hr) >= 0 && vmxBasic != 0 } else { caps.NestedVirtProbeError = fmt.Sprintf("0x%08x", uint32(hr)) } diff --git a/internal/i18n/catalog_gen.go b/internal/i18n/catalog_gen.go index 0b2e1b0..717aa3b 100644 --- a/internal/i18n/catalog_gen.go +++ b/internal/i18n/catalog_gen.go @@ -552,6 +552,8 @@ var catalog = map[Locale]map[string]string{ "vm.resize.stop_first": "请先停止 {name} 再扩容虚拟磁盘", "vm.typed": "{count, plural, other {已敲入 # 个键。}}", "vmstart.compat.nested_virt": "[兼容] 当前 Windows 不支持嵌套虚拟化属性({code}),已自动启用 kernel-irqchip=off", + "vmstart.nested_vmx.invalid": "无法读取嵌套虚拟化设置。虚拟机将按默认 CPU 设置启动。", + "vmstart.nested_vmx.unavailable": "当前 Windows 宿主机和中断控制器设置无法启用嵌套虚拟化。", "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} 线程),已使用全部核心避免超售卡顿", @@ -1109,6 +1111,8 @@ var catalog = map[Locale]map[string]string{ "vm.resize.stop_first": "stop {name} before resizing its disk", "vm.typed": "{count, plural, one {Typed # key.} other {Typed # keys.}}", "vmstart.compat.nested_virt": "[compat] Host rejects nested-virtualization property ({code}); enabled kernel-irqchip=off automatically", + "vmstart.nested_vmx.invalid": "The nested virtualization setting could not be read. Starting with the default CPU settings.", + "vmstart.nested_vmx.unavailable": "Nested virtualization is unavailable with the current Windows host and interrupt controller settings.", "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", diff --git a/internal/macos/macosdriver/prepare.go b/internal/macos/macosdriver/prepare.go index f54d092..6f02c22 100644 --- a/internal/macos/macosdriver/prepare.go +++ b/internal/macos/macosdriver/prepare.go @@ -148,9 +148,7 @@ func (d *ReimsMacOSDriver) prepareStart(ctx context.Context, cfg config.Config, if err := d.prepareColdReboot(cfg, name, cur.Directory, rep, &in); err != nil { return in, err } - if err := d.prepareNestedVirt(cur.Directory, &in); err != nil { - return in, err - } + AppendNestedVirtIntent(&in, cfg.Locale, cur.Directory, userExtraArgs, rep) d.prepareHostMemorySMBIOS(cfg, rep, userExtraArgs, func() bool { return reims.ProbeQEMUSupportsSMBIOSMemoryType(active.QemuPath(), c.Env) }, &in) @@ -241,22 +239,27 @@ func (d *ReimsMacOSDriver) prepareColdReboot(cfg config.Config, name, vmDir stri return nil } -// prepareNestedVirt asks for VMX in the guest's CPU when the VM's nested-virtualization switch -// is on, and takes the argument away when it is off. The argument belongs to this driver in the -// ledger, so it never shows up among the VM's own extra arguments. A switch that cannot be -// read stops the start: the VM must not come up without VMX when the user switched it on. -func (d *ReimsMacOSDriver) prepareNestedVirt(vmDir string, in *plugin.StartIntent) error { +// AppendNestedVirtIntent keeps generated VMX arguments in the driver's ledger. +func AppendNestedVirtIntent(in *plugin.StartIntent, locale i18n.Locale, vmDir, userArgs string, rep host.Report) { + in.ClearKeys = append(in.ClearKeys, keyNestedVirt) cfg, err := vmstart.ReadVMNestedVirt(vmDir) if err != nil { - return fmt.Errorf("read the nested virtualization switch: %w", err) + in.Warnings = append(in.Warnings, i18n.NewCodedError(locale, "E_NESTED_VMX_CONFIG", "vmstart.nested_vmx.invalid", nil, err).Error()) + return } if !cfg.Enabled { - in.ClearKeys = append(in.ClearKeys, keyNestedVirt) - return nil + return } - in.Args = append(in.Args, plugin.ArgFragment{PluginID: d.opts.OwnerID, Key: keyNestedVirt, - Tokens: reims.NestedVirtTokens, Builtin: true, Priority: 90}) - return nil + if !rep.WHPXCaps.NestedVMX || rep.NeedsColdRebootWorkaround || strings.Contains(userArgs, "kernel-irqchip=off") { + in.Warnings = append(in.Warnings, i18n.T(locale, "vmstart.nested_vmx.unavailable")) + return + } + const property = "driver=x86_64-cpu,property=vmx,value=on" + if strings.Contains(userArgs, "-global "+property) { + return + } + in.Args = append(in.Args, plugin.ArgFragment{PluginID: in.PluginID, Key: keyNestedVirt, + Tokens: []string{"-global", property}, Builtin: true, Priority: 90}) } // prepareHostMemorySMBIOS appends `-smbios type=17,speed=...,memory_type=...` @@ -296,8 +299,5 @@ func startBaseArgs(extraArgs string, managedByDesktop bool, active map[string]bo s = reims.StripOfflineHelperArgs(s) s = qmp.StripLegacyWin10RebootArgs(s) s = reims.StripIncomingDeferArgs(s) - // The nested-virtualization argument is the driver's (prepareNestedVirt). One written by a - // start without the plugin manager counts as the VM's own and would outlive the switch. - s = reims.StripNestedVirtArgs(s) return strings.TrimSpace(s) } diff --git a/internal/macos/macosdriver/prepare_test.go b/internal/macos/macosdriver/prepare_test.go index 8f8754a..77fbe12 100644 --- a/internal/macos/macosdriver/prepare_test.go +++ b/internal/macos/macosdriver/prepare_test.go @@ -98,47 +98,47 @@ func TestPrepareWorkaroundsHonourSettingsAndRuntime(t *testing.T) { func TestNestedVirtFollowsTheVMSwitch(t *testing.T) { const owner = "test.macos" + const owned = "-global driver=x86_64-cpu,property=vmx,value=on" dir := t.TempDir() - d := &ReimsMacOSDriver{opts: Options{OwnerID: owner}} - prepare := func() plugin.StartIntent { + rep := host.Report{WHPXCaps: host.WHPXCapabilities{NestedVMX: true}} + prepare := func(userArgs string, rep host.Report) plugin.StartIntent { in := plugin.StartIntent{PluginID: owner} - if err := d.prepareNestedVirt(dir, &in); err != nil { - t.Fatal(err) - } + AppendNestedVirtIntent(&in, "en-US", dir, userArgs, rep) return in } - if in := prepare(); !slices.Contains(in.ClearKeys, keyNestedVirt) || len(in.Args) != 0 { + if in := prepare("", rep); !slices.Contains(in.ClearKeys, keyNestedVirt) || len(in.Args) != 0 { t.Fatalf("switched off = %+v", in) } - // A switch that cannot be read stops the start instead of leaving VMX out silently. if err := os.WriteFile(filepath.Join(dir, ".reims-go-nested-virt.json"), []byte("{"), 0o644); err != nil { t.Fatal(err) } - damaged := plugin.StartIntent{PluginID: owner} - if err := d.prepareNestedVirt(dir, &damaged); err == nil || len(damaged.Args) != 0 { - t.Fatalf("a damaged switch file: err = %v, args = %+v", err, damaged.Args) + if in := prepare("", rep); len(in.Warnings) != 1 || len(in.Args) != 0 { + t.Fatalf("damaged switch = %+v", in) } if err := vmstart.SaveVMNestedVirt(dir, vmstart.VMNestedVirtConfig{Enabled: true}); err != nil { t.Fatal(err) } - in := prepare() + if in := prepare("", host.Report{}); len(in.Args) != 0 || len(in.Warnings) != 1 { + t.Fatalf("unsupported host = %+v", in) + } + if in := prepare("-accel whpx,kernel-irqchip=off", rep); len(in.Args) != 0 || len(in.Warnings) != 1 { + t.Fatalf("userspace interrupt controller = %+v", in) + } + if in := prepare(owned, rep); len(in.Args) != 0 { + t.Fatalf("user owns VMX argument = %+v", in) + } + in := prepare("", rep) if !slices.Equal(argKeys(in), []string{keyNestedVirt}) || !in.Args[0].Builtin || - in.Args[0].PluginID != owner || !slices.Equal(in.Args[0].Tokens, reims.NestedVirtTokens) { + in.Args[0].PluginID != owner || strings.Join(in.Args[0].Tokens, " ") != owned { t.Fatalf("switched on = %+v", in.Args) } const user = "-cpu host -machine kernel-irqchip=on" - own := strings.Join(reims.NestedVirtTokens, " ") active := map[string]bool{owner: true} ledger := &plugin.ArgLedger{} - // An argument written by a start without the ledger must not pass for the VM's own. - base := startBaseArgs(user+" "+own, false, active) - if base != user { - t.Fatalf("startBaseArgs = %q", base) - } - on := plugin.ReconcileStartIntentsForDriver(base, ledger, active, owner, []plugin.StartIntent{in}) - if on.ExtraArgs != user+" "+own { + on := plugin.ReconcileStartIntentsForDriver(user, ledger, active, owner, []plugin.StartIntent{in}) + if on.ExtraArgs != user+" "+owned { t.Fatalf("launch args with the switch on = %q", on.ExtraArgs) } if got := plugin.UserExtraArgs(on.ExtraArgs, ledger); got != user { @@ -148,7 +148,7 @@ func TestNestedVirtFollowsTheVMSwitch(t *testing.T) { if err := vmstart.SaveVMNestedVirt(dir, vmstart.VMNestedVirtConfig{}); err != nil { t.Fatal(err) } - off := plugin.ReconcileStartIntentsForDriver(on.ExtraArgs, ledger, active, owner, []plugin.StartIntent{prepare()}) + off := plugin.ReconcileStartIntentsForDriver(on.ExtraArgs, ledger, active, owner, []plugin.StartIntent{prepare("", rep)}) if off.ExtraArgs != user { t.Fatalf("launch args after switching off = %q", off.ExtraArgs) } diff --git a/internal/macos/reims/nested_virt_args.go b/internal/macos/reims/nested_virt_args.go deleted file mode 100644 index b8cb207..0000000 --- a/internal/macos/reims/nested_virt_args.go +++ /dev/null @@ -1,40 +0,0 @@ -package reims - -import "strings" - -// NestedVirtTokens asks QEMU for VMX in the guest's CPU, so that macOS can run VMs of its own -// (Docker Desktop, UTM). reims-ctl adds `vmx=on` to `-cpu` only where KVM offers VMX -// (reims-vgpu 3731afd9 crates/reims-ctl/src/qemu.rs:310-315), never on Windows. QEMU registers -// a `-cpu` `name=value` flag as a global property of the CPU type (qemu-reims-vgpu 4571bc5 -// target/i386/cpu.c:7952-7956) and applies every global property to each device it creates -// (qom/object.c:445-480), so `-global` on the x86-64 CPU type adds that one feature to any -// CPU model and every vCPU without restating the rest of `-cpu`. Whether the hypervisor then -// gives VMX shows only in the guest: on some PCs Windows refuses nested virtualization (see -// prepareWHPXFallback in the macOS driver), and the switch has no effect there. -var NestedVirtTokens = []string{"-global", "driver=x86_64-cpu,property=vmx,value=on"} - -// StripNestedVirtArgs takes NestedVirtTokens out of a QEMU extra-args string and leaves the -// other arguments as they are. -func StripNestedVirtArgs(extraArgs string) string { - tokens := splitShellTokens(extraArgs) - kept := make([]string, 0, len(tokens)) - for i := 0; i < len(tokens); i++ { - if tokens[i] == NestedVirtTokens[0] && i+1 < len(tokens) && tokens[i+1] == NestedVirtTokens[1] { - i++ - continue - } - kept = append(kept, tokens[i]) - } - return strings.Join(kept, " ") -} - -// MergeNestedVirtArgs puts NestedVirtTokens at the end of a QEMU extra-args string, or takes -// them out. They then count as the VM's own arguments, so this is for starts that have no -// argument ledger (startprep.Prepare); with one, the macOS driver owns them. -func MergeNestedVirtArgs(extraArgs string, enabled bool) string { - base := strings.TrimSpace(StripNestedVirtArgs(extraArgs)) - if !enabled { - return base - } - return strings.TrimSpace(base + " " + strings.Join(NestedVirtTokens, " ")) -} diff --git a/internal/macos/reims/nested_virt_args_test.go b/internal/macos/reims/nested_virt_args_test.go deleted file mode 100644 index 9710587..0000000 --- a/internal/macos/reims/nested_virt_args_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package reims - -import ( - "slices" - "strings" - "testing" -) - -func TestMergeNestedVirtArgs(t *testing.T) { - // The user's arguments, one of them quoted around a path with a space. - const user = "-cpu host -drive 'id=disk,file=D:/My VMs/disk.img'" - on := user + " " + strings.Join(NestedVirtTokens, " ") - for _, tc := range []struct { - name string - in string - enabled bool - want string - }{ - {"adds them after the VM's own arguments", user, true, on}, - {"adds nothing else", on, true, on}, - {"takes them out", on, false, user}, - {"leaves a VM without them as it is", user, false, user}, - {"empties a VM that had only them", strings.Join(NestedVirtTokens, " "), false, ""}, - {"fills an empty string", "", true, strings.Join(NestedVirtTokens, " ")}, - } { - if got := MergeNestedVirtArgs(tc.in, tc.enabled); got != tc.want { - t.Errorf("%s: MergeNestedVirtArgs(%q, %v) = %q, want %q", tc.name, tc.in, tc.enabled, got, tc.want) - } - } -} - -func TestNestedVirtLeavesAHandWrittenCPUModelAlone(t *testing.T) { - // What a user may have written by hand before the switch existed. - const own = "-cpu host,kvm=on,check,vmx=on -global driver=x86_64-cpu,property=vmx,value=off" - if got := StripNestedVirtArgs(own); got != own { - t.Fatalf("StripNestedVirtArgs(%q) = %q", own, got) - } -} - -func TestNestedVirtIsNotAReimsCtlOption(t *testing.T) { - yes := true - args, err := BuildSetArgs(SetOpts{Name: "mac", NestedVirt: &yes}) - if err != nil || !slices.Equal(args, []string{"set", "mac"}) { - t.Fatalf("BuildSetArgs = %q, %v", args, err) - } - if HasCtlSetChanges(SetOpts{Name: "mac", NestedVirt: &yes}) { - t.Fatal("the switch alone would call reims-ctl set") - } -} diff --git a/internal/macos/reims/reims.go b/internal/macos/reims/reims.go index da17914..1f15133 100644 --- a/internal/macos/reims/reims.go +++ b/internal/macos/reims/reims.go @@ -84,11 +84,12 @@ 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"` // NestedVirt is the VM's nested-virtualization switch (vmstart.ReadVMNestedVirt). - NestedVirt bool `json:"nested_virt"` - SuspendInfo *SuspendInfo `json:"suspend_info,omitempty"` + NestedVirt bool `json:"nested_virt"` + NestedVirtInvalid bool `json:"nested_virt_invalid,omitempty"` + SuspendInfo *SuspendInfo `json:"suspend_info,omitempty"` } type ValidationIssue struct { diff --git a/internal/macos/startprep/startprep.go b/internal/macos/startprep/startprep.go index 786ea1b..12f7fe3 100644 --- a/internal/macos/startprep/startprep.go +++ b/internal/macos/startprep/startprep.go @@ -79,10 +79,7 @@ func (p *Prep) CheckMemory(memory string, rep host.Report) error { // the offline-install helper disk, the recovery boot picker, the macOS // language preset and the WHPX nested-virtualization fallback. cur is updated // to match what was written through `reims-ctl set`. -// -// It fails when the VM's nested-virtualization switch cannot be read or applied; the -// other steps report what they could not do in the log. -func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) error { +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 @@ -94,11 +91,7 @@ func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *r if !p.SkipWHPXFallback { p.applyProbedWHPXCompat(ctx, name, rep, cur) } - if err := p.syncNestedVirt(ctx, name, cur); err != nil { - return err - } p.syncHostMemorySMBIOS(ctx, name, rep, cur) - return nil } func (p *Prep) syncHostMemorySMBIOS(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) { @@ -199,25 +192,6 @@ func (p *Prep) applyProbedWHPXCompat(ctx context.Context, name string, rep host. p.log(i18n.M(p.cfg.Locale, "vmstart.compat.nested_virt", i18n.Vars{"code": code})) } -// syncNestedVirt follows the VM's nested-virtualization switch. These starts have no -// argument ledger, so the argument goes in as the VM's own; the macOS driver takes it over -// from there. -func (p *Prep) syncNestedVirt(ctx context.Context, name string, cur *reims.VMDetail) error { - cfg, err := vmstart.ReadVMNestedVirt(cur.Directory) - if err != nil { - return fmt.Errorf("read the nested virtualization switch: %w", err) - } - merged := reims.MergeNestedVirtArgs(cur.ExtraArgs, cfg.Enabled) - if merged == cur.ExtraArgs { - return nil - } - if err := p.setExtraArgs(ctx, name, merged); err != nil { - return fmt.Errorf("apply the nested virtualization switch: %w", err) - } - cur.ExtraArgs = merged - return nil -} - // RuntimeHasPatch reports whether the active runtime was built with a patch // whose name contains substr (case-insensitive). func (p *Prep) RuntimeHasPatch(substr string) bool { diff --git a/locales/en-US/native.json b/locales/en-US/native.json index 1bda9d3..9082381 100644 --- a/locales/en-US/native.json +++ b/locales/en-US/native.json @@ -234,6 +234,8 @@ "err.whpx_missing": "Windows Hypervisor Platform (WHPX) is not enabled. Enable WHPX on the Host page and restart Windows before starting the VM", "err.whpx_no_hypervisor": "Windows Hypervisor is not active (unrelated to disk space). Ensure Intel VT-x / AMD SVM is enabled in BIOS, enable WHPX on the Host page, run `bcdedit /set hypervisorlaunchtype auto` as Administrator, and restart Windows", "err.whpx_unsupported": "Windows Hypervisor Platform (WHPX) is not supported on this OS; Windows 10 1803 or newer is required", + "vmstart.nested_vmx.invalid": "The nested virtualization setting could not be read. Starting with the default CPU settings.", + "vmstart.nested_vmx.unavailable": "Nested virtualization is unavailable with the current Windows host and interrupt controller settings.", "installer.paused": { "message": "Paused. Run `reims-go installer download {ver}` again to continue where it stopped.", "$params": [ diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index 7b3ee50..d251ecb 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -339,7 +339,9 @@ "kernelIrqchipOn": "On", "kernelIrqchipOff": "Off", "nestedVirtLabel": "Nested virtualization", - "nestedVirtDesc": "Lets macOS run VMs of its own, such as Docker Desktop; some PCs cannot enable it", + "nestedVirtDesc": "Lets macOS run its own virtual machines. Applies on a full restart.", + "nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.", + "nestedVirtInvalid": "The saved setting could not be read. The VM starts with the default CPU settings.", "diskControllerNvmeHint": "NVMe is faster", "diskControllerInstallHint": "Keep SATA while installing; switch to NVMe after ejecting the installer", "gpuUnavailableHint": "No GPU available for acceleration; try VMware SVGA", diff --git a/locales/zh-CN/native.json b/locales/zh-CN/native.json index ddf0aa5..4f8d516 100644 --- a/locales/zh-CN/native.json +++ b/locales/zh-CN/native.json @@ -234,6 +234,8 @@ "err.whpx_missing": "未启用 Windows 虚拟机监控程序平台(WHPX)。在「宿主机」页启用 WHPX 并重启 Windows 后再启动虚拟机", "err.whpx_no_hypervisor": "Windows Hypervisor 虚拟化引擎未激活(与磁盘空间无关)。确认 BIOS 已开启 Intel VT-x / AMD SVM,在「宿主机」页启用 WHPX,以管理员运行 bcdedit /set hypervisorlaunchtype auto,然后重启 Windows", "err.whpx_unsupported": "当前系统不支持 Windows 虚拟机监控程序平台(WHPX),需要 Windows 10 1803 或更高版本", + "vmstart.nested_vmx.invalid": "无法读取嵌套虚拟化设置。虚拟机将按默认 CPU 设置启动。", + "vmstart.nested_vmx.unavailable": "当前 Windows 宿主机和中断控制器设置无法启用嵌套虚拟化。", "installer.paused": { "message": "已暂停。再次运行 `reims-go installer download {ver}` 会从中断处继续。", "$params": [ diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index df8b338..6c4e81e 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -339,7 +339,9 @@ "kernelIrqchipOn": "开启", "kernelIrqchipOff": "关闭", "nestedVirtLabel": "嵌套虚拟化", - "nestedVirtDesc": "在 macOS 里再运行虚拟机(如 Docker Desktop),部分电脑不支持,可能无法启用", + "nestedVirtDesc": "允许 macOS 运行自己的虚拟机,完全关机后再次启动时生效。", + "nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。", + "nestedVirtInvalid": "保存的设置无法读取,虚拟机将按默认 CPU 设置启动。", "diskControllerNvmeHint": "NVMe 读写更快", "diskControllerInstallHint": "装机时保持 SATA,装完弹出安装盘再改 NVMe", "gpuUnavailableHint": "没有找到能加速的显卡,可改用 VMware SVGA", From fbdecc722167db6a5e453629de407b3bb582cd49 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Wed, 2 Dec 2026 04:35:52 +0800 Subject: [PATCH 11/47] fix(network): restore guest DNS before disabling the host proxy --- changes/guest-tools-host-dns.json | 7 +++ frontend/src/components/AppSettingsPage.tsx | 24 +++++----- frontend/src/components/VMPage.tsx | 47 +++++++++----------- frontend/src/i18n/domains/vm.gen.ts | 12 ++--- frontend/src/i18n/keys.gen.ts | 2 +- frontend/src/styles/app.css | 5 +-- internal/app/host_dns_flow.go | 6 +++ internal/app/host_dns_flow_test.go | 26 +++++++++++ internal/guesttools/Apply-Host-DNS.command | 36 ++++++++------- internal/guesttools/Disable-Host-DNS.command | 4 +- internal/guesttools/dns-proxy.pl | 4 +- internal/guesttools/dns.go | 6 +-- internal/guesttools/folder_agent_test.go | 2 +- internal/guesttools/image.go | 9 ++-- internal/guesttools/server.go | 22 ++++++--- locales/en-US/vm.json | 6 +-- locales/zh-CN/vm.json | 6 +-- 17 files changed, 131 insertions(+), 93 deletions(-) create mode 100644 changes/guest-tools-host-dns.json diff --git a/changes/guest-tools-host-dns.json b/changes/guest-tools-host-dns.json new file mode 100644 index 0000000..02eb650 --- /dev/null +++ b/changes/guest-tools-host-dns.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 27, + "authors": ["reiasu2", "yxc0915"], + "zh": "已安装的 macOS 虚拟机可通过 Guest Tools 使用宿主系统 DNS 或 DoH,适用于直连 DNS 受限的网络。 [#65](https://github.com/Nwflower/Reims-Go/pull/65)", + "en": "Use the host DNS resolver or DoH through Guest Tools in installed macOS VMs on networks that block direct DNS. [#65](https://github.com/Nwflower/Reims-Go/pull/65)" +} diff --git a/frontend/src/components/AppSettingsPage.tsx b/frontend/src/components/AppSettingsPage.tsx index 758d94f..30f2954 100644 --- a/frontend/src/components/AppSettingsPage.tsx +++ b/frontend/src/components/AppSettingsPage.tsx @@ -92,6 +92,7 @@ export const AppSettingsPage: React.FC = ({ setDnsSavedHint(false) setDnsTestResult(null) setDnsTesting(false) + setDnsSaving(false) api.GetHostDNSConfig() .then((cfg) => { if (!live || !cfg || dnsEditSeq.current !== seq) return @@ -130,7 +131,7 @@ export const AppSettingsPage: React.FC = ({ const saveHostDNS = async (nextMode: HostDNSMode, nextUrl: string, nextCustom: boolean) => { const seq = ++dnsEditSeq.current - dnsTestSeq.current += 1 + resetDNSTest() setDnsSaving(true) setDnsValidationErr('') setDnsSavedHint(false) @@ -156,23 +157,20 @@ export const AppSettingsPage: React.FC = ({ } } + const resetDNSTest = () => { + dnsTestSeq.current += 1 + setDnsTesting(false) + setDnsTestResult(null) + } + const handleDNSModeChange = (nextMode: HostDNSMode) => { if (nextMode === dnsMode || dnsSaving) return - dnsTestSeq.current += 1 - setDnsTestResult(null) - const candidate = dohCustom ? dohDraft.trim() : dohUrl - if (dohCustom && !isValidDoHURL(candidate)) { - setDnsMode(nextMode) - setDnsValidationErr(tr('hostDNSInvalidURL')) - return - } - void saveHostDNS(nextMode, candidate || DEFAULT_DOH_URL, dohCustom) + void saveHostDNS(nextMode, savedDohUrl, dohCustom) } const handleDoHPresetChange = (val: string) => { if (dnsSaving) return - dnsTestSeq.current += 1 - setDnsTestResult(null) + resetDNSTest() setDnsSavedHint(false) if (val === CUSTOM_DOH_VALUE) { dnsEditSeq.current += 1 @@ -380,7 +378,7 @@ export const AppSettingsPage: React.FC = ({ setDohDraft(e.target.value) setDnsValidationErr('') setDnsSavedHint(false) - setDnsTestResult(null) + resetDNSTest() }} onBlur={() => commitCustomDoH(false)} onKeyDown={(e) => { diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 4f4f598..a865b33 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -1251,9 +1251,9 @@ export const VMPage: React.FC = ({ const toolsAttached = !!detail.guest_tools_attached const disableCmd = toolsAttached ? HOST_DNS_DISABLE_CMD - : 'sh "/Library/Application Support/ReimsGuestTools/Disable-Host-DNS.command"' - const showApplySub = dnsEnabled && (dnsStale || !dnsActive || !dnsReported) - const showDisableSub = !dnsEnabled && (dnsActive || (running && !dnsReported)) + : 'sh /private/etc/reims-host-dns/Disable-Host-DNS.command' + const showApplySub = dnsEnabled && (dnsStale || !dnsActive) + const showDisableSub = dnsActive || dnsStale || (dnsEnabled && running && !dnsReported) let dnsStatus: React.ReactNode if (hostDNSLoadErr && hostDNS === null) { @@ -1279,7 +1279,7 @@ export const VMPage: React.FC = ({ {tr('hostDNSStatusPending')}
) - } else if (dnsReported && dnsActive) { + } else if (dnsReported && (dnsActive || dnsStale)) { dnsStatus = (