diff --git a/NOTICE.md b/NOTICE.md index ff828e8..eabcaa8 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -37,6 +37,53 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +### Unicode CLDR Windows timezone data + +The Windows timezone fallback table uses the +[CLDR 48 Windows zone mappings](https://github.com/unicode-org/cldr/blob/release-48/common/supplemental/windowsZones.xml). + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2004-2025 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +SPDX-License-Identifier: Unicode-3.0 + ## Portable runtime The portable runtime bundle (`reims-runtime-win-x64-.tar.zst`) contains diff --git a/changes/guest-tools-timezone.json b/changes/guest-tools-timezone.json new file mode 100644 index 0000000..29d9ddd --- /dev/null +++ b/changes/guest-tools-timezone.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 35, + "authors": ["reiasu2", "yxc0915"], + "zh": "在 macOS 虚拟机设置中选择跟随宿主机或固定时区。同步需要更新并授权 Guest Tools。 [#66](https://github.com/Nwflower/Reims-Go/pull/66)", + "en": "Set a fixed timezone or follow the host in macOS VM settings. Sync requires updated and authorized Guest Tools. [#66](https://github.com/Nwflower/Reims-Go/pull/66)" +} diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 5cfd705..c3c4a71 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -1,5 +1,5 @@ import * as Alert from '@radix-ui/react-alert-dialog' -import { CircleAlert, Copy, Cpu, Eye, EyeOff, FolderPlus, HardDrive, Info, Keyboard, LucideIcon, Monitor, Shuffle, Trash2, Wrench } from 'lucide-react' +import { Check, CircleAlert, Copy, Cpu, Eye, EyeOff, FolderPlus, HardDrive, Info, Keyboard, LucideIcon, Monitor, Shuffle, Trash2, Wrench } from 'lucide-react' import React, { Suspense, lazy, useEffect, useMemo, useRef, useState } from 'react' import '../i18n/domains/settings.gen' import { I18nKey, parseAppError, t } from '../i18n' @@ -32,6 +32,7 @@ import { import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations' import { useVMStats } from '../lib/vmStats' import { createKeymapRequests, keymapPresetUpdate, type KeymapState } from '../lib/vmKeymap' +import { createVMSettingRequests, type VMSettingState } from '../lib/vmSettingRequests' import { DiskCompactResult, DiskResizeResult, DisplayInfo, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, SharedFolderInfo, SharedFolderMode, SharedFolderSettings, SMBIOSIdentity, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types' import { Button, IconButton } from '../ui/controls' import { Modal } from '../ui/dialog' @@ -90,6 +91,26 @@ const CUSTOM = '__custom' const PRIMARY_DISPLAY_OPT = '__primary' const RES_RE = /^\s*\d{3,5}\s*[x×]\s*\d{3,5}\s*$/i +type VMTimezoneStatus = Awaited> + +const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command' +const GUEST_TIMEZONE_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Timezone.command' + +const GUEST_TIMEZONE_PRESETS: ReadonlyArray<{ value: string; labelKey: I18nKey; detail?: string }> = [ + { value: 'Asia/Shanghai', labelKey: 'guestTimezoneShanghai', detail: 'Asia/Shanghai' }, + { value: 'Asia/Hong_Kong', labelKey: 'guestTimezoneHongKong', detail: 'Asia/Hong_Kong' }, + { value: 'Asia/Taipei', labelKey: 'guestTimezoneTaipei', detail: 'Asia/Taipei' }, + { value: 'Asia/Tokyo', labelKey: 'guestTimezoneTokyo', detail: 'Asia/Tokyo' }, + { value: 'Asia/Seoul', labelKey: 'guestTimezoneSeoul', detail: 'Asia/Seoul' }, + { value: 'Asia/Singapore', labelKey: 'guestTimezoneSingapore', detail: 'Asia/Singapore' }, + { value: 'Europe/London', labelKey: 'guestTimezoneLondon', detail: 'Europe/London' }, + { value: 'Europe/Berlin', labelKey: 'guestTimezoneBerlin', detail: 'Europe/Berlin' }, + { value: 'America/Los_Angeles', labelKey: 'guestTimezoneLosAngeles', detail: 'America/Los_Angeles' }, + { value: 'America/New_York', labelKey: 'guestTimezoneNewYork', detail: 'America/New_York' }, + { value: 'Australia/Sydney', labelKey: 'guestTimezoneSydney', detail: 'Australia/Sydney' }, + { value: 'UTC', labelKey: 'guestTimezoneUTC' }, +] + const normPath = (s: string | undefined) => (s ?? '').replace(/\//g, '\\').toLowerCase() const normRes = (s: string | undefined) => (s ?? '').replace(/\s/g, '').replace(/×/g, 'x').toLowerCase() @@ -202,6 +223,11 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats const [vmPlugins, setVmPlugins] = useState([]) const [vmPluginVals, setVmPluginVals] = useState>>({}) const vmSettingsKey = `${driverID}:${detail.name}` + const activeVMKeyRef = useRef(vmSettingsKey) + activeVMKeyRef.current = vmSettingsKey + const [{ value: tzStatus, error: tzErr, busy: tzBusy }, setTzState] = useState>({ value: null, error: '', busy: false }) + const [tzRequests] = useState(() => createVMSettingRequests(() => activeVMKeyRef.current, + (patch) => setTzState((state) => ({ ...state, ...patch })))) const [smbios, setSmbios] = useState(null) const [smbiosErr, setSmbiosErr] = useState('') const [smbiosReveal, setSmbiosReveal] = useState(false) @@ -384,6 +410,27 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats return () => { active = false } }, [driverID, detail.name, running, hostDisplaysSig, cat === 'display']) + useEffect(() => { + setTzState({ value: null, error: '', busy: tzRequests.isWriting(vmSettingsKey) }) + }, [vmSettingsKey, tzRequests]) + + useEffect(() => { + if (cat !== 'general') return + const { refresh, stop } = tzRequests.watch(vmSettingsKey, () => api.GetVMTimezoneWithDriver(driverID, detail.name)) + void refresh() + const timer = window.setInterval(refresh, 3000) + return () => { stop(); window.clearInterval(timer) } + }, [cat, driverID, detail.name, running, vmSettingsKey, tzRequests]) + + const updateTimezone = async (nextSetting: string) => { + if (busy || displayBusyRef.current || !tzStatus) return + const currentSetting = tzStatus.mode === 'off' ? 'off' : tzStatus.mode === 'custom' ? tzStatus.timezone : 'host' + if (nextSetting === currentSetting) return + if (await tzRequests.write(vmSettingsKey, () => api.SetVMTimezoneWithDriver(driverID, detail.name, nextSetting))) { + onToast({ kind: 'ok', title: tr('guestTimezoneSaved') }) + } + } + useEffect(() => { let active = true setSmbios(null) @@ -552,7 +599,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats } const handleTargetDisplayChange = async (nextValue: string) => { - if (busy || displayBusyRef.current || displayStatus === null) return + if (busy || displayBusyRef.current || tzRequests.isWriting(vmSettingsKey) || displayStatus === null) return const nextTarget = nextValue === PRIMARY_DISPLAY_OPT ? '' : nextValue const currentTarget = displayStatus.target_display ?? '' if (nextTarget.toLowerCase() === currentTarget.toLowerCase()) return @@ -605,7 +652,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats } const handleSave = async () => { - if (busy || displayBusyRef.current || changed.length === 0 || localBlock) return + if (busy || displayBusyRef.current || tzRequests.isWriting(vmSettingsKey) || changed.length === 0 || localBlock) return setErr('') setIssues([]) setBusy(true) @@ -653,6 +700,53 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats // ── Pages ──────────────────────────────────────────────── + const detectedHostTZ = tzStatus?.host_timezone || host.timezone || '' + const tzSelectedValue = tzStatus?.mode === 'custom' ? tzStatus.timezone : tzStatus?.mode + const tzOptions = [ + { value: 'host', label: tr('guestTimezoneHost'), detail: detectedHostTZ || undefined }, + ...GUEST_TIMEZONE_PRESETS.map((p) => ({ + value: p.value, + label: tr(p.labelKey), + detail: p.detail, + })), + ...(tzStatus?.mode === 'custom' && tzStatus.timezone && !GUEST_TIMEZONE_PRESETS.some((p) => p.value === tzStatus.timezone) + ? [{ value: tzStatus.timezone, label: tzStatus.timezone }] + : []), + { value: 'off', label: tr('guestTimezoneOff') }, + ] + let tzDesc: React.ReactNode = tr('guestTimezoneDesc') + let tzCommand = '' + if (tzStatus) { + const tzEffective = tzStatus.effective_timezone + if (tzStatus.mode === 'off') { + tzDesc = tr('guestTimezoneOffDesc') + } else if (detail.guest_tools_disabled) { + tzDesc = {tr('gtStatusOffTip')} + } else if (!tzEffective) { + tzDesc = {tr('guestTimezoneHostUnknown')} + } else if (tzStatus.running && tzStatus.guest_connected) { + const tzFailure = tzStatus.timezone_error + ? {tr('guestTimezoneApplyFailed', { tz: tzEffective })} + : null + if (tzStatus.guest_agent_version < tzStatus.required_agent_version) { + tzDesc = {tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzStatus.required_agent_version })} + if (detail.guest_tools_attached) tzCommand = GUEST_TOOLS_INSTALL_CMD + } else if (!tzStatus.helper_ready) { + const hint = tr(detail.guest_tools_attached ? 'guestTimezoneApplyHint' : 'guestTimezoneApplyAttachHint') + tzDesc = tzFailure ?
{tzFailure}{hint}
: hint + if (detail.guest_tools_attached) tzCommand = GUEST_TIMEZONE_APPLY_CMD + } else if (tzFailure) { + tzDesc = tzFailure + } else if (tzStatus.guest_applied === tzEffective) { + tzDesc = + } else { + tzDesc = tr('guestTimezoneSyncing', { tz: tzEffective }) + } + } else if (detail.guest_tools_attached) { + tzCommand = GUEST_TOOLS_INSTALL_CMD + } + } + const general = ( <> @@ -674,6 +768,29 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats /> } /> + + } + block={tzCommand ? ( +
+ {tzCommand} + {onCopy && ( + } onClick={() => onCopy(tzCommand)} /> + )} +
+ ) : undefined} + />
@@ -1634,7 +1751,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats title={tr('settingsTitle', { name: detail.name })} subtitle={`${tr(running ? 'state_running' : 'state_stopped')} · ${tr('appliesNextStart')}`} closeLabel={tr('close')} - dismissable={!busy && !displayBusy && !confirmRWFolder} + dismissable={!busy && !displayBusy && !tzBusy && !confirmRWFolder} onClose={onClose} >
@@ -1683,8 +1800,8 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats )} - - + diff --git a/frontend/src/components/VMPage.tsx b/frontend/src/components/VMPage.tsx index 6b6b2f4..e818bd6 100644 --- a/frontend/src/components/VMPage.tsx +++ b/frontend/src/components/VMPage.tsx @@ -973,7 +973,7 @@ export const VMPage: React.FC = ({ 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 < 10 + const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < 11 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 diff --git a/frontend/src/i18n/domains/settings.gen.ts b/frontend/src/i18n/domains/settings.gen.ts index 4b8e02a..e376d83 100644 --- a/frontend/src/i18n/domains/settings.gen.ts +++ b/frontend/src/i18n/domains/settings.gen.ts @@ -219,6 +219,33 @@ export const settingsZh: Record = { "guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言", "guestLangShort": "系统语言", "guestMemory": "分配内存", + "guestTimezoneApplyAttachHint": "先在虚拟机详情页挂载 Guest Tools 镜像,即可查看授权时区同步的命令", + "guestTimezoneApplyFailed": "Guest Tools 无法在 macOS 中应用时区 {tz}", + "guestTimezoneApplyHint": "在 macOS 终端运行以下命令,一次性授权时区同步", + "guestTimezoneBerlin": "柏林", + "guestTimezoneDesc": "经 Guest Tools 即时生效", + "guestTimezoneHongKong": "香港", + "guestTimezoneHost": "跟随宿主机(推荐)", + "guestTimezoneHostUnknown": "未探测到宿主机时区,可手动选择固定时区", + "guestTimezoneLoading": "读取中…", + "guestTimezoneLondon": "伦敦", + "guestTimezoneLosAngeles": "洛杉矶", + "guestTimezoneNewYork": "纽约", + "guestTimezoneOff": "不管理(由 macOS 自行设置)", + "guestTimezoneOffDesc": "不同步时区,由 macOS 系统设置管理", + "guestTimezoneSaved": "已保存时区设置", + "guestTimezoneSeoul": "首尔", + "guestTimezoneShanghai": "上海", + "guestTimezoneSingapore": "新加坡", + "guestTimezoneSydney": "悉尼", + "guestTimezoneSynced": "已同步:{tz}", + "guestTimezoneSyncing": "正在通过 Guest Tools 同步到 {tz}", + "guestTimezoneTaipei": "台北", + "guestTimezoneTitle": "系统时区", + "guestTimezoneTokyo": "东京", + "guestTimezoneUTC": "UTC(协调世界时)", + "guestTimezoneUpgradeAttachHint": "先在虚拟机详情页挂载 Guest Tools 镜像,即可查看升级到版本 {version} 的命令", + "guestTimezoneUpgradeHint": "在 macOS 终端运行以下命令,将 Guest Tools 升级到版本 {version}", "guestToolsConnected": "已连接", "guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效", "guestToolsReady": "已配置", @@ -658,6 +685,33 @@ export const settingsEn: Record = { "guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window", "guestLangShort": "System language", "guestMemory": "Memory", + "guestTimezoneApplyAttachHint": "Attach the Guest Tools image on the VM details page to see the command for authorizing timezone sync", + "guestTimezoneApplyFailed": "Guest Tools could not apply {tz} in macOS", + "guestTimezoneApplyHint": "Run the command below once in macOS Terminal to authorize timezone sync", + "guestTimezoneBerlin": "Berlin", + "guestTimezoneDesc": "Applies immediately via Guest Tools", + "guestTimezoneHongKong": "Hong Kong", + "guestTimezoneHost": "Follow host (recommended)", + "guestTimezoneHostUnknown": "Host timezone was not detected; pick a fixed timezone", + "guestTimezoneLoading": "Loading…", + "guestTimezoneLondon": "London", + "guestTimezoneLosAngeles": "Los Angeles", + "guestTimezoneNewYork": "New York", + "guestTimezoneOff": "Do not manage (set in macOS)", + "guestTimezoneOffDesc": "Timezone sync is off; managed in macOS System Settings", + "guestTimezoneSaved": "Timezone setting saved", + "guestTimezoneSeoul": "Seoul", + "guestTimezoneShanghai": "Shanghai", + "guestTimezoneSingapore": "Singapore", + "guestTimezoneSydney": "Sydney", + "guestTimezoneSynced": "Synced: {tz}", + "guestTimezoneSyncing": "Syncing to {tz} via Guest Tools", + "guestTimezoneTaipei": "Taipei", + "guestTimezoneTitle": "System timezone", + "guestTimezoneTokyo": "Tokyo", + "guestTimezoneUTC": "UTC", + "guestTimezoneUpgradeAttachHint": "Attach the Guest Tools image on the VM details page to see the command for updating to version {version}", + "guestTimezoneUpgradeHint": "Run the command below in macOS Terminal to update Guest Tools to version {version}", "guestToolsConnected": "Connected", "guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately", "guestToolsReady": "Configured", diff --git a/frontend/src/i18n/keys.gen.ts b/frontend/src/i18n/keys.gen.ts index 51792de..a3ac454 100644 --- a/frontend/src/i18n/keys.gen.ts +++ b/frontend/src/i18n/keys.gen.ts @@ -368,6 +368,33 @@ export type I18nKey = | "guestLangZhHansUS" | "guestLangZhHantUS" | "guestMemory" + | "guestTimezoneApplyAttachHint" + | "guestTimezoneApplyFailed" + | "guestTimezoneApplyHint" + | "guestTimezoneBerlin" + | "guestTimezoneDesc" + | "guestTimezoneHongKong" + | "guestTimezoneHost" + | "guestTimezoneHostUnknown" + | "guestTimezoneLoading" + | "guestTimezoneLondon" + | "guestTimezoneLosAngeles" + | "guestTimezoneNewYork" + | "guestTimezoneOff" + | "guestTimezoneOffDesc" + | "guestTimezoneSaved" + | "guestTimezoneSeoul" + | "guestTimezoneShanghai" + | "guestTimezoneSingapore" + | "guestTimezoneSydney" + | "guestTimezoneSynced" + | "guestTimezoneSyncing" + | "guestTimezoneTaipei" + | "guestTimezoneTitle" + | "guestTimezoneTokyo" + | "guestTimezoneUTC" + | "guestTimezoneUpgradeAttachHint" + | "guestTimezoneUpgradeHint" | "guestToolsConnected" | "guestToolsModeSync" | "guestToolsModeWebDAV" diff --git a/frontend/src/lib/vmKeymap.ts b/frontend/src/lib/vmKeymap.ts index 51564df..f523b76 100644 --- a/frontend/src/lib/vmKeymap.ts +++ b/frontend/src/lib/vmKeymap.ts @@ -1,5 +1,5 @@ -import { parseAppError } from '../i18n' import type { VMKeymapPreset, VMKeymapStatus, VMKeymapUpdate } from '../types' +import { createVMSettingRequests } from './vmSettingRequests' type KeymapAPI = { GetVMKeymap(name: string): Promise @@ -14,48 +14,19 @@ export function keymapPresetUpdate(current: VMKeymapStatus, preset: VMKeymapPres } export function createKeymapRequests(api: KeymapAPI, activeVM: () => string, update: (patch: Partial) => void) { - const writes = new Set() - const revisions = new Map() + const requests = createVMSettingRequests(activeVM, ({ value, ...patch }) => { + update(value === undefined ? patch : { ...patch, keymap: value }) + }) return { initial(name: string): KeymapState { - return { keymap: null, error: '', busy: writes.has(name) } + return { keymap: null, error: '', busy: requests.isWriting(name) } }, watch(name: string) { - let active = true - let pending = false - return { - async refresh() { - if (!active || pending || writes.has(name)) return - const revision = revisions.get(name) - const current = () => active && activeVM() === name && revision === revisions.get(name) - pending = true - try { - const keymap = await api.GetVMKeymap(name) - if (current()) update({ keymap, error: '' }) - } catch (error) { - if (current()) update({ error: parseAppError(error).summary }) - } finally { - pending = false - } - }, - stop() { active = false }, - } + return requests.watch(name, () => api.GetVMKeymap(name)) }, - async write(name: string, request: VMKeymapUpdate) { - if (writes.has(name)) return - revisions.set(name, (revisions.get(name) ?? 0) + 1) - writes.add(name) - update({ busy: true, error: '' }) - try { - const keymap = await api.SetVMKeymap(name, request) - if (activeVM() === name) update({ keymap }) - } catch (error) { - if (activeVM() === name) update({ error: parseAppError(error).summary }) - } finally { - writes.delete(name) - if (activeVM() === name) update({ busy: false }) - } + write(name: string, request: VMKeymapUpdate) { + return requests.write(name, () => api.SetVMKeymap(name, request)) }, } } diff --git a/frontend/src/lib/vmSettingRequests.ts b/frontend/src/lib/vmSettingRequests.ts new file mode 100644 index 0000000..c431884 --- /dev/null +++ b/frontend/src/lib/vmSettingRequests.ts @@ -0,0 +1,51 @@ +import { parseAppError } from '../i18n' + +export type VMSettingState = { value: T | null; error: string; busy: boolean } + +export function createVMSettingRequests(activeVM: () => string, update: (patch: Partial>) => void) { + const writes = new Set() + const revisions = new Map() + + return { + isWriting: (name: string) => writes.has(name), + watch(name: string, read: () => Promise) { + let active = true + let pending = false + return { + async refresh() { + if (!active || pending || writes.has(name)) return + const revision = revisions.get(name) + const current = () => active && activeVM() === name && revision === revisions.get(name) + pending = true + try { + const value = await read() + if (current()) update({ value, error: '' }) + } catch (error) { + if (current()) update({ error: parseAppError(error).summary }) + } finally { + pending = false + } + }, + stop() { active = false }, + } + }, + async write(name: string, save: () => Promise): Promise { + if (writes.has(name)) return false + revisions.set(name, (revisions.get(name) ?? 0) + 1) + writes.add(name) + update({ busy: true, error: '' }) + try { + const value = await save() + if (activeVM() !== name) return false + update({ value }) + return true + } catch (error) { + if (activeVM() === name) update({ error: parseAppError(error).summary }) + return false + } finally { + writes.delete(name) + if (activeVM() === name) update({ busy: false }) + } + }, + } +} diff --git a/frontend/wailsjs/go/app/App.d.ts b/frontend/wailsjs/go/app/App.d.ts index ab52fd2..6abc669 100644 --- a/frontend/wailsjs/go/app/App.d.ts +++ b/frontend/wailsjs/go/app/App.d.ts @@ -169,6 +169,10 @@ export function GetVMThumbnail(arg1:string):Promise; export function GetVMThumbnailWithDriver(arg1:string,arg2:string):Promise; +export function GetVMTimezone(arg1:string):Promise; + +export function GetVMTimezoneWithDriver(arg1:string,arg2:string):Promise; + export function InspectPluginArchive(arg1:string):Promise; export function InstallAppUpdate():Promise; @@ -307,6 +311,10 @@ export function SetVMSSHUserWithDriver(arg1:string,arg2:string,arg3:string):Prom export function SetVMSharedFolderMode(arg1:string,arg2:string,arg3:string):Promise; +export function SetVMTimezone(arg1:string,arg2:string):Promise; + +export function SetVMTimezoneWithDriver(arg1:string,arg2:string,arg3:string):Promise; + export function ShowMainWindow():Promise; export function StartVM(arg1:string):Promise; diff --git a/frontend/wailsjs/go/app/App.js b/frontend/wailsjs/go/app/App.js index 9c6cb94..fd4cc0a 100644 --- a/frontend/wailsjs/go/app/App.js +++ b/frontend/wailsjs/go/app/App.js @@ -318,6 +318,14 @@ export function GetVMThumbnailWithDriver(arg1, arg2) { return window['go']['app']['App']['GetVMThumbnailWithDriver'](arg1, arg2); } +export function GetVMTimezone(arg1) { + return window['go']['app']['App']['GetVMTimezone'](arg1); +} + +export function GetVMTimezoneWithDriver(arg1, arg2) { + return window['go']['app']['App']['GetVMTimezoneWithDriver'](arg1, arg2); +} + export function InspectPluginArchive(arg1) { return window['go']['app']['App']['InspectPluginArchive'](arg1); } @@ -594,6 +602,14 @@ export function SetVMSharedFolderMode(arg1, arg2, arg3) { return window['go']['app']['App']['SetVMSharedFolderMode'](arg1, arg2, arg3); } +export function SetVMTimezone(arg1, arg2) { + return window['go']['app']['App']['SetVMTimezone'](arg1, arg2); +} + +export function SetVMTimezoneWithDriver(arg1, arg2, arg3) { + return window['go']['app']['App']['SetVMTimezoneWithDriver'](arg1, arg2, arg3); +} + export function ShowMainWindow() { return window['go']['app']['App']['ShowMainWindow'](); } diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 48c6d5c..947ca70 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -1,5 +1,38 @@ export namespace app { + export class VMTimezoneStatus { + mode: string; + timezone: string; + host_timezone: string; + effective_timezone: string; + guest_applied: string; + timezone_error: string; + helper_ready: boolean; + guest_connected: boolean; + guest_agent_version: number; + required_agent_version: number; + running: boolean; + + static createFrom(source: any = {}) { + return new VMTimezoneStatus(source); + } + + constructor(source: any = {}) { + if (typeof source === "string") source = JSON.parse(source); + this.mode = source?.mode; + this.timezone = source?.timezone; + this.host_timezone = source?.host_timezone; + this.effective_timezone = source?.effective_timezone; + this.guest_applied = source?.guest_applied; + this.timezone_error = source?.timezone_error; + this.helper_ready = source?.helper_ready; + this.guest_connected = source?.guest_connected; + this.guest_agent_version = source?.guest_agent_version; + this.required_agent_version = source?.required_agent_version; + this.running = source?.running; + } + } + export class VMKeymapUpdate { preset: string; bindings: Record; @@ -854,6 +887,39 @@ export namespace driver { } +export namespace guesttools { + export class GuestStatus { + keymap_active: boolean; + connected: boolean; + mount_mode?: string; + prevent_sleep: boolean; + sleep_active: boolean; + agent_version?: number; + last_seen?: string; + timezone_applied?: string; + timezone_helper_ready?: boolean; + timezone_error?: string; + + static createFrom(source: any = {}) { + return new GuestStatus(source); + } + + constructor(source: any = {}) { + if (typeof source === "string") source = JSON.parse(source); + this.keymap_active = source?.keymap_active; + this.connected = source?.connected; + this.mount_mode = source?.mount_mode; + this.prevent_sleep = source?.prevent_sleep; + this.sleep_active = source?.sleep_active; + this.agent_version = source?.agent_version; + this.last_seen = source?.last_seen; + this.timezone_applied = source?.timezone_applied; + this.timezone_helper_ready = source?.timezone_helper_ready; + this.timezone_error = source?.timezone_error; + } + } +} + export namespace host { export class AudioInfo { @@ -1049,6 +1115,7 @@ export namespace host { export class Report { os: string; arch: string; + timezone?: string; logical_cpus: number; physical_cores: number; has_hybrid_cores: boolean; @@ -1098,6 +1165,7 @@ export namespace host { if ('string' === typeof source) source = JSON.parse(source); this.os = source["os"]; this.arch = source["arch"]; + this.timezone = source["timezone"]; this.logical_cpus = source["logical_cpus"]; this.physical_cores = source["physical_cores"]; this.has_hybrid_cores = source["has_hybrid_cores"]; diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index c667e56..7352e72 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -86,7 +86,9 @@ func (a *App) buildGuestToolsImage(vmName, vmDir string) error { if err != nil { return err } + unlock := a.lockGuestToolsVM(vmName) cfg, err := guesttools.LoadOrCreateVMConfig(vmDir, vmName, a.vmSharedDir(vmName), port) + unlock() if err != nil { return err } diff --git a/internal/app/timezone_flow.go b/internal/app/timezone_flow.go new file mode 100644 index 0000000..6ebd838 --- /dev/null +++ b/internal/app/timezone_flow.go @@ -0,0 +1,126 @@ +package app + +import ( + "fmt" + "os" + "time" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/guesttools" + "github.com/Nwflower/reims-go/internal/host" +) + +type VMTimezoneStatus struct { + Mode string `json:"mode"` + Timezone string `json:"timezone"` + HostTimezone string `json:"host_timezone"` + EffectiveTimezone string `json:"effective_timezone"` + GuestApplied string `json:"guest_applied"` + TimezoneError string `json:"timezone_error"` + HelperReady bool `json:"helper_ready"` + GuestConnected bool `json:"guest_connected"` + GuestAgentVersion int `json:"guest_agent_version"` + RequiredAgentVersion int `json:"required_agent_version"` + Running bool `json:"running"` +} + +func (a *App) GetVMTimezone(name string) (VMTimezoneStatus, error) { + return a.GetVMTimezoneWithDriver("", name) +} + +func (a *App) GetVMTimezoneWithDriver(driverID, name string) (VMTimezoneStatus, error) { + vm, err := a.resolveVMInfo(driverID, name) + if err != nil { + return VMTimezoneStatus{}, err + } + unlock := a.lockGuestToolsVM(vm.Name) + defer unlock() + cfg, _, err := guesttools.ReadVMConfigStrict(vm.Directory) + if err != nil { + return VMTimezoneStatus{}, err + } + return a.timezoneStatus(vm, cfg.GuestTimezone), nil +} + +func (a *App) SetVMTimezone(name, setting string) (VMTimezoneStatus, error) { + return a.SetVMTimezoneWithDriver("", name, setting) +} + +func (a *App) SetVMTimezoneWithDriver(driverID, name, setting string) (VMTimezoneStatus, error) { + if err := a.requireWritableDataRoot(); err != nil { + return VMTimezoneStatus{}, err + } + switch setting { + case "", "host", "off": + default: + if !host.ValidateIANATimezone(setting) { + return VMTimezoneStatus{}, fmt.Errorf("invalid IANA timezone: %q", setting) + } + } + epoch := a.vmDeleteEpoch(name) + vm, err := a.resolveVMInfo(driverID, name) + if err != nil { + return VMTimezoneStatus{}, err + } + if vm.Directory == "" { + return VMTimezoneStatus{}, fmt.Errorf("VM %s has no directory", vm.Name) + } + unlock := a.lockGuestToolsVM(vm.Name) + defer unlock() + if a.vmDeleteEpoch(name) != epoch { + return VMTimezoneStatus{}, os.ErrNotExist + } + if vm.Ref().DriverID == driver.BuiltinReimsMacOSDriverID { + if err := requireGuestToolsVM(vm.Directory); err != nil { + return VMTimezoneStatus{}, err + } + } + a.mu.Lock() + srv := a.guestTools + a.mu.Unlock() + cfg, err := guesttools.LoadOrCreateVMConfig(vm.Directory, vm.Name, "", 0) + if err != nil { + return VMTimezoneStatus{}, err + } + cfg.DriverID = vm.DriverID + cfg.GuestTimezone = setting + if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil { + return VMTimezoneStatus{}, err + } + if srv != nil { + srv.SetTimezone(vm.Ref().Key(), cfg.Token, setting) + } + a.emitStateChanged() + return a.timezoneStatus(vm, setting), nil +} + +func (a *App) timezoneStatus(vm driver.VMInfo, setting string) VMTimezoneStatus { + hostTZ := host.DetectHostTimezone() + status := VMTimezoneStatus{ + HostTimezone: hostTZ, + EffectiveTimezone: guesttools.ResolveEffectiveTimezone(setting, hostTZ), + RequiredAgentVersion: guesttools.TimezoneAgentVersion, + Running: vm.State == "running", + } + switch setting { + case "", "host": + status.Mode = "host" + case "off": + status.Mode = "off" + default: + status.Mode = "custom" + status.Timezone = setting + } + a.mu.Lock() + srv := a.guestTools + a.mu.Unlock() + if srv != nil && status.Running { + guest := srv.Status(vm.Ref().Key(), 30*time.Second) + status.GuestApplied = guest.TimezoneApplied + status.TimezoneError = guest.TimezoneError + status.HelperReady = guest.TimezoneHelperReady + status.GuestConnected = guest.Connected + status.GuestAgentVersion = guest.AgentVersion + } + return status +} diff --git a/internal/app/timezone_flow_test.go b/internal/app/timezone_flow_test.go new file mode 100644 index 0000000..9761d1d --- /dev/null +++ b/internal/app/timezone_flow_test.go @@ -0,0 +1,147 @@ +package app + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "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 TestVMTimezone(t *testing.T) { + const driverID = driver.BuiltinReimsMacOSDriverID + vm := folderTestVM(t, t.TempDir()) + drv := &appSecondDriver{id: driverID, vms: []driver.VMInfo{{Name: vm.Name, DriverID: driverID, Directory: vm.Directory, State: "running"}}} + reg := plugin.NewRegistry(nil) + if err := reg.Register(plugin.PluginDef{ + Manifest: plugin.Manifest{ID: "test.timezone", Version: "1.0.0"}, Source: plugin.SourceBuiltin, Desired: true, + Activate: func(_ context.Context, scope *plugin.Scope) error { + reg.RegisterGuestDriver(scope, driverID, drv) + return nil + }, + }); err != nil { + t.Fatal(err) + } + reg.Reconcile(context.Background()) + 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{}, guestTools: srv, + lifecycleSvc: vmlifecycle.New(reg, driver.NewRouter(reg, nil), nil), + } + + initial, err := a.GetVMTimezone(vm.Name) + if err != nil || initial.Mode != "host" || initial.EffectiveTimezone != initial.HostTimezone || + !initial.Running || initial.RequiredAgentVersion != 11 || initial.GuestConnected { + t.Fatalf("initial timezone = %+v, %v", initial, err) + } + if _, err := os.Stat(filepath.Join(vm.Directory, guesttools.ConfigFileName)); !os.IsNotExist(err) { + t.Fatalf("reading timezone created a config: %v", err) + } + + cfg, err := guesttools.LoadOrCreateVMConfig(vm.Directory, vm.Name, t.TempDir(), port) + if err != nil { + t.Fatal(err) + } + cfg.PreventSleep = true + if err := guesttools.SaveVMConfig(vm.Directory, cfg); err != nil { + t.Fatal(err) + } + srv.RegisterVM(cfg) + checkLiveTimezone := func(t *testing.T, want string) { + t.Helper() + req, err := http.NewRequest(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) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + var live struct { + Timezone string `json:"timezone"` + } + if err := json.NewDecoder(res.Body).Decode(&live); err != nil || res.StatusCode != http.StatusOK || live.Timezone != want { + t.Fatalf("live config = %+v, HTTP %d, %v, want timezone %q", live, res.StatusCode, err, want) + } + } + for _, tc := range []struct{ setting, mode, custom, effective string }{ + {"host", "host", "", initial.HostTimezone}, + {"off", "off", "", ""}, + {"America/Argentina/Buenos_Aires", "custom", "America/Argentina/Buenos_Aires", "America/Argentina/Buenos_Aires"}, + {"", "host", "", initial.HostTimezone}, + } { + got, err := a.SetVMTimezone(vm.Name, tc.setting) + if err != nil || got.Mode != tc.mode || got.Timezone != tc.custom || got.EffectiveTimezone != tc.effective { + t.Fatalf("set %q = %+v, %v", tc.setting, got, err) + } + stored, _, err := guesttools.ReadVMConfigStrict(vm.Directory) + if err != nil || stored.GuestTimezone != tc.setting || stored.Token != cfg.Token || + stored.Port != cfg.Port || stored.SharedDir != cfg.SharedDir || !stored.PreventSleep { + t.Fatalf("stored timezone = %q, other settings preserved = %v, %v", + stored.GuestTimezone, stored.Token == cfg.Token && stored.Port == cfg.Port && stored.SharedDir == cfg.SharedDir && stored.PreventSleep, err) + } + persisted, err := a.GetVMTimezoneWithDriver(driverID, vm.Name) + if err != nil || persisted.Mode != tc.mode || persisted.EffectiveTimezone != tc.effective { + t.Fatalf("get after set = %+v, %v", persisted, err) + } + checkLiveTimezone(t, tc.effective) + } + if _, err := a.SetVMTimezoneWithDriver(driverID, vm.Name, "../Asia/Shanghai"); err == nil { + t.Fatal("accepted invalid timezone") + } + stored, _, err := guesttools.ReadVMConfigStrict(vm.Directory) + if err != nil || stored.GuestTimezone != "" { + t.Fatalf("invalid timezone changed persisted setting: %q, %v", stored.GuestTimezone, err) + } + t.Run("guest_apply_failed", func(t *testing.T) { + req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("http://127.0.0.1:%d/v1/status", port), + bytes.NewBufferString(`{"agent_version":11,"timezone_helper_ready":true,"timezone_error":"apply_failed"}`)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+cfg.Token) + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + res.Body.Close() + status, err := a.GetVMTimezoneWithDriver(driverID, vm.Name) + if err != nil || res.StatusCode != http.StatusOK || !status.GuestConnected || + !status.HelperReady || status.TimezoneError != "apply_failed" { + t.Fatalf("guest timezone status = %+v, HTTP %d, %v", status, res.StatusCode, err) + } + }) + t.Run("read_only", func(t *testing.T) { + path := filepath.Join(vm.Directory, guesttools.ConfigFileName) + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + a.root = dataroot.Status{ReadOnly: true, Reason: dataroot.ReasonNewer} + if got, err := a.SetVMTimezoneWithDriver(driverID, vm.Name, "off"); err == nil || got != (VMTimezoneStatus{}) { + t.Fatalf("set on read-only root = %+v, %v", got, err) + } + after, err := os.ReadFile(path) + if err != nil || !bytes.Equal(before, after) { + t.Fatalf("read-only update changed config on disk: %v", err) + } + checkLiveTimezone(t, initial.HostTimezone) + }) +} diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 55e21c6..b094577 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -462,6 +462,7 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e res := fs.String("resolution", "", "Window resolution WIDTHxHEIGHT") audioBackend := fs.String("audio-backend", "", "Audio backend (auto, dsound, none, wav)") guestLang := fs.String("guest-lang", "", "macOS boot/recovery language prev-lang:kbd") + nestedVirt := fs.Bool("nested-virt", false, "Enable nested virtualization on the next cold start (macOS only)") if err := fs.Parse(args[1:]); err != nil { return err } @@ -487,6 +488,11 @@ func cmdVM(cfg *config.Config, loc i18n.Locale, args []string, viaWindow bool) e if *guestLang != "" { changes["guest_lang"] = *guestLang } + fs.Visit(func(f *flag.Flag) { + if f.Name == "nested-virt" { + changes["nested_virt"] = *nestedVirt + } + }) return setVM(ctx, cfg, *driverID, fs.Arg(0), changes) case "start": fs := flag.NewFlagSet("vm start", flag.ContinueOnError) diff --git a/internal/guesttools/drive_mount_test.go b/internal/guesttools/drive_mount_test.go index a71d667..0f1d4be 100644 --- a/internal/guesttools/drive_mount_test.go +++ b/internal/guesttools/drive_mount_test.go @@ -45,8 +45,8 @@ print $mounts "$url on $target (webdav, read-only)\n"; t.Fatal(err) } script := string(GuestAgentScript()) - if DriveShareAgentVersion != 8 || !strings.Contains(script, `"agent_version\":10,`) { - t.Fatal("Windows drive sharing requires version 8 and the generated agent reports version 10") + if DriveShareAgentVersion != 8 || !strings.Contains(script, `"agent_version\":11,`) { + t.Fatal("Windows drive sharing requires version 8 and the generated agent reports version 11") } harness := `set -eu PATH="$PWD:/usr/bin:/bin:$PATH" @@ -128,8 +128,8 @@ test "$(wc -l <"$MOUNT_STATE")" -eq 1 } func TestShellSingleQuoteAndAgentVersion(t *testing.T) { - if !strings.Contains(string(GuestAgentScript()), `\"agent_version\":10,`) { - t.Fatal("GuestAgentScript must report agent_version 10") + if !strings.Contains(string(GuestAgentScript()), `\"agent_version\":11,`) { + t.Fatal("GuestAgentScript must report agent_version 11") } if DriveShareAgentVersion != 8 { t.Fatalf("DriveShareAgentVersion = %d, want 8", DriveShareAgentVersion) diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 2129aae..ca53782 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -37,14 +37,15 @@ func TestGuestAgentFolderMounts(t *testing.T) { } } agent, uninstall, install := string(GuestAgentScript()), string(GuestUninstallScript()), string(GuestInstallScript()) - if CurrentAgentVersion != KeymapAgentVersion { - t.Fatalf("CurrentAgentVersion = %d, want keymap version %d", CurrentAgentVersion, KeymapAgentVersion) + if CurrentAgentVersion != TimezoneAgentVersion { + t.Fatalf("CurrentAgentVersion = %d, want timezone version %d", CurrentAgentVersion, TimezoneAgentVersion) } versionMarker := `"agent_version\":` + strconv.Itoa(CurrentAgentVersion) + `,` if !strings.Contains(agent, versionMarker) || !strings.Contains(install, "Reims Guest Tools installed") { t.Fatal("Guest Tools scripts do not advertise the current agent version") } - mounts := scriptSection(t, agent, "urlencode() {", "\nhash_file() {") + + mounts := guestTimezoneAgent + guestTimezoneConfig + + scriptSection(t, agent, "urlencode() {", "\nhash_file() {") + scriptSection(t, agent, "\ndrive_mount_failures=", "\nreport_status() {") t.Run("reconcile", func(t *testing.T) { run(t, folderShellFixture+mounts+folderReconcileChecks, "-s") @@ -58,7 +59,7 @@ func TestGuestAgentFolderMounts(t *testing.T) { for _, name := range []string{"owned", "user_file", "user_link"} { t.Run("uninstall_"+name, func(t *testing.T) { run(t, folderShellFixture+folderUninstallSetup+ - "\nrun_uninstall() {\n"+uninstall+"\n}\nrun_uninstall\n"+folderUninstallChecks, "-s", "--", name) + "\nrun_uninstall() {\n"+uninstall+"\n}\nrun_uninstall --user-only\n"+folderUninstallChecks, "-s", "--", name) }) } t.Run("uninstall_busy", func(t *testing.T) { @@ -125,7 +126,7 @@ curl() { shift done case "$1" in - */v1/config) printf '{"shared_folders_count":%s,"shared_drives":[]}\n' "$count" ;; + */v1/config) printf '{"shared_folders_count":%s,"shared_drives":[],"timezone":""}\n' "$count" ;; */v1/folders) printf 'folders\n' >> calls [ "$format" = '\n%{http_code}' ] || return 1 @@ -284,7 +285,7 @@ esac const folderUninstallBusyChecks = ` busy=1 -if (run_uninstall) > uninstall_stdout 2> uninstall_stderr; then +if (run_uninstall --user-only) > uninstall_stdout 2> uninstall_stderr; then echo "busy uninstall succeeded" >&2 exit 1 fi @@ -295,7 +296,7 @@ expect "$(grep -c 'uninstalled' uninstall_stdout || true)" 0 expect "$(readlink "$FOLDER_DESKTOP_LINK")" "$FOLDER_MOUNT_ROOT" grep -Fq "on $FOLDER_MOUNT_ROOT/work (" mounts busy=0 -run_uninstall +run_uninstall --user-only ` const folderOwnershipChecks = ` diff --git a/internal/guesttools/folder_share.go b/internal/guesttools/folder_share.go index e43e97d..2090138 100644 --- a/internal/guesttools/folder_share.go +++ b/internal/guesttools/folder_share.go @@ -15,7 +15,8 @@ import ( const SharedFolderAgentVersion = 9 const KeymapAgentVersion = 10 -const CurrentAgentVersion = KeymapAgentVersion +const TimezoneAgentVersion = 11 +const CurrentAgentVersion = TimezoneAgentVersion type SharedFolderConfig struct { ID string `json:"id"` diff --git a/internal/guesttools/guesttools_test.go b/internal/guesttools/guesttools_test.go index 8ee7263..ded141b 100644 --- a/internal/guesttools/guesttools_test.go +++ b/internal/guesttools/guesttools_test.go @@ -606,7 +606,7 @@ func TestServerWebDAVAuthAndOperations(t *testing.T) { func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) { tmp := t.TempDir() imgPath := filepath.Join(tmp, "reims-tools.img") - cfg := VMConfig{VMName: "macos-tahoe", Token: strings.Repeat("ab", 32), Port: 19847, PreventSleep: true} + cfg := VMConfig{VMName: "macos-tahoe", Token: strings.Repeat("ab", 32), Port: 19847, PreventSleep: true, GuestTimezone: "Etc/GMT+8"} if err := BuildToolsDiskImage(imgPath, cfg); err != nil { t.Fatalf("BuildToolsDiskImage: %v", err) } @@ -615,37 +615,56 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) { t.Fatal(err) } defer f.Close() - for _, name := range []string{ - "config", - "guest-tools.sh", - "Install-Reims-Tools.command", - "Uninstall-Reims-Tools.command", - "Apply-Prevent-Sleep-pmset.command", + for _, file := range []struct{ name, content string }{ + {"config", "REIMS_VM='macos-tahoe'\n"}, + {"guest-tools.sh", `\"agent_version\":11,`}, + {"Install-Reims-Tools.command", "Apply-Timezone.command"}, + {"Uninstall-Reims-Tools.command", guestTimezoneSudoers}, + {"Apply-Prevent-Sleep-pmset.command", ""}, + {"set-timezone.sh", guestTimezoneHelper}, + {"Apply-Timezone.command", guestApplyTimezone}, } { - if _, sz, err := installer.FindFileInHFSPlusImage(f, name); err != nil || sz == 0 { - t.Fatalf("missing %s in REIMSTOOLS image: err=%v size=%d", name, err, sz) + offset, sz, err := installer.FindFileInHFSPlusImage(f, file.name) + if err != nil || sz == 0 { + t.Fatalf("missing %s in REIMSTOOLS image: err=%v size=%d", file.name, err, sz) + } + data := make([]byte, sz) + if _, err := f.ReadAt(data, offset); err != nil || !strings.Contains(string(data), file.content) { + t.Errorf("unexpected %s contents: %v", file.name, err) + } + if file.name == "config" && strings.Contains(string(data), "REIMS_TIMEZONE=") { + t.Error("tools image config contains a build-time timezone") } } // Syntax check every generated POSIX script if sh is available. shBin, err := exec.LookPath("sh") + if runtime.GOOS == "windows" { + const gitSH = "C:/Program Files/Git/bin/sh.exe" + if _, statErr := os.Stat(gitSH); statErr == nil { + shBin, err = gitSH, nil + } + } if err != nil { - for _, cand := range []string{`C:\Program Files\Git\bin\sh.exe`, `D:\DevTools\msys64\usr\bin\sh.exe`} { - if _, serr := os.Stat(cand); serr == nil { - shBin = cand - break - } + const msysSH = `D:\DevTools\msys64\usr\bin\sh.exe` + if _, statErr := os.Stat(msysSH); statErr == nil { + shBin = msysSH } } if shBin == "" { return } lockShellFixture(t) + _, rootScript, _ := strings.Cut(guestApplyTimezone, "<<'ROOT'\n") + rootScript, _, _ = strings.Cut(rootScript, "\nROOT\n") for name, content := range map[string][]byte{ "guest-tools.sh": GuestAgentScript(), "Install-Reims-Tools.command": GuestInstallScript(), "Uninstall-Reims-Tools.command": GuestUninstallScript(), "Apply-Prevent-Sleep-pmset.command": GuestPmsetScript(), + "set-timezone.sh": []byte(guestTimezoneHelper), + "Apply-Timezone.command": []byte(guestApplyTimezone), + "apply-timezone-root.sh": []byte(rootScript), } { p := filepath.Join(tmp, name) if err := os.WriteFile(p, content, 0o755); err != nil { @@ -655,6 +674,37 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) { t.Fatalf("sh -n %s failed: %v\n%s", name, err, out) } } + for _, tc := range []struct { + tz string + valid bool + }{ + {"UTC", true}, {"Asia/Shanghai", true}, {"America/Argentina/Buenos_Aires", true}, {"Etc/GMT+8", true}, + {"", false}, {"../UTC", false}, {"-UTC", false}, {"/UTC", false}, {"UTC/", false}, {"a/b/c/d", false}, + {"America/New York", false}, {"UTC\nUTC", false}, {"UTC;date", false}, {strings.Repeat("A", 65), false}, + } { + cmd := exec.Command(shBin, "-s") + cmd.Stdin = strings.NewReader(guestTimezoneValidation + "valid_timezone \"$REIMS_TEST_TIMEZONE\"\n") + cmd.Env = append(os.Environ(), "REIMS_TEST_TIMEZONE="+tc.tz) + if out, err := cmd.CombinedOutput(); (err == nil) != tc.valid { + t.Errorf("shell validation for %q = %v, want %v: %s", tc.tz, err == nil, tc.valid, out) + } + } + for _, tc := range []struct { + config, want string + present bool + }{ + {`{"timezone":"America/Argentina/Buenos_Aires","vm":"mac"}`, "America/Argentina/Buenos_Aires", true}, + {`{"timezone":"","vm":"mac"}`, "", true}, + {`{"vm":"\"timezone\":\"UTC\""}`, "", false}, + } { + cmd := exec.Command(shBin, "-s") + cmd.Stdin = strings.NewReader(guestTimezoneConfig + "config_timezone \"$REIMS_TEST_CONFIG\"\n") + cmd.Env = append(os.Environ(), "REIMS_TEST_CONFIG="+tc.config) + if out, err := cmd.CombinedOutput(); (err == nil) != tc.present || strings.TrimSpace(string(out)) != tc.want { + t.Errorf("shell timezone from %s = %q, %v, want %q", tc.config, out, err, tc.want) + } + } + testTimezoneScripts(t, shBin, rootScript) } func TestTextInputV3HandshakeAndV2Fallback(t *testing.T) { diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 56ab1e4..ce3f380 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -7,6 +7,7 @@ import ( "io" "os" "path/filepath" + "strconv" "strings" "github.com/Nwflower/reims-go/internal/macos/installer" @@ -26,7 +27,7 @@ var guestFileSync string // BuildToolsDiskImage creates a read-only HFS+ disk image ("REIMSTOOLS") // containing the per-VM Bearer token config, the POSIX guest agent script, and -// install/uninstall/pmset helper scripts. +// installation, pmset, and timezone helper scripts. func BuildToolsDiskImage(outPath string, cfg VMConfig) error { if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil { return err @@ -69,16 +70,28 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { Size: int64(len(pmsetBytes)), Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(pmsetBytes)), nil }, }, + { + Name: "set-timezone.sh", + Mode: 0o100755, + Size: int64(len(guestTimezoneHelper)), + Open: func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(guestTimezoneHelper)), nil }, + }, + { + Name: "Apply-Timezone.command", + Mode: 0o100755, + Size: int64(len(guestApplyTimezone)), + Open: func() (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(guestApplyTimezone)), nil }, + }, } return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files) } // GuestAgentScript returns the stock-macOS POSIX shell daemon handling // clipboard sync, WebDAV and fallback folder shares, read-only host drive -// mounts, and caffeinate prevent-sleep. +// mounts, caffeinate prevent-sleep, and timezone sync. func GuestAgentScript() []byte { return []byte(`#!/bin/sh -# Reims Guest Tools agent: clipboard, WebDAV shares, read-only Windows drives, prevent-sleep. +# Reims Guest Tools agent: clipboard, WebDAV shares, read-only Windows drives, prevent-sleep, timezone sync. set -u # Force UTF-8 for macOS pbpaste/pbcopy under launchd (otherwise Simplified @@ -106,7 +119,7 @@ CAFFEINATE_PID="" TEXT_INPUT_PID="" keymap_active="false" keymap_applied="false" -` + guestKeymapCarrier + ` +` + guestKeymapCarrier + guestTimezoneAgent + guestTimezoneConfig + ` cleanup() { if [ "$keymap_applied" = "true" ]; then @@ -407,6 +420,7 @@ apply_host_config() { folders_count=$(printf '%s\n' "$cfg_json" | sed -n 's/.*"shared_folders_count"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p') sync_folder_mounts "${folders_count:-0}" sync_keymap_carrier "$cfg_json" + sync_timezone "$cfg_json" if printf '%s' "$cfg_json" | grep -q '"clipboard_enabled"[[:space:]]*:[[:space:]]*false'; then clip_enabled="0" else @@ -435,10 +449,11 @@ apply_host_config() { report_status() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 + 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\":10,\"keymap_active\":$keymap_active}" \ + -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\"}" \ "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true } @@ -771,6 +786,21 @@ if curl -fsS -m 5 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/pi else echo "Reims Guest Tools installed (waiting for Windows host bridge at $REIMS_HOST_URL)..." fi +` + guestTimezoneSelection + ` +if [ -t 0 ]; then + if tz=$(requested_timezone) && [ -n "$tz" ]; then + printf 'Apply timezone %s and enable future sync with sudo? [y/N] ' "$tz" + if read -r answer; then + case "$answer" in + y|Y|yes|YES) + if ! /bin/sh "$SRC/Apply-Timezone.command" "$tz"; then + echo "Timezone setup failed. You can retry with $SRC/Apply-Timezone.command." >&2 + fi + ;; + esac + fi + fi +fi `) } @@ -778,6 +808,10 @@ fi func GuestUninstallScript() []byte { return []byte(`#!/bin/sh set -e +case "$#:$*" in + 0:|1:--user-only) ;; + *) echo "Usage: Uninstall-Reims-Tools.command [--user-only]" >&2; exit 1 ;; +esac APP_DIR="$HOME/Library/Application Support/ReimsGuestTools" CONF="$APP_DIR/config" PLIST="$HOME/Library/LaunchAgents/com.reimsgo.guest-tools.plist" @@ -801,6 +835,7 @@ if owns_folder_link; then fi rm -f "$PLIST" rm -rf "$APP_DIR" +` + guestTimezoneUninstall + ` echo "Reims Guest Tools uninstalled. Your ~/ReimsShare files were kept." `) } diff --git a/internal/guesttools/keymap_agent_test.go b/internal/guesttools/keymap_agent_test.go index 569ae06..89f1590 100644 --- a/internal/guesttools/keymap_agent_test.go +++ b/internal/guesttools/keymap_agent_test.go @@ -22,8 +22,8 @@ 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\":10,\"keymap_active\":$keymap_active`) { - t.Fatal("missing guest keymap script or version 10 status") + if start < 0 || end <= start || !strings.Contains(agent, `"agent_version\":11,\"keymap_active\":$keymap_active`) { + t.Fatal("missing guest keymap script or version 11 status") } for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} { t.Run(input, func(t *testing.T) { diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 16b1ad5..d1fda43 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -24,6 +24,7 @@ import ( "unicode/utf8" "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" ) const ( @@ -81,6 +82,7 @@ type VMConfig struct { SharedDrives []string `json:"shared_drives,omitempty"` DriveVolumes map[string]string `json:"drive_volumes,omitempty"` SharedFolders []SharedFolderConfig `json:"shared_folders,omitempty"` + GuestTimezone string `json:"guest_timezone,omitempty"` // DriveRoots is a runtime-only test/platform override keyed by NormalizeDriveLetter. // Persisted configuration stores drive letters only, never arbitrary host roots. DriveRoots map[string]string `json:"-"` @@ -91,13 +93,16 @@ type VMConfig struct { // GuestStatus summarizes live Guest Tools connection and capability state. type GuestStatus struct { - KeymapActive bool `json:"keymap_active"` - Connected bool `json:"connected"` - MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync" - PreventSleep bool `json:"prevent_sleep"` - SleepActive bool `json:"sleep_active"` - AgentVersion int `json:"agent_version,omitempty"` - LastSeen time.Time `json:"last_seen,omitempty"` + KeymapActive bool `json:"keymap_active"` + Connected bool `json:"connected"` + MountMode string `json:"mount_mode,omitempty"` // "webdav" | "sync" + PreventSleep bool `json:"prevent_sleep"` + SleepActive bool `json:"sleep_active"` + AgentVersion int `json:"agent_version,omitempty"` + LastSeen time.Time `json:"last_seen,omitempty"` + TimezoneApplied string `json:"timezone_applied,omitempty"` + TimezoneHelperReady bool `json:"timezone_helper_ready,omitempty"` + TimezoneError string `json:"timezone_error,omitempty"` } // LoadOrCreateVMConfig loads an existing per-VM Guest Tools config or generates @@ -215,6 +220,10 @@ type registeredVM struct { sharedDir string sharedRoot sharedRoot preventSleep bool + guestTimezone string + timezoneApplied string + timezoneHelperReady bool + timezoneError string driveSharingEnabled bool sharedDriveRoots map[string]string driveVolumeGUIDs map[string]string @@ -508,6 +517,7 @@ func (s *Server) RegisterVM(cfg VMConfig) { cur.sharedDir = cfg.SharedDir cur.sharedRoot = root cur.preventSleep = cfg.PreventSleep + cur.guestTimezone = cfg.GuestTimezone cur.driveSharingEnabled = cfg.DriveSharingEnabled cur.sharedDriveRoots = driveRoots cur.driveVolumeGUIDs = cloneStringMap(cfg.DriveVolumes) @@ -704,14 +714,23 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { return GuestStatus{} } connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= maxAge + freshStatus := connected && time.Since(vm.lastStatus) <= maxAge + var timezone, timezoneError string + if freshStatus { + timezone = vm.timezoneApplied + timezoneError = vm.timezoneError + } return GuestStatus{ - KeymapActive: connected && vm.keymapCarrierEnabled && vm.keymapActive && time.Since(vm.lastStatus) <= maxAge, - Connected: connected, - MountMode: vm.mountMode, - PreventSleep: vm.preventSleep, - SleepActive: connected && vm.sleepActive, - AgentVersion: vm.agentVersion, - LastSeen: vm.lastSeen, + KeymapActive: freshStatus && vm.keymapCarrierEnabled && vm.keymapActive, + Connected: connected, + MountMode: vm.mountMode, + PreventSleep: vm.preventSleep, + SleepActive: connected && vm.sleepActive, + AgentVersion: vm.agentVersion, + LastSeen: vm.lastSeen, + TimezoneApplied: timezone, + TimezoneHelperReady: freshStatus && vm.timezoneHelperReady, + TimezoneError: timezoneError, } } @@ -767,6 +786,7 @@ func (s *Server) authenticate(r *http.Request) *registeredVM { sharedDir: vm.sharedDir, sharedRoot: vm.sharedRoot, preventSleep: vm.preventSleep, + guestTimezone: vm.guestTimezone, driveSharingEnabled: vm.driveSharingEnabled, sharedDriveRoots: cloneStringMap(vm.sharedDriveRoots), driveVolumeGUIDs: cloneStringMap(vm.driveVolumeGUIDs), @@ -840,6 +860,7 @@ func (s *Server) handleConfig(w http.ResponseWriter, r *http.Request) { "vm": vm.name, "keymap_carrier_enabled": vm.keymapCarrierEnabled, "prevent_sleep": vm.preventSleep, + "timezone": effectiveTimezone(vm.guestTimezone), "webdav_path": "/dav/" + vm.name + "/", "shared_drives": enabledDriveLetters(vm), "shared_folders_count": len(vm.resolvedFolders), @@ -861,10 +882,13 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { return } var req struct { - KeymapActive bool `json:"keymap_active"` - MountMode string `json:"mount_mode"` - SleepActive bool `json:"sleep_active"` - AgentVersion int `json:"agent_version"` + KeymapActive bool `json:"keymap_active"` + MountMode string `json:"mount_mode"` + SleepActive bool `json:"sleep_active"` + AgentVersion int `json:"agent_version"` + TimezoneApplied string `json:"timezone_applied"` + TimezoneHelperReady bool `json:"timezone_helper_ready"` + TimezoneError string `json:"timezone_error"` } if err := json.NewDecoder(io.LimitReader(r.Body, 4096)).Decode(&req); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) @@ -874,6 +898,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { if mode != "webdav" && mode != "sync" { mode = "" } + if !host.ValidateIANATimezone(req.TimezoneApplied) { + req.TimezoneApplied = "" + } s.mu.Lock() var notify func(string) if cur := s.vms[vm.key]; cur != nil && cur.token == vm.token { @@ -888,6 +915,9 @@ func (s *Server) handleStatus(w http.ResponseWriter, r *http.Request) { cur.mountMode = mode } cur.sleepActive = req.SleepActive + cur.timezoneApplied = req.TimezoneApplied + cur.timezoneHelperReady = req.TimezoneHelperReady + cur.timezoneError = req.TimezoneError if req.AgentVersion > 0 { cur.agentVersion = req.AgentVersion } diff --git a/internal/guesttools/timezone.go b/internal/guesttools/timezone.go new file mode 100644 index 0000000..69ae96f --- /dev/null +++ b/internal/guesttools/timezone.go @@ -0,0 +1,363 @@ +package guesttools + +import "github.com/Nwflower/reims-go/internal/host" + +func ResolveEffectiveTimezone(setting, hostTZ string) string { + switch setting { + case "off": + return "" + case "", "host": + setting = hostTZ + } + if host.ValidateIANATimezone(setting) { + return setting + } + return "" +} + +func effectiveTimezone(setting string) string { + if setting == "" || setting == "host" { + return ResolveEffectiveTimezone(setting, host.DetectHostTimezone()) + } + return ResolveEffectiveTimezone(setting, "") +} + +// SetTimezone updates the setting served on the guest's next config poll. +func (s *Server) SetTimezone(vmKey, token, setting string) { + s.mu.Lock() + defer s.mu.Unlock() + if vm := s.vms[normalizeVMRegistryKey(vmKey)]; vm != nil && vm.token == token && vm.guestTimezone != setting { + vm.guestTimezone = setting + vm.timezoneError = "" + } +} + +const guestTimezonePath = "/private/etc/reims-timezone/set-timezone.sh" +const guestTimezoneSudoers = "/private/etc/sudoers.d/reims-timezone-" + +const guestTimezoneValidation = ` +valid_timezone() { + case "$1" in + ""|-*|/*|*/|*//*|*/*/*/*|*[!ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_+/-]*) return 1 ;; + esac + [ "${#1}" -le 64 ] +} +` + +const guestTimezoneAgent = ` +TIMEZONE_HELPER="` + guestTimezonePath + `" +timezone_error="" +timezone_helper_ready=false +timezone_check_at=0 +` + guestTimezoneValidation + ` +current_timezone() ( + link=$(/usr/bin/readlink /etc/localtime) || return 0 + case "$link" in + */zoneinfo/*) tz=${link#*/zoneinfo/} ;; + *) return 0 ;; + esac + if valid_timezone "$tz"; then + printf '%s\n' "$tz" + fi +) + +sync_timezone() { + desired_timezone=$(config_timezone "$1") || desired_timezone="" + timezone_error="" + if [ -z "$desired_timezone" ] || [ ! -x "$TIMEZONE_HELPER" ]; then + timezone_helper_ready=false + timezone_check_at=0 + return 0 + fi + timezone_now=$(/bin/date +%s) + if [ "$timezone_now" -ge "$timezone_check_at" ]; then + timezone_helper_ready=false + if /usr/bin/sudo -n -l -- "$TIMEZONE_HELPER" >/dev/null 2>&1; then + timezone_helper_ready=true + fi + timezone_check_at=$((timezone_now + 30)) + fi + if [ "$timezone_helper_ready" = true ] && [ "$desired_timezone" != "$(current_timezone)" ]; then + if ! /usr/bin/sudo -n -- "$TIMEZONE_HELPER" "$desired_timezone" >/dev/null 2>&1; then + timezone_error=apply_failed + fi + fi +} +` + +const guestTimezoneConfig = ` +# The bridge emits compact JSON and timezone IDs contain no JSON escapes. +config_timezone() ( + case "$1" in + *'"timezone":"'*) + value=${1#*'"timezone":"'} + printf '%s\n' "${value%%\"*}" + ;; + *) return 1 ;; + esac +) +` + +const guestTimezoneSelection = guestTimezoneConfig + ` +requested_timezone() ( + cfg=$(/usr/bin/curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null) || return 1 + config_timezone "$cfg" +) +` + +const guestTimezoneFile = guestTimezoneValidation + ` +resolve_timezone_path() ( + if [ -x /usr/bin/realpath ]; then + /usr/bin/realpath "$1" + return $? + fi + path=$1 + hops=0 + while :; do + dir=$(CDPATH= cd -P "$(/usr/bin/dirname "$path")" 2>/dev/null && pwd -P) || return 1 + path="$dir/$(/usr/bin/basename "$path")" + if [ ! -L "$path" ]; then + [ -e "$path" ] || return 1 + printf '%s\n' "$path" + return 0 + fi + [ "$hops" -lt 40 ] || return 1 + hops=$((hops + 1)) + target=$(/usr/bin/readlink "$path") || return 1 + case "$target" in + /*) path=$target ;; + *) path="$dir/$target" ;; + esac + done +) + +timezone_file() ( + [ "$1" != Local ] && valid_timezone "$1" || return 1 + for zone_dir in /var/db/timezone/zoneinfo /usr/share/zoneinfo; do + tz_file="$zone_dir/$1" + [ -f "$tz_file" ] || continue + real_dir=$(resolve_timezone_path "$zone_dir") || continue + real_file=$(resolve_timezone_path "$tz_file") || continue + case "$real_file" in + "$real_dir/"*) + [ "$(/bin/dd if="$real_file" bs=4 count=1 2>/dev/null)" = TZif ] || continue + printf '%s\n' "$tz_file" + return 0 + ;; + esac + done + return 1 +) +` + +const guestTimezoneHelper = `#!/bin/sh +set -eu +export LC_ALL=C +` + guestTimezoneFile + ` +if [ "$#" -ne 1 ] || ! tz_file=$(timezone_file "$1"); then + echo "Usage: set-timezone.sh IANA_TIMEZONE (with an installed zoneinfo file)" >&2 + exit 1 +fi +/usr/bin/defaults write /Library/Preferences/com.apple.timezone.auto Active -bool NO +/bin/ln -sfn "$tz_file" /etc/localtime +/usr/bin/killall -HUP timed 2>/dev/null || true +` + +const guestTimezoneSystemPaths = ` +case "$1" in + ""|*[!0-9]*) exit 1 ;; +esac +helper="` + guestTimezonePath + `" +rule_prefix="` + guestTimezoneSudoers + `" +sudoers="$rule_prefix$1" +helper_dir=${helper%/*} +sudoers_dir=${sudoers%/*} + +secure_path() { + if [ ! -L "$1" ] && test "$2" "$1"; then + owner=$(/usr/bin/stat -f '%u' "$1") || return 1 + mode=$(/usr/bin/stat -f '%Lp' "$1") || return 1 + acl=$(/bin/ls -lde "$1") || return 1 + if [ "$owner" = 0 ] && [ "$((0$mode & $3))" -eq 0 ] && + ! printf '%s\n' "$acl" | /usr/bin/grep -Eq '^[[:space:]]*[0-9]+: .* allow '; then + return 0 + fi + fi + echo "Reims Guest Tools cannot use $1" >&2 + return 1 +} + +lock_timezone_files() { + lock="$sudoers_dir/.reims-timezone.lock" + if ! /bin/mkdir "$lock"; then + echo "Could not lock Reims timezone files. Please retry." >&2 + return 1 + fi + trap 'exit 1' HUP INT TERM +} +` + +const guestApplyTimezone = `#!/bin/sh +set -eu +export LC_ALL=C +SRC="/Volumes/REIMSTOOLS" +TIMEZONE_HELPER="` + guestTimezonePath + `" +` + guestTimezoneFile + guestTimezoneSelection + ` +case "$#" in + 0) + . "$SRC/config" + if ! tz=$(requested_timezone); then + echo "Could not read the current timezone policy from the Reims host bridge at $REIMS_HOST_URL." >&2 + exit 1 + fi + ;; + 1) tz=$1 ;; + *) + echo "Usage: Apply-Timezone.command [IANA_TIMEZONE]" >&2 + exit 1 + ;; +esac + +if [ -z "$tz" ] && [ "$#" -eq 0 ]; then + echo "Reims Guest Tools has no timezone to apply." + exit 0 +fi +if ! timezone_file "$tz" >/dev/null; then + echo "Invalid IANA timezone: $tz" >&2 + exit 1 +fi + +/usr/bin/sudo /bin/sh -s -- "$(/usr/bin/id -u)" <<'ROOT' +set -eu +export LC_ALL=C +` + guestTimezoneSystemPaths + ` +secure_path /private -d 022 +secure_path /private/etc -d 022 +if [ ! -e "$sudoers_dir" ] && [ ! -L "$sudoers_dir" ]; then + /usr/bin/install -d -o root -g wheel -m 0755 "$sudoers_dir" +fi +secure_path "$sudoers_dir" -d 022 +lock_timezone_files +trap '/bin/rmdir "$lock"' EXIT +if [ ! -e "$helper_dir" ] && [ ! -L "$helper_dir" ]; then + /usr/bin/install -d -o root -g wheel -m 0755 "$helper_dir" +fi +secure_path "$helper_dir" -d 022 + +for backup in "$helper.bak" "$sudoers.bak"; do + if [ -e "$backup" ] || [ -L "$backup" ]; then + echo "An earlier Reims timezone backup remains at $backup." >&2 + exit 1 + fi +done + +backup_file() { + if [ -e "$1" ] || [ -L "$1" ]; then + secure_path "$1" -f 022 && /bin/ln "$1" "$1.bak" + fi +} + +restore_file() { + if [ -f "$1.bak" ]; then + if [ "$1" -ef "$1.bak" ]; then + /bin/rm -f "$1.bak" + else + /bin/mv -f "$1.bak" "$1" + fi + elif [ "$2" = 1 ]; then + /bin/rm -f "$1" + fi +} + +rule_tmp="" +helper_tmp="" +helper_replacing=0 +rule_replacing=0 +committed=0 +cleanup_timezone_install() { + result=$? + trap '' HUP INT TERM + set +e + if [ "$committed" = 0 ]; then + echo "Could not configure Reims timezone sudo access." >&2 + restore_file "$sudoers" "$rule_replacing" || echo "Could not restore $sudoers" >&2 + restore_file "$helper" "$helper_replacing" || echo "Could not restore $helper" >&2 + else + /bin/rm -f "$helper.bak" "$sudoers.bak" || result=1 + fi + if [ -n "$helper_tmp" ]; then + /bin/rm -f "$helper_tmp" || result=1 + fi + if [ -n "$rule_tmp" ]; then + /bin/rm -f "$rule_tmp" || result=1 + fi + /bin/rmdir "$lock" || result=1 + exit "$result" +} +trap cleanup_timezone_install EXIT + +rule_tmp=$(/usr/bin/mktemp "$sudoers_dir/.reims-timezone.XXXXXX") +# A numeric sudoers user ID avoids interpreting special characters in a username. +printf '#%s ALL=(root) NOPASSWD: %s\n' "$1" "$helper" >"$rule_tmp" +/usr/sbin/chown root:wheel "$rule_tmp" +/bin/chmod 0440 "$rule_tmp" +/usr/sbin/visudo -cf "$rule_tmp" + +helper_tmp=$(/usr/bin/mktemp "$helper_dir/.set-timezone.XXXXXX") +/usr/bin/install -o root -g wheel -m 0755 /Volumes/REIMSTOOLS/set-timezone.sh "$helper_tmp" +backup_file "$helper" +backup_file "$sudoers" +helper_replacing=1 +/bin/mv -f "$helper_tmp" "$helper" +rule_replacing=1 +/bin/mv -f "$rule_tmp" "$sudoers" +/usr/sbin/visudo -cf "$sudoers" +committed=1 +ROOT + +/usr/bin/sudo -n -- "$TIMEZONE_HELPER" "$tz" +/bin/date +` + +const guestTimezoneUninstall = ` +if [ "$#" -eq 0 ]; then + TIMEZONE_HELPER="` + guestTimezonePath + `" + TIMEZONE_SUDOERS="` + guestTimezoneSudoers + `$uid" + if [ -e "$TIMEZONE_SUDOERS" ] || [ -L "$TIMEZONE_SUDOERS" ] || + [ -e "$TIMEZONE_HELPER" ] || [ -L "$TIMEZONE_HELPER" ]; then + if ! /usr/bin/sudo /bin/sh -s -- "$uid" <<'ROOT' +set -eu +export LC_ALL=C +` + guestTimezoneSystemPaths + ` +secure_path /private -d 022 +secure_path /private/etc -d 022 +if [ -e "$sudoers_dir" ] || [ -L "$sudoers_dir" ]; then + secure_path "$sudoers_dir" -d 022 +else + /usr/bin/install -d -o root -g wheel -m 0755 "$sudoers_dir" +fi +lock_timezone_files +trap '/bin/rmdir "$lock"' EXIT +/bin/rm -f "$sudoers" +for rule in "$rule_prefix"*; do + if [ -e "$rule" ] || [ -L "$rule" ]; then + exit 0 + fi +done +if [ -e "$helper" ] || [ -L "$helper" ]; then + secure_path "$helper_dir" -d 022 + /bin/rm -f "$helper" +fi +ROOT + then + for path in "$TIMEZONE_SUDOERS" "$TIMEZONE_HELPER"; do + if [ -e "$path" ] || [ -L "$path" ]; then + echo "Remaining Reims timezone file: $path" >&2 + fi + done + echo "Could not remove Reims timezone sync. Run this uninstaller again to retry." >&2 + exit 1 + fi + fi +fi +` diff --git a/internal/guesttools/timezone_test.go b/internal/guesttools/timezone_test.go new file mode 100644 index 0000000..41b34db --- /dev/null +++ b/internal/guesttools/timezone_test.go @@ -0,0 +1,295 @@ +package guesttools + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os/exec" + "strings" + "testing" + "time" + + "github.com/Nwflower/reims-go/internal/host" +) + +func testTimezoneScripts(t *testing.T, sh, rootInstall string) { + t.Helper() + rewrite := strings.NewReplacer( + "/private/etc/sudoers.d", "system/sudoers.d", + "/private/etc", "system/etc", + "/private", "system", + "/Volumes/REIMSTOOLS", "tools", + "/var/db/timezone/zoneinfo", "zones", + "/usr/share/zoneinfo", "missing-zones", + "/usr/bin/stat", "mock_stat", + "/bin/ls", "mock_ls", + "/usr/bin/install", "mock_install", + "/usr/sbin/chown", "mock_chown", + "/usr/sbin/visudo", "mock_visudo", + "/usr/bin/curl", "mock_curl", + "/usr/bin/sudo", "mock_sudo", + "/bin/rm ", "mock_rm ", + "/bin/mv", "mock_mv", + ) + run := func(t *testing.T, script string, args ...string) (string, error) { + t.Helper() + cmd := exec.Command(sh, append([]string{"-s", "--"}, args...)...) + cmd.Dir = t.TempDir() + cmd.Env = append(cmd.Environ(), "MSYS=winsymlinks:sys") + cmd.Stdin = strings.NewReader(timezoneShellFixture + rewrite.Replace(script)) + out, err := cmd.CombinedOutput() + return string(out), err + } + t.Run("resolve_without_realpath", func(t *testing.T) { + validation := strings.ReplaceAll(guestTimezoneFile, "/usr/bin/realpath", "./unavailable-realpath") + script := validation + ` +ln -s Shanghai zones/Asia/Link +ln -s "$(pwd -P)/zones/Asia/Link" zones/Alias +printf TZif > outside +ln -s ../outside zones/Escape +ln -s .. zones/DirectoryEscape +ln -s Missing zones/Dangling +ln -s LoopB zones/LoopA +ln -s LoopA zones/LoopB +[ "$(timezone_file Asia/Shanghai)" = zones/Asia/Shanghai ] +[ "$(timezone_file Alias)" = zones/Alias ] +for name in Escape DirectoryEscape/outside Dangling LoopA; do + if timezone_file "$name"; then exit 1; fi +done +if resolve_timezone_path zones/LoopA; then exit 1; fi +` + if out, err := run(t, script); err != nil { + t.Fatalf("timezone path fallback: %v\n%s", err, out) + } + }) + t.Run("reports_failed_sync_and_clears_it", func(t *testing.T) { + report := scriptSection(t, string(GuestAgentScript()), "report_status() {", "\nread_local_clipboard() {") + script := guestTimezoneAgent + guestTimezoneConfig + report + ` +. tools/config +TIMEZONE_HELPER=tools/set-timezone.sh +printf '#!/bin/sh\nexit 0\n' > "$TIMEZONE_HELPER" +chmod +x "$TIMEZONE_HELPER" +mount_mode=sync +sleep_active=false +keymap_active=false +current_timezone() { printf Asia/Shanghai; } +curl() { + while [ "$1" != "-d" ]; do shift; done + payload=$2 +} +expect_timezone_error() { + case "$payload" in + *"\"timezone_error\":\"$1\""*) ;; + *) printf 'expected timezone_error=%s in %s\n' "$1" "$payload" >&2; return 1 ;; + esac +} +fail_sudo=1 +sync_timezone '{"timezone":"Asia/Tokyo"}' +report_status +expect_timezone_error apply_failed +case "$payload" in + *'"timezone_helper_ready":true'*) ;; + *) printf 'expected a ready helper in %s\n' "$payload" >&2; exit 1 ;; +esac +sync_timezone '{"timezone":""}' +report_status +expect_timezone_error "" +sync_timezone '{"timezone":"Asia/Tokyo"}' +fail_sudo=0 +sync_timezone '{"timezone":"Asia/Tokyo"}' +report_status +expect_timezone_error "" +` + if out, err := run(t, script); err != nil { + t.Fatalf("timezone agent status: %v\n%s", err, out) + } + }) + for _, tc := range []struct{ name, setup, checks string }{ + {"first_install", "", "[ \"$result\" -eq 0 ] && [ \"$(cat \"$helper\")\" = new-helper ] && grep -q '^#501 ALL=' \"$rule\""}, + {"reinstall", "seed_old", "[ \"$result\" -eq 0 ] && [ \"$(cat \"$helper\")\" = new-helper ] && grep -q '^#501 ALL=' \"$rule\""}, + {"rollback_reinstall", "seed_old; fail_visudo=1", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"}, + {"rollback_failed_rule_replace", "seed_old; fail_rule_replace=1", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"}, + {"rollback_first_install", "fail_visudo=1", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"}, + {"reject_group_writable_parent", "parent_mode=0775", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"}, + {"reject_group_writable_helper", "seed_old; helper_mode=0775", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"}, + } { + t.Run(tc.name, func(t *testing.T) { + script := tc.setup + "\nset +e\n(\n" + rootInstall + "\n)\nresult=$?\nset -e\n" + + "[ ! -e \"$helper.bak\" ] && [ ! -e \"$rule.bak\" ] && [ ! -e system/sudoers.d/.reims-timezone.lock ] || exit 1\n" + tc.checks + "\n" + if out, err := run(t, script, "501"); err != nil { + t.Fatalf("timezone install fixture: %v\n%s", err, out) + } + }) + } + for _, tc := range []struct { + name, setup, message string + args []string + fail bool + }{ + {"offline", "", "Could not read the current timezone policy", nil, true}, + {"off", "bridge='{\"timezone\":\"\"}'", "no timezone to apply", nil, false}, + {"online", "bridge='{\"timezone\":\"Asia/Shanghai\"}'", "applied Asia/Shanghai", nil, false}, + {"offline_explicit", "", "applied Asia/Shanghai", []string{"Asia/Shanghai"}, false}, + {"reject_non_TZif", "printf 'not zoneinfo' > zones/Asia/Shanghai", "Invalid IANA timezone", []string{"Asia/Shanghai"}, true}, + } { + t.Run(tc.name, func(t *testing.T) { + script := tc.setup + "\n" + guestApplyTimezone + out, err := run(t, script, tc.args...) + if (err != nil) != tc.fail || !strings.Contains(out, tc.message) || + (tc.args == nil && tc.name != "online" && strings.Contains(out, "applied ")) { + t.Fatalf("apply timezone: %v\n%s", err, out) + } + }) + } + t.Run("install_prompt_online_only", func(t *testing.T) { + prompt := scriptSection(t, string(GuestInstallScript()), "if [ -t 0 ]; then", "\nfi\n") + "\nfi\n" + prompt = strings.NewReplacer("[ -t 0 ]", "true", "read -r answer", "answer=n").Replace(prompt) + for _, tc := range []struct{ response, want string }{ + {"", ""}, + {`{"timezone":""}`, ""}, + {`{"timezone":"Asia/Shanghai"}`, "Apply timezone Asia/Shanghai"}, + } { + script := ". tools/config\nbridge='" + tc.response + "'\n" + guestTimezoneSelection + prompt + out, err := run(t, script) + if err != nil || (tc.want == "" && out != "") || !strings.HasPrefix(out, tc.want) { + t.Errorf("prompt for %q: %v\n%s", tc.response, err, out) + } + } + }) + t.Run("uninstall_by_uid", func(t *testing.T) { + script := "seed_old\nuid=501\nprintf 'other\\n' > system/sudoers.d/reims-timezone-502\n" + guestTimezoneUninstall + + "\n[ ! -e \"$rule\" ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat system/sudoers.d/reims-timezone-502)\" = other ] || exit 1\n" + + "uid=502\n" + guestTimezoneUninstall + "\n[ ! -e \"$helper\" ] && [ ! -e system/sudoers.d/reims-timezone-502 ]\n" + if out, err := run(t, script); err != nil { + t.Fatalf("timezone uninstall fixture: %v\n%s", err, out) + } + }) + t.Run("uninstall_failure", func(t *testing.T) { + script := "seed_old\nuid=501\nfail_rm=$helper\n" + guestTimezoneUninstall + "\necho 'Uninstalled'\n" + out, err := run(t, script) + if err == nil || !strings.Contains(out, "Remaining Reims timezone file: system/etc/reims-timezone/set-timezone.sh") || + !strings.Contains(out, "retry") || strings.Contains(out, "Uninstalled") { + t.Fatalf("timezone uninstall failure: %v\n%s", err, out) + } + }) +} + +const timezoneShellFixture = ` +set -eu +parent_mode=0755 +helper_mode=0755 +helper=system/etc/reims-timezone/set-timezone.sh +rule=system/sudoers.d/reims-timezone-501 +mkdir -p "${helper%/*}" system/sudoers.d tools zones/Asia +printf new-helper > tools/set-timezone.sh +printf TZif > zones/Asia/Shanghai +printf 'REIMS_TOKEN=test\nREIMS_HOST_URL=http://stub\n' > tools/config +seed_old() { + printf old-helper > "$helper" + printf old-rule > "$rule" +} +mock_stat() { + if [ "$2" = '%u' ]; then + echo 0 + else + case "$3" in + system|system/etc) echo "$parent_mode" ;; + "$helper") echo "$helper_mode" ;; + *) echo 0755 ;; + esac + fi +} +mock_ls() { :; } +mock_install() { cp "$7" "$8"; } +mock_chown() { :; } +mock_visudo() { [ "$2" != "$rule" ] || [ "${fail_visudo:-0}" = 0 ]; } +mock_curl() { [ -n "${bridge:-}" ] && printf '%s\n' "$bridge"; } +mock_sudo() { + case "$1" in + -n) + [ "$2" != -l ] || return 0 + [ "${fail_sudo:-0}" = 0 ] || return 1 + printf 'applied %s\n' "$4" + ;; + *) + if [ "$#" -eq 4 ] && [ "$4" = "${uid:-}" ]; then + shift 3 + (eval "$(cat)") + else + cat >/dev/null + fi + ;; + esac +} +mock_rm() { + [ "$2" != "${fail_rm:-}" ] || return 1 + command rm "$@" +} +mock_mv() { + if [ "${fail_rule_replace:-0}" = 1 ] && [ "$3" = "$rule" ] && [ "$2" != "$rule.bak" ]; then + return 1 + fi + command mv "$@" +} +` + +func TestResolveEffectiveTimezone(t *testing.T) { + for _, tc := range []struct{ setting, host, want string }{ + {"", "Asia/Shanghai", "Asia/Shanghai"}, + {"host", "UTC", "UTC"}, + {"host", "/UTC", ""}, + {"host", "", ""}, + {"off", "UTC", ""}, + {"Asia/Tokyo", "UTC", "Asia/Tokyo"}, + {"Asia/../UTC", "UTC", ""}, + } { + if got := ResolveEffectiveTimezone(tc.setting, tc.host); got != tc.want { + t.Errorf("ResolveEffectiveTimezone(%q, %q) = %q, want %q", tc.setting, tc.host, got, tc.want) + } + } +} + +func TestTimezoneBridge(t *testing.T) { + const token = "timezone-bridge-token" + const vm = "mac" + srv := NewTransportServer(nil) + srv.RegisterVM(VMConfig{VMName: vm, Token: token}) + for _, tc := range []struct{ setting, want string }{ + {"", host.DetectHostTimezone()}, {"America/Argentina/Buenos_Aires", "America/Argentina/Buenos_Aires"}, {"off", ""}, + } { + srv.SetTimezone(vm, token, tc.setting) + req := httptest.NewRequest(http.MethodGet, "/v1/config", nil) + req.Header.Set("Authorization", "Bearer "+token) + res := httptest.NewRecorder() + srv.handleConfig(res, req) + var cfg map[string]json.RawMessage + if res.Code != http.StatusOK || json.Unmarshal(res.Body.Bytes(), &cfg) != nil { + t.Fatalf("config = %d %s", res.Code, res.Body) + } + var tz string + if err := json.Unmarshal(cfg["timezone"], &tz); err != nil || tz != tc.want { + t.Errorf("config timezone = %q, want %q (error %v)", tz, tc.want, err) + } + } + + for _, tc := range []struct { + body, applied, timezoneError string + ready bool + version int + }{ + {`{"agent_version":11,"timezone_applied":"Etc/GMT+8","timezone_helper_ready":true,"timezone_error":"apply_failed"}`, "Etc/GMT+8", "apply_failed", true, 11}, + {`{"agent_version":11,"timezone_applied":"Asia/Tokyo","timezone_helper_ready":true,"timezone_error":""}`, "Asia/Tokyo", "", true, 11}, + {`{"agent_version":11,"timezone_applied":"../UTC","timezone_helper_ready":true}`, "", "", true, 11}, + {`{"agent_version":10}`, "", "", false, 10}, + } { + req := httptest.NewRequest(http.MethodPost, "/v1/status", strings.NewReader(tc.body)) + req.Header.Set("Authorization", "Bearer "+token) + res := httptest.NewRecorder() + srv.handleStatus(res, req) + guest := srv.Status(vm, time.Minute) + if res.Code != http.StatusOK || !guest.Connected || guest.AgentVersion != tc.version || + guest.TimezoneApplied != tc.applied || guest.TimezoneHelperReady != tc.ready || guest.TimezoneError != tc.timezoneError { + t.Errorf("status for %s = %d %+v", tc.body, res.Code, guest) + } + } +} diff --git a/internal/host/host.go b/internal/host/host.go index 83a2df2..ba09151 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -1,6 +1,8 @@ package host -import "strings" +import ( + "strings" +) type GPUKind string @@ -62,6 +64,7 @@ type Report struct { DefenderRealtimeActive bool `json:"defender_realtime_active,omitempty"` OS string `json:"os"` Arch string `json:"arch"` + Timezone string `json:"timezone,omitempty"` LogicalCPUs int `json:"logical_cpus"` PhysicalCores int `json:"physical_cores"` HasHybridCores bool `json:"has_hybrid_cores"` diff --git a/internal/host/host_other.go b/internal/host/host_other.go index 3958091..f9673dd 100644 --- a/internal/host/host_other.go +++ b/internal/host/host_other.go @@ -18,6 +18,7 @@ func Inspect(dataRoot string) Report { LogicalCPUs: runtime.NumCPU(), CPUTopology: DefaultCPUTopology(runtime.NumCPU()), DataRoot: dataRoot, + Timezone: DetectHostTimezone(), DeepBackingChains: InspectVMDiskChains(dataRoot), WHPX: WHPXUnsupported, Displays: displays, diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 784d5ec..46ab8a1 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -126,11 +126,12 @@ func Inspect(dataRoot string) Report { memSpecCopy = &cp } rep := Report{ - DefenderRealtimeActive: probeDefenderRealtime(), + DefenderRealtimeActive: probeDefenderRealtime(), OS: "windows", Arch: runtime.GOARCH, LogicalCPUs: runtime.NumCPU(), DataRoot: dataRoot, + Timezone: DetectHostTimezone(), WHPX: probeWHPX(), NeedsColdRebootWorkaround: st.needsColdReboot, GPUs: gpusCopy, diff --git a/internal/host/timezone.go b/internal/host/timezone.go new file mode 100644 index 0000000..4084573 --- /dev/null +++ b/internal/host/timezone.go @@ -0,0 +1,164 @@ +package host + +import ( + "regexp" + "strings" + "time" + _ "time/tzdata" +) + +var ianaTimezonePattern = regexp.MustCompile(`^[A-Za-z0-9_+-]+(/[A-Za-z0-9_+-]+){0,2}$`) + +// ValidateIANATimezone checks that tz names a zone in the IANA database. +func ValidateIANATimezone(tz string) bool { + if tz == "" || tz == "Local" || len(tz) > 64 || strings.HasPrefix(tz, "-") || !ianaTimezonePattern.MatchString(tz) { + return false + } + _, err := time.LoadLocation(tz) + return err == nil +} + +// CLDR 48 windowsZones.xml, territory 001 (global defaults). +// Copyright © 2004-2025 Unicode, Inc. See NOTICE.md for the Unicode license. +// https://github.com/unicode-org/cldr/blob/release-48/common/supplemental/windowsZones.xml +var windowsIANATimezones = map[string]string{ + "Dateline Standard Time": "Etc/GMT+12", + "UTC-11": "Etc/GMT+11", + "Aleutian Standard Time": "America/Adak", + "Hawaiian Standard Time": "Pacific/Honolulu", + "Marquesas Standard Time": "Pacific/Marquesas", + "Alaskan Standard Time": "America/Anchorage", + "UTC-09": "Etc/GMT+9", + "Pacific Standard Time (Mexico)": "America/Tijuana", + "UTC-08": "Etc/GMT+8", + "Pacific Standard Time": "America/Los_Angeles", + "US Mountain Standard Time": "America/Phoenix", + "Mountain Standard Time (Mexico)": "America/Mazatlan", + "Mountain Standard Time": "America/Denver", + "Yukon Standard Time": "America/Whitehorse", + "Central America Standard Time": "America/Guatemala", + "Central Standard Time": "America/Chicago", + "Easter Island Standard Time": "Pacific/Easter", + "Central Standard Time (Mexico)": "America/Mexico_City", + "Canada Central Standard Time": "America/Regina", + "SA Pacific Standard Time": "America/Bogota", + "Eastern Standard Time (Mexico)": "America/Cancun", + "Eastern Standard Time": "America/New_York", + "Haiti Standard Time": "America/Port-au-Prince", + "Cuba Standard Time": "America/Havana", + "US Eastern Standard Time": "America/Indianapolis", + "Turks And Caicos Standard Time": "America/Grand_Turk", + "Paraguay Standard Time": "America/Asuncion", + "Atlantic Standard Time": "America/Halifax", + "Venezuela Standard Time": "America/Caracas", + "Central Brazilian Standard Time": "America/Cuiaba", + "SA Western Standard Time": "America/La_Paz", + "Pacific SA Standard Time": "America/Santiago", + "Newfoundland Standard Time": "America/St_Johns", + "Tocantins Standard Time": "America/Araguaina", + "E. South America Standard Time": "America/Sao_Paulo", + "SA Eastern Standard Time": "America/Cayenne", + "Argentina Standard Time": "America/Buenos_Aires", + "Greenland Standard Time": "America/Godthab", + "Montevideo Standard Time": "America/Montevideo", + "Magallanes Standard Time": "America/Punta_Arenas", + "Saint Pierre Standard Time": "America/Miquelon", + "Bahia Standard Time": "America/Bahia", + "UTC-02": "Etc/GMT+2", + "Azores Standard Time": "Atlantic/Azores", + "Cape Verde Standard Time": "Atlantic/Cape_Verde", + "UTC": "Etc/UTC", + "GMT Standard Time": "Europe/London", + "Greenwich Standard Time": "Atlantic/Reykjavik", + "Sao Tome Standard Time": "Africa/Sao_Tome", + "Morocco Standard Time": "Africa/Casablanca", + "W. Europe Standard Time": "Europe/Berlin", + "Central Europe Standard Time": "Europe/Budapest", + "Romance Standard Time": "Europe/Paris", + "Central European Standard Time": "Europe/Warsaw", + "W. Central Africa Standard Time": "Africa/Lagos", + "Jordan Standard Time": "Asia/Amman", + "GTB Standard Time": "Europe/Bucharest", + "Middle East Standard Time": "Asia/Beirut", + "Egypt Standard Time": "Africa/Cairo", + "E. Europe Standard Time": "Europe/Chisinau", + "Syria Standard Time": "Asia/Damascus", + "West Bank Standard Time": "Asia/Hebron", + "South Africa Standard Time": "Africa/Johannesburg", + "FLE Standard Time": "Europe/Kiev", + "Israel Standard Time": "Asia/Jerusalem", + "South Sudan Standard Time": "Africa/Juba", + "Kaliningrad Standard Time": "Europe/Kaliningrad", + "Sudan Standard Time": "Africa/Khartoum", + "Libya Standard Time": "Africa/Tripoli", + "Namibia Standard Time": "Africa/Windhoek", + "Arabic Standard Time": "Asia/Baghdad", + "Turkey Standard Time": "Europe/Istanbul", + "Arab Standard Time": "Asia/Riyadh", + "Belarus Standard Time": "Europe/Minsk", + "Russian Standard Time": "Europe/Moscow", + "E. Africa Standard Time": "Africa/Nairobi", + "Iran Standard Time": "Asia/Tehran", + "Arabian Standard Time": "Asia/Dubai", + "Astrakhan Standard Time": "Europe/Astrakhan", + "Azerbaijan Standard Time": "Asia/Baku", + "Russia Time Zone 3": "Europe/Samara", + "Mauritius Standard Time": "Indian/Mauritius", + "Saratov Standard Time": "Europe/Saratov", + "Georgian Standard Time": "Asia/Tbilisi", + "Volgograd Standard Time": "Europe/Volgograd", + "Caucasus Standard Time": "Asia/Yerevan", + "Afghanistan Standard Time": "Asia/Kabul", + "West Asia Standard Time": "Asia/Tashkent", + "Ekaterinburg Standard Time": "Asia/Yekaterinburg", + "Pakistan Standard Time": "Asia/Karachi", + "Qyzylorda Standard Time": "Asia/Qyzylorda", + "India Standard Time": "Asia/Calcutta", + "Sri Lanka Standard Time": "Asia/Colombo", + "Nepal Standard Time": "Asia/Katmandu", + "Central Asia Standard Time": "Asia/Bishkek", + "Bangladesh Standard Time": "Asia/Dhaka", + "Omsk Standard Time": "Asia/Omsk", + "Myanmar Standard Time": "Asia/Rangoon", + "SE Asia Standard Time": "Asia/Bangkok", + "Altai Standard Time": "Asia/Barnaul", + "W. Mongolia Standard Time": "Asia/Hovd", + "North Asia Standard Time": "Asia/Krasnoyarsk", + "N. Central Asia Standard Time": "Asia/Novosibirsk", + "Tomsk Standard Time": "Asia/Tomsk", + "China Standard Time": "Asia/Shanghai", + "North Asia East Standard Time": "Asia/Irkutsk", + "Singapore Standard Time": "Asia/Singapore", + "W. Australia Standard Time": "Australia/Perth", + "Taipei Standard Time": "Asia/Taipei", + "Ulaanbaatar Standard Time": "Asia/Ulaanbaatar", + "Aus Central W. Standard Time": "Australia/Eucla", + "Transbaikal Standard Time": "Asia/Chita", + "Tokyo Standard Time": "Asia/Tokyo", + "North Korea Standard Time": "Asia/Pyongyang", + "Korea Standard Time": "Asia/Seoul", + "Yakutsk Standard Time": "Asia/Yakutsk", + "Cen. Australia Standard Time": "Australia/Adelaide", + "AUS Central Standard Time": "Australia/Darwin", + "E. Australia Standard Time": "Australia/Brisbane", + "AUS Eastern Standard Time": "Australia/Sydney", + "West Pacific Standard Time": "Pacific/Port_Moresby", + "Tasmania Standard Time": "Australia/Hobart", + "Vladivostok Standard Time": "Asia/Vladivostok", + "Lord Howe Standard Time": "Australia/Lord_Howe", + "Bougainville Standard Time": "Pacific/Bougainville", + "Russia Time Zone 10": "Asia/Srednekolymsk", + "Magadan Standard Time": "Asia/Magadan", + "Norfolk Standard Time": "Pacific/Norfolk", + "Sakhalin Standard Time": "Asia/Sakhalin", + "Central Pacific Standard Time": "Pacific/Guadalcanal", + "Russia Time Zone 11": "Asia/Kamchatka", + "New Zealand Standard Time": "Pacific/Auckland", + "UTC+12": "Etc/GMT-12", + "Fiji Standard Time": "Pacific/Fiji", + "Chatham Islands Standard Time": "Pacific/Chatham", + "UTC+13": "Etc/GMT-13", + "Tonga Standard Time": "Pacific/Tongatapu", + "Samoa Standard Time": "Pacific/Apia", + "Line Islands Standard Time": "Pacific/Kiritimati", +} diff --git a/internal/host/timezone_other.go b/internal/host/timezone_other.go new file mode 100644 index 0000000..ef39eeb --- /dev/null +++ b/internal/host/timezone_other.go @@ -0,0 +1,24 @@ +//go:build !windows + +package host + +import ( + "os" + "strings" + "time" +) + +func DetectHostTimezone() string { + if tz := os.Getenv("TZ"); tz != "Local" && ValidateIANATimezone(tz) { + return tz + } + if link, err := os.Readlink("/etc/localtime"); err == nil { + if _, tz, ok := strings.Cut("/"+link, "/zoneinfo/"); ok && ValidateIANATimezone(tz) { + return tz + } + } + if tz := time.Now().Location().String(); tz != "Local" && ValidateIANATimezone(tz) { + return tz + } + return "" +} diff --git a/internal/host/timezone_test.go b/internal/host/timezone_test.go new file mode 100644 index 0000000..7bf164e --- /dev/null +++ b/internal/host/timezone_test.go @@ -0,0 +1,68 @@ +package host + +import ( + "encoding/json" + "runtime" + "strings" + "testing" +) + +func TestValidateIANATimezone(t *testing.T) { + for _, tz := range []string{"UTC", "Asia/Shanghai", "America/Argentina/Buenos_Aires", "Etc/GMT+8"} { + if !ValidateIANATimezone(tz) { + t.Errorf("valid timezone %q was rejected", tz) + } + } + for _, tz := range []string{"", "Local", "Mars/Olympus", strings.Repeat("A", 64), "..", "Asia/../UTC", "/UTC", "-UTC", "Asia/", "Asia//Shanghai", "a/b/c/d", + "Asia/Hong Kong", "Asia/Shanghai\n", "UTC;date", "UTC$(date)", strings.Repeat("A", 65)} { + if ValidateIANATimezone(tz) { + t.Errorf("invalid timezone %q was accepted", tz) + } + } +} + +func TestWindowsIANATimezoneMapping(t *testing.T) { + for id, want := range map[string]string{ + "China Standard Time": "Asia/Shanghai", + "Tokyo Standard Time": "Asia/Tokyo", + "Pacific Standard Time": "America/Los_Angeles", + "UTC": "Etc/UTC", + "GMT Standard Time": "Europe/London", + "AUS Eastern Standard Time": "Australia/Sydney", + } { + if got := windowsIANATimezones[id]; got != want { + t.Errorf("%q mapped to %q, want %q", id, got, want) + } + } + for id, tz := range windowsIANATimezones { + if !ValidateIANATimezone(tz) { + t.Errorf("%q mapped to invalid timezone %q", id, tz) + } + } +} + +func TestDetectHostTimezone(t *testing.T) { + if runtime.GOOS != "windows" { + t.Setenv("TZ", "Asia/Shanghai") + } + tz := DetectHostTimezone() + if !ValidateIANATimezone(tz) || tz == "Local" || tz == "Etc/Unknown" { + t.Fatalf("DetectHostTimezone() = %q", tz) + } + t.Logf("detected host timezone %s", tz) + inspected := Inspect(t.TempDir()) + if inspected.Timezone != tz { + t.Fatalf("Inspect().Timezone = %q, want %q", inspected.Timezone, tz) + } + data, err := json.Marshal(inspected) + if err != nil { + t.Fatal(err) + } + var report Report + if err := json.Unmarshal(data, &report); err != nil { + t.Fatal(err) + } + if report.Timezone != tz { + t.Errorf("report timezone = %q, want %q", report.Timezone, tz) + } +} diff --git a/internal/host/timezone_windows.go b/internal/host/timezone_windows.go new file mode 100644 index 0000000..fac232b --- /dev/null +++ b/internal/host/timezone_windows.go @@ -0,0 +1,58 @@ +package host + +import ( + "unsafe" + + "golang.org/x/sys/windows" +) + +var ( + icu = windows.NewLazySystemDLL("icu.dll") + icuTimezoneForWindowsID = icu.NewProc("ucal_getTimeZoneIDForWindowsID") + getDynamicTimezone = windows.NewLazySystemDLL("kernel32.dll").NewProc("GetDynamicTimeZoneInformation") +) + +type dynamicTimezoneInformation struct { + Bias int32 + StandardName [32]uint16 + StandardDate windows.Systemtime + StandardBias int32 + DaylightName [32]uint16 + DaylightDate windows.Systemtime + DaylightBias int32 + TimeZoneKeyName [128]uint16 + DynamicDaylightTimeDisabled uint8 +} + +func DetectHostTimezone() string { + var info dynamicTimezoneInformation + result, _, _ := getDynamicTimezone.Call(uintptr(unsafe.Pointer(&info))) + if uint32(result) == 0xffffffff { + return "" + } + if icuTimezoneForWindowsID.Find() == nil { + var buf [65]uint16 + var status int32 + n, _, _ := icuTimezoneForWindowsID.Call(uintptr(unsafe.Pointer(&info.TimeZoneKeyName[0])), uintptr(^uint32(0)), 0, + uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&status))) + if tz := readICUTimezone(buf[:], int32(n), status); tz != "" { + return tz + } + } + tz := windowsIANATimezones[windows.UTF16ToString(info.TimeZoneKeyName[:])] + if ValidateIANATimezone(tz) { + return tz + } + return "" +} + +func readICUTimezone(buf []uint16, n, status int32) string { + if status > 0 || n <= 0 || int(n) >= len(buf) { + return "" + } + tz := windows.UTF16ToString(buf[:n]) + if tz == "Etc/Unknown" || !ValidateIANATimezone(tz) { + return "" + } + return tz +} diff --git a/locales/en-US/settings.json b/locales/en-US/settings.json index d251ecb..2a282c2 100644 --- a/locales/en-US/settings.json +++ b/locales/en-US/settings.json @@ -447,5 +447,32 @@ "targetDisplayHint": "Target display: {name} ({w}×{h} at {scale}%)", "targetDisplayToastMoved": "Switched to {display}", "targetDisplayToastSaved": "Launch display set to {display}; applies on next start", - "targetDisplaySaveFailed": "Could not update launch display" + "targetDisplaySaveFailed": "Could not update launch display", + "guestTimezoneTitle": "System timezone", + "guestTimezoneLoading": "Loading…", + "guestTimezoneHost": "Follow host (recommended)", + "guestTimezoneOff": "Do not manage (set in macOS)", + "guestTimezoneDesc": "Applies immediately via Guest Tools", + "guestTimezoneSynced": "Synced: {tz}", + "guestTimezoneSyncing": "Syncing to {tz} via Guest Tools", + "guestTimezoneApplyFailed": "Guest Tools could not apply {tz} in macOS", + "guestTimezoneUpgradeHint": "Run the command below in macOS Terminal to update Guest Tools to version {version}", + "guestTimezoneUpgradeAttachHint": "Attach the Guest Tools image on the VM details page to see the command for updating to version {version}", + "guestTimezoneApplyHint": "Run the command below once in macOS Terminal to authorize timezone sync", + "guestTimezoneApplyAttachHint": "Attach the Guest Tools image on the VM details page to see the command for authorizing timezone sync", + "guestTimezoneOffDesc": "Timezone sync is off; managed in macOS System Settings", + "guestTimezoneHostUnknown": "Host timezone was not detected; pick a fixed timezone", + "guestTimezoneSaved": "Timezone setting saved", + "guestTimezoneShanghai": "Shanghai", + "guestTimezoneHongKong": "Hong Kong", + "guestTimezoneTaipei": "Taipei", + "guestTimezoneTokyo": "Tokyo", + "guestTimezoneSeoul": "Seoul", + "guestTimezoneSingapore": "Singapore", + "guestTimezoneLondon": "London", + "guestTimezoneBerlin": "Berlin", + "guestTimezoneLosAngeles": "Los Angeles", + "guestTimezoneNewYork": "New York", + "guestTimezoneSydney": "Sydney", + "guestTimezoneUTC": "UTC" } diff --git a/locales/zh-CN/settings.json b/locales/zh-CN/settings.json index 6c4e81e..151637e 100644 --- a/locales/zh-CN/settings.json +++ b/locales/zh-CN/settings.json @@ -447,5 +447,32 @@ "targetDisplayHint": "目标显示器:{name}({w}×{h},{scale}% 缩放)", "targetDisplayToastMoved": "已切换至「{display}」", "targetDisplayToastSaved": "启动显示器已设为「{display}」,下次启动生效", - "targetDisplaySaveFailed": "无法更新启动显示器" + "targetDisplaySaveFailed": "无法更新启动显示器", + "guestTimezoneTitle": "系统时区", + "guestTimezoneLoading": "读取中…", + "guestTimezoneHost": "跟随宿主机(推荐)", + "guestTimezoneOff": "不管理(由 macOS 自行设置)", + "guestTimezoneDesc": "经 Guest Tools 即时生效", + "guestTimezoneSynced": "已同步:{tz}", + "guestTimezoneSyncing": "正在通过 Guest Tools 同步到 {tz}", + "guestTimezoneApplyFailed": "Guest Tools 无法在 macOS 中应用时区 {tz}", + "guestTimezoneUpgradeHint": "在 macOS 终端运行以下命令,将 Guest Tools 升级到版本 {version}", + "guestTimezoneUpgradeAttachHint": "先在虚拟机详情页挂载 Guest Tools 镜像,即可查看升级到版本 {version} 的命令", + "guestTimezoneApplyHint": "在 macOS 终端运行以下命令,一次性授权时区同步", + "guestTimezoneApplyAttachHint": "先在虚拟机详情页挂载 Guest Tools 镜像,即可查看授权时区同步的命令", + "guestTimezoneOffDesc": "不同步时区,由 macOS 系统设置管理", + "guestTimezoneHostUnknown": "未探测到宿主机时区,可手动选择固定时区", + "guestTimezoneSaved": "已保存时区设置", + "guestTimezoneShanghai": "上海", + "guestTimezoneHongKong": "香港", + "guestTimezoneTaipei": "台北", + "guestTimezoneTokyo": "东京", + "guestTimezoneSeoul": "首尔", + "guestTimezoneSingapore": "新加坡", + "guestTimezoneLondon": "伦敦", + "guestTimezoneBerlin": "柏林", + "guestTimezoneLosAngeles": "洛杉矶", + "guestTimezoneNewYork": "纽约", + "guestTimezoneSydney": "悉尼", + "guestTimezoneUTC": "UTC(协调世界时)" }