Recognize quoted managed arguments and integrate latest main

This commit is contained in:
YXC0915 committed 2026-12-02 04:50:52 +08:00
commit 4083e407ff
34 files changed
+2627 -29

No files matched your search

+2
View File
@@ -1,3 +1,5 @@
*.patch -text
*.diff -text
internal/guesttools/file_sync.sh text eol=lf
internal/guesttools/*-Host-DNS.command text eol=lf
internal/guesttools/dns-proxy.pl text eol=lf
+7
View File
@@ -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)"
}
+305 -3
View File
@@ -1,7 +1,7 @@
import React from 'react'
import { PowerOff } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { Check, CircleAlert, PowerOff } from 'lucide-react'
import '../i18n/domains/settings.gen'
import { getLocaleOptions, I18nKey, t } from '../i18n'
import { getLocaleOptions, I18nKey, parseAppError, t } from '../i18n'
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
import { AppState, Locale, ResolvedLocalePack } from '../types'
import { Button } from '../ui/controls'
@@ -10,6 +10,42 @@ import { api } from '../wails'
export type ThemeMode = 'light' | 'dark' | 'system'
type HostDNSMode = 'system' | 'doh'
const DEFAULT_DOH_URL = 'https://dns.alidns.com/dns-query'
const CUSTOM_DOH_VALUE = '__custom__'
const DOH_PRESETS: ReadonlyArray<{ url: string; labelKey: I18nKey; host: string }> = [
{ url: 'https://dns.alidns.com/dns-query', labelKey: 'hostDNSPresetAliDNS', host: 'dns.alidns.com' },
{ url: 'https://doh.pub/dns-query', labelKey: 'hostDNSPresetDNSPod', host: 'doh.pub' },
{ url: 'https://cloudflare-dns.com/dns-query', labelKey: 'hostDNSPresetCloudflare', host: 'cloudflare-dns.com' },
{ url: 'https://dns.google/dns-query', labelKey: 'hostDNSPresetGoogle', host: 'dns.google' },
]
function normalizeHostDNSMode(mode?: string): HostDNSMode {
return mode === 'doh' ? 'doh' : 'system'
}
function normalizeDoHURL(url?: string): string {
const trimmed = url?.trim() ?? ''
return trimmed || DEFAULT_DOH_URL
}
function isPresetDoHURL(url: string): boolean {
return DOH_PRESETS.some((p) => p.url === url)
}
function isValidDoHURL(raw: string): boolean {
const trimmed = raw.trim()
if (!trimmed.startsWith('https://')) return false
try {
const parsed = new URL(trimmed)
return parsed.protocol === 'https:' && Boolean(parsed.hostname) && !parsed.username && !parsed.password && !parsed.hash
} catch {
return false
}
}
interface Props {
state: AppState
locale: Locale
@@ -30,6 +66,49 @@ export const AppSettingsPage: React.FC<Props> = ({
const { host, config, optimizations } = state
const quitMode = state.quit_mode
const [savedDnsMode, setSavedDnsMode] = useState<HostDNSMode>(() => normalizeHostDNSMode(config.host_dns_mode))
const [savedDohUrl, setSavedDohUrl] = useState<string>(() => normalizeDoHURL(config.host_dns_doh_url))
const [dnsMode, setDnsMode] = useState<HostDNSMode>(() => normalizeHostDNSMode(config.host_dns_mode))
const [dohUrl, setDohUrl] = useState<string>(() => normalizeDoHURL(config.host_dns_doh_url))
const [dohCustom, setDohCustom] = useState<boolean>(() => !isPresetDoHURL(normalizeDoHURL(config.host_dns_doh_url)))
const [dohDraft, setDohDraft] = useState<string>(() => normalizeDoHURL(config.host_dns_doh_url))
const [dnsSaving, setDnsSaving] = useState(false)
const [dnsSavedHint, setDnsSavedHint] = useState(false)
const [dnsValidationErr, setDnsValidationErr] = useState('')
const [dnsTesting, setDnsTesting] = useState(false)
const [dnsTestResult, setDnsTestResult] = useState<
| { ok: true; domain: string; addresses: string[]; elapsedMs: number }
| { ok: false; reason: string }
| null
>(null)
const dnsEditSeq = useRef(0)
const dnsTestSeq = useRef(0)
useEffect(() => {
let live = true
const seq = ++dnsEditSeq.current
dnsTestSeq.current += 1
setDnsValidationErr('')
setDnsSavedHint(false)
setDnsTestResult(null)
setDnsTesting(false)
setDnsSaving(false)
api.GetHostDNSConfig()
.then((cfg) => {
if (!live || !cfg || dnsEditSeq.current !== seq) return
const mode = normalizeHostDNSMode(cfg.mode)
const url = normalizeDoHURL(cfg.doh_url)
setSavedDnsMode(mode)
setSavedDohUrl(url)
setDnsMode(mode)
setDohUrl(url)
setDohDraft(url)
setDohCustom(!isPresetDoHURL(url))
})
.catch((e) => console.warn('[settings] GetHostDNSConfig failed:', e))
return () => { live = false }
}, [config.data_root])
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
const missingFontScript = state.missing_font_hint || ''
const memSpecLabel = host.memory_spec?.speed_mhz
@@ -50,6 +129,116 @@ export const AppSettingsPage: React.FC<Props> = ({
if (dir) await api.SetDataRoot(dir)
})
const saveHostDNS = async (nextMode: HostDNSMode, nextUrl: string, nextCustom: boolean) => {
const seq = ++dnsEditSeq.current
resetDNSTest()
setDnsSaving(true)
setDnsValidationErr('')
setDnsSavedHint(false)
try {
await api.SetHostDNSConfig({ mode: nextMode, doh_url: nextUrl })
if (dnsEditSeq.current !== seq) return
setSavedDnsMode(nextMode)
setSavedDohUrl(nextUrl)
setDnsMode(nextMode)
setDohUrl(nextUrl)
setDohDraft(nextUrl)
setDohCustom(nextCustom)
setDnsSavedHint(true)
onRefresh()
} catch (e) {
if (dnsEditSeq.current === seq) {
onError(tr('failGeneric'), e)
}
} finally {
if (dnsEditSeq.current === seq) {
setDnsSaving(false)
}
}
}
const resetDNSTest = () => {
dnsTestSeq.current += 1
setDnsTesting(false)
setDnsTestResult(null)
}
const handleDNSModeChange = (nextMode: HostDNSMode) => {
if (nextMode === dnsMode || dnsSaving) return
void saveHostDNS(nextMode, savedDohUrl, dohCustom)
}
const handleDoHPresetChange = (val: string) => {
if (dnsSaving) return
resetDNSTest()
setDnsSavedHint(false)
if (val === CUSTOM_DOH_VALUE) {
dnsEditSeq.current += 1
setDohCustom(true)
setDohDraft(dohUrl)
setDnsValidationErr('')
return
}
if (val !== savedDohUrl || dnsMode !== savedDnsMode) {
void saveHostDNS(dnsMode, val, false)
} else {
dnsEditSeq.current += 1
setDohCustom(false)
setDohDraft(val)
setDnsValidationErr('')
}
}
const commitCustomDoH = (forceSave: boolean) => {
if (dnsSaving) return
const nextUrl = dohDraft.trim()
if (!isValidDoHURL(nextUrl)) {
setDnsValidationErr(tr('hostDNSInvalidURL'))
setDnsSavedHint(false)
return
}
setDnsValidationErr('')
if (!forceSave && nextUrl === savedDohUrl && dnsMode === savedDnsMode) return
setDnsTestResult(null)
void saveHostDNS(dnsMode, nextUrl, true)
}
const handleTestHostDNS = async () => {
if (dnsTesting || dnsSaving) return
const targetUrl = dohCustom ? dohDraft.trim() : dohUrl
if (!isValidDoHURL(targetUrl)) {
setDnsValidationErr(tr('hostDNSInvalidURL'))
setDnsTestResult(null)
return
}
const testSeq = ++dnsTestSeq.current
setDnsValidationErr('')
setDnsSavedHint(false)
setDnsTesting(true)
setDnsTestResult(null)
try {
const res = await api.TestHostDNS({ mode: dnsMode, doh_url: targetUrl })
if (dnsTestSeq.current !== testSeq) return
setDnsTestResult({
ok: true,
domain: res.domain || 'example.com',
addresses: res.addresses ?? [],
elapsedMs: res.elapsed_ms ?? 0,
})
} catch (e) {
if (dnsTestSeq.current !== testSeq) return
const parsed = parseAppError(e)
setDnsTestResult({ ok: false, reason: parsed.summary || String(e) })
} finally {
if (dnsTestSeq.current === testSeq) {
setDnsTesting(false)
}
}
}
const dohSelectValue = dohCustom ? CUSTOM_DOH_VALUE : (isPresetDoHURL(dohUrl) ? dohUrl : CUSTOM_DOH_VALUE)
const showDoHExtra = dohCustom || Boolean(dnsValidationErr) || dnsSavedHint || dnsTestResult !== null
const forceQuit = async () => {
try {
await api.ForceQuitApp()
@@ -128,6 +317,119 @@ export const AppSettingsPage: React.FC<Props> = ({
/>
</div>
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('hostDNSModeTitle')}</div>
<div className="row-sub">
{tr(dnsMode === 'doh' ? 'hostDNSModeDoHSub' : 'hostDNSModeSystemSub')}
</div>
</div>
<div className="row-right">
<PopupSelect<HostDNSMode>
label={tr('hostDNSModeTitle')}
value={dnsMode}
onChange={handleDNSModeChange}
options={[
{ value: 'system', label: tr('hostDNSModeSystem') },
{ value: 'doh', label: tr('hostDNSModeDoH') },
]}
/>
</div>
</div>
<div className="row row-stack">
<div className="row-head">
<div className="row-main">
<div className="row-title">{tr('hostDNSDoHTitle')}</div>
<div className="row-sub">{tr('hostDNSDoHSub')}</div>
</div>
<div className="row-right">
<PopupSelect
label={tr('hostDNSDoHTitle')}
value={dohSelectValue}
onChange={handleDoHPresetChange}
options={[
...DOH_PRESETS.map((p) => ({
value: p.url,
label: tr(p.labelKey),
detail: p.host,
})),
{ value: CUSTOM_DOH_VALUE, label: tr('hostDNSPresetCustom') },
]}
/>
<Button busy={dnsTesting} disabled={dnsSaving} onClick={() => void handleTestHostDNS()}>
{tr(dnsTesting ? 'hostDNSTesting' : 'hostDNSTest')}
</Button>
</div>
</div>
{showDoHExtra && (
<div className="host-dns-extra">
{dohCustom && (
<div className="host-dns-custom">
<input
className="input rg-p-input mono"
type="url"
value={dohDraft}
spellCheck={false}
autoComplete="off"
placeholder={tr('hostDNSCustomPlaceholder')}
aria-label={tr('hostDNSDoHTitle')}
aria-invalid={dnsValidationErr ? true : undefined}
onChange={(e) => {
setDohDraft(e.target.value)
setDnsValidationErr('')
setDnsSavedHint(false)
resetDNSTest()
}}
onBlur={() => commitCustomDoH(false)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
commitCustomDoH(true)
}
}}
/>
<Button
busy={dnsSaving}
disabled={dnsSaving || !dohDraft.trim()}
onMouseDown={(e) => e.preventDefault()}
onClick={() => commitCustomDoH(true)}
>
{tr('save')}
</Button>
</div>
)}
{dnsValidationErr && (
<div className="host-dns-feedback danger-text" role="alert">
<CircleAlert size={13} aria-hidden="true" />
<span>{dnsValidationErr}</span>
</div>
)}
{!dnsValidationErr && dnsSavedHint && (
<div className="host-dns-feedback ok-text" role="status">
<Check size={13} aria-hidden="true" />
<span>{tr('hostDNSSaved')}</span>
</div>
)}
{dnsTestResult && (
<div
className={`host-dns-feedback ${dnsTestResult.ok ? 'ok-text' : 'danger-text'}`}
role={dnsTestResult.ok ? 'status' : 'alert'}
>
{dnsTestResult.ok ? <Check size={13} aria-hidden="true" /> : <CircleAlert size={13} aria-hidden="true" />}
<span className={dnsTestResult.ok ? 'mono' : undefined}>
{dnsTestResult.ok
? tr('hostDNSTestOK', {
domain: dnsTestResult.domain,
ips: dnsTestResult.addresses.slice(0, 2).join(', '),
ms: dnsTestResult.elapsedMs,
})
: tr('hostDNSTestFailed', { reason: dnsTestResult.reason })}
</span>
</div>
)}
</div>
)}
</div>
<div className="row">
<div className="row-main">
<div className="row-title">{tr('forceQuitAppTitle')}</div>
+197 -2
View File
@@ -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<Props> = ({
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.
@@ -973,7 +1062,7 @@ export const VMPage: React.FC<Props> = ({
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 11
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 12
const gtAttachPending = running && pending.some((p) => p.field === 'guest_tools' && p.to === 'attached')
// Plugin switched off: show the state and hide controls that would only fail.
const gtOff = !!detail.guest_tools_disabled
@@ -1154,6 +1243,112 @@ export const VMPage: React.FC<Props> = ({
</div>
</div>
)}
{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 /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) {
dnsStatus = <span className="conn-meta danger-text">{hostDNSLoadErr}</span>
} else if (dnsEnabled && dnsReported && dnsStale) {
dnsStatus = (
<span className="conn-status is-warn">
<span className="conn-status-dot" aria-hidden="true" />
{tr('hostDNSStatusStale')}
</span>
)
} else if (dnsEnabled && dnsReported && dnsActive) {
dnsStatus = (
<span className="conn-status is-ok">
<span className="conn-status-dot" aria-hidden="true" />
{tr('hostDNSStatusActive')}
</span>
)
} else if (dnsEnabled) {
dnsStatus = (
<span className="conn-status">
<span className="conn-status-dot" aria-hidden="true" />
{tr('hostDNSStatusPending')}
</span>
)
} else if (dnsReported && (dnsActive || dnsStale)) {
dnsStatus = (
<span className="conn-status is-warn">
<span className="conn-status-dot" aria-hidden="true" />
{tr('hostDNSStatusStillActive')}
</span>
)
} else {
dnsStatus = (
<span className="conn-meta" title={tr('hostDNSOffHint')}>
{tr('hostDNSOffHint')}
</span>
)
}
return (
<>
<div className="conn-row">
<div className="conn-main">
<span className="conn-title">{tr('guestToolsHostDNS')}</span>
{dnsStatus}
</div>
<div className="conn-ctrl">
<Switch
label={tr('guestToolsHostDNS')}
checked={dnsEnabled}
disabled={busy || guestToolsLocked || hostDNSBusy || hostDNS === null || (dnsEnabled && (dnsActive || dnsStale))}
onChange={(checked) => void handleToggleHostDNS(checked)}
/>
</div>
</div>
{showApplySub && (
<div className="conn-row conn-sub">
<div className="conn-main">
<span className="conn-meta">
{tr(!toolsAttached ? 'hostDNSAttachHint' : dnsStale ? 'hostDNSStaleHint' : 'hostDNSApplyHint')}
</span>
</div>
{toolsAttached && (
<div className="conn-ctrl conn-ctrl-grow">
<div className="ssh-pill">
<code title={HOST_DNS_APPLY_CMD}>{HOST_DNS_APPLY_CMD}</code>
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(HOST_DNS_APPLY_CMD)} />
{running && (
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(HOST_DNS_APPLY_CMD)} />
)}
</div>
</div>
)}
</div>
)}
{showDisableSub && (
<div className="conn-row conn-sub">
<div className="conn-main">
<span className="conn-meta">{tr('hostDNSDisableCmdHint')}</span>
</div>
<div className="conn-ctrl conn-ctrl-grow">
<div className="ssh-pill">
<code title={disableCmd}>{disableCmd}</code>
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(disableCmd)} />
{running && (
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(disableCmd)} />
)}
</div>
</div>
</div>
)}
</>
)
})()}
</div>
</section>
)
+38
View File
@@ -256,6 +256,25 @@ export const settingsZh: Record<string, string> = {
"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": "主屏",
@@ -722,6 +741,25 @@ export const settingsEn: Record<string, string> = {
"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",
+24
View File
@@ -87,6 +87,7 @@ export const vmZh: Record<string, string> = {
"gtStatusWaiting": "未连接",
"gtStatusWaitingTip": "在 macOS 里运行安装命令后会自动连接",
"gtUpdate": "更新…",
"guestToolsHostDNS": "宿主机 DNS 代理",
"guestToolsModeSync": "文件同步模式",
"guestToolsModeWebDAV": "WebDAV 挂载",
"guestToolsPreventSleep": "防止 macOS 睡眠",
@@ -107,6 +108,15 @@ export const vmZh: Record<string, string> = {
"guideStep2": "回到恢复主界面,选「Reinstall macOS Tahoe」,装到刚抹好的磁盘,中途会重启几次",
"guideStep3": "看到「设置助理」后,点「退出恢复模式」弹出安装盘",
"guideTitle": "恢复模式",
"hostDNSApplyHint": "在 macOS 终端运行以启用",
"hostDNSAttachHint": "挂载 Guest Tools 后应用代理",
"hostDNSDisableCmdHint": "在 macOS 终端运行以恢复原有 DNS 设置",
"hostDNSOffHint": "上游过滤 UDP/53 导致虚拟机无网络时开启",
"hostDNSStaleHint": "在 macOS 终端重新运行以修复代理",
"hostDNSStatusActive": "运行中",
"hostDNSStatusPending": "待应用",
"hostDNSStatusStale": "配置已过期",
"hostDNSStatusStillActive": "macOS 代理未移除",
"netOff": "无网络",
"netShared": "共享网络",
"onlineRecoveryConfirm": "拉取并挂载(约 1 GB)",
@@ -192,6 +202,8 @@ export const vmZh: Record<string, string> = {
"toastGuestToolsAttachedNextStart": "已挂载 Guest Tools 工具盘,重启虚拟机后在访达中可见",
"toastGuestToolsDetached": "已弹出工具盘",
"toastGuestToolsDetachedNextStart": "已弹出工具盘,下次启动生效",
"toastHostDNSOff": "已关闭宿主机 DNS 代理",
"toastHostDNSOn": "已开启宿主机 DNS 代理",
"toastInstallFinished": "已退出恢复模式",
"toastInstallerAttached": "已挂载离线镜像:{name}",
"toastInstallerAttachedNextStart": "已挂载离线镜像(重启后生效):{name}",
@@ -303,6 +315,7 @@ export const vmEn: Record<string, string> = {
"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<string, string> = {
"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",
"hostDNSAttachHint": "Attach Guest Tools to apply the proxy",
"hostDNSDisableCmdHint": "Run in macOS Terminal to restore previous DNS settings",
"hostDNSOffHint": "Enable when upstream blocks UDP/53 and the VM loses network",
"hostDNSStaleHint": "Run again in macOS Terminal to repair the proxy",
"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<string, string> = {
"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}",
+31
View File
@@ -396,6 +396,7 @@ export type I18nKey =
| "guestTimezoneUpgradeAttachHint"
| "guestTimezoneUpgradeHint"
| "guestToolsConnected"
| "guestToolsHostDNS"
| "guestToolsModeSync"
| "guestToolsModeWebDAV"
| "guestToolsPreventSleep"
@@ -433,6 +434,34 @@ export type I18nKey =
| "hostAudioOutput"
| "hostCPU"
| "hostCoresThreads"
| "hostDNSApplyHint"
| "hostDNSAttachHint"
| "hostDNSCustomPlaceholder"
| "hostDNSDisableCmdHint"
| "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"
@@ -992,6 +1021,8 @@ export type I18nKey =
| "toastGuestToolsAttachedNextStart"
| "toastGuestToolsDetached"
| "toastGuestToolsDetachedNextStart"
| "toastHostDNSOff"
| "toastHostDNSOn"
| "toastInstallFinished"
| "toastInstallerAttached"
| "toastInstallerAttachedNextStart"
+10 -2
View File
@@ -640,11 +640,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 +1161,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 +2019,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 +2029,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, .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%; }
+11
View File
@@ -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<app.SharedFolderSettings>;
@@ -121,6 +122,10 @@ export function GenerateVMSMBIOS(arg1:string):Promise<opencore.SMBIOSIdentity>;
export function GetActiveTheme():Promise<plugin.ActiveThemePayload>;
export function GetGuestToolsHostDNS(arg1:string):Promise<app.GuestToolsHostDNSStatus>;
export function GetHostDNSConfig():Promise<guesttools.HostDNSConfig>;
export function GetLicenseTexts():Promise<app.LicenseTexts>;
export function GetPluginSettings(arg1:string,arg2:string):Promise<Record<string, any>>;
@@ -283,6 +288,10 @@ export function SetDataRoot(arg1:string):Promise<void>;
export function SetGuestPreventSleep(arg1:string,arg2:boolean):Promise<void>;
export function SetGuestToolsHostDNS(arg1:string,arg2:boolean):Promise<void>;
export function SetHostDNSConfig(arg1:guesttools.HostDNSConfig):Promise<void>;
export function SetLocale(arg1:string):Promise<void>;
export function SetMinimizeToTray(arg1:boolean):Promise<void>;
@@ -333,6 +342,8 @@ export function SuspendVM(arg1:string):Promise<void>;
export function SuspendVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise<guesttools.HostDNSTestResult>;
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
export function ToggleVMFullscreen(arg1:string):Promise<boolean>;
+20
View File
@@ -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']();
}
@@ -546,6 +554,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);
}
@@ -646,6 +662,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);
}
+63
View File
@@ -246,6 +246,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;
@@ -654,6 +673,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);
@@ -670,6 +691,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"];
}
}
@@ -888,6 +911,38 @@ 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 class GuestStatus {
keymap_active: boolean;
connected: boolean;
@@ -899,6 +954,10 @@ export namespace guesttools {
timezone_applied?: string;
timezone_helper_ready?: boolean;
timezone_error?: string;
host_dns_enabled: boolean;
host_dns_active: boolean;
host_dns_reported: boolean;
host_dns_config_stale: boolean;
static createFrom(source: any = {}) {
return new GuestStatus(source);
@@ -916,6 +975,10 @@ export namespace guesttools {
this.timezone_applied = source?.timezone_applied;
this.timezone_helper_ready = source?.timezone_helper_ready;
this.timezone_error = source?.timezone_error;
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;
}
}
}
+5
View File
@@ -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)
+1
View File
@@ -118,6 +118,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
}
+126
View File
@@ -0,0 +1,126 @@
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
}
if !enabled {
live := srv.Status(d.Name, 45*time.Second)
if live.HostDNSActive || live.HostDNSConfigStale {
return fmt.Errorf("remove the Host DNS proxy in macOS before disabling it")
}
}
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
}
+179
View File
@@ -0,0 +1,179 @@
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 {
report := func(body string) {
t.Helper()
req, err := http.NewRequestWithContext(t.Context(), http.MethodPost,
fmt.Sprintf("http://127.0.0.1:%d/v1/status", port), strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Bearer "+token)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
t.Fatalf("status report returned %d", resp.StatusCode)
}
}
report(`{"host_dns_active":true}`)
if err := a.SetGuestToolsHostDNS(name, false); err == nil {
t.Fatal("disabled the host endpoint while macOS still pointed to the proxy")
}
cfg, _, err := guesttools.ReadVMConfigStrict(vmDir)
if err != nil || !cfg.HostDNSEnabled {
t.Fatalf("failed disable changed the DNS policy, err = %v", err)
}
report(`{"host_dns_active":false}`)
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)
}
}
+3 -1
View File
@@ -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.
+125
View File
@@ -0,0 +1,125 @@
#!/bin/sh
set -eu
export LC_ALL=C
MEDIA=/Volumes/REIMSTOOLS
APP_DIR=/private/etc/reims-host-dns
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
if sudo test -L "$APP_DIR" ||
{ sudo test -e "$APP_DIR" && [ "$(sudo stat -f '%u:%Lp' "$APP_DIR")" != 0:755 ]; }; then
echo "Host DNS requires a root-owned directory at $APP_DIR." >&2
exit 1
fi
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"
rollback() {
result=$?
trap - EXIT HUP INT TERM
if [ "$result" -ne 0 ]; then
if ! "$APP_DIR/Disable-Host-DNS.command"; then
echo "Could not restore DNS. Rerun $APP_DIR/Disable-Host-DNS.command to retry." >&2
fi
fi
exit "$result"
}
trap rollback EXIT
trap 'exit 1' HUP INT TERM
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 <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key><string>com.reimsgo.dns-proxy</string>
<key>ProgramArguments</key>
<array><string>/usr/bin/perl</string><string>$APP_DIR/dns-proxy.pl</string></array>
<key>EnvironmentVariables</key>
<dict>
<key>REIMS_HOST_PORT</key><string>$port</string>
<key>REIMS_TOKEN_SHA256</key><string>$token_sha256</string>
</dict>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
</dict>
</plist>
EOF
sudo launchctl bootstrap system "$PLIST"
# 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
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")
if [ "$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
[ "$previous" != 127.0.0.1 ] || continue
sudo networksetup -setdnsservers "$svc" 127.0.0.1
done
sudo dscacheutil -flushcache
echo "Host DNS is active."
@@ -0,0 +1,34 @@
#!/bin/sh
set -eu
export LC_ALL=C
APP_DIR=/private/etc/reims-host-dns
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" "$APP_DIR/dns-proxy.conf.new" "$BACKUP" "$LOCAL_DISABLE"
echo "Host DNS is disabled."
+157
View File
@@ -0,0 +1,157 @@
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::INET;
use IO::Select;
my $config = '/private/etc/reims-host-dns/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 + 4 - 12);
}
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;
}
}
+598
View File
@@ -0,0 +1,598 @@
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))
vm := s.authenticateToken(bearerToken(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
}
+392
View File
@@ -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)
}
}
}
}
+5 -4
View File
@@ -5,6 +5,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
@@ -45,8 +46,8 @@ print $mounts "$url on $target (webdav, read-only)\n";
t.Fatal(err)
}
script := string(GuestAgentScript())
if DriveShareAgentVersion != 8 || !strings.Contains(script, `"agent_version\":11,`) {
t.Fatal("Windows drive sharing requires version 8 and the generated agent reports version 11")
if DriveShareAgentVersion != 8 || !strings.Contains(script, `"agent_version\":`+strconv.Itoa(CurrentAgentVersion)+",") {
t.Fatal("Windows drive sharing requires version 8 and the generated agent must report the current version")
}
harness := `set -eu
PATH="$PWD:/usr/bin:/bin:$PATH"
@@ -128,8 +129,8 @@ test "$(wc -l <"$MOUNT_STATE")" -eq 1
}
func TestShellSingleQuoteAndAgentVersion(t *testing.T) {
if !strings.Contains(string(GuestAgentScript()), `\"agent_version\":11,`) {
t.Fatal("GuestAgentScript must report agent_version 11")
if !strings.Contains(string(GuestAgentScript()), `\"agent_version\":`+strconv.Itoa(CurrentAgentVersion)+",") {
t.Fatal("GuestAgentScript must report the current version")
}
if DriveShareAgentVersion != 8 {
t.Fatalf("DriveShareAgentVersion = %d, want 8", DriveShareAgentVersion)
+86 -2
View File
@@ -37,8 +37,14 @@ func TestGuestAgentFolderMounts(t *testing.T) {
}
}
agent, uninstall, install := string(GuestAgentScript()), string(GuestUninstallScript()), string(GuestInstallScript())
if CurrentAgentVersion != TimezoneAgentVersion {
t.Fatalf("CurrentAgentVersion = %d, want timezone version %d", CurrentAgentVersion, TimezoneAgentVersion)
dnsPaths := strings.NewReplacer(
"/Library/LaunchDaemons/com.reimsgo.dns-proxy.plist", "$PWD/dns-proxy.plist",
"/private/etc/reims-host-dns", `"$PWD/system tools"`,
"/Volumes/REIMSTOOLS/Disable-Host-DNS.command", "$PWD/media/Disable-Host-DNS.command",
)
uninstall = dnsPaths.Replace(uninstall)
if CurrentAgentVersion != HostDNSAgentVersion {
t.Fatalf("CurrentAgentVersion = %d, want Host DNS version %d", CurrentAgentVersion, HostDNSAgentVersion)
}
versionMarker := `"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,`
if !strings.Contains(agent, versionMarker) || !strings.Contains(install, "Reims Guest Tools installed") {
@@ -66,6 +72,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) {
@@ -299,6 +314,75 @@ busy=0
run_uninstall --user-only
`
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
+2 -1
View File
@@ -16,7 +16,8 @@ import (
const SharedFolderAgentVersion = 9
const KeymapAgentVersion = 10
const TimezoneAgentVersion = 11
const CurrentAgentVersion = TimezoneAgentVersion
const HostDNSAgentVersion = 12
const CurrentAgentVersion = HostDNSAgentVersion
type SharedFolderConfig struct {
ID string `json:"id"`
+20 -1
View File
@@ -617,7 +617,7 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
defer f.Close()
for _, file := range []struct{ name, content string }{
{"config", "REIMS_VM='macos-tahoe'\n"},
{"guest-tools.sh", `\"agent_version\":11,`},
{"guest-tools.sh", fmt.Sprintf(`\"agent_version\":%d,`, CurrentAgentVersion)},
{"Install-Reims-Tools.command", "Apply-Timezone.command"},
{"Uninstall-Reims-Tools.command", guestTimezoneSudoers},
{"Apply-Prevent-Sleep-pmset.command", ""},
@@ -636,6 +636,23 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) {
t.Error("tools image config contains a build-time timezone")
}
}
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")
@@ -662,6 +679,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,
"set-timezone.sh": []byte(guestTimezoneHelper),
"Apply-Timezone.command": []byte(guestApplyTimezone),
"apply-timezone-root.sh": []byte(rootScript),
+55 -3
View File
@@ -25,9 +25,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
// installation, pmset, and timezone helper scripts.
// installation, pmset, DNS, and timezone scripts.
func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {
return err
@@ -83,6 +92,23 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error {
Open: func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(guestApplyTimezone)), 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)
}
@@ -449,11 +475,25 @@ 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 [ "$host_dns_active" != true ] || [ "$dns_port" != "$REIMS_HOST_PORT" ] || [ "$dns_token_sha" != "$cur_token_sha" ]; then
host_dns_config_stale=true
fi
fi
timezone_applied=$(current_timezone)
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\":` + strconv.Itoa(CurrentAgentVersion) + `,\"keymap_active\":$keymap_active,\"timezone_applied\":\"$timezone_applied\",\"timezone_helper_ready\":$timezone_helper_ready,\"timezone_error\":\"$timezone_error\"}" \
-d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,\"keymap_active\":$keymap_active,\"timezone_applied\":\"$timezone_applied\",\"timezone_helper_ready\":$timezone_helper_ready,\"timezone_error\":\"$timezone_error\",\"host_dns_active\":$host_dns_active,\"host_dns_config_stale\":$host_dns_config_stale}" \
"$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true
}
@@ -804,7 +844,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
@@ -820,6 +860,18 @@ 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
DNS_DIR=/private/etc/reims-host-dns
if [ -f "$DNS_PLIST" ] || [ -f "$DNS_DIR/dns-proxy.previous-dns" ]; then
DNS_DISABLE="$DNS_DIR/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)
+2 -1
View File
@@ -6,6 +6,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
@@ -22,7 +23,7 @@ func TestGuestAgentKeymapScript(t *testing.T) {
agent := string(GuestAgentScript())
start := strings.Index(agent, "apply_hidutil_carrier() {")
end := strings.Index(agent, "load_conf() {")
if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":11,\"keymap_active\":$keymap_active`) {
if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":`+strconv.Itoa(CurrentAgentVersion)+`,\"keymap_active\":$keymap_active`) {
t.Fatal("missing guest keymap script or version 11 status")
}
for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} {
+42 -6
View File
@@ -78,6 +78,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"`
@@ -103,6 +104,10 @@ type GuestStatus struct {
TimezoneApplied string `json:"timezone_applied,omitempty"`
TimezoneHelperReady bool `json:"timezone_helper_ready,omitempty"`
TimezoneError string `json:"timezone_error,omitempty"`
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"`
}
// LoadOrCreateVMConfig loads an existing per-VM Guest Tools config or generates
@@ -220,6 +225,10 @@ type registeredVM struct {
sharedDir string
sharedRoot sharedRoot
preventSleep bool
hostDNSEnabled bool
hostDNSActive bool
hostDNSReported bool
hostDNSConfigStale bool
guestTimezone string
timezoneApplied string
timezoneHelperReady bool
@@ -274,6 +283,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.
@@ -291,6 +302,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
@@ -338,6 +350,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)
@@ -517,6 +530,7 @@ func (s *Server) RegisterVM(cfg VMConfig) {
cur.sharedDir = cfg.SharedDir
cur.sharedRoot = root
cur.preventSleep = cfg.PreventSleep
cur.hostDNSEnabled = cfg.HostDNSEnabled
cur.guestTimezone = cfg.GuestTimezone
cur.driveSharingEnabled = cfg.DriveSharingEnabled
cur.sharedDriveRoots = driveRoots
@@ -720,7 +734,12 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus {
timezone = vm.timezoneApplied
timezoneError = vm.timezoneError
}
dnsReported := freshStatus && vm.hostDNSReported
return GuestStatus{
HostDNSEnabled: vm.hostDNSEnabled,
HostDNSActive: dnsReported && vm.hostDNSActive,
HostDNSReported: dnsReported,
HostDNSConfigStale: dnsReported && vm.hostDNSConfigStale,
KeymapActive: freshStatus && vm.keymapCarrierEnabled && vm.keymapActive,
Connected: connected,
MountMode: vm.mountMode,
@@ -759,15 +778,25 @@ func (s *Server) touchLastSeen(vmName string) {
s.mu.Unlock()
}
func (s *Server) authenticate(r *http.Request) *registeredVM {
var tok string
func bearerToken(r *http.Request) string {
auth := strings.TrimSpace(r.Header.Get("Authorization"))
const bearerPrefix = "Bearer "
if strings.HasPrefix(auth, bearerPrefix) {
tok = strings.TrimSpace(auth[len(bearerPrefix):])
} else if _, pass, ok := r.BasicAuth(); ok {
token, ok := strings.CutPrefix(auth, "Bearer ")
if !ok {
return ""
}
return strings.TrimSpace(token)
}
func (s *Server) authenticate(r *http.Request) *registeredVM {
tok := bearerToken(r)
if tok == "" {
_, pass, _ := r.BasicAuth()
tok = strings.TrimSpace(pass)
}
return s.authenticateToken(tok)
}
func (s *Server) authenticateToken(tok string) *registeredVM {
if tok == "" {
return nil
}
@@ -786,6 +815,7 @@ func (s *Server) authenticate(r *http.Request) *registeredVM {
sharedDir: vm.sharedDir,
sharedRoot: vm.sharedRoot,
preventSleep: vm.preventSleep,
hostDNSEnabled: vm.hostDNSEnabled,
guestTimezone: vm.guestTimezone,
driveSharingEnabled: vm.driveSharingEnabled,
sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots),
@@ -860,6 +890,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,
"timezone": effectiveTimezone(vm.guestTimezone),
"webdav_path": "/dav/" + vm.name + "/",
"shared_drives": enabledDriveLetters(vm),
@@ -889,6 +920,8 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) {
TimezoneApplied string `json:"timezone_applied"`
TimezoneHelperReady bool `json:"timezone_helper_ready"`
TimezoneError string `json:"timezone_error"`
HostDNSActive *bool `json:"host_dns_active"`
HostDNSConfigStale bool `json:"host_dns_config_stale"`
}
if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil {
http.Error(w, "invalid json", http.StatusBadRequest)
@@ -915,6 +948,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
cur.timezoneApplied = req.TimezoneApplied
cur.timezoneHelperReady = req.TimezoneHelperReady
cur.timezoneError = req.TimezoneError
+4 -2
View File
@@ -141,14 +141,16 @@ func TestNestedVirtFollowsTheVMSwitch(t *testing.T) {
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 {
// reims-ctl 3731afd-p3 quotes the property when returning extra args.
readback := user + " -global 'driver=x86_64-cpu,property=vmx,value=on'"
if got := plugin.UserExtraArgs(readback, ledger); got != user {
t.Fatalf("what is left to the VM's own arguments = %q", got)
}
if err := vmstart.SaveVMNestedVirt(dir, vmstart.VMNestedVirtConfig{}); err != nil {
t.Fatal(err)
}
off := plugin.ReconcileStartIntentsForDriver(on.ExtraArgs, ledger, active, owner, []plugin.StartIntent{prepare("", rep)})
off := plugin.ReconcileStartIntentsForDriver(readback, ledger, active, owner, []plugin.StartIntent{prepare("", rep)})
if off.ExtraArgs != user {
t.Fatalf("launch args after switching off = %q", off.ExtraArgs)
}
+21 -1
View File
@@ -667,13 +667,33 @@ func tokensEqual(a, b []string) bool {
return false
}
for i := range a {
if a[i] != b[i] {
if a[i] != b[i] && unquoteShellToken(a[i]) != unquoteShellToken(b[i]) {
return false
}
}
return true
}
// reims-ctl can add shell quotes when it renders stored arguments. Compare
// their contents without changing the original spelling of unowned tokens.
func unquoteShellToken(token string) string {
if len(token) < 2 || token[0] != token[len(token)-1] {
return token
}
quote, value := token[0], token[1:len(token)-1]
switch quote {
case '\'':
if !strings.ContainsRune(value, '\'') {
return value
}
case '"':
if !strings.ContainsAny(value, "\\\"") {
return value
}
}
return token
}
// SplitShellTokens splits a QEMU extra-args string preserving quoted tokens.
func SplitShellTokens(s string) []string {
var out []string
+19
View File
@@ -448,6 +448,25 @@
"targetDisplayToastMoved": "Switched to {display}",
"targetDisplayToastSaved": "Launch display set to {display}; applies on next start",
"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}",
"guestTimezoneTitle": "System timezone",
"guestTimezoneLoading": "Loading…",
"guestTimezoneHost": "Follow host (recommended)",
+12
View File
@@ -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",
"hostDNSAttachHint": "Attach Guest Tools to apply the proxy",
"hostDNSStaleHint": "Run again in macOS Terminal to repair the proxy",
"hostDNSDisableCmdHint": "Run in macOS Terminal to restore previous DNS settings",
"toastHostDNSOn": "Host DNS proxy enabled",
"toastHostDNSOff": "Host DNS proxy disabled",
"toastFileDelivered": "Sent {name}",
"toastPreventSleepOn": "Prevent-sleep guard enabled",
"toastPreventSleepOff": "Prevent-sleep guard disabled",
+19
View File
@@ -448,6 +448,25 @@
"targetDisplayToastMoved": "已切换至「{display}」",
"targetDisplayToastSaved": "启动显示器已设为「{display}」,下次启动生效",
"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}",
"guestTimezoneTitle": "系统时区",
"guestTimezoneLoading": "读取中…",
"guestTimezoneHost": "跟随宿主机(推荐)",
+12
View File
@@ -195,6 +195,18 @@
"guestToolsUpgradeHint": "macOS 里的工具是旧版,重新运行安装命令即可升级",
"guestToolsPreventSleep": "防止 macOS 睡眠",
"guestToolsSleepActive": "正在保持唤醒",
"guestToolsHostDNS": "宿主机 DNS 代理",
"hostDNSStatusActive": "运行中",
"hostDNSStatusStale": "配置已过期",
"hostDNSStatusPending": "待应用",
"hostDNSStatusStillActive": "macOS 代理未移除",
"hostDNSOffHint": "上游过滤 UDP/53 导致虚拟机无网络时开启",
"hostDNSApplyHint": "在 macOS 终端运行以启用",
"hostDNSAttachHint": "挂载 Guest Tools 后应用代理",
"hostDNSStaleHint": "在 macOS 终端重新运行以修复代理",
"hostDNSDisableCmdHint": "在 macOS 终端运行以恢复原有 DNS 设置",
"toastHostDNSOn": "已开启宿主机 DNS 代理",
"toastHostDNSOff": "已关闭宿主机 DNS 代理",
"toastFileDelivered": "已发送 {name}",
"toastPreventSleepOn": "已开启 macOS 防休眠守护",
"toastPreventSleepOff": "已关闭 macOS 防休眠守护",