From fe838368d76af0c9f4b79dabeca6612d3a978a63 Mon Sep 17 00:00:00 2001 From: YXC0915 Date: Wed, 2 Dec 2026 04:21:27 +0800 Subject: [PATCH] fix(guesttools): protect timezone helper and simplify status --- NOTICE.md | 47 +++++++++++++++++++++++ changes/guest-tools-timezone.json | 7 ++++ frontend/src/components/SettingsModal.tsx | 27 ++++--------- internal/guesttools/image.go | 4 -- internal/guesttools/server.go | 5 ++- internal/guesttools/timezone.go | 37 ++++++++++++------ internal/guesttools/timezone_test.go | 15 ++++---- internal/host/timezone.go | 2 +- internal/host/timezone_windows.go | 26 +------------ 9 files changed, 101 insertions(+), 69 deletions(-) create mode 100644 changes/guest-tools-timezone.json diff --git a/NOTICE.md b/NOTICE.md index ff828e8..eabcaa8 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -37,6 +37,53 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +### Unicode CLDR Windows timezone data + +The Windows timezone fallback table uses the +[CLDR 48 Windows zone mappings](https://github.com/unicode-org/cldr/blob/release-48/common/supplemental/windowsZones.xml). + +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 2004-2025 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. + +SPDX-License-Identifier: Unicode-3.0 + ## Portable runtime The portable runtime bundle (`reims-runtime-win-x64-.tar.zst`) contains diff --git a/changes/guest-tools-timezone.json b/changes/guest-tools-timezone.json new file mode 100644 index 0000000..29d9ddd --- /dev/null +++ b/changes/guest-tools-timezone.json @@ -0,0 +1,7 @@ +{ + "group": "new", + "order": 35, + "authors": ["reiasu2", "yxc0915"], + "zh": "在 macOS 虚拟机设置中选择跟随宿主机或固定时区。同步需要更新并授权 Guest Tools。 [#66](https://github.com/Nwflower/Reims-Go/pull/66)", + "en": "Set a fixed timezone or follow the host in macOS VM settings. Sync requires updated and authorized Guest Tools. [#66](https://github.com/Nwflower/Reims-Go/pull/66)" +} diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index ec88986..105d2ac 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -698,13 +698,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats // ── Pages ──────────────────────────────────────────────── const detectedHostTZ = tzStatus?.host_timezone || host.timezone || '' - const tzSelectedValue = tzStatus - ? tzStatus.mode === 'off' - ? 'off' - : tzStatus.mode === 'custom' && tzStatus.timezone - ? tzStatus.timezone - : 'host' - : undefined + const tzSelectedValue = tzStatus?.mode === 'custom' ? tzStatus.timezone : tzStatus?.mode const tzOptions = [ { value: 'host', label: tr('guestTimezoneHost'), detail: detectedHostTZ || undefined }, ...GUEST_TIMEZONE_PRESETS.map((p) => ({ @@ -717,37 +711,30 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats : []), { value: 'off', label: tr('guestTimezoneOff') }, ] - const tzRequiredVer = tzStatus?.required_agent_version || 11 - const tzAgentVer = tzStatus?.guest_agent_version ?? 0 - const tzRunning = tzStatus?.running ?? running - const tzConnected = tzStatus?.guest_connected ?? false - const tzHelperReady = tzStatus?.helper_ready ?? false - const tzEffective = tzStatus?.effective_timezone || '' - const tzApplied = tzStatus?.guest_applied || '' - let tzDesc: React.ReactNode = tr('guestTimezoneDesc') let tzCommand = '' if (tzStatus) { + const tzEffective = tzStatus.effective_timezone if (tzStatus.mode === 'off') { tzDesc = tr('guestTimezoneOffDesc') } else if (detail.guest_tools_disabled) { tzDesc = {tr('gtStatusOffTip')} } else if (!tzEffective) { tzDesc = {tr('guestTimezoneHostUnknown')} - } else if (tzRunning && tzConnected) { + } else if (tzStatus.running && tzStatus.guest_connected) { const tzFailure = tzStatus.timezone_error ? {tr('guestTimezoneApplyFailed', { tz: tzEffective })} : null - if (tzAgentVer < tzRequiredVer) { - tzDesc = {tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzRequiredVer })} + if (tzStatus.guest_agent_version < tzStatus.required_agent_version) { + tzDesc = {tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzStatus.required_agent_version })} if (detail.guest_tools_attached) tzCommand = GUEST_TOOLS_INSTALL_CMD - } else if (!tzHelperReady) { + } else if (!tzStatus.helper_ready) { const hint = tr(detail.guest_tools_attached ? 'guestTimezoneApplyHint' : 'guestTimezoneApplyAttachHint') tzDesc = tzFailure ?
{tzFailure}{hint}
: hint if (detail.guest_tools_attached) tzCommand = GUEST_TIMEZONE_APPLY_CMD } else if (tzFailure) { tzDesc = tzFailure - } else if (tzApplied === tzEffective) { + } else if (tzStatus.guest_applied === tzEffective) { tzDesc = } else { tzDesc = tr('guestTimezoneSyncing', { tz: tzEffective }) diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 126daba..ce3f380 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -450,10 +450,6 @@ apply_host_config() { report_status() { [ -n "$REIMS_HOST_URL" ] && [ -n "$REIMS_TOKEN" ] || return 0 timezone_applied=$(current_timezone) - timezone_helper_ready=false - if [ -x "$TIMEZONE_HELPER" ] && /usr/bin/sudo -n -l -- "$TIMEZONE_HELPER" >/dev/null 2>&1; then - timezone_helper_ready=true - fi curl -fsS -m "${1:-3}" -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index fb80b17..d1fda43 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -715,8 +715,9 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { } connected := !vm.lastSeen.IsZero() && time.Since(vm.lastSeen) <= maxAge freshStatus := connected && time.Since(vm.lastStatus) <= maxAge - timezoneError := "" + var timezone, timezoneError string if freshStatus { + timezone = vm.timezoneApplied timezoneError = vm.timezoneError } return GuestStatus{ @@ -727,7 +728,7 @@ func (s *Server) Status(vmName string, maxAge time.Duration) GuestStatus { SleepActive: connected && vm.sleepActive, AgentVersion: vm.agentVersion, LastSeen: vm.lastSeen, - TimezoneApplied: vm.timezoneApplied, + TimezoneApplied: timezone, TimezoneHelperReady: freshStatus && vm.timezoneHelperReady, TimezoneError: timezoneError, } diff --git a/internal/guesttools/timezone.go b/internal/guesttools/timezone.go index a7d8529..69ae96f 100644 --- a/internal/guesttools/timezone.go +++ b/internal/guesttools/timezone.go @@ -32,8 +32,8 @@ func (s *Server) SetTimezone(vmKey, token, setting string) { } } -const guestTimezonePath = "/Library/Application Support/ReimsGuestTools/set-timezone.sh" -const guestTimezoneSudoers = "/etc/sudoers.d/reims-timezone-" +const guestTimezonePath = "/private/etc/reims-timezone/set-timezone.sh" +const guestTimezoneSudoers = "/private/etc/sudoers.d/reims-timezone-" const guestTimezoneValidation = ` valid_timezone() { @@ -47,6 +47,8 @@ valid_timezone() { const guestTimezoneAgent = ` TIMEZONE_HELPER="` + guestTimezonePath + `" timezone_error="" +timezone_helper_ready=false +timezone_check_at=0 ` + guestTimezoneValidation + ` current_timezone() ( link=$(/usr/bin/readlink /etc/localtime) || return 0 @@ -62,10 +64,23 @@ current_timezone() ( sync_timezone() { desired_timezone=$(config_timezone "$1") || desired_timezone="" timezone_error="" - if [ -n "$desired_timezone" ] && [ -x "$TIMEZONE_HELPER" ] && - [ "$desired_timezone" != "$(current_timezone)" ] && - ! /usr/bin/sudo -n -- "$TIMEZONE_HELPER" "$desired_timezone" >/dev/null 2>&1; then - timezone_error=apply_failed + if [ -z "$desired_timezone" ] || [ ! -x "$TIMEZONE_HELPER" ]; then + timezone_helper_ready=false + timezone_check_at=0 + return 0 + fi + timezone_now=$(/bin/date +%s) + if [ "$timezone_now" -ge "$timezone_check_at" ]; then + timezone_helper_ready=false + if /usr/bin/sudo -n -l -- "$TIMEZONE_HELPER" >/dev/null 2>&1; then + timezone_helper_ready=true + fi + timezone_check_at=$((timezone_now + 30)) + fi + if [ "$timezone_helper_ready" = true ] && [ "$desired_timezone" != "$(current_timezone)" ]; then + if ! /usr/bin/sudo -n -- "$TIMEZONE_HELPER" "$desired_timezone" >/dev/null 2>&1; then + timezone_error=apply_failed + fi fi } ` @@ -216,8 +231,8 @@ fi set -eu export LC_ALL=C ` + guestTimezoneSystemPaths + ` -secure_path /Library -d 002 -secure_path "${helper_dir%/*}" -d 002 +secure_path /private -d 022 +secure_path /private/etc -d 022 if [ ! -e "$sudoers_dir" ] && [ ! -L "$sudoers_dir" ]; then /usr/bin/install -d -o root -g wheel -m 0755 "$sudoers_dir" fi @@ -283,7 +298,7 @@ trap cleanup_timezone_install EXIT rule_tmp=$(/usr/bin/mktemp "$sudoers_dir/.reims-timezone.XXXXXX") # A numeric sudoers user ID avoids interpreting special characters in a username. -printf '#%s ALL=(root) NOPASSWD: /Library/Application\\ Support/ReimsGuestTools/set-timezone.sh\n' "$1" >"$rule_tmp" +printf '#%s ALL=(root) NOPASSWD: %s\n' "$1" "$helper" >"$rule_tmp" /usr/sbin/chown root:wheel "$rule_tmp" /bin/chmod 0440 "$rule_tmp" /usr/sbin/visudo -cf "$rule_tmp" @@ -314,6 +329,8 @@ if [ "$#" -eq 0 ]; then set -eu export LC_ALL=C ` + guestTimezoneSystemPaths + ` +secure_path /private -d 022 +secure_path /private/etc -d 022 if [ -e "$sudoers_dir" ] || [ -L "$sudoers_dir" ]; then secure_path "$sudoers_dir" -d 022 else @@ -328,8 +345,6 @@ for rule in "$rule_prefix"*; do fi done if [ -e "$helper" ] || [ -L "$helper" ]; then - secure_path /Library -d 002 - secure_path "${helper_dir%/*}" -d 002 secure_path "$helper_dir" -d 022 /bin/rm -f "$helper" fi diff --git a/internal/guesttools/timezone_test.go b/internal/guesttools/timezone_test.go index b35fef6..41b34db 100644 --- a/internal/guesttools/timezone_test.go +++ b/internal/guesttools/timezone_test.go @@ -15,8 +15,9 @@ import ( func testTimezoneScripts(t *testing.T, sh, rootInstall string) { t.Helper() rewrite := strings.NewReplacer( - "/Library", "system/Library", - "/etc/sudoers.d", "system/sudoers.d", + "/private/etc/sudoers.d", "system/sudoers.d", + "/private/etc", "system/etc", + "/private", "system", "/Volumes/REIMSTOOLS", "tools", "/var/db/timezone/zoneinfo", "zones", "/usr/share/zoneinfo", "missing-zones", @@ -109,7 +110,7 @@ expect_timezone_error "" {"rollback_reinstall", "seed_old; fail_visudo=1", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"}, {"rollback_failed_rule_replace", "seed_old; fail_rule_replace=1", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"}, {"rollback_first_install", "fail_visudo=1", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"}, - {"reject_world_writable_parent", "parent_mode=0777", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"}, + {"reject_group_writable_parent", "parent_mode=0775", "[ \"$result\" -ne 0 ] && [ ! -e \"$helper\" ] && [ ! -e \"$rule\" ]"}, {"reject_group_writable_helper", "seed_old; helper_mode=0775", "[ \"$result\" -ne 0 ] && [ \"$(cat \"$helper\")\" = old-helper ] && [ \"$(cat \"$rule\")\" = old-rule ]"}, } { t.Run(tc.name, func(t *testing.T) { @@ -166,7 +167,7 @@ expect_timezone_error "" t.Run("uninstall_failure", func(t *testing.T) { script := "seed_old\nuid=501\nfail_rm=$helper\n" + guestTimezoneUninstall + "\necho 'Uninstalled'\n" out, err := run(t, script) - if err == nil || !strings.Contains(out, "Remaining Reims timezone file: system/Library/Application Support/ReimsGuestTools/set-timezone.sh") || + if err == nil || !strings.Contains(out, "Remaining Reims timezone file: system/etc/reims-timezone/set-timezone.sh") || !strings.Contains(out, "retry") || strings.Contains(out, "Uninstalled") { t.Fatalf("timezone uninstall failure: %v\n%s", err, out) } @@ -175,9 +176,9 @@ expect_timezone_error "" const timezoneShellFixture = ` set -eu -parent_mode=0775 +parent_mode=0755 helper_mode=0755 -helper='system/Library/Application Support/ReimsGuestTools/set-timezone.sh' +helper=system/etc/reims-timezone/set-timezone.sh rule=system/sudoers.d/reims-timezone-501 mkdir -p "${helper%/*}" system/sudoers.d tools zones/Asia printf new-helper > tools/set-timezone.sh @@ -192,7 +193,7 @@ mock_stat() { echo 0 else case "$3" in - system/Library|'system/Library/Application Support') echo "$parent_mode" ;; + system|system/etc) echo "$parent_mode" ;; "$helper") echo "$helper_mode" ;; *) echo 0755 ;; esac diff --git a/internal/host/timezone.go b/internal/host/timezone.go index 388ff09..4084573 100644 --- a/internal/host/timezone.go +++ b/internal/host/timezone.go @@ -19,7 +19,7 @@ func ValidateIANATimezone(tz string) bool { } // CLDR 48 windowsZones.xml, territory 001 (global defaults). -// Copyright © 1991-2013 Unicode, Inc. https://www.unicode.org/copyright.html +// Copyright © 2004-2025 Unicode, Inc. See NOTICE.md for the Unicode license. // https://github.com/unicode-org/cldr/blob/release-48/common/supplemental/windowsZones.xml var windowsIANATimezones = map[string]string{ "Dateline Standard Time": "Etc/GMT+12", diff --git a/internal/host/timezone_windows.go b/internal/host/timezone_windows.go index 931607e..fac232b 100644 --- a/internal/host/timezone_windows.go +++ b/internal/host/timezone_windows.go @@ -1,7 +1,6 @@ package host import ( - "sync" "unsafe" "golang.org/x/sys/windows" @@ -9,17 +8,10 @@ import ( var ( icu = windows.NewLazySystemDLL("icu.dll") - icuDefaultTimezone = icu.NewProc("ucal_getDefaultTimeZone") icuTimezoneForWindowsID = icu.NewProc("ucal_getTimeZoneIDForWindowsID") getDynamicTimezone = windows.NewLazySystemDLL("kernel32.dll").NewProc("GetDynamicTimeZoneInformation") ) -var initialWindowsTimezone struct { - sync.Once - key [128]uint16 - iana string -} - type dynamicTimezoneInformation struct { Bias int32 StandardName [32]uint16 @@ -33,28 +25,14 @@ type dynamicTimezoneInformation struct { } func DetectHostTimezone() string { - var buf [65]uint16 - var status int32 - var info dynamicTimezoneInformation result, _, _ := getDynamicTimezone.Call(uintptr(unsafe.Pointer(&info))) - // ICU caches the default zone for the process. Use the live Windows key - // for lookups if the system setting has changed since the first probe. - initialWindowsTimezone.Do(func() { - initialWindowsTimezone.key = info.TimeZoneKeyName - if icuDefaultTimezone.Find() == nil { - n, _, _ := icuDefaultTimezone.Call(uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&status))) - initialWindowsTimezone.iana = readICUTimezone(buf[:], int32(n), status) - } - }) - if initialWindowsTimezone.key == info.TimeZoneKeyName && initialWindowsTimezone.iana != "" { - return initialWindowsTimezone.iana - } if uint32(result) == 0xffffffff { return "" } if icuTimezoneForWindowsID.Find() == nil { - status = 0 + var buf [65]uint16 + var status int32 n, _, _ := icuTimezoneForWindowsID.Call(uintptr(unsafe.Pointer(&info.TimeZoneKeyName[0])), uintptr(^uint32(0)), 0, uintptr(unsafe.Pointer(&buf[0])), uintptr(len(buf)), uintptr(unsafe.Pointer(&status))) if tz := readICUTimezone(buf[:], int32(n), status); tz != "" {