From 107a8d73e0986875d1f2bd220fa6e2b572f00e91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <105714958+Nwflower@users.noreply.github.com> Date: Sat, 5 Dec 2026 20:54:41 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E6=94=B6=E6=8B=A2=E6=A0=B8?= =?UTF-8?q?=E5=BF=83=E7=AE=A1=E7=BA=BF=E3=80=81=E5=BC=BA=E5=8C=96=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E5=A4=84=E7=90=86=E3=80=81=E4=BC=98=E5=8C=96=E7=83=AD?= =?UTF-8?q?=E8=B7=AF=E5=BE=84=E4=B8=8E=E6=9B=B4=E6=96=B0=E4=BD=93=E7=A7=AF?= =?UTF-8?q?=20(#200)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * refactor: 收拢核心管线、强化错误处理、优化热路径与更新体积 * fix: preserve download recovery and bound PBZX decoding Keep VM diagnostics available during plugin initialization failures and verify settings through the unified driver lifecycle. --- .github/workflows/dev-release.yml | 2 + .github/workflows/release.yml | 2 + changes/refactor-pipeline-update-perf.json | 7 + frontend/scripts/test-no-empty-catch.mjs | 45 +- frontend/src/App.tsx | 276 ++++------- frontend/src/components/AboutPage.tsx | 5 +- frontend/src/components/AppDialogs.tsx | 257 ++++++++++ frontend/src/components/Setup.tsx | 9 +- frontend/src/components/vmPage/snapshots.tsx | 7 +- frontend/src/components/vmPage/ssh.tsx | 7 +- frontend/src/lib/uiSdk.ts | 3 +- internal/app/app.go | 4 +- internal/app/appupdate_flow.go | 65 ++- internal/app/appupdate_flow_test.go | 57 +++ internal/app/guesttools_flow.go | 118 +---- internal/app/legacy_ledger_test.go | 27 +- internal/app/lifecycle_flow.go | 72 ++- internal/app/lifecycle_flow_test.go | 100 ---- internal/app/macos_detail.go | 7 - internal/app/macos_lifecycle_native.go | 469 +------------------ internal/app/macos_settings.go | 66 +-- internal/app/macos_settings_test.go | 432 ++++++++--------- internal/app/network_review_test.go | 129 ----- internal/app/plugins_flow.go | 192 ++++---- internal/app/thumbnail_flow.go | 7 +- internal/archtest/error_handling_test.go | 95 ++++ internal/archtest/macos_boundary_test.go | 1 - internal/cli/plugin.go | 52 +- internal/datamigrate/datamigrate.go | 4 +- internal/downloader/parallel.go | 28 +- internal/fetch/fetch.go | 44 +- internal/fetch/fetch_test.go | 76 ++- internal/guesttools/drop_agent_test.go | 24 +- internal/guesttools/guesttools_test.go | 45 +- internal/guesttools/image.go | 30 +- internal/host/audio_other.go | 23 - internal/host/close_vm_other.go | 22 - internal/host/console_other.go | 8 - internal/host/defender_other.go | 11 - internal/host/display_move_other.go | 11 - internal/host/display_other.go | 7 - internal/host/drives_other.go | 36 -- internal/host/elevate_other.go | 17 - internal/host/fonts_other.go | 9 - internal/host/foreground_other.go | 12 - internal/host/fullscreen_hotkey_other.go | 13 - internal/host/fullscreen_other.go | 13 - internal/host/host_other.go | 50 -- internal/host/hypervisor_other.go | 21 - internal/host/ime_hook_other.go | 14 - internal/host/input_service_other.go | 11 - internal/host/memory_other.go | 6 - internal/host/open_other.go | 26 - internal/host/procwait_other.go | 16 - internal/host/qemu_aslr_other.go | 14 - internal/host/rawdisk_other.go | 9 - internal/host/scheduling_other.go | 18 - internal/host/smbios_memory_other.go | 7 - internal/host/stats_other.go | 13 - internal/host/stubs_hardware_other.go | 152 ++++++ internal/host/stubs_system_other.go | 95 ++++ internal/host/stubs_window_other.go | 76 +++ internal/host/timezone_other.go | 24 - internal/host/volume_other.go | 50 -- internal/host/vulkan_driverstore_windows.go | 12 +- internal/host/whpx_probe_other.go | 9 - internal/macos/installer/pkg_extract.go | 175 +++++-- internal/macos/installer/pkg_extract_test.go | 102 ++++ internal/macos/macosdriver/driver.go | 9 +- internal/macos/opencore/image.go | 4 +- internal/packetbridge/bridge.go | 42 +- internal/packetbridge/frame.go | 41 +- internal/plugin/builtin/bootstrap.go | 104 ++++ internal/plugin/builtin/builtin_test.go | 6 +- internal/plugin/kernel_test.go | 4 +- internal/plugin/ledger.go | 15 +- internal/plugin/registry.go | 2 +- internal/plugin/scope.go | 11 +- internal/selfupdate/takeover_windows.go | 77 ++- internal/selfupdate/takeover_windows_test.go | 19 + internal/thumb/preview.go | 10 +- internal/tray/tray.go | 7 +- internal/tray/tray_test.go | 6 +- internal/version/version.go | 32 +- 84 files changed, 2120 insertions(+), 2115 deletions(-) create mode 100644 changes/refactor-pipeline-update-perf.json create mode 100644 frontend/src/components/AppDialogs.tsx create mode 100644 internal/archtest/error_handling_test.go delete mode 100644 internal/host/audio_other.go delete mode 100644 internal/host/close_vm_other.go delete mode 100644 internal/host/console_other.go delete mode 100644 internal/host/defender_other.go delete mode 100644 internal/host/display_move_other.go delete mode 100644 internal/host/display_other.go delete mode 100644 internal/host/drives_other.go delete mode 100644 internal/host/elevate_other.go delete mode 100644 internal/host/fonts_other.go delete mode 100644 internal/host/foreground_other.go delete mode 100644 internal/host/fullscreen_hotkey_other.go delete mode 100644 internal/host/fullscreen_other.go delete mode 100644 internal/host/host_other.go delete mode 100644 internal/host/hypervisor_other.go delete mode 100644 internal/host/ime_hook_other.go delete mode 100644 internal/host/input_service_other.go delete mode 100644 internal/host/memory_other.go delete mode 100644 internal/host/open_other.go delete mode 100644 internal/host/procwait_other.go delete mode 100644 internal/host/qemu_aslr_other.go delete mode 100644 internal/host/rawdisk_other.go delete mode 100644 internal/host/scheduling_other.go delete mode 100644 internal/host/smbios_memory_other.go delete mode 100644 internal/host/stats_other.go create mode 100644 internal/host/stubs_hardware_other.go create mode 100644 internal/host/stubs_system_other.go create mode 100644 internal/host/stubs_window_other.go delete mode 100644 internal/host/timezone_other.go delete mode 100644 internal/host/volume_other.go delete mode 100644 internal/host/whpx_probe_other.go create mode 100644 internal/macos/installer/pkg_extract_test.go create mode 100644 internal/plugin/builtin/bootstrap.go diff --git a/.github/workflows/dev-release.yml b/.github/workflows/dev-release.yml index ed6b869..a33b18a 100644 --- a/.github/workflows/dev-release.yml +++ b/.github/workflows/dev-release.yml @@ -137,6 +137,8 @@ jobs: - name: Build Windows x64 binary shell: pwsh + env: + CGO_ENABLED: "0" run: | $ErrorActionPreference = 'Stop' $ver = $env:DEV_VERSION diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index da3ab89..1ed9ac7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -103,6 +103,8 @@ jobs: - name: Build Windows x64 binary shell: pwsh + env: + CGO_ENABLED: "0" run: | $ErrorActionPreference = 'Stop' $tag = $env:RELEASE_TAG diff --git a/changes/refactor-pipeline-update-perf.json b/changes/refactor-pipeline-update-perf.json new file mode 100644 index 0000000..e50c642 --- /dev/null +++ b/changes/refactor-pipeline-update-perf.json @@ -0,0 +1,7 @@ +{ + "group": "improvements", + "order": 10, + "authors": ["Nwflower"], + "zh": "应用内更新改为优先下载已校验的 `.zip` 压缩包(更新流量减少约 62%),并优化物理桥接转发吞吐与离线安装镜像 PBZX 并发解压速度。", + "en": "Download verified `.zip` release archives for in-app updates (~62% smaller update downloads), reduce per-packet allocations in the packet bridge, and parallelize PBZX chunk decompression for offline installer packages." +} diff --git a/frontend/scripts/test-no-empty-catch.mjs b/frontend/scripts/test-no-empty-catch.mjs index 71cfbd7..d1c8781 100644 --- a/frontend/scripts/test-no-empty-catch.mjs +++ b/frontend/scripts/test-no-empty-catch.mjs @@ -30,11 +30,39 @@ function isEmptyBlock(block) { return ts.isBlock(block) && block.statements.every((stmt) => ts.isEmptyStatement(stmt)) } -function isEmptyFunctionBody(expr) { +function isSilentLiteralExpr(expr) { + let current = expr + while (ts.isParenthesizedExpression(current)) current = current.expression + if ( + current.kind === ts.SyntaxKind.NullKeyword || + current.kind === ts.SyntaxKind.TrueKeyword || + current.kind === ts.SyntaxKind.FalseKeyword || + ts.isStringLiteralLike(current) || + ts.isNumericLiteral(current) || + ts.isVoidExpression(current) + ) { + return true + } + if (ts.isIdentifier(current) && current.text === 'undefined') return true + if (ts.isArrayLiteralExpression(current) && current.elements.length === 0) return true + if (ts.isObjectLiteralExpression(current) && current.properties.length === 0) return true + return false +} + +function isSilentFunctionBody(expr) { let current = expr while (ts.isParenthesizedExpression(current)) current = current.expression if (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) { - return isEmptyBlock(current.body) + if (isEmptyBlock(current.body)) return true + if (!ts.isBlock(current.body) && isSilentLiteralExpr(current.body)) return true + if ( + ts.isBlock(current.body) && + current.body.statements.length === 1 && + ts.isReturnStatement(current.body.statements[0]) && + (!current.body.statements[0].expression || isSilentLiteralExpr(current.body.statements[0].expression)) + ) { + return true + } } return false } @@ -70,9 +98,9 @@ export function findEmptyCatchesInJS(sourceText, filePath = 'sample.ts') { record(node, 'empty-catch-clause') } else if (ts.isCallExpression(node)) { const method = getCalleeMethodName(node.expression) - if (method === 'catch' && node.arguments.length >= 1 && isEmptyFunctionBody(node.arguments[0])) { + if (method === 'catch' && node.arguments.length >= 1 && isSilentFunctionBody(node.arguments[0])) { record(node.arguments[0], 'empty-promise-catch') - } else if (method === 'then' && node.arguments.length >= 2 && isEmptyFunctionBody(node.arguments[1])) { + } else if (method === 'then' && node.arguments.length >= 2 && isSilentFunctionBody(node.arguments[1])) { record(node.arguments[1], 'empty-promise-then-reject') } } @@ -321,10 +349,15 @@ test('detector self-test: catches all empty JS/TS catch forms and allows handled 'p.catch(async () => { ; })', 'p.then(ok, () => {})', 'p.then(ok, (err) => { // noop\n})', + 'p.catch(() => null)', + 'p.catch(() => "")', + 'p.catch(() => false)', + 'p.catch(() => [])', + 'p.catch(() => { return null })', ].join('\n') const badFindings = findEmptyCatchesInJS(bad, 'bad.ts') - assert.equal(badFindings.length, 11, `expected 11 findings, got ${JSON.stringify(badFindings)}`) + assert.equal(badFindings.length, 16, `expected 16 findings, got ${JSON.stringify(badFindings)}`) const good = [ 'const text = "try { a() } catch {} .catch(() => {})"', @@ -332,7 +365,7 @@ test('detector self-test: catches all empty JS/TS catch forms and allows handled 'try { a() } catch (e) { console.warn(e) }', 'try { a() } catch { return fallback }', 'p.catch((e) => console.warn(e))', - 'p.catch(() => null)', + 'p.catch((e) => { console.warn(e); return null })', 'p.then(ok, (e) => handle(e))', ].join('\n') diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d14c315..69c7496 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,11 +1,8 @@ import { Minus, Moon, Square, Sun, X } from 'lucide-react' import React, { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react' import type { WizardDraft } from './components/CreateWizard' -import { DeleteDialog } from './components/DeleteDialog' -import { ElevationDialog } from './components/ElevationDialog' -import { CloneDialog } from './components/CloneDialog' +import { AppDialogs } from './components/AppDialogs' import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog' -import { SendTextDialog } from './components/SendTextDialog' import { LogPanel, LogTab } from './components/LogPanel' import { TitleMenus } from './components/TitleMenus' import { UpdateCapsule } from './components/UpdateCapsule' @@ -24,7 +21,7 @@ import { creatingVMTasks, currentTask, finishedTaskTTL, isActiveInstallerTask, p import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine' import type { UIStateSnapshot } from './lib/uiSdk' import { hasVisibleDialog } from './lib/dialogState' -import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats' +import { refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats' import { useAppearance } from './lib/useAppearance' import { useAppUpdate } from './lib/useAppUpdate' import { useFileDrop } from './lib/useFileDrop' @@ -35,18 +32,13 @@ import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCond import { publishPluginHostEvent } from './lib/pluginViewEvents' import { buildSafePluginAssetURL } from './lib/pluginAssets' import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types' -import { Button, Tip, TooltipProvider } from './ui/controls' -import { ConfirmDialog, Modal } from './ui/dialog' +import { Tip, TooltipProvider } from './ui/controls' import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast' import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals' import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails' // Opened on demand, so each is its own chunk and stays out of the startup -// bundle: the wizard, VM settings and affinity dialogs, first-run setup, and -// the Engine / Installers / Settings pages. -const CreateWizard = lazy(() => import('./components/CreateWizard').then((m) => ({ default: m.CreateWizard }))) -const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) => ({ default: m.SettingsModal }))) -const AffinityDialog = lazy(() => import('./components/AffinityDialog').then((m) => ({ default: m.AffinityDialog }))) +// bundle: first-run setup, and the Engine / Installers / Settings pages. const Setup = lazy(() => import('./components/Setup').then((m) => ({ default: m.Setup }))) const HostView = lazy(() => import('./components/HostView').then((m) => ({ default: m.HostView }))) const ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage }))) @@ -152,7 +144,7 @@ export const App: React.FC = () => { // Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user. const [sidebarOpen, setSidebarOpen] = useState(() => { - try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch { return true } + try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch (e) { console.warn('[app] read sidebar state failed:', e); return true } }) const toggleSidebar = () => setSidebarOpen((open) => { try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch (e) { console.warn('[app] persist sidebar state failed:', e) } @@ -372,7 +364,10 @@ export const App: React.FC = () => { let live = true api.GetVMDetail(selectedVM.name) .then((d) => { if (live) setDetail(d) }) - .catch(() => { if (live) setDetail(null) }) + .catch((e) => { + console.warn('[app] GetVMDetail failed:', selectedVM.name, e) + if (live) setDetail(null) + }) return () => { live = false } }, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision, state?.active_runtime?.commit, state?.runtime_capture_supported]) @@ -597,9 +592,15 @@ export const App: React.FC = () => { } } const folderDone = async () => { - const s = await api.GetState().catch(() => null) - if (s) setState(s) - setSetupStage(s?.active_runtime ? null : 'runtime') + try { + const s = await api.GetState() + setState(s) + setSetupStage(s?.active_runtime ? null : 'runtime') + } catch (e) { + console.warn('[app] GetState after setup failed:', e) + fail(tr('failGeneric'), e) + setSetupStage('runtime') + } } const showSetup = !!state && (state.needs_setup || setupStage === 'runtime') // The data folder opened read-only (internal/dataroot): nothing in it may be @@ -1447,149 +1448,80 @@ export const App: React.FC = () => { /> )} - {showWizard && state && ( - - { setShowWizard(false); setWizardDraft(null) }} - onSubmit={submitCreate} - /> - - )} - - {showSettings && state && detail && ( - - setAffinityTarget({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })} - affinityVersion={affinityVersion} - onHostChanged={refresh} - onToast={toasts.push} - onClose={() => setShowSettings(false)} - onSaved={() => { - setShowSettings(false) - toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') }) - refresh() - }} - /> - - )} - - {affinityTarget && state && ( - - setAffinityTarget(null)} - onApplied={(st) => { - setAffinityTarget(null) - setAffinityVersion((v) => v + 1) - const count = st.effective_cpus?.length ?? 0 - const mask = st.live_mask_hex || st.effective_mask_hex || '0x0' - toasts.push({ - kind: 'ok', - title: st.running - ? tr('toastAffinityApplied', { count, mask }) - : tr('toastAffinitySaved'), - }) - refresh() - }} - /> - - )} - - {update.confirming && ( - update.cancelInstall()} - > -
-

{tr('updateConfirmBody', { n: runningVMCount })}

- {state?.host.needs_cold_reboot_workaround &&

{tr('updateConfirmWin10')}

} -
-
- - - - - -
-
- )} - - {deleteTarget && ( - setDeleteTarget(null)} onConfirm={confirmDelete} /> - )} - - {closeDownloadsOpen && ( - setCloseDownloadsOpen(false)} - onConfirm={() => { setCloseDownloadsOpen(false); void api.QuitApp() }} - /> - )} - - {elevationQueue.length > 0 && ( - { - const active = elevationQueue[0] - setElevationQueue((q) => q.filter((item) => item.id !== active.id)) - api.ResolveElevationRequest(active.id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e)) - }} - /> - )} - - {discardSuspendTarget && (() => { - const targetVM = findVM(discardSuspendTarget) - const targetName = targetVM?.name ?? discardSuspendTarget - return ( - setDiscardSuspendTarget(null)} - onConfirm={confirmDiscardSuspend} - /> - ) - })()} - - {cloneSource && ( - setCloneSource(null)} - onConfirm={confirmClone} - /> - )} + { setShowWizard(false); setWizardDraft(null) }} + onSubmitCreate={submitCreate} + showSettings={showSettings} + onCloseSettings={() => setShowSettings(false)} + onSavedSettings={() => { + setShowSettings(false) + toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastSavedNextStart' : 'toastSaved') }) + refresh() + }} + affinityTarget={affinityTarget} + affinityVersion={affinityVersion} + onOpenAffinity={setAffinityTarget} + onCloseAffinity={() => setAffinityTarget(null)} + onAffinityApplied={(st) => { + setAffinityTarget(null) + setAffinityVersion((v) => v + 1) + const count = st.effective_cpus?.length ?? 0 + const mask = st.live_mask_hex || st.effective_mask_hex || '0x0' + toasts.push({ + kind: 'ok', + title: st.running + ? tr('toastAffinityApplied', { count, mask }) + : tr('toastAffinitySaved'), + }) + refresh() + }} + updateConfirming={update.confirming} + updateLatest={update.info?.latest ?? ''} + onCancelInstallUpdate={() => update.cancelInstall()} + onConfirmInstallUpdate={update.confirmInstall} + deleteTarget={deleteTarget} + onCancelDelete={() => setDeleteTarget(null)} + onConfirmDelete={confirmDelete} + closeDownloadsOpen={closeDownloadsOpen} + onCancelCloseDownloads={() => setCloseDownloadsOpen(false)} + elevationQueue={elevationQueue} + onResolveElevation={(id, approved) => { + setElevationQueue((q) => q.filter((item) => item.id !== id)) + api.ResolveElevationRequest(id, approved).catch((e) => console.warn('[app] ResolveElevationRequest failed:', e)) + }} + discardSuspendTarget={discardSuspendTarget} + onCancelDiscardSuspend={() => setDiscardSuspendTarget(null)} + onConfirmDiscardSuspend={confirmDiscardSuspend} + cloneSource={cloneSource} + onCancelClone={() => setCloneSource(null)} + onConfirmClone={confirmClone} + sendTextTarget={sendTextTarget} + onCancelSendText={() => setSendTextTarget(null)} + onConfirmSendText={(key, driverID, name, text) => { + setSendTextTarget(null) + typeInto(key, () => api.TypeText(driverID, name, text)) + }} + pluginDialogs={pluginViewState.dialogs} + findRouteView={findRouteView} + renderPluginView={renderPluginView} + findVM={findVM} + onCopy={copy} + onRefresh={refresh} + onToast={toasts.push} + /> {onlineRecoveryTarget && ( { /> )} - {sendTextTarget && (() => { - const sendVM = findVM(sendTextTarget) - const sendName = sendVM?.name ?? sendTextTarget - return ( - setSendTextTarget(null)} - onConfirm={(text) => { - const target = sendTextTarget - setSendTextTarget(null) - typeInto(sendVM ? vmRefKey(sendVM) : target, () => api.TypeText(sendVM?.driver_id ?? '', sendName, text)) - }} - /> - ) - })()} - - {/* Every open dialog stays mounted so the ones underneath keep their state. */} - {pluginViewState.dialogs.map((route) => { - const view = findRouteView(route) - return view && renderPluginView(route, view, true) - })} - {/* Outside the isolated shell so toasts stay above dialogs and the overlay layer. */} diff --git a/frontend/src/components/AboutPage.tsx b/frontend/src/components/AboutPage.tsx index 38efb9a..83585af 100644 --- a/frontend/src/components/AboutPage.tsx +++ b/frontend/src/components/AboutPage.tsx @@ -98,7 +98,10 @@ export const AboutPage: React.FC = ({ let cancelled = false api.CanOpenQQGroup() .then((ok) => { if (!cancelled) setQQInstalled(!!ok) }) - .catch(() => { if (!cancelled) setQQInstalled(false) }) + .catch((e) => { + console.warn('[about] CanOpenQQGroup failed:', e) + if (!cancelled) setQQInstalled(false) + }) return () => { mountedRef.current = false cancelled = true diff --git a/frontend/src/components/AppDialogs.tsx b/frontend/src/components/AppDialogs.tsx new file mode 100644 index 0000000..ac13144 --- /dev/null +++ b/frontend/src/components/AppDialogs.tsx @@ -0,0 +1,257 @@ +import React, { Suspense, lazy } from 'react' +import type { WizardDraft } from './CreateWizard' +import { DeleteDialog } from './DeleteDialog' +import { ElevationDialog } from './ElevationDialog' +import { CloneDialog } from './CloneDialog' +import { SendTextDialog } from './SendTextDialog' +import { I18nKey, t } from '../i18n' +import { latestVMStats } from '../lib/vmStats' +import { vmRefKey } from '../lib/vmRef' +import type { PluginViewRoute } from '../lib/pluginViewRouter' +import type { AppState, CreateOpts, Locale, Task, VMDetail, VMListItem, ViewContribution } from '../types' +import { Button } from '../ui/controls' +import { ConfirmDialog, Modal } from '../ui/dialog' +import type { ToastInput } from '../ui/toast' +import { api, type ElevationPrompt } from '../wails' + +const CreateWizard = lazy(() => import('./CreateWizard').then((m) => ({ default: m.CreateWizard }))) +const SettingsModal = lazy(() => import('./SettingsModal').then((m) => ({ default: m.SettingsModal }))) +const AffinityDialog = lazy(() => import('./AffinityDialog').then((m) => ({ default: m.AffinityDialog }))) + +interface AppDialogsProps { + locale: Locale + state: AppState | null + detail: VMDetail | null + selectedVM: VMListItem | undefined + selectedIsMacOS: boolean + effectiveState: string + fixedModeSupported: boolean + diskCacheSupported: boolean + runningVMCount: number + tasks: Task[] + displayNames: Record + + showWizard: boolean + wizardDraft: WizardDraft | null + onCloseWizard: () => void + onSubmitCreate: (payload: CreateOpts, draft: WizardDraft) => void + + showSettings: boolean + onCloseSettings: () => void + onSavedSettings: () => void + + affinityTarget: { name: string; driverID: string } | null + affinityVersion: number + onOpenAffinity: (target: { name: string; driverID: string }) => void + onCloseAffinity: () => void + onAffinityApplied: (st: { running?: boolean; effective_cpus?: number[]; live_mask_hex?: string; effective_mask_hex?: string }) => void + + updateConfirming: boolean + updateLatest: string + onCancelInstallUpdate: () => void + onConfirmInstallUpdate: () => void + + deleteTarget: string | null + onCancelDelete: () => void + onConfirmDelete: (keepFiles: boolean) => void + + closeDownloadsOpen: boolean + onCancelCloseDownloads: () => void + + elevationQueue: ElevationPrompt[] + onResolveElevation: (id: string, approved: boolean) => void + + discardSuspendTarget: string | null + onCancelDiscardSuspend: () => void + onConfirmDiscardSuspend: () => void + + cloneSource: { name: string; driverID: string } | null + onCancelClone: () => void + onConfirmClone: (cloneName: string) => void + + sendTextTarget: string | null + onCancelSendText: () => void + onConfirmSendText: (vmKey: string, driverID: string, vmName: string, text: string) => void + + pluginDialogs: PluginViewRoute[] + findRouteView: (route: PluginViewRoute) => ViewContribution | undefined + renderPluginView: (route: PluginViewRoute, view: ViewContribution, asDialog: boolean) => React.ReactNode + + findVM: (keyOrName: string) => VMListItem | undefined + onCopy: (text: string) => void + onRefresh: () => void + onToast: (toast: ToastInput) => void +} + +export const AppDialogs: React.FC = (props) => { + const { + locale, state, detail, selectedVM, selectedIsMacOS, effectiveState, + fixedModeSupported, diskCacheSupported, runningVMCount, tasks, displayNames, + showWizard, wizardDraft, onCloseWizard, onSubmitCreate, + showSettings, onCloseSettings, onSavedSettings, + affinityTarget, affinityVersion, onOpenAffinity, onCloseAffinity, onAffinityApplied, + updateConfirming, updateLatest, onCancelInstallUpdate, onConfirmInstallUpdate, + deleteTarget, onCancelDelete, onConfirmDelete, + closeDownloadsOpen, onCancelCloseDownloads, + elevationQueue, onResolveElevation, + discardSuspendTarget, onCancelDiscardSuspend, onConfirmDiscardSuspend, + cloneSource, onCancelClone, onConfirmClone, + sendTextTarget, onCancelSendText, onConfirmSendText, + pluginDialogs, findRouteView, renderPluginView, + findVM, onCopy, onRefresh, onToast, + } = props + const tr = (k: I18nKey, v?: Record) => t(locale, k, v) + + return ( + <> + {showWizard && state && ( + + + + )} + + {showSettings && state && detail && ( + + onOpenAffinity({ name: detail.name, driverID: selectedVM?.driver_id ?? '' })} + affinityVersion={affinityVersion} + onHostChanged={onRefresh} + onToast={onToast} + onClose={onCloseSettings} + onSaved={onSavedSettings} + /> + + )} + + {affinityTarget && state && ( + + + + )} + + {updateConfirming && ( + +
+

{tr('updateConfirmBody', { n: runningVMCount })}

+ {state?.host.needs_cold_reboot_workaround &&

{tr('updateConfirmWin10')}

} +
+
+ + + + + +
+
+ )} + + {deleteTarget && ( + + )} + + {closeDownloadsOpen && ( + { onCancelCloseDownloads(); void api.QuitApp() }} + /> + )} + + {elevationQueue.length > 0 && ( + onResolveElevation(elevationQueue[0].id, approved)} + /> + )} + + {discardSuspendTarget && (() => { + const targetVM = findVM(discardSuspendTarget) + const targetName = targetVM?.name ?? discardSuspendTarget + return ( + + ) + })()} + + {cloneSource && ( + + )} + + {sendTextTarget && (() => { + const sendVM = findVM(sendTextTarget) + const sendName = sendVM?.name ?? sendTextTarget + return ( + onConfirmSendText(sendVM ? vmRefKey(sendVM) : sendTextTarget, sendVM?.driver_id ?? '', sendName, text)} + /> + ) + })()} + + {/* Every open dialog stays mounted so the ones underneath keep their state. */} + {pluginDialogs.map((route) => { + const view = findRouteView(route) + return view && renderPluginView(route, view, true) + })} + + ) +} diff --git a/frontend/src/components/Setup.tsx b/frontend/src/components/Setup.tsx index b12cac7..960e2db 100644 --- a/frontend/src/components/Setup.tsx +++ b/frontend/src/components/Setup.tsx @@ -80,8 +80,13 @@ const FolderStep: React.FC = ({ locale, locales, state, tr, onLocale, }, [selected]) const browse = async () => { - const dir = await api.PickDirectory(tr('setupTitle')).catch(() => '') - if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) } + try { + const dir = await api.PickDirectory(tr('setupTitle')) + if (dir) { setCustom(dir); setCustomMode(true); setSelected(dir) } + } catch (e) { + console.warn('[setup] PickDirectory failed:', e) + onError(tr('failGeneric'), e) + } } const next = async () => { diff --git a/frontend/src/components/vmPage/snapshots.tsx b/frontend/src/components/vmPage/snapshots.tsx index d65f786..0d0a017 100644 --- a/frontend/src/components/vmPage/snapshots.tsx +++ b/frontend/src/components/vmPage/snapshots.tsx @@ -32,7 +32,12 @@ export const SnapshotSection: React.FC = ({ locale, driverID, name, state const loadSnapshots = () => { if (!shown) { setSnapshots([]); return } - api.ListSnapshots(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([])) + api.ListSnapshots(driverID, name) + .then((list) => setSnapshots(list ?? [])) + .catch((e) => { + console.warn('[snapshots] ListSnapshots failed:', driverID, name, e) + setSnapshots([]) + }) } useEffect(() => { setCreatingSnap(false) diff --git a/frontend/src/components/vmPage/ssh.tsx b/frontend/src/components/vmPage/ssh.tsx index fce7e65..e6c2296 100644 --- a/frontend/src/components/vmPage/ssh.tsx +++ b/frontend/src/components/vmPage/ssh.tsx @@ -29,7 +29,12 @@ export function useSSHAccess({ locale, driverID, name, enabled, onToast, onError useEffect(() => { if (!enabled) { setSshUser(''); return } let live = true - api.GetVMSSHUser(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') }) + api.GetVMSSHUser(driverID, name) + .then((u) => { if (live) setSshUser(u ?? '') }) + .catch((e) => { + console.warn('[ssh] GetVMSSHUser failed:', driverID, name, e) + if (live) setSshUser('') + }) return () => { live = false } }, [driverID, name, enabled]) diff --git a/frontend/src/lib/uiSdk.ts b/frontend/src/lib/uiSdk.ts index 6129cdd..bb08991 100644 --- a/frontend/src/lib/uiSdk.ts +++ b/frontend/src/lib/uiSdk.ts @@ -159,8 +159,9 @@ export async function mountInteractiveThemeScript( addDisposer(localDispose) try { setup((fn) => localDisposers.push(fn)) - } catch { + } catch (e) { // Feature-isolated error: tear down only this feature. + console.warn('[uiSdk] feature setup failed:', _name, e) localDispose() } }, diff --git a/internal/app/app.go b/internal/app/app.go index 130ba97..0b8dd88 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -542,10 +542,8 @@ func (a *App) startTray() { } items = append(items, tray.VMItem{DriverID: vm.DriverID, Name: vm.Name, Label: label, State: state}) } - effLoc := i18n.EffectiveLocale(loc) return tray.Snapshot{ - Locale: effLoc, - LocaleZh: effLoc == i18n.ZhCN, + Locale: i18n.EffectiveLocale(loc), CanSuspend: canSuspend, VMs: items, } diff --git a/internal/app/appupdate_flow.go b/internal/app/appupdate_flow.go index 513ab6b..db5ad52 100644 --- a/internal/app/appupdate_flow.go +++ b/internal/app/appupdate_flow.go @@ -6,9 +6,13 @@ package app // running; Guest Tools reconnects once the new window is up. import ( + "archive/zip" "context" + "crypto/sha256" + "encoding/hex" "errors" "fmt" + "io" "os" "path/filepath" "strings" @@ -121,8 +125,10 @@ func (a *App) DownloadAppUpdate() (string, error) { return id, nil } -// downloadAppUpdate fetches info's executable into dir and checks it against -// GitHub's assets[].digest SHA-256. It returns the file and its hash. +// downloadAppUpdate fetches info's release asset (.zip or .exe) into dir, +// checks it against GitHub's assets[].digest SHA-256, extracts the executable +// when a .zip archive was downloaded, and returns the executable path and its +// SHA-256 hash. func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string, onProgress fetch.Progress) (string, string, error) { want := strings.ToLower(strings.TrimSpace(info.AssetSHA256)) if len(want) != 64 { @@ -136,9 +142,64 @@ func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string, if err != nil { return "", "", err } + if strings.HasSuffix(strings.ToLower(path), ".zip") { + exePath, exeSum, err := extractAppUpdateZip(path, dir) + if err != nil { + return "", "", err + } + return exePath, exeSum, nil + } return path, want, nil } +// extractAppUpdateZip extracts the single Windows executable from a verified +// release .zip into dir and returns its path and SHA-256 digest. +func extractAppUpdateZip(zipPath, dir string) (string, string, error) { + zr, err := zip.OpenReader(zipPath) + if err != nil { + return "", "", fmt.Errorf("open update archive: %w", err) + } + defer zr.Close() + + const maxUpdateExeBytes = 256 << 20 // 256 MiB safety cap against zip bombs + for _, f := range zr.File { + if f.FileInfo().IsDir() { + continue + } + base := filepath.Base(f.Name) + if base == "." || base == ".." || strings.ContainsAny(f.Name, `/\`) { + continue + } + lower := strings.ToLower(base) + if !strings.HasSuffix(lower, ".exe") || strings.Contains(lower, "-cli-") { + continue + } + rc, err := f.Open() + if err != nil { + return "", "", fmt.Errorf("read %s from update archive: %w", base, err) + } + dest := filepath.Join(dir, base) + out, err := os.OpenFile(dest, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755) + if err != nil { + _ = rc.Close() + return "", "", fmt.Errorf("create extracted update %s: %w", base, err) + } + h := sha256.New() + n, copyErr := io.Copy(io.MultiWriter(out, h), io.LimitReader(rc, maxUpdateExeBytes+1)) + closeErr := errors.Join(rc.Close(), out.Close()) + if copyErr != nil || closeErr != nil { + _ = os.Remove(dest) + return "", "", fmt.Errorf("extract %s from update archive: %w", base, errors.Join(copyErr, closeErr)) + } + if n > maxUpdateExeBytes { + _ = os.Remove(dest) + return "", "", fmt.Errorf("extracted update %s exceeds %d byte limit", base, maxUpdateExeBytes) + } + return dest, hex.EncodeToString(h.Sum(nil)), nil + } + return "", "", errors.New("update archive does not contain a Windows executable") +} + // InstallAppUpdate swaps the downloaded update in for the running executable, // starts it, and quits this window. The new window waits for this process to // exit before it opens. Running VMs are not touched. diff --git a/internal/app/appupdate_flow_test.go b/internal/app/appupdate_flow_test.go index 66f0d08..c8d6a16 100644 --- a/internal/app/appupdate_flow_test.go +++ b/internal/app/appupdate_flow_test.go @@ -1,6 +1,8 @@ package app import ( + "archive/zip" + "bytes" "context" "crypto/sha256" "encoding/hex" @@ -56,6 +58,61 @@ func TestDownloadAppUpdateVerifiesAgainstAssetDigest(t *testing.T) { } } +func TestDownloadAppUpdateExtractsZipAndVerifiesDigest(t *testing.T) { + exePayload := []byte("MZ-reims-go-zip-update-binary") + exeHash := sha256.Sum256(exePayload) + wantExeSum := hex.EncodeToString(exeHash[:]) + + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + w, err := zw.Create("reims-go-v9.9.9-windows-amd64.exe") + if err != nil { + t.Fatal(err) + } + if _, err := w.Write(exePayload); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + zipBytes := buf.Bytes() + zipHash := sha256.Sum256(zipBytes) + wantZipSum := hex.EncodeToString(zipHash[:]) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/app.zip" { + _, _ = w.Write(zipBytes) + return + } + http.NotFound(w, r) + })) + defer srv.Close() + + dir := t.TempDir() + info := version.UpdateInfo{ + Latest: "v9.9.9", + HasUpdate: true, + AssetName: "reims-go-v9.9.9-windows-amd64.zip", + AssetSize: int64(len(zipBytes)), + DownloadURL: srv.URL + "/app.zip", + AssetSHA256: wantZipSum, + } + gotPath, gotSum, err := downloadAppUpdate(context.Background(), info, dir, nil) + if err != nil { + t.Fatalf("downloadAppUpdate(zip): %v", err) + } + if filepath.Base(gotPath) != "reims-go-v9.9.9-windows-amd64.exe" { + t.Fatalf("extracted path = %s, want reims-go-v9.9.9-windows-amd64.exe", gotPath) + } + if gotSum != wantExeSum { + t.Fatalf("extracted exe sum = %s, want %s", gotSum, wantExeSum) + } + gotBody, err := os.ReadFile(gotPath) + if err != nil || !bytes.Equal(gotBody, exePayload) { + t.Fatalf("extracted exe content mismatch: %q, err=%v", gotBody, err) + } +} + func TestInstallAppUpdateGuards(t *testing.T) { cfg := config.Default() cfg.Locale = i18n.EnUS diff --git a/internal/app/guesttools_flow.go b/internal/app/guesttools_flow.go index 7f58561..e422532 100644 --- a/internal/app/guesttools_flow.go +++ b/internal/app/guesttools_flow.go @@ -14,6 +14,7 @@ import ( "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/macos/installer" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/macos/startprep" "github.com/Nwflower/reims-go/internal/networkmsg" @@ -119,6 +120,23 @@ func (a *App) guestToolsImagePath(name string) string { return filepath.Join(cacheDir, "reims-go", "guest-tools", name+"-tools.img") } +func buildToolsHFSImage(outPath string, cfg guesttools.VMConfig) error { + if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil { + return err + } + src := guesttools.ToolsDiskFiles(cfg) + files := make([]installer.HFSFile, len(src)) + for i, f := range src { + files[i] = installer.HFSFile{ + Name: f.Name, + Mode: f.Mode, + Size: f.Size, + Open: f.Open, + } + } + return installer.BuildHFSPlusDiskImage(outPath, guesttools.ToolsVolumeName, files) +} + // buildGuestToolsImage runs in the macOS driver after all start hooks pass. func (a *App) buildGuestToolsImage(vmName, vmDir string) error { _, port, _, err := a.startGuestToolsServer() @@ -132,7 +150,7 @@ func (a *App) buildGuestToolsImage(vmName, vmDir string) error { return err } cfg, _ = a.validatedShareConfig(cfg) - return guesttools.BuildToolsDiskImage(a.guestToolsImagePath(vmName), cfg) + return buildToolsHFSImage(a.guestToolsImagePath(vmName), cfg) } // startGuestToolsServer starts the shared localhost HTTP bridge once. Only the @@ -213,49 +231,6 @@ func (a *App) guestToolsEnabled() bool { return err == nil } -// inputBridgeEnv returns REIMS_GO_INPUT_URL and REIMS_GO_INPUT_TOKEN env vars -// for the VM's QEMU/reims-vgpu-window child process so direct WM_CHAR / IME -// commits can forward to reims-go's local text router. -func (a *App) inputBridgeEnv(name, vmDir string, epoch uint64) []string { - if vmDir == "" { - return nil - } - srv, port, err := a.ensureGuestToolsBridge() - if err != nil || port <= 0 { - return nil - } - cfg, err := a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch) - if err != nil || cfg.Token == "" { - return nil - } - return []string{ - fmt.Sprintf("REIMS_GO_INPUT_URL=http://127.0.0.1:%d/v1/host-text", port), - "REIMS_GO_INPUT_TOKEN=" + cfg.Token, - } -} - -func (a *App) dropBridgeEnv(name, vmDir string, epoch uint64) []string { - if vmDir == "" { - return nil - } - srv, port, err := a.ensureGuestToolsBridge() - if err != nil || port <= 0 { - return nil - } - cfg, err := a.loadAndRegisterGuestTools(srv, port, vmDir, name, epoch) - if err != nil || cfg.Token == "" { - return nil - } - token := srv.HostDropToken(cfg.DriverID, name) - if token == "" { - return nil - } - return []string{ - fmt.Sprintf("REIMS_GO_DROP_URL=http://127.0.0.1:%d/v1/host-drop", port), - "REIMS_GO_DROP_TOKEN=" + token, - } -} - func (a *App) registerExistingGuestTools(ctx context.Context) { srv, port, err := a.ensureGuestToolsBridge() if err != nil { @@ -383,59 +358,6 @@ func (a *App) populateGuestToolsDetail(d *reims.VMDetail, epoch uint64) { } } -// syncGuestTools ensures the host HTTP bridge is running and refreshes the -// REIMSTOOLS HFS+ image before VM start when Guest Tools is configured or attached. -func (a *App) syncGuestTools(c *reims.Client, name string, cur *reims.VMDetail, epoch uint64) { - if cur.Directory == "" { - return - } - attached := reims.HasGuestToolsArgs(cur.ExtraArgs) - unlock := a.lockGuestToolsVM(name) - _, configured, err := guesttools.ReadVMConfigStrict(cur.Directory) - unlock() - if err != nil { - a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error()) - return - } - if !attached && !configured { - return - } - srv, port, err := a.ensureGuestToolsBridge() - if err != nil { - a.emitVMLog(name, "Warning: could not start Guest Tools bridge: "+err.Error()) - return - } - cfg, err := a.loadAndRegisterGuestTools(srv, port, cur.Directory, name, epoch, cur.NetworkMode) - if err != nil { - a.emitVMLog(name, "Warning: could not load Guest Tools config: "+err.Error()) - return - } - merged := reims.StripGuestToolsNetworkArgs(cur.ExtraArgs) - if cur.NetworkMode == "bridge" && a.npcapPluginEnabled() { - tokens, argsErr := reims.GuestToolsNetworkUnixArgs(cur.Directory, cfg.ManagementOutSock, cfg.ManagementInSock) - if argsErr != nil { - a.emitVMLog(name, networkmsg.Localize(argsErr, a.locale()).Error()) - return - } - merged = strings.TrimSpace(merged + " " + strings.Join(tokens, " ")) - } else { - srv.StopManagementNetwork(name) - } - if attached { - imgPath := a.guestToolsImagePath(name) - if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil { - a.emitVMLog(name, "Warning: could not refresh REIMSTOOLS disk: "+err.Error()) - return - } - merged = reims.MergeGuestToolsArgs(merged, imgPath) - } - if merged != cur.ExtraArgs { - if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err == nil { - cur.ExtraArgs = merged - } - } -} - // AttachGuestTools prepares the per-VM Bearer token, ensures the shared folder // and localhost bridge are active, builds the read-only REIMSTOOLS HFS+ disk, // and attaches it to the VM via `reims-ctl set --extra-args`. @@ -464,7 +386,7 @@ func (a *App) AttachGuestTools(name string) error { } imgPath := a.guestToolsImagePath(name) - if err := guesttools.BuildToolsDiskImage(imgPath, cfg); err != nil { + if err := buildToolsHFSImage(imgPath, cfg); err != nil { return fmt.Errorf("build REIMSTOOLS disk: %w", err) } merged := reims.MergeGuestToolsArgs(d.ExtraArgs, imgPath) diff --git a/internal/app/legacy_ledger_test.go b/internal/app/legacy_ledger_test.go index ec81419..d665e6a 100644 --- a/internal/app/legacy_ledger_test.go +++ b/internal/app/legacy_ledger_test.go @@ -1,9 +1,11 @@ package app import ( + "encoding/json" "strings" "testing" + "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/macos/guest" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" @@ -11,6 +13,23 @@ import ( "github.com/Nwflower/reims-go/internal/qmp" ) +func stripLegacyManagedExtraArgs(extraArgs string) string { + s := reims.StripGuestToolsArgs(extraArgs) + s = reims.StripPacketBridgeArgs(s) + s = reims.StripGuestToolsNetworkArgs(s) + s = reims.StripOfflineHelperArgs(s) + s = qmp.StripLegacyWin10RebootArgs(s) + s = reims.StripIncomingDeferArgs(s) + return strings.TrimSpace(s) +} + +func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo { + raw, _ := json.Marshal(detail) + var data map[string]any + _ = json.Unmarshal(raw, &data) + return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data} +} + func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) { // Simulate an existing pre-plugin VM whose vm.toml already contains: // user arg + REIMSTOOLS + REIMSHELP + Win10 managed QMP args, with NO ledger file yet. @@ -45,7 +64,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) { } base := stripLegacyManagedExtraArgs(legacy) - res := plugin.ReconcileStartIntents(base, ledger, active, intents) + res := plugin.ReconcileStartIntentsForDriver(base, ledger, active, "", intents) if !strings.Contains(res.ExtraArgs, "-cpu host") { t.Fatalf("user arg lost: %s", res.ExtraArgs) @@ -62,7 +81,7 @@ func TestLegacyExtraArgsAdoptedWithoutDuplication(t *testing.T) { {PluginID: guest.ID, ClearKeys: []string{"reimshelp", "win10-cold-reboot"}}, } base2 := stripLegacyManagedExtraArgs(res.ExtraArgs) - res2 := plugin.ReconcileStartIntents(base2, ledger, active, nextIntents) + res2 := plugin.ReconcileStartIntentsForDriver(base2, ledger, active, "", nextIntents) if res2.ExtraArgs != "-cpu host" { t.Fatalf("expected only user arg after clearing managed keys, got: %q", res2.ExtraArgs) } @@ -94,7 +113,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) { }} } - unmigrated := plugin.ReconcileStartIntents(extra, newLedger(), active, intents) + unmigrated := plugin.ReconcileStartIntentsForDriver(extra, newLedger(), active, "", intents) if strings.Contains(unmigrated.ExtraArgs, "kernel-irqchip") { t.Fatalf("test premise: an unmigrated ledger should drop the fragment, got %q", unmigrated.ExtraArgs) } @@ -103,7 +122,7 @@ func TestPreMergeLedgerFragmentsCarriedIntoCore(t *testing.T) { if !guest.MigrateLedger(ledger) { t.Fatal("MigrateLedger reported no change for a retired owner") } - res := plugin.ReconcileStartIntents(extra, ledger, active, intents) + res := plugin.ReconcileStartIntentsForDriver(extra, ledger, active, "", intents) if got := strings.Count(res.ExtraArgs, "kernel-irqchip=off"); got != 1 { t.Fatalf("want kernel-irqchip=off carried exactly once, got %d in %q", got, res.ExtraArgs) } diff --git a/internal/app/lifecycle_flow.go b/internal/app/lifecycle_flow.go index 7c49fdf..1352379 100644 --- a/internal/app/lifecycle_flow.go +++ b/internal/app/lifecycle_flow.go @@ -75,7 +75,12 @@ func (a *App) resolveVMInfo(driverID, name string) (driver.VMInfo, error) { if err != nil { return driver.VMInfo{}, err } - return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort}, nil + return driver.VMInfo{ + Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, + State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, + DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, + Network: detail.Network, SSHPort: detail.SSHPort, + }, nil } func (a *App) GetVMInfo(driverID, name string) (driver.VMInfo, error) { @@ -101,16 +106,7 @@ func (a *App) StartVM(driverID, name string) error { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { - return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID) - } - vm, err := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name) - if err != nil { - return err - } - return a.withComputerUseVM(context.Background(), vm.Directory, func(context.Context) error { - return a.startMacOSVM(vm.Name) - }) + return errors.New("driver lifecycle is not initialized") } _, vm, err := svc.Resolve(context.Background(), driverID, name) if err != nil { @@ -128,7 +124,7 @@ func (a *App) startResolvedVMLocked(ctx context.Context, svc interface { Start(context.Context, driver.VMRef, io.Writer, io.Writer) (driver.StartResult, error) }, vm driver.VMInfo) error { if svc == nil { - return a.startMacOSVM(vm.Name) + return errors.New("driver lifecycle is not initialized") } ref := vm.Ref() key := ref.Key() @@ -179,10 +175,7 @@ func (a *App) stopVM(ctx context.Context, driverID, name string, force bool) err svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { - return errors.New("driver is unavailable without the plugin manager") - } - return a.stopMacOSVM(ctx, name, force) + return errors.New("driver lifecycle is not initialized") } _, vm, err := svc.Resolve(ctx, driverID, name) if err != nil { @@ -222,10 +215,7 @@ func (a *App) EjectInstaller(driverID, name string) error { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { - return errors.New("driver is unavailable without the plugin manager") - } - return a.ejectMacOSInstaller(name) + return errors.New("driver lifecycle is not initialized") } vm, err := a.resolveVMInfo(driverID, name) if err != nil { @@ -247,7 +237,14 @@ func (a *App) ReadVMLogs(driverID, name string, serial bool) (string, error) { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - return a.readMacOSVMLogs(name, serial) + if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { + return "", fmt.Errorf("driver %q is unavailable without the plugin manager", driverID) + } + c, err := a.client() + if err != nil { + return "", err + } + return c.ReadLogs(context.Background(), name, serial) } return svc.ReadLogs(context.Background(), driver.VMRef{DriverID: driverID, Name: name}, serial) } @@ -261,27 +258,15 @@ func (a *App) RestartVM(driverID, name string) error { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() - var ref driver.VMRef - if svc != nil { - _, vm, err := svc.Resolve(context.Background(), driverID, name) - if err != nil { - return err - } - ref = vm.Ref() - } else { - if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { - return fmt.Errorf("driver %q is unavailable without the plugin manager", driverID) - } - ref = driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, name) + if svc == nil { + return errors.New("driver lifecycle is not initialized") } + _, vm, err := svc.Resolve(context.Background(), driverID, name) + if err != nil { + return err + } + ref := vm.Ref() if ref.DriverID != driver.BuiltinReimsMacOSDriverID { - if svc == nil { - return errors.New("driver lifecycle is not initialized") - } - _, vm, err := svc.Resolve(a.baseCtx(), ref.DriverID, ref.Name) - if err != nil { - return err - } return a.withComputerUseVM(a.baseCtx(), vm.Directory, func(ctx context.Context) error { if err := a.stopVM(ctx, ref.DriverID, ref.Name, false); err != nil { return err @@ -289,7 +274,7 @@ func (a *App) RestartVM(driverID, name string) error { return a.startResolvedVMLocked(ctx, svc, vm) }) } - _, err := a.restartMacOSVM(a.baseCtx(), ref.Name) + _, err = a.restartMacOSVM(a.baseCtx(), ref.Name) return err } @@ -298,10 +283,7 @@ func (a *App) DeleteVM(driverID, name string, keepFiles bool) error { svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - if driverID != "" && driver.CanonicalDriverID(driverID) != driver.BuiltinReimsMacOSDriverID { - return errors.New("driver is unavailable without the plugin manager") - } - return a.deleteMacOSVM(name, keepFiles) + return errors.New("driver lifecycle is not initialized") } d, vm, err := svc.ResolveForDelete(context.Background(), driverID, name) if err != nil { diff --git a/internal/app/lifecycle_flow_test.go b/internal/app/lifecycle_flow_test.go index 488cdde..57e33e6 100644 --- a/internal/app/lifecycle_flow_test.go +++ b/internal/app/lifecycle_flow_test.go @@ -1,12 +1,9 @@ package app import ( - "bufio" "context" "errors" - "fmt" "io" - "net" "os" "path/filepath" "strings" @@ -15,12 +12,10 @@ import ( "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" - "github.com/Nwflower/reims-go/internal/i18n" vmlifecycle "github.com/Nwflower/reims-go/internal/lifecycle" "github.com/Nwflower/reims-go/internal/macos/macosdriver" "github.com/Nwflower/reims-go/internal/macos/reims" "github.com/Nwflower/reims-go/internal/plugin" - "github.com/Nwflower/reims-go/internal/qmp" rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/tray" "github.com/Nwflower/reims-go/internal/vmstart" @@ -67,101 +62,6 @@ func TestMacOSLaunchUsesLatestRuntimeSelection(t *testing.T) { } } -func TestPrepareLegacyColdStart(t *testing.T) { - log := func(line string) { t.Log(line) } - t.Run("recoverable snapshot", func(t *testing.T) { - dir := t.TempDir() - state := reims.SuspendStatePath(dir) + ".tmp" - meta := reims.SuspendMetaPath(dir) + ".tmp" - for _, path := range []string{state, meta} { - if err := os.WriteFile(path, []byte("snapshot data"), 0o600); err != nil { - t.Fatal(err) - } - } - err := prepareLegacyColdStart(t.Context(), i18n.EnUS, "mac", "", reims.VMDetail{Directory: dir, State: "stopped"}, log) - var coded *i18n.CodedError - if !errors.As(err, &coded) || coded.Code != "E_VM_SUSPENDED" || coded.Key != "err.suspend.action_blocked" { - t.Fatalf("legacy cold start = %v, want E_VM_SUSPENDED", err) - } - if !reims.HasSuspendState(dir) { - t.Fatal("recoverable snapshot was removed") - } - }) - - t.Run("inspection error", func(t *testing.T) { - dir := t.TempDir() - staged := reims.SuspendStatePath(dir) + ".tmp" - if err := os.WriteFile(staged, []byte("snapshot data"), 0o600); err != nil { - t.Fatal(err) - } - if err := os.Mkdir(reims.SuspendMetaPath(dir)+".tmp", 0o700); err != nil { - t.Fatal(err) - } - err := prepareLegacyColdStart(t.Context(), i18n.EnUS, "mac", "", reims.VMDetail{Directory: dir, State: "stopped"}, log) - if !errors.Is(err, reims.ErrSuspendArtifactsUncertain) { - t.Fatalf("legacy cold start = %v, want inspection error", err) - } - if data, err := os.ReadFile(staged); err != nil || string(data) != "snapshot data" { - t.Fatalf("staged state = %q, %v", data, err) - } - }) - - for _, tt := range []struct { - name, dir string - }{ - {"postmigrate", "."}, - {"postmigrate on short socket for long VM directory", strings.Repeat("v", 100)}, - } { - t.Run(tt.name, func(t *testing.T) { - t.Chdir(t.TempDir()) - const name, tmpDir = "mac", "tmp" - if err := os.MkdirAll(tt.dir, 0o700); err != nil { - t.Fatal(err) - } - staged := reims.SuspendStatePath(tt.dir) + ".tmp" - if err := os.WriteFile(staged, []byte("snapshot data"), 0o600); err != nil { - t.Fatal(err) - } - socket := qmp.SocketPathForVM(tt.dir, name, tmpDir) - if err := os.MkdirAll(filepath.Dir(socket), 0o700); err != nil { - t.Fatal(err) - } - ln, err := net.Listen("unix", socket) - if err != nil { - t.Fatal(err) - } - t.Cleanup(func() { _ = ln.Close() }) - if tt.dir != "." { - if _, err := os.Lstat(qmp.SocketPath(tt.dir)); !os.IsNotExist(err) { - t.Fatalf("unexpected VM directory socket: %v", err) - } - } - go func() { - conn, err := ln.Accept() - if err != nil { - return - } - defer conn.Close() - _, _ = fmt.Fprintln(conn, `{"QMP":{}}`) - sc := bufio.NewScanner(conn) - if sc.Scan() { - _, _ = fmt.Fprintln(conn, `{"return":{}}`) - } - if sc.Scan() { - _, _ = fmt.Fprintln(conn, `{"return":{"running":false,"status":"postmigrate"}}`) - } - }() - err = prepareLegacyColdStart(t.Context(), i18n.EnUS, name, tmpDir, reims.VMDetail{Directory: tt.dir, State: "stopped"}, log) - if err == nil || !strings.Contains(err.Error(), "QEMU is still active (QMP status: postmigrate)") { - t.Fatalf("legacy cold start = %v, want active QEMU error", err) - } - if data, err := os.ReadFile(staged); err != nil || string(data) != "snapshot data" { - t.Fatalf("staged state = %q, %v", data, err) - } - }) - } -} - type appSecondDriver struct { id string vms []driver.VMInfo diff --git a/internal/app/macos_detail.go b/internal/app/macos_detail.go index 7229263..9bffb41 100644 --- a/internal/app/macos_detail.go +++ b/internal/app/macos_detail.go @@ -23,13 +23,6 @@ func macOSDetailFromVMInfo(vm driver.VMInfo) (reims.VMDetail, error) { return detail, nil } -func vmInfoFromMacOSDetail(detail reims.VMDetail) driver.VMInfo { - raw, _ := json.Marshal(detail) - var data map[string]any - _ = json.Unmarshal(raw, &data) - return driver.VMInfo{Name: detail.Name, DriverID: driver.BuiltinReimsMacOSDriverID, State: detail.State, CPUs: detail.CPUs, Memory: detail.Memory, DiskSummary: detail.Disk, DiskPath: detail.DiskPath(), Directory: detail.Directory, Network: detail.Network, SSHPort: detail.SSHPort, DriverData: data} -} - func (a *App) loadMacOSVMDetail(name string, epoch uint64) (reims.VMDetail, error) { c, err := a.client() if err != nil { diff --git a/internal/app/macos_lifecycle_native.go b/internal/app/macos_lifecycle_native.go index 8ee0b54..0e3c856 100644 --- a/internal/app/macos_lifecycle_native.go +++ b/internal/app/macos_lifecycle_native.go @@ -4,23 +4,11 @@ import ( "context" "errors" "fmt" - "io" - "os" - "path/filepath" - "strings" - "sync" "time" "github.com/Nwflower/reims-go/internal/driver" "github.com/Nwflower/reims-go/internal/host" - "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/macos/guest" - "github.com/Nwflower/reims-go/internal/macos/macosdriver" "github.com/Nwflower/reims-go/internal/macos/reims" - "github.com/Nwflower/reims-go/internal/macos/startprep" - "github.com/Nwflower/reims-go/internal/networkmsg" - "github.com/Nwflower/reims-go/internal/plugin" - "github.com/Nwflower/reims-go/internal/plugin/builtin" "github.com/Nwflower/reims-go/internal/qmp" "github.com/Nwflower/reims-go/internal/vmstart" ) @@ -178,356 +166,6 @@ func (a *App) watchWin10ColdReboot(name, qmpAddr string) { }() } -// stripLegacyManagedExtraArgs removes reims-go internally managed QEMU arg -// fragments (reimstools, reimshelp, and legacy managed Win10 QMP targets) -// before ledger reconciliation so pre-plugin VMs and out-of-band helpers never -// produce duplicate QEMU device IDs on upgrade. -func stripLegacyManagedExtraArgs(extraArgs string) string { - s := reims.StripGuestToolsArgs(extraArgs) - s = reims.StripPacketBridgeArgs(s) - s = reims.StripGuestToolsNetworkArgs(s) - s = reims.StripOfflineHelperArgs(s) - s = qmp.StripLegacyWin10RebootArgs(s) - s = reims.StripIncomingDeferArgs(s) - return strings.TrimSpace(s) -} - -func (a *App) startMacOSVM(name string) error { - return a.startMacOSVMWithHost(name, host.Inspect) -} - -func (a *App) startMacOSVMWithHost(name string, inspect func(string) host.Report) error { - if err := a.requireWritableDataRoot(); err != nil { - return err - } - prep, err := a.prep(name) - if err != nil { - return err - } - c := prep.Client - a.mu.Lock() - root := a.cfg.DataRoot - tmpDir := a.cfg.TempDir() - locale := a.cfg.Locale - a.mu.Unlock() - rep := inspect(root) - if err := prep.CheckWHPX(rep); err != nil { - a.emitVMLog(name, "Start refused: "+err.Error()) - return err - } - curDetail, release, err := startprep.LockVM(context.Background(), c, name) - if err != nil { - return err - } - unlock := sync.OnceFunc(release) - defer unlock() - if err := prepareLegacyColdStart(context.Background(), c.Locale, name, tmpDir, curDetail, func(line string) { - a.emitVMLog(name, line) - }); err != nil { - return err - } - releaseNet, err := a.prepareManagedVMNetwork(context.Background(), name, false) - if err != nil { - return err - } - if releaseNet != nil { - defer releaseNet() - } - if err := prep.CheckMemory(curDetail.Memory, rep); err != nil { - a.emitVMLog(name, "Start refused: "+err.Error()) - return err - } - a.cancelRebootWatcher(name) - - a.mu.Lock() - mgr := a.pluginMgr - a.mu.Unlock() - var qmpAddr string - if mgr != nil { - // Unified plugin-kernel start pipeline (§4.4): collect all vm.beforeStart - // intents (builtin + L1 rule hooks + L3 code hooks) and write merged - // extra-args via AT MOST ONE `reims-ctl set --extra-args` call. - rtCaps := prep.Runtime.Manifest.EffectiveCapabilities() - intents, blockErr := mgr.Registry().Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{ - VMName: name, - VMSettingsKey: driver.NewVMRef(builtin.IDDriverReimsMacOS, name).Key(), - VMDir: curDetail.Directory, - DriverID: builtin.IDDriverReimsMacOS, - ExtraArgs: curDetail.ExtraArgs, - HasInstaller: curDetail.HasInstaller, - InstallerPath: curDetail.InstallerPath, - RuntimeKind: prep.Runtime.Manifest.EffectiveKind(), - RuntimeCaps: rtCaps, - HostFacts: buildHostFacts(rep, rtCaps), - VMCaps: macosdriver.ReimsMacOSCapabilities, - State: curDetail.State, - }) - if blockErr != nil { - a.emitVMLog(name, "Start blocked: "+blockErr.Error()) - return blockErr - } - ledger, ledgerErr := plugin.LoadArgLedger(curDetail.Directory) - if ledgerErr != nil { - a.emitVMLog(name, "Warning: could not read arg ledger: "+ledgerErr.Error()) - ledger = &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}} - } - // Reassign macOS-owned fragments from legacy builtin.core records to - // builtin.guest.macos before reconciling. - guest.MigrateLedger(ledger) - // Strip pre-ledger or out-of-band managed fragments so upgrading existing - // VMs never duplicates QEMU device IDs. - baseExtraArgs := stripLegacyManagedExtraArgs(curDetail.ExtraArgs) - nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS} - macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(baseExtraArgs, ledger), rep) - reconciled := plugin.ReconcileStartIntentsForDriver(baseExtraArgs, ledger, mgr.Registry().ActivePluginIDs(), nested.PluginID, append(intents, nested)) - reconciled.Changed = strings.TrimSpace(curDetail.ExtraArgs) != reconciled.ExtraArgs - for _, warn := range reconciled.Warnings { - a.emitVMLog(name, "[plugin] "+warn) - } - if len(reconciled.Env) > 0 { - c.Env = append(c.Env, reconciled.Env...) - } - if reconciled.Changed { - if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil { - a.emitVMLog(name, "Warning: could not apply reconciled start extra-args: "+err.Error()) - } else { - curDetail.ExtraArgs = reconciled.ExtraArgs - _ = plugin.SaveArgLedger(curDetail.Directory, ledger) - } - } else { - _ = plugin.SaveArgLedger(curDetail.Directory, ledger) - } - for _, act := range reconciled.PostStart { - if act.Kind == "qmp.watch_cold_reboot" { - if addr, ok := act.Params["qmp_addr"].(string); ok && addr != "" { - qmpAddr = addr - } - } - } - } else { - if err := a.reconcileLegacyBridgeArgs(context.Background(), c, &curDetail); err != nil { - return err - } - a.syncGuestTools(c, name, &curDetail, a.vmDeleteEpoch(name)) - if prep.Runtime.Manifest.HasCapability("win32-unicode-input") { - if env := a.inputBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name)); len(env) > 0 { - c.Env = append(c.Env, env...) - } - } - if prep.Runtime.Manifest.HasCapability("window-file-drop") { - c.Env = append(c.Env, a.dropBridgeEnv(name, curDetail.Directory, a.vmDeleteEpoch(name))...) - } - prep.Prepare(context.Background(), name, rep, &curDetail) - if rep.NeedsColdRebootWorkaround { - sockPath := qmp.RebootSocketPath(curDetail.Directory, tmpDir, name) - _ = os.MkdirAll(filepath.Dir(sockPath), 0o755) - _ = os.Remove(sockPath) - merged := qmp.MergeWin10RebootUnixArgs(curDetail.ExtraArgs, sockPath) - if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &merged}, io.Discard, io.Discard); err != nil { - a.emitVMLog(name, "Win10 cold-reboot extra-args setup skipped: "+err.Error()) - } else { - qmpAddr = "unix:" + sockPath - curDetail.ExtraArgs = merged - } - } - ledger, err := plugin.LoadArgLedger(curDetail.Directory) - if err != nil { - return err - } - nested := plugin.StartIntent{PluginID: builtin.IDDriverReimsMacOS} - macosdriver.AppendNestedVirtIntent(&nested, locale, curDetail.Directory, plugin.UserExtraArgs(curDetail.ExtraArgs, ledger), rep) - reconciled := plugin.ReconcileStartIntentsForDriver(curDetail.ExtraArgs, ledger, nil, nested.PluginID, []plugin.StartIntent{nested}) - for _, warning := range reconciled.Warnings { - a.emitVMLog(name, warning) - } - if reconciled.Changed { - if err := c.Set(context.Background(), reims.SetOpts{Name: name, ExtraArgs: &reconciled.ExtraArgs}, io.Discard, io.Discard); err != nil { - return err - } - if err := plugin.SaveArgLedger(curDetail.Directory, ledger); err != nil { - return err - } - curDetail.ExtraArgs = reconciled.ExtraArgs - } - } - - w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) }) - if err := macosdriver.PrepareColdStartDisplay(context.Background(), c, &curDetail, rep.Displays, w); err != nil { - return err - } - if prep.Runtime.Manifest.HasCapability("client-window-close") { - c.Env = append(c.Env, vmstart.CloseRequestEnv(name)...) - } - - a.mu.Lock() - a.transitions[vmKey(name)] = "starting" - delete(a.pendingChanges, vmKey(name)) - a.mu.Unlock() - a.emitStateChanged() - - startAt := time.Now() - a.emitStartSummary(name, vmInfoFromMacOSDetail(curDetail), rep, qmpAddr) - a.emitVMLog(name, "Starting "+name+"...") - err = c.StartWithCompat(context.Background(), name, w, w, func(msg string) { - a.emitVMLog(name, msg) - }) - unlock() - if err != nil { - a.mu.Lock() - delete(a.transitions, vmKey(name)) - a.mu.Unlock() - a.emitVMLog(name, "Start error: "+err.Error()) - a.emitStateChanged() - return err - } - if qmpAddr != "" && mgr == nil { - a.watchWin10ColdReboot(name, qmpAddr) - } - if mgr != nil { - mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStart, plugin.VMEventPayload{ - VMName: name, - VMDir: curDetail.Directory, - DriverID: builtin.IDDriverReimsMacOS, - QMPAddr: qmpAddr, - }) - } - a.startVMMonitor(name, vmInfoFromMacOSDetail(curDetail), startAt) - a.wakePoll() - a.emitStateChanged() - return nil -} - -// 备用启动同样记录参数归属,停用扩展时可精确移除桥接片段。 -func (a *App) reconcileLegacyBridgeArgs(ctx context.Context, c networkControlClient, detail *reims.VMDetail) error { - ledger, err := plugin.LoadArgLedger(detail.Directory) - if err != nil { - return err - } - intent := plugin.StartIntent{PluginID: builtin.IDNpcapBridge, ClearKeys: []string{"bridge-network", "npcap-bridge"}} - if detail.NetworkMode == "bridge" { - record, err := reims.ReadNetworkRecord(detail.Directory) - if err != nil { - return err - } - if record.Corrupt { - return networkmsg.Error("record_invalid", nil) - } - if record.Pending { - return networkmsg.Error("packet_pending", nil) - } - mac, err := resolveVMNetworkMAC(ctx, c, *detail) - if err != nil { - return err - } - sockPath := record.SocketPath - if sockPath == "" { - sockPath = reims.VMUnixSocketPath(detail.Directory, a.tempDir(), detail.Name, "bridge.sock") - } - tokens, err := reims.PacketBridgeUnixTokens(mac, sockPath) - if err != nil { - return err - } - intent.Args = []plugin.ArgFragment{{PluginID: builtin.IDNpcapBridge, Key: "bridge-network", Tokens: tokens, Builtin: true, Priority: 78}} - } - // 先剥除旧版未登记的主通道;管理网卡和用户参数保持各自归属。 - extra := reims.StripPacketBridgeArgs(detail.ExtraArgs) - result := plugin.ReconcileStartIntents(extra, ledger, nil, []plugin.StartIntent{intent}) - for _, warning := range result.Warnings { - a.emitVMLog(detail.Name, warning) - } - if result.ExtraArgs != detail.ExtraArgs { - if err := c.Set(ctx, reims.SetOpts{Name: detail.Name, ExtraArgs: &result.ExtraArgs}, io.Discard, io.Discard); err != nil { - return networkmsg.Error("config_save", err) - } - } - if err := plugin.SaveArgLedger(detail.Directory, ledger); err != nil { - return err - } - detail.ExtraArgs = result.ExtraArgs - return nil -} - -// prepareLegacyColdStart guards the older start path against a stopped VM that -// still holds suspend artifacts. It drops provably orphaned files, then refuses -// the start while a recoverable snapshot remains: this path cannot resume one, -// and cold-starting over it would discard the guest's saved state. Resume or -// discard the snapshot from the UI first. -func prepareLegacyColdStart(ctx context.Context, locale i18n.Locale, name, tmpDir string, cur reims.VMDetail, log func(string)) error { - if cur.State != "stopped" { - return nil - } - suspended, err := reims.InspectSuspendState(cur.Directory) - if err != nil { - return err - } - if !suspended { - err := startprep.CleanStaleSuspendBeforeStart(ctx, cur.Directory, name, tmpDir, log, log) - if !errors.Is(err, reims.ErrSuspendStatePresent) { - return err - } - } - return i18n.NewCodedError(locale, "E_VM_SUSPENDED", "err.suspend.action_blocked", i18n.Vars{"name": name}, nil) -} - -func (a *App) stopMacOSVM(ctx context.Context, name string, force bool) error { - c, err := a.client() - if err != nil { - return err - } - detail, err := c.Show(ctx, name) - if err != nil { - return err - } - return a.withComputerUseVM(ctx, detail.Directory, func(operationCtx context.Context) error { - return a.stopMacOSVMLocked(operationCtx, name, force, c) - }) -} - -func (a *App) stopMacOSVMLocked(ctx context.Context, name string, force bool, c *reims.Client) error { - a.cancelRebootWatcher(name) - stopVMMonitor(name) - a.mu.Lock() - mgr := a.pluginMgr - a.transitions[vmKey(name)] = "stopping" - a.mu.Unlock() - if mgr != nil { - mgr.Registry().Hooks().DispatchBeforeStop(ctx, plugin.VMEventPayload{ - VMName: name, - DriverID: builtin.IDDriverReimsMacOS, - }) - } - a.emitStateChanged() - - w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) }) - a.emitVMLog(name, fmt.Sprintf("Stopping %s (force=%v)...", name, force)) - var err error - if force { - err = c.StopForce(ctx, name, w, w) - } else { - err = c.Stop(ctx, name, w, w) - } - if err != nil { - a.mu.Lock() - delete(a.transitions, vmKey(name)) - a.mu.Unlock() - a.emitVMLog(name, "Stop error: "+err.Error()) - return err - } - a.stopPacketBridge(name) - a.mu.Lock() - delete(a.pendingChanges, vmKey(name)) - a.mu.Unlock() - if mgr != nil { - mgr.Registry().Hooks().DispatchObserve(plugin.EventVMAfterStop, plugin.VMEventPayload{ - VMName: name, - DriverID: builtin.IDDriverReimsMacOS, - }) - } - a.wakePoll() - a.emitStateChanged() - return nil -} - // restartMacOSVM restarts a built-in macOS VM, waiting for the old QEMU // process and its committed memory to go away before starting again. func (a *App) restartMacOSVM(ctx context.Context, name string) (stopped bool, err error) { @@ -558,11 +196,7 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo svc := a.lifecycleSvc a.mu.Unlock() if svc == nil { - vm, resolveErr := a.resolveVMInfo(driver.BuiltinReimsMacOSDriverID, name) - if resolveErr != nil { - return true, resolveErr - } - return true, a.startResolvedVMLocked(ctx, nil, vm) + return true, errors.New("driver lifecycle is not initialized") } _, vm, err := svc.Resolve(ctx, driver.BuiltinReimsMacOSDriverID, name) if err != nil { @@ -571,99 +205,6 @@ func (a *App) restartMacOSVMLocked(ctx context.Context, name string) (stopped bo return true, a.startResolvedVMLocked(ctx, svc, vm) } -func (a *App) ejectMacOSInstaller(name string) error { - c, err := a.client() - if err != nil { - return err - } - detail, err := c.Show(context.Background(), name) - if err != nil { - return err - } - w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) }) - a.emitVMLog(name, "Ejecting installer from "+name+"...") - if err := a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error { - return c.Eject(ctx, name, w, w) - }); err != nil { - a.emitVMLog(name, "Eject error: "+err.Error()) - return err - } - a.emitVMLog(name, "Installer ejected.") - a.emitStateChanged() - return nil -} - -func (a *App) deleteMacOSVM(name string, keepFiles bool) error { - c, err := a.client() - if err != nil { - return err - } - detail, err := c.Show(context.Background(), name) - if err != nil { - return err - } - removed := false - err = a.withComputerUseVM(context.Background(), detail.Directory, func(ctx context.Context) error { - return a.deleteMacOSVMLocked(ctx, detail, keepFiles, c, &removed) - }) - if removed { - releaseVMTyping(name) - releaseVMThumbnail(name) - } - return err -} - -func (a *App) deleteMacOSVMLocked(ctx context.Context, detail reims.VMDetail, keepFiles bool, c *reims.Client, removed *bool) error { - name := detail.Name - if detail.State != "running" { - a.cancelRebootWatcher(name) - stopVMMonitor(name) - a.stopPacketBridge(name) - } - w := vmstart.LineWriter(func(line string) { a.emitVMLog(name, line) }) - a.emitVMLog(name, fmt.Sprintf("Deleting VM %s (keepFiles=%v)...", name, keepFiles)) - deleted, deleteErr := a.deleteVMWithGuestTools(name, func() error { - return c.Delete(ctx, name, keepFiles, w, w) - }, func() (bool, error) { - vms, err := c.List(ctx) - if err != nil { - return false, err - } - for _, vm := range vms { - if strings.EqualFold(vm.Name, name) { - return true, nil - } - } - return false, nil - }) - if deleteErr != nil { - a.emitVMLog(name, "Delete error: "+deleteErr.Error()) - } - if !deleted { - return deleteErr - } - *removed = true - a.cancelRebootWatcher(name) - stopVMMonitor(name) - a.stopPacketBridge(name) - a.mu.Lock() - delete(a.pendingChanges, vmKey(name)) - delete(a.transitions, vmKey(name)) - delete(a.diskPaths, vmKey(name)) - delete(a.procSamples, vmKey(name)) - delMgr := a.pluginMgr - a.mu.Unlock() - if delMgr != nil { - delMgr.Registry().Hooks().DispatchObserve(plugin.EventVMDeleted, plugin.VMEventPayload{ - VMName: name, - DriverID: builtin.IDDriverReimsMacOS, - }) - } - a.wakePoll() - a.emitStateChanged() - return deleteErr -} - // OpenVMFolder shows the VM's directory in File Explorer. func (a *App) OpenVMFolder(name string) error { d, err := a.GetVMDetail(name) @@ -675,11 +216,3 @@ func (a *App) OpenVMFolder(name string) error { } return host.OpenFolder(d.Directory) } - -func (a *App) readMacOSVMLogs(name string, serial bool) (string, error) { - c, err := a.client() - if err != nil { - return "", err - } - return c.ReadLogs(context.Background(), name, serial) -} diff --git a/internal/app/macos_settings.go b/internal/app/macos_settings.go index b5ba267..7cdaf72 100644 --- a/internal/app/macos_settings.go +++ b/internal/app/macos_settings.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "io" + "log" "path/filepath" "slices" "strconv" @@ -141,53 +142,20 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) { a.mu.Lock() svc := a.lifecycleSvc a.mu.Unlock() - if svc != nil { - raw, _ := json.Marshal(opts) - var changes map[string]any - _ = json.Unmarshal(raw, &changes) - if err := svc.Set(ctx, driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, opts.Name), changes, w, w); err != nil { - a.emitVMLog(opts.Name, "Set error: "+err.Error()) - return err - } - } else { - if strings.TrimSpace(opts.DiskCache) != "" { - cfg := a.runtimeConfig() - active, err := rt.ResolveActive(&cfg) - if err != nil { - return fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed")) - } - if !active.Manifest.HasCapability("win32-native-aio") { - return errors.New(i18n.T(i18n.EffectiveLocale(loc), "validate.disk_cache_requires_runtime")) - } - } - c, err := a.client() - if err != nil { - return err - } - locked, release, err := startprep.LockMutableVM(a.baseCtx(), c, opts.Name) - if err != nil { - return err - } - defer release() - if err := macosdriver.ApplyVMOptions(ctx, c, locked, opts, w, w, func(cur reims.VMDetail) error { - live := cur.State == "running" || cur.State == "paused" - if lang := strings.TrimSpace(opts.GuestLang); lang != "" && lang != cur.GuestLang { - prep, err := a.prep(opts.Name) - if err == nil { - err = prep.ApplyGuestLang(ctx, cur.Directory, opts.GuestLang, live) - } - return err - } - if !live && opts.Graphics != "" && opts.Graphics != cur.Graphics { - if prep, err := a.prep(opts.Name); err == nil { - prep.ReplayGuestLang(ctx, cur.Directory) - } - } - return nil - }); err != nil { - a.emitVMLog(opts.Name, "Set error: "+err.Error()) - return err - } + if svc == nil { + return errors.New("driver lifecycle is not initialized") + } + raw, merr := json.Marshal(opts) + if merr != nil { + return fmt.Errorf("encode VM settings: %w", merr) + } + var changes map[string]any + if uerr := json.Unmarshal(raw, &changes); uerr != nil { + return fmt.Errorf("decode VM settings: %w", uerr) + } + if err := svc.Set(ctx, driver.NewVMRef(driver.BuiltinReimsMacOSDriverID, opts.Name), changes, w, w); err != nil { + a.emitVMLog(opts.Name, "Set error: "+err.Error()) + return err } if diffs := pendingVMSettingsChanges(outcome, opts); len(diffs) > 0 { a.mu.Lock() @@ -334,7 +302,9 @@ func clearManagedNetworkLedger(vmDir string) { } } if changed { - _ = plugin.SaveArgLedger(vmDir, ledger) + if err := plugin.SaveArgLedger(vmDir, ledger); err != nil { + log.Printf("[app] save plugin arg ledger failed (%s): %v", vmDir, err) + } } } diff --git a/internal/app/macos_settings_test.go b/internal/app/macos_settings_test.go index 99d1790..e41b960 100644 --- a/internal/app/macos_settings_test.go +++ b/internal/app/macos_settings_test.go @@ -288,41 +288,39 @@ func newDisplayCtlApp(t *testing.T, vm displayCtlFixture, useDriver bool) (*App, } func TestApplyAutoResolutionWhileRunning(t *testing.T) { - for _, useDriver := range []bool{false, true} { - for _, state := range []string{"running", "paused"} { - t.Run(fmt.Sprintf("driver=%t/%s", useDriver, state), func(t *testing.T) { - initial := "1234x876" - a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: state, Resolution: initial}, useDriver) - on := true - if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on}); err != nil { - t.Fatal(err) - } - vm := fixture() - want := []PendingChange{ - {Field: "auto_resolution", From: "false", To: "true"}, - } - if vm.Resolution != initial || len(vm.Commands) != 0 || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) { - t.Fatalf("enable auto: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want) - } - if raw, found := reims.ReadConfiguredResolution(vm.Dir); !found || raw != initial { - t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial) - } - if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: initial}); err != nil { - t.Fatal(err) - } - vm = fixture() - if vm.Resolution != initial || vmstart.ReadVMDisplay(vm.Dir).AutoResolution || len(a.pendingChanges) != 0 { - t.Fatalf("manual resolution: VM %+v, want initial resolution and no pending changes, got %+v", vm, a.pendingChanges) - } - if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800"}); err != nil { - t.Fatal(err) - } - want = []PendingChange{{Field: "resolution", From: initial, To: "1280x800"}} - if vm = fixture(); vm.Resolution != "1280x800" || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) { - t.Fatalf("changed fixed resolution: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want) - } - }) - } + for _, state := range []string{"running", "paused"} { + t.Run(state, func(t *testing.T) { + initial := "1234x876" + a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: state, Resolution: initial}, true) + on := true + if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on}); err != nil { + t.Fatal(err) + } + vm := fixture() + want := []PendingChange{ + {Field: "auto_resolution", From: "false", To: "true"}, + } + if vm.Resolution != initial || len(vm.Commands) != 0 || !vmstart.ReadVMDisplay(vm.Dir).AutoResolution || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) { + t.Fatalf("enable auto: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want) + } + if raw, found := reims.ReadConfiguredResolution(vm.Dir); !found || raw != initial { + t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial) + } + if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: initial}); err != nil { + t.Fatal(err) + } + vm = fixture() + if vm.Resolution != initial || vmstart.ReadVMDisplay(vm.Dir).AutoResolution || len(a.pendingChanges) != 0 { + t.Fatalf("manual resolution: VM %+v, want initial resolution and no pending changes, got %+v", vm, a.pendingChanges) + } + if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800"}); err != nil { + t.Fatal(err) + } + want = []PendingChange{{Field: "resolution", From: initial, To: "1280x800"}} + if vm = fixture(); vm.Resolution != "1280x800" || !slices.Equal(a.pendingChanges[vmKey(displayFixtureVM)], want) { + t.Fatalf("changed fixed resolution: VM %+v, changes %+v, want %+v", vm, a.pendingChanges, want) + } + }) } } @@ -358,26 +356,22 @@ func TestApplyAutoResolutionDoesNotReadBackSettings(t *testing.T) { } func TestApplyAutoResolutionUsesLockedSettingsForPendingChanges(t *testing.T) { - for _, useDriver := range []bool{false, true} { - t.Run(fmt.Sprintf("driver=%t", useDriver), func(t *testing.T) { - a, fixture := newDisplayCtlApp(t, displayCtlFixture{ - State: "running", Resolution: "1234x876", BeforeLockResolution: "2560x1600", Memory: "2G", - }, useDriver) - if _, err := vmstart.SaveVMAutoResolution(fixture().Dir, true); err != nil { - t.Fatal(err) - } - if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Memory: "3G"}); err != nil { - t.Fatal(err) - } - vm := fixture() - if vm.Resolution != "2560x1600" || vm.Memory != "3G" || vmstart.ReadVMDisplay(vm.Dir).AutoResolution { - t.Fatalf("saved VM = %+v, display = %+v", vm, vmstart.ReadVMDisplay(vm.Dir)) - } - want := []PendingChange{{Field: "memory", From: "2G", To: "3G"}} - if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) { - t.Fatalf("pending changes = %+v, want %+v", got, want) - } - }) + a, fixture := newDisplayCtlApp(t, displayCtlFixture{ + State: "running", Resolution: "1234x876", BeforeLockResolution: "2560x1600", Memory: "2G", + }, true) + if _, err := vmstart.SaveVMAutoResolution(fixture().Dir, true); err != nil { + t.Fatal(err) + } + if err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Memory: "3G"}); err != nil { + t.Fatal(err) + } + vm := fixture() + if vm.Resolution != "2560x1600" || vm.Memory != "3G" || vmstart.ReadVMDisplay(vm.Dir).AutoResolution { + t.Fatalf("saved VM = %+v, display = %+v", vm, vmstart.ReadVMDisplay(vm.Dir)) + } + want := []PendingChange{{Field: "memory", From: "2G", To: "3G"}} + if got := a.pendingChanges[vmKey(displayFixtureVM)]; !slices.Equal(got, want) { + t.Fatalf("pending changes = %+v, want %+v", got, want) } } @@ -422,178 +416,170 @@ func TestMergePendingChangesKeepsRunningValues(t *testing.T) { } func TestApplyAutoResolutionTransaction(t *testing.T) { - for _, useDriver := range []bool{false, true} { - for _, tc := range []struct { - name string - failSidecar, failSet bool - }{ - {name: "saved"}, - {name: "sidecar write fails", failSidecar: true}, - {name: "set fails", failSet: true}, - } { - t.Run(fmt.Sprintf("driver=%t/%s", useDriver, tc.name), func(t *testing.T) { - const initial = "1234x876" - a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, FailSet: tc.failSet}, useDriver) - dir := fixture().Dir - prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"} - if tc.failSidecar { - if err := os.Mkdir(filepath.Join(dir, ".reims-go-display.json"), 0o700); err != nil { - t.Fatal(err) - } - } else if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil { + for _, tc := range []struct { + name string + failSidecar, failSet bool + }{ + {name: "saved"}, + {name: "sidecar write fails", failSidecar: true}, + {name: "set fails", failSet: true}, + } { + t.Run(tc.name, func(t *testing.T) { + const initial = "1234x876" + a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, FailSet: tc.failSet}, true) + dir := fixture().Dir + prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"} + if tc.failSidecar { + if err := os.Mkdir(filepath.Join(dir, ".reims-go-display.json"), 0o700); err != nil { t.Fatal(err) } - on := true - err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on, NestedVirt: &on}) - if tc.failSidecar { - if err == nil || len(fixture().Commands) != 0 { - t.Fatalf("save = %v, commands = %v, want sidecar error before set", err, fixture().Commands) - } - return + } else if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil { + t.Fatal(err) + } + on := true + err := a.ApplyVMSettings(reims.SetOpts{Name: displayFixtureVM, Resolution: "1280x800", AutoResolution: &on, NestedVirt: &on}) + if tc.failSidecar { + if err == nil || len(fixture().Commands) != 0 { + t.Fatalf("save = %v, commands = %v, want sidecar error before set", err, fixture().Commands) } - vm := fixture() - target, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true) - if !slices.Equal(vm.Commands, []string{"set test-vm --resolution " + target}) { - t.Fatalf("commands = %v", vm.Commands) + return + } + vm := fixture() + target, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), false, true) + if !slices.Equal(vm.Commands, []string{"set test-vm --resolution " + target}) { + t.Fatalf("commands = %v", vm.Commands) + } + if nested, readErr := vmstart.ReadVMNestedVirt(dir); readErr != nil || nested.Enabled != !tc.failSet { + t.Fatalf("nested virtualization = %+v, %v, want enabled = %t", nested, readErr, !tc.failSet) + } + if tc.failSet { + if err == nil || !vm.NestedVirtBeforeSet || vm.Resolution != initial || vmstart.ReadVMDisplay(dir) != prev { + t.Fatalf("save = %v, VM = %+v, display = %+v, want original settings", err, vm, vmstart.ReadVMDisplay(dir)) } - if nested, readErr := vmstart.ReadVMNestedVirt(dir); readErr != nil || nested.Enabled != !tc.failSet { - t.Fatalf("nested virtualization = %+v, %v, want enabled = %t", nested, readErr, !tc.failSet) - } - if tc.failSet { - if err == nil || !vm.NestedVirtBeforeSet || vm.Resolution != initial || vmstart.ReadVMDisplay(dir) != prev { - t.Fatalf("save = %v, VM = %+v, display = %+v, want original settings", err, vm, vmstart.ReadVMDisplay(dir)) - } - return - } - prev.AutoResolution = true - if err != nil || vm.Resolution != target || vmstart.ReadVMDisplay(dir) != prev { - t.Fatalf("save = %v, VM = %+v, display = %+v, want %s and %+v", err, vm, vmstart.ReadVMDisplay(dir), target, prev) - } - }) - } + return + } + prev.AutoResolution = true + if err != nil || vm.Resolution != target || vmstart.ReadVMDisplay(dir) != prev { + t.Fatalf("save = %v, VM = %+v, display = %+v, want %s and %+v", err, vm, vmstart.ReadVMDisplay(dir), target, prev) + } + }) } } func TestApplyAutoResolutionWithSVGA(t *testing.T) { - for _, useDriver := range []bool{false, true} { - for _, graphics := range []string{"vmware-svga", "reims-vgpu"} { - t.Run(fmt.Sprintf("driver=%t/from=%s", useDriver, graphics), func(t *testing.T) { - const initial = "1234x876" - a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, Graphics: graphics}, useDriver) - dir := fixture().Dir - prev := vmstart.VMDisplayConfig{TargetDisplay: "secondary", AutoResolution: true} - if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil { - t.Fatal(err) - } - detail, err := a.GetVMDetail(displayFixtureVM) - if err != nil || detail.AutoResolution != (graphics == "reims-vgpu") { - t.Fatalf("details = %+v, %v", detail, err) - } - on := true - opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on} - var want []string - if graphics != "vmware-svga" { - opts.Graphics = "vmware-svga" - want = []string{"set test-vm --graphics vmware-svga"} - } - if err := a.ApplyVMSettings(opts); err != nil { - t.Fatal(err) - } - prev.AutoResolution = false - if vm := fixture(); vm.Graphics != "vmware-svga" || vm.Resolution != initial || - !slices.Equal(vm.Commands, want) || vmstart.ReadVMDisplay(dir) != prev { - t.Fatalf("VM = %+v, display = %+v, want commands %v and display %+v", vm, vmstart.ReadVMDisplay(dir), want, prev) - } - }) - } + for _, graphics := range []string{"vmware-svga", "reims-vgpu"} { + t.Run(graphics, func(t *testing.T) { + const initial = "1234x876" + a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: initial, Graphics: graphics}, true) + dir := fixture().Dir + prev := vmstart.VMDisplayConfig{TargetDisplay: "secondary", AutoResolution: true} + if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil { + t.Fatal(err) + } + detail, err := a.GetVMDetail(displayFixtureVM) + if err != nil || detail.AutoResolution != (graphics == "reims-vgpu") { + t.Fatalf("details = %+v, %v", detail, err) + } + on := true + opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on} + var want []string + if graphics != "vmware-svga" { + opts.Graphics = "vmware-svga" + want = []string{"set test-vm --graphics vmware-svga"} + } + if err := a.ApplyVMSettings(opts); err != nil { + t.Fatal(err) + } + prev.AutoResolution = false + if vm := fixture(); vm.Graphics != "vmware-svga" || vm.Resolution != initial || + !slices.Equal(vm.Commands, want) || vmstart.ReadVMDisplay(dir) != prev { + t.Fatalf("VM = %+v, display = %+v, want commands %v and display %+v", vm, vmstart.ReadVMDisplay(dir), want, prev) + } + }) } } func TestApplyAutoResolutionRollsBackDisplayOnLaterFailure(t *testing.T) { - for _, useDriver := range []bool{false, true} { - for _, tc := range []struct { - state, blockedFile string - }{ - {"running", ".reims-go-nested-virt.json"}, - {"stopped", ".reims-go-nested-virt.json"}, - {"running", ".reims-go-guest-lang"}, - {"stopped", ".reims-go-guest-lang"}, - } { - t.Run(fmt.Sprintf("driver=%t/%s/%s", useDriver, tc.state, tc.blockedFile), func(t *testing.T) { - const initial = "1234x876" - a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: tc.state, Resolution: initial}, useDriver) - dir := fixture().Dir - prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"} - if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil { - t.Fatal(err) + for _, tc := range []struct { + state, blockedFile string + }{ + {"running", ".reims-go-nested-virt.json"}, + {"stopped", ".reims-go-nested-virt.json"}, + {"running", ".reims-go-guest-lang"}, + {"stopped", ".reims-go-guest-lang"}, + } { + t.Run(tc.state+"/"+tc.blockedFile, func(t *testing.T) { + const initial = "1234x876" + a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: tc.state, Resolution: initial}, true) + dir := fixture().Dir + prev := vmstart.VMDisplayConfig{TargetDisplay: "unplugged-display"} + if _, err := vmstart.SaveVMDisplay(dir, prev); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(dir, tc.blockedFile), 0o700); err != nil { + t.Fatal(err) + } + on := true + opts := reims.SetOpts{Name: displayFixtureVM, Memory: "4G", AutoResolution: &on, NestedVirt: &on} + if tc.blockedFile == ".reims-go-guest-lang" { + opts.GuestLang = "zh-Hans:0" + } + if err := a.ApplyVMSettings(opts); err == nil || !strings.Contains(err.Error(), tc.blockedFile) { + t.Fatalf("save = %v, want error writing %s", err, tc.blockedFile) + } + if commands := fixture().Commands; len(commands) != 0 { + t.Fatalf("commands = %v, want no reims-ctl set call before local failures", commands) + } + if got := vmstart.ReadVMDisplay(dir); got != prev || len(a.pendingChanges) != 0 { + t.Fatalf("display = %+v, want %+v; pending = %+v", got, prev, a.pendingChanges) + } + if raw, found := reims.ReadConfiguredResolution(dir); !found || raw != initial { + t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial) + } + if opts.GuestLang != "" { + if nested, err := vmstart.ReadVMNestedVirt(dir); err != nil || nested.Enabled { + t.Fatalf("nested virtualization = %+v, %v, want disabled", nested, err) } - if err := os.Mkdir(filepath.Join(dir, tc.blockedFile), 0o700); err != nil { - t.Fatal(err) - } - on := true - opts := reims.SetOpts{Name: displayFixtureVM, Memory: "4G", AutoResolution: &on, NestedVirt: &on} - if tc.blockedFile == ".reims-go-guest-lang" { - opts.GuestLang = "zh-Hans:0" - } - if err := a.ApplyVMSettings(opts); err == nil || !strings.Contains(err.Error(), tc.blockedFile) { - t.Fatalf("save = %v, want error writing %s", err, tc.blockedFile) - } - if commands := fixture().Commands; len(commands) != 0 { - t.Fatalf("commands = %v, want no reims-ctl set call before local failures", commands) - } - if got := vmstart.ReadVMDisplay(dir); got != prev || len(a.pendingChanges) != 0 { - t.Fatalf("display = %+v, want %+v; pending = %+v", got, prev, a.pendingChanges) - } - if raw, found := reims.ReadConfiguredResolution(dir); !found || raw != initial { - t.Fatalf("configured resolution = %q, found = %t, want %q", raw, found, initial) - } - if opts.GuestLang != "" { - if nested, err := vmstart.ReadVMNestedVirt(dir); err != nil || nested.Enabled { - t.Fatalf("nested virtualization = %+v, %v, want disabled", nested, err) - } - } - }) - } + } + }) } } func TestApplyAutoResolutionSyncsExistingConfiguration(t *testing.T) { - for _, useDriver := range []bool{false, true} { - for _, tc := range []struct { - name, graphics string - borderless bool - }{ - {name: "windowed multi-display"}, - {name: "borderless multi-display", borderless: true}, - {name: "from SVGA", graphics: "vmware-svga"}, - } { - t.Run(fmt.Sprintf("driver=%t/%s", useDriver, tc.name), func(t *testing.T) { - res, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), tc.borderless, true) - raw := res - want := "set test-vm --resolution " + res - on := true - opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on} - if tc.graphics == "vmware-svga" { - opts.Graphics = "reims-vgpu" - want = "set test-vm --graphics reims-vgpu --resolution " + res - } else { - raw += ",2560x1440" - } - a, fixture := newDisplayCtlApp(t, displayCtlFixture{ - State: "stopped", Resolution: res, Graphics: tc.graphics, Borderless: tc.borderless, - }, useDriver) - dir := fixture().Dir - if err := writeDisplayCtlResolution(dir, raw); err != nil { - t.Fatal(err) - } - if err := a.ApplyVMSettings(opts); err != nil { - t.Fatal(err) - } - if got := fixture().Commands; !slices.Equal(got, []string{want}) { - t.Fatalf("commands = %v, want %q", got, want) - } - }) - } + for _, tc := range []struct { + name, graphics string + borderless bool + }{ + {name: "windowed multi-display"}, + {name: "borderless multi-display", borderless: true}, + {name: "from SVGA", graphics: "vmware-svga"}, + } { + t.Run(tc.name, func(t *testing.T) { + res, _ := host.RecommendAutoResolution(host.PrimaryDisplayOf(host.ConnectedDisplays()), tc.borderless, true) + raw := res + want := "set test-vm --resolution " + res + on := true + opts := reims.SetOpts{Name: displayFixtureVM, AutoResolution: &on} + if tc.graphics == "vmware-svga" { + opts.Graphics = "reims-vgpu" + want = "set test-vm --graphics reims-vgpu --resolution " + res + } else { + raw += ",2560x1440" + } + a, fixture := newDisplayCtlApp(t, displayCtlFixture{ + State: "stopped", Resolution: res, Graphics: tc.graphics, Borderless: tc.borderless, + }, true) + dir := fixture().Dir + if err := writeDisplayCtlResolution(dir, raw); err != nil { + t.Fatal(err) + } + if err := a.ApplyVMSettings(opts); err != nil { + t.Fatal(err) + } + if got := fixture().Commands; !slices.Equal(got, []string{want}) { + t.Fatalf("commands = %v, want %q", got, want) + } + }) } } @@ -675,29 +661,3 @@ func TestClonePreservesAutoResolution(t *testing.T) { t.Fatalf("cloned display preference = %+v", got) } } - -func TestLegacyColdStartAutoResolution(t *testing.T) { - for _, tc := range []struct { - name, initial, graphics string - auto bool - want []string - }{ - {"changed", "3840x2160", "reims-vgpu", true, []string{"set test-vm --resolution 5120x2880", "start test-vm fixed=1"}}, - {"already current", "5120x2880", "reims-vgpu", true, []string{"start test-vm fixed=1"}}, - {"disabled", "3840x2160", "reims-vgpu", false, []string{"start test-vm fixed="}}, - {"SVGA", "3840x2160", "vmware-svga", true, []string{"start test-vm fixed="}}, - } { - t.Run(tc.name, func(t *testing.T) { - a, fixture := newDisplayCtlApp(t, displayCtlFixture{State: "stopped", Resolution: tc.initial, Graphics: tc.graphics, Borderless: true}, false) - if _, err := vmstart.SaveVMAutoResolution(fixture().Dir, tc.auto); err != nil { - t.Fatal(err) - } - err := a.startMacOSVMWithHost(displayFixtureVM, func(string) host.Report { - return host.Report{WHPX: host.WHPXReady, Displays: []host.DisplayInfo{{Width: 3840, Height: 2160, ScalePct: 150, Primary: true}}} - }) - if err == nil || !slices.Equal(fixture().Commands, tc.want) { - t.Fatalf("legacy start = %v, commands %v, want %v", err, fixture().Commands, tc.want) - } - }) - } -} diff --git a/internal/app/network_review_test.go b/internal/app/network_review_test.go index 1bf2858..044dced 100644 --- a/internal/app/network_review_test.go +++ b/internal/app/network_review_test.go @@ -1,143 +1,14 @@ package app import ( - "context" - "errors" "fmt" - "io" - "path/filepath" "runtime" - "strings" "sync" "sync/atomic" "testing" "time" - - "github.com/Nwflower/reims-go/internal/i18n" - "github.com/Nwflower/reims-go/internal/macos/reims" - "github.com/Nwflower/reims-go/internal/plugin" - "github.com/Nwflower/reims-go/internal/plugin/builtin" ) -type reviewNetworkControl struct { - extra string - writes int - setErr error -} - -func (*reviewNetworkControl) List(context.Context) ([]reims.VMListItem, error) { return nil, nil } -func (*reviewNetworkControl) Show(context.Context, string) (reims.VMDetail, error) { - return reims.VMDetail{}, nil -} -func (*reviewNetworkControl) CommandText(context.Context, string) (string, error) { - return "qemu -netdev user,id=net0 -device virtio-net-pci,netdev=net0,id=net0,mac=02:00:00:00:00:01", nil -} -func (c *reviewNetworkControl) Set(_ context.Context, opts reims.SetOpts, _, _ io.Writer) error { - if c.setErr != nil { - return c.setErr - } - if opts.ExtraArgs != nil { - c.extra = *opts.ExtraArgs - c.writes++ - } - return nil -} - -func TestLegacyBridgeArgsHaveRemovableOwner(t *testing.T) { - dir := t.TempDir() - detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"} - if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil { - t.Fatal(err) - } - control := &reviewNetworkControl{} - a := &App{} - if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil { - t.Fatal(err) - } - if !strings.Contains(control.extra, "id=reimsbridge0") { - t.Fatal("隔离客户端未收到桥接参数") - } - ledger, err := plugin.LoadArgLedger(dir) - if err != nil { - t.Fatal(err) - } - if len(ledger.Owners[builtin.IDNpcapBridge]) != 1 { - t.Fatalf("桥接参数已写入,但 Npcap 账本条目数为 %d", len(ledger.Owners[builtin.IDNpcapBridge])) - } - if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil { - t.Fatal(err) - } - if control.writes != 1 { - t.Fatalf("重复准备写入了 %d 次参数", control.writes) - } - if strings.Count(detail.ExtraArgs, "id=reimsbridge0,") != 1 { - t.Fatal("重复准备产生重复桥接设备") - } - clean := plugin.ReconcileStartIntents(detail.ExtraArgs, ledger, map[string]bool{}, nil) - if clean.ExtraArgs != "-cpu host" { - t.Fatalf("停用后残留桥接参数:%s", clean.ExtraArgs) - } -} - -func TestLegacyBridgeArgsStopOnInvalidRecordOrWriteFailure(t *testing.T) { - for _, mode := range []string{"corrupt", "pending", "set failure"} { - t.Run(mode, func(t *testing.T) { - dir := t.TempDir() - detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"} - record := reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")} - code := "E_NETWORK_CONFIG_SAVE" - control := &reviewNetworkControl{setErr: errors.New("模拟配置写入失败")} - if mode == "corrupt" { - record.Version = 99 - code = "E_NETWORK_RECORD_INVALID" - } - if mode == "pending" { - record.Pending = true - code = "E_NETWORK_PACKET_PENDING" - } - if err := reims.SaveNetworkRecord(dir, record); err != nil { - t.Fatal(err) - } - err := (&App{}).reconcileLegacyBridgeArgs(context.Background(), control, &detail) - var coded *i18n.CodedError - if !errors.As(err, &coded) || coded.Code != code { - t.Fatalf("错误 = %v,预期 %s", err, code) - } - ledger, err := plugin.LoadArgLedger(dir) - if err != nil { - t.Fatal(err) - } - if detail.ExtraArgs != "-cpu host" || len(ledger.Owners) != 0 { - t.Fatal("准备失败却更新了参数或归属") - } - }) - } -} - -func TestLegacyBridgeArgsClearOwnerWhenLeavingBridge(t *testing.T) { - dir := t.TempDir() - detail := reims.VMDetail{Name: "fake-vm", Directory: dir, NetworkMode: "bridge", ExtraArgs: "-cpu host"} - if err := reims.SaveNetworkRecord(dir, reims.NetworkRecord{Mode: "bridge", SocketPath: filepath.Join(dir, "bridge.sock")}); err != nil { - t.Fatal(err) - } - a := &App{} - control := &reviewNetworkControl{} - if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil { - t.Fatal(err) - } - detail.NetworkMode = "nat" - if err := a.reconcileLegacyBridgeArgs(context.Background(), control, &detail); err != nil { - t.Fatal(err) - } - ledger, err := plugin.LoadArgLedger(dir) - if err != nil { - t.Fatal(err) - } - if detail.ExtraArgs != "-cpu host" || len(ledger.Owners[builtin.IDNpcapBridge]) != 0 { - t.Fatal("离开桥接后仍残留参数或归属") - } -} - func networkLockCount(a *App) int { count := 0 a.vmNetworkLocks.Range(func(_, _ any) bool { count++; return true }) diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index 83aac50..88531d5 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -70,18 +70,19 @@ func (a *App) initPlugins() { return } var mgr *plugin.Manager - mgr, err := plugin.NewManager(plugin.ManagerOptions{ - DataRoot: dataRoot, - HostVersion: version.Version, - SafeMode: safeMode, - RedactFn: host.RedactText, - LocaleFn: a.locale, + var drvRouter *driver.Router + mgr, drvRouter, err := builtin.BootstrapKernel(builtin.KernelBootstrapOptions{ + DataRoot: dataRoot, + DataRootFn: func() string { + a.mu.Lock() + defer a.mu.Unlock() + return a.cfg.DataRoot + }, + SafeMode: safeMode, + LocaleFn: a.locale, Logger: func(source, line string) { a.emitLog(source, line) }, - SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any { - return driver.NewSidecarDriver(contrib, sup) - }, HostHandlers: func(pluginID string) map[string]plugin.RPCRequestHandler { a.mu.Lock() current := a.pluginMgr @@ -96,23 +97,86 @@ func (a *App) initPlugins() { // longer release it, so the host lifts what it left down. a.releaseHeldForPlugin(pluginID) }, + VMInventory: guest.VMInventory(), + Callbacks: builtin.HostCallbacks{ + GetConfig: a.runtimeConfig, + Log: func(source, line string) { + a.emitLog(source, line) + }, + EnsureGuestTools: func() (*guesttools.Server, int, error) { + srv, port, created, err := a.startGuestToolsServer() + if err == nil && created { + // A fresh server knows no VM tokens: at startup and when the + // plugin is switched back on, re-register configured VMs. + go a.registerVMsWithBridge(context.Background(), srv, port) + } + return srv, port, err + }, + StopGuestTools: func() { + a.mu.Lock() + gt := a.guestTools + a.guestTools = nil + a.mu.Unlock() + if gt != nil { + shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + _ = gt.Close(shutCtx) + cancel() + } + }, + LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) { + epoch := a.vmDeleteEpoch(name) + // The start hook can receive a directory read before the VM was deleted. + if epoch != 0 { + vms, err := a.listVMsInternal(context.Background()) + if err != nil { + return guesttools.VMConfig{}, err + } + if !slices.ContainsFunc(vms, func(vm driver.VMListItem) bool { + return strings.EqualFold(vm.Name, name) && filepath.Clean(vm.Dir) == filepath.Clean(dir) + }) { + return guesttools.VMConfig{}, os.ErrNotExist + } + } + return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch) + }, + OnIMEText: func(target host.IMETarget, text string) { + go a.injectRemoteText(target.VMName, target.VMDir, text) + }, + StartColdReboot: func(vmName, qmpAddr string) { + a.watchWin10ColdReboot(vmName, qmpAddr) + }, + CancelColdReboot: func(vmName string) { + a.cancelRebootWatcher(vmName) + }, + GuestToolsImg: func(vmName string) string { + return a.guestToolsImagePath(vmName) + }, + BuildGuestToolsImage: a.buildGuestToolsImage, + OpenAppWindow: a.openAppWindow, + PrepareVMNetwork: a.prepareManagedVMNetwork, + RestorePacketBridges: func(ctx context.Context) func() { + return a.startPacketBridgeRestore(ctx, func(ctx context.Context) { + if a.dataRootUsable() { + a.registerExistingPacketBridges(ctx) + } + }) + }, + StopPacketBridges: a.closePacketBridges, + OnInstallGuidesChanged: func() { + a.emitStateChanged() + }, + SyncInstallGuides: func() { + a.wakePoll() + }, + }, + RegisterGuest: guest.Register, }) if err != nil { - a.emitLog("plugin", "Plugin state warning: "+err.Error()) - if mgr == nil { - return - } + a.emitLog("plugin", "Could not initialize plugin manager: "+err.Error()) + return } kindReg := rt.NewKindRegistry() - drvRouter := driver.NewRouter(mgr.Registry(), func() string { - a.mu.Lock() - defer a.mu.Unlock() - return a.cfg.DataRoot - }, guest.VMInventory()) - - mgr.Registry().SetInUseChecker(drvRouter.PluginInUseChecker()) - mgr.Registry().SetBusyChecker(drvRouter.PluginBusyChecker()) // Drivers push the state of the VMs they host; the router merges the table // into what the drivers return. A spawned VM's exit wakes the poll at once. @@ -133,92 +197,6 @@ func (a *App) initPlugins() { a.emitLog("plugin:"+pluginID, title+": "+body) }) - cb := builtin.HostCallbacks{ - GetConfig: a.runtimeConfig, - Log: func(source, line string) { - a.emitLog(source, line) - }, - EnsureGuestTools: func() (*guesttools.Server, int, error) { - srv, port, created, err := a.startGuestToolsServer() - if err == nil && created { - // A fresh server knows no VM tokens: at startup and when the - // plugin is switched back on, re-register configured VMs. - go a.registerVMsWithBridge(context.Background(), srv, port) - } - return srv, port, err - }, - StopGuestTools: func() { - a.mu.Lock() - gt := a.guestTools - a.guestTools = nil - a.mu.Unlock() - if gt != nil { - shutCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) - _ = gt.Close(shutCtx) - cancel() - } - }, - LoadAndRegisterGuestTools: func(srv *guesttools.Server, port int, dir, name string) (guesttools.VMConfig, error) { - epoch := a.vmDeleteEpoch(name) - // The start hook can receive a directory read before the VM was deleted. - if epoch != 0 { - vms, err := a.listVMsInternal(context.Background()) - if err != nil { - return guesttools.VMConfig{}, err - } - if !slices.ContainsFunc(vms, func(vm driver.VMListItem) bool { - return strings.EqualFold(vm.Name, name) && filepath.Clean(vm.Dir) == filepath.Clean(dir) - }) { - return guesttools.VMConfig{}, os.ErrNotExist - } - } - return a.loadAndRegisterNetworkGuestTools(srv, port, dir, name, epoch) - }, - OnIMEText: func(target host.IMETarget, text string) { - go a.injectRemoteText(target.VMName, target.VMDir, text) - }, - StartColdReboot: func(vmName, qmpAddr string) { - a.watchWin10ColdReboot(vmName, qmpAddr) - }, - CancelColdReboot: func(vmName string) { - a.cancelRebootWatcher(vmName) - }, - GuestToolsImg: func(vmName string) string { - return a.guestToolsImagePath(vmName) - }, - BuildGuestToolsImage: a.buildGuestToolsImage, - OpenAppWindow: a.openAppWindow, - PrepareVMNetwork: a.prepareManagedVMNetwork, - RestorePacketBridges: func(ctx context.Context) func() { - return a.startPacketBridgeRestore(ctx, func(ctx context.Context) { - if a.dataRootUsable() { - a.registerExistingPacketBridges(ctx) - } - }) - }, - StopPacketBridges: a.closePacketBridges, - OnInstallGuidesChanged: func() { - a.emitStateChanged() - }, - SyncInstallGuides: func() { - a.wakePoll() - }, - GetSetting: func(pluginID, vmName, key string) (any, bool) { - v, ok := mgr.GetSettings(pluginID, vmName, false)[key] - return v, ok - }, - } - - if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil { - a.emitLog("plugin", "Builtin extension register error: "+err.Error()) - } - if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil { - a.emitLog("plugin", "macOS guest plugin register error: "+err.Error()) - } - if err := mgr.LoadExternal(); err != nil { - a.emitLog("plugin", "External plugin load warning: "+err.Error()) - } - // Sync runtime kinds, input filters, clipboard policies, and locales whenever registry state changes. mgr.Registry().OnChange(func() { active := map[string]bool{} diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index 0bff8f8..fcc5ed2 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -12,6 +12,7 @@ import ( "errors" "fmt" "image/png" + "log" "os" "path/filepath" "strings" @@ -281,8 +282,10 @@ func (a *App) captureThumb(driverID, name, path string) (VMThumbnail, bool) { if err != nil { return VMThumbnail{}, false } - if err := os.MkdirAll(filepath.Dir(path), 0o755); err == nil { - _ = atomicfile.Write(path, jpg, 0o644) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + log.Printf("[thumb] create cache dir failed (%s): %v", filepath.Dir(path), err) + } else if err := atomicfile.Write(path, jpg, 0o644); err != nil { + log.Printf("[thumb] write cache failed (%s): %v", path, err) } return VMThumbnail{ DataURL: "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(jpg), diff --git a/internal/archtest/error_handling_test.go b/internal/archtest/error_handling_test.go new file mode 100644 index 0000000..c0b8ed4 --- /dev/null +++ b/internal/archtest/error_handling_test.go @@ -0,0 +1,95 @@ +package archtest + +import ( + "go/ast" + "go/token" + "testing" +) + +// TestNoSilentRecover forbids bare `recover()` and `_ = recover()` statements +// in production code so panics are never silently swallowed without logging or +// surfacing an error. +func TestNoSilentRecover(t *testing.T) { + for _, s := range sources(t) { + if s.isTest() { + continue + } + ast.Inspect(s.file, func(n ast.Node) bool { + switch stmt := n.(type) { + case *ast.ExprStmt: + if isRecoverCall(stmt.X) { + pos := fileSet.Position(stmt.Pos()) + t.Errorf("%s:%d: bare recover() silently swallows panics; bind and log/report it", s.rel, pos.Line) + } + case *ast.AssignStmt: + if len(stmt.Rhs) == 1 && isRecoverCall(stmt.Rhs[0]) && allBlankIdents(stmt.Lhs) { + pos := fileSet.Position(stmt.Pos()) + t.Errorf("%s:%d: `_ = recover()` silently swallows panics; bind and log/report it", s.rel, pos.Line) + } + } + return true + }) + } +} + +func isRecoverCall(expr ast.Expr) bool { + call, ok := expr.(*ast.CallExpr) + if !ok { + return false + } + ident, ok := call.Fun.(*ast.Ident) + return ok && ident.Name == "recover" +} + +func allBlankIdents(exprs []ast.Expr) bool { + if len(exprs) == 0 { + return false + } + for _, e := range exprs { + id, ok := e.(*ast.Ident) + if !ok || id.Name != "_" { + return false + } + } + return true +} + +// TestNoSilentFatalPersistenceDiscards guards against `_ = ` on critical +// persistence/rollback primitives where dropping an error silently corrupts +// on-disk state. +func TestNoSilentFatalPersistenceDiscards(t *testing.T) { + guarded := map[string]bool{ + "atomicfile.Write": true, + "atomicfile.WriteJSON": true, + "plugin.SaveArgLedger": true, + } + for _, s := range sources(t) { + if s.isTest() { + continue + } + ast.Inspect(s.file, func(n ast.Node) bool { + assign, ok := n.(*ast.AssignStmt) + if !ok || assign.Tok != token.ASSIGN || len(assign.Rhs) != 1 || !allBlankIdents(assign.Lhs) { + return true + } + call, ok := assign.Rhs[0].(*ast.CallExpr) + if !ok { + return true + } + sel, ok := call.Fun.(*ast.SelectorExpr) + if !ok { + return true + } + pkg, ok := sel.X.(*ast.Ident) + if !ok { + return true + } + key := pkg.Name + "." + sel.Sel.Name + if guarded[key] { + pos := fileSet.Position(assign.Pos()) + t.Errorf("%s:%d: discarding error from %s with `_ =` is forbidden; handle or log the error", s.rel, pos.Line, key) + } + return true + }) + } +} diff --git a/internal/archtest/macos_boundary_test.go b/internal/archtest/macos_boundary_test.go index 7804269..12e7c8d 100644 --- a/internal/archtest/macos_boundary_test.go +++ b/internal/archtest/macos_boundary_test.go @@ -20,7 +20,6 @@ var macosImporters = map[string]macosImporter{ "internal/app": {test: true, why: "GUI composition root tests may exercise native macOS flows"}, "internal/datamigrate": {src: true, test: true, why: "data layout v3 invokes and verifies the macOS-owned state and ledger migration"}, "internal/plugin/builtin": {src: true, why: "host Guest Tools bridge still uses reims argument helpers; guest registration moved to internal/macos/guest"}, - "internal/guesttools": {src: true, test: true, why: "mixed: host transport and clipboard next to the macOS guest agent image"}, } // macosSourceFiles is the file-scoped native macOS boundary. plugins_flow.go diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index 25e1d41..3928f48 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -10,7 +10,6 @@ import ( "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" - "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/macos/guest" "github.com/Nwflower/reims-go/internal/plugin" @@ -22,49 +21,30 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * if err := guest.MigrateFiles(cfg.DataRoot); err != nil { return nil, nil, err } - mgr, err := plugin.NewManager(plugin.ManagerOptions{ - DataRoot: cfg.DataRoot, - HostVersion: version.Version, - SafeMode: safeMode, - RedactFn: host.RedactText, + logf := func(source, line string) { + fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line) + } + mgr, router, err := builtin.BootstrapKernel(builtin.KernelBootstrapOptions{ + DataRoot: cfg.DataRoot, + SafeMode: safeMode, LocaleFn: func() i18n.Locale { return i18n.EffectiveLocale(cfg.Locale) }, - Logger: func(source, line string) { - fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line) - }, - SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any { - return driver.NewSidecarDriver(contrib, sup) + Logger: logf, + VMInventory: guest.VMInventory(), + Callbacks: builtin.HostCallbacks{ + GetConfig: func() config.Config { return *cfg }, + PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) { + return nil, checkDirectMacOSNetwork(ctx, cfg, name) + }, + Log: logf, }, + RegisterGuest: guest.Register, + StrictRegister: true, }) if err != nil { return nil, nil, err } - cb := builtin.HostCallbacks{ - GetConfig: func() config.Config { return *cfg }, - PrepareVMNetwork: func(ctx context.Context, name string, _ bool) (func(), error) { - return nil, checkDirectMacOSNetwork(ctx, cfg, name) - }, - Log: func(source, line string) { - fmt.Fprintf(os.Stderr, "[%s] %s\n", source, line) - }, - GetSetting: func(pluginID, vmName, key string) (any, bool) { - value, ok := mgr.GetSettings(pluginID, vmName, false)[key] - return value, ok - }, - } - router := driver.NewRouter(mgr.Registry(), func() string { return cfg.DataRoot }, guest.VMInventory()) - mgr.Registry().SetInUseChecker(router.PluginInUseChecker()) - mgr.Registry().SetBusyChecker(router.PluginBusyChecker()) - if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil { - mgr.Close() - return nil, nil, err - } - if err := guest.Register(mgr.Registry(), cb, mgr.DesiredFor); err != nil { - mgr.Close() - return nil, nil, err - } - _ = mgr.LoadExternal() mgr.Registry().Reconcile(context.Background()) mgr.MarkBootComplete() diff --git a/internal/datamigrate/datamigrate.go b/internal/datamigrate/datamigrate.go index f93a6cc..bd0608b 100644 --- a/internal/datamigrate/datamigrate.go +++ b/internal/datamigrate/datamigrate.go @@ -99,7 +99,9 @@ func run(dataRoot, appVersion string, steps []Step, current int, now func() time } if err := s.Run(dataRoot); err != nil { if res.To > res.From { - _ = writeStamp(dataRoot, Stamp{DataVersion: res.To, WrittenBy: appVersion, UpdatedAt: now()}) + if serr := writeStamp(dataRoot, Stamp{DataVersion: res.To, WrittenBy: appVersion, UpdatedAt: now()}); serr != nil { + return res, fmt.Errorf("data migration %q (to v%d): %w (also failed to persist partial stamp v%d: %v)", s.Name, s.To, err, res.To, serr) + } } return res, fmt.Errorf("data migration %q (to v%d): %w", s.Name, s.To, err) } diff --git a/internal/downloader/parallel.go b/internal/downloader/parallel.go index f62b7f2..2040091 100644 --- a/internal/downloader/parallel.go +++ b/internal/downloader/parallel.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "io" + "log" "net" "net/http" "os" @@ -141,6 +142,28 @@ func statePath(destPath string) string { return filepath.Join(filepath.Dir(destPath), "."+filepath.Base(destPath)+".reims-dl.json") } +// DiscardPartial removes the checkpoint before deleting the payload it tracks. +func DiscardPartial(destPath string) error { + for _, path := range []string{statePath(destPath), destPath} { + if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { + return fmt.Errorf("discard download partial: %w", err) + } + } + return nil +} + +// PrepareHTTPResume removes a parallel partial before a sequential client +// treats the file's length as a contiguous download offset. +func PrepareHTTPResume(destPath string) error { + if _, err := os.Stat(statePath(destPath)); err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil + } + return fmt.Errorf("check download checkpoint: %w", err) + } + return DiscardPartial(destPath) +} + func loadResumeState(destPath, rawURL string, destOffset, totalSize int64, chunkCount int) []bool { raw, err := os.ReadFile(statePath(destPath)) if err != nil { @@ -166,9 +189,12 @@ func saveResumeState(destPath, rawURL string, destOffset, totalSize int64, done } raw, err := json.Marshal(st) if err != nil { + log.Printf("[downloader] marshal resume state failed (%s): %v", destPath, err) return } - _ = atomicfile.Write(statePath(destPath), raw, 0o644) + if err := atomicfile.Write(statePath(destPath), raw, 0o644); err != nil { + log.Printf("[downloader] save resume state failed (%s): %v", destPath, err) + } } // Download fetches req.URL into req.DestPath (at req.DestOffset) using concurrent diff --git a/internal/fetch/fetch.go b/internal/fetch/fetch.go index fc5812e..b0feac3 100644 --- a/internal/fetch/fetch.go +++ b/internal/fetch/fetch.go @@ -8,8 +8,10 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "io" + "log" "net/http" "os" "path/filepath" @@ -146,7 +148,8 @@ func resumeWithOptions(ctx context.Context, client *http.Client, url, final stri } part := final + ".part" - // Try the active downloader plugin first unless bypassed for security-sensitive paths. + // Try the active downloader first unless this transfer requires the + // caller's HTTP client (for example, plugin market downloads). if !opts.BypassDownloader { if prov := activeDownloader(); prov != nil { err := prov.Download(ctx, downloader.Request{ @@ -158,23 +161,46 @@ func resumeWithOptions(ctx context.Context, client *http.Client, url, final stri }, func(p downloader.Progress) { onProgress(p.Done, p.Total) }) + if ctx.Err() != nil { + return "", ctx.Err() + } if err == nil { - if got, herr := FileSHA256(part); herr == nil && strings.EqualFold(got, want) { - if rerr := os.Rename(part, final); rerr != nil { - return "", rerr + got, hashErr := FileSHA256(part) + switch { + case hashErr != nil: + err = hashErr + case !strings.EqualFold(got, want): + err = fmt.Errorf("SHA256 mismatch (got %s, want %s)", got, want) + default: + if err := os.Rename(part, final); err != nil { + return "", err } return final, nil } } - if ctx.Err() != nil { - return "", ctx.Err() + // A parallel partial can contain holes. Discard its checkpoint + // together with the file before the HTTP client starts over. + providerErr := fmt.Errorf("download %s (%s): %w", name, prov.ID(), err) + if err := downloader.DiscardPartial(part); err != nil { + return "", errors.Join(providerErr, err) } - // Clean up any partial multi-range file before single-stream fallback so - // sequential append doesn't concatenate onto sparse holes. - _ = os.Remove(part) + log.Printf("[fetch] downloader %s failed for %s; retrying with the HTTP client", prov.ID(), name) + path, err := resumeHTTP(ctx, client, url, final, size, want, onProgress, opts) + if err != nil { + return "", errors.Join(providerErr, err) + } + return path, nil } } + return resumeHTTP(ctx, client, url, final, size, want, onProgress, opts) +} +func resumeHTTP(ctx context.Context, client *http.Client, url, final string, size int64, want string, onProgress Progress, opts ResumeOptions) (string, error) { + name := filepath.Base(final) + part := final + ".part" + if err := downloader.PrepareHTTPResume(part); err != nil { + return "", err + } for attempt := 0; ; attempt++ { var have int64 if st, err := os.Stat(part); err == nil { diff --git a/internal/fetch/fetch_test.go b/internal/fetch/fetch_test.go index aa1caf9..848812a 100644 --- a/internal/fetch/fetch_test.go +++ b/internal/fetch/fetch_test.go @@ -4,6 +4,7 @@ import ( "context" "crypto/sha256" "encoding/hex" + "errors" "fmt" "net/http" "net/http/httptest" @@ -101,15 +102,88 @@ var timeZero = time.Time{} type spyDownloader struct { called atomic.Int32 + run func(context.Context, downloader.Request) error } func (s *spyDownloader) ID() string { return "test.spy" } -func (s *spyDownloader) Download(_ context.Context, _ downloader.Request, _ func(downloader.Progress)) error { +func (s *spyDownloader) Download(ctx context.Context, req downloader.Request, _ func(downloader.Progress)) error { s.called.Add(1) + if s.run != nil { + return s.run(ctx, req) + } return nil } +func TestResumePreservesCanceledDownloadAndDiscardsFailedCheckpoint(t *testing.T) { + body := []byte("verified download") + srv := rangeServer(t, "app.exe", body, "") + final := filepath.Join(t.TempDir(), "app.exe") + part := final + ".part" + checkpoint := filepath.Join(filepath.Dir(part), ".app.exe.part.reims-dl.json") + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + pluginErr := errors.New("plugin transfer failed") + provider := &spyDownloader{run: func(_ context.Context, req downloader.Request) error { + if req.DestPath != part || !req.Resume { + t.Fatalf("wrong resumable destination: %+v", req) + } + if err := os.WriteFile(part, make([]byte, len(body)), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(checkpoint, []byte("checkpoint"), 0o600); err != nil { + t.Fatal(err) + } + cancel() + return pluginErr + }} + SetDefaultDownloader(func() downloader.Provider { return provider }) + t.Cleanup(func() { SetDefaultDownloader(nil) }) + + if _, err := Resume(ctx, srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), nil); !errors.Is(err, context.Canceled) { + t.Fatalf("canceled resume = %v, want context.Canceled", err) + } + for _, path := range []string{part, checkpoint} { + if _, err := os.Stat(path); err != nil { + t.Fatalf("canceled resume lost %s: %v", path, err) + } + } + + provider.run = func(context.Context, downloader.Request) error { return pluginErr } + path, err := Resume(t.Context(), srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), nil) + if err != nil || path != final { + t.Fatalf("HTTP fallback = %q, %v", path, err) + } + for _, path := range []string{part, checkpoint} { + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("HTTP fallback kept %s: %v", path, err) + } + } +} + +func TestResumeClearsParallelCheckpointWhenPluginIsDisabled(t *testing.T) { + body := []byte("verified download") + srv := rangeServer(t, "app.exe", body, "") + final := filepath.Join(t.TempDir(), "app.exe") + part := final + ".part" + checkpoint := filepath.Join(filepath.Dir(part), ".app.exe.part.reims-dl.json") + if err := os.WriteFile(part, make([]byte, len(body)/2), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(checkpoint, []byte("checkpoint"), 0o600); err != nil { + t.Fatal(err) + } + + path, err := Resume(t.Context(), srv.Client(), srv.URL+"/file", final, int64(len(body)), sum(body), nil) + if err != nil || path != final { + t.Fatalf("HTTP resume = %q, %v", path, err) + } + if _, err := os.Stat(checkpoint); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("HTTP resume kept %s: %v", checkpoint, err) + } +} + func TestResumeDirectBypassesDownloaderAndEnforcesMaxBytesAndStall(t *testing.T) { spy := &spyDownloader{} SetDefaultDownloader(func() downloader.Provider { return spy }) diff --git a/internal/guesttools/drop_agent_test.go b/internal/guesttools/drop_agent_test.go index ad96711..882a83e 100644 --- a/internal/guesttools/drop_agent_test.go +++ b/internal/guesttools/drop_agent_test.go @@ -2,6 +2,7 @@ package guesttools import ( "bytes" + "io" "os" "os/exec" "path/filepath" @@ -20,13 +21,24 @@ func TestToolsDiskImageIncludesDropResolveJS(t *testing.T) { if !strings.Contains(resolver, "com.apple.finder") || strings.Contains(resolver, "'Finder'") { t.Fatal("drop resolver must identify Finder by bundle ID") } - path := filepath.Join(t.TempDir(), "tools.img") - if err := BuildToolsDiskImage(path, VMConfig{VMName: "mac"}); err != nil { - t.Fatal(err) + var foundResolver bool + for _, f := range ToolsDiskFiles(VMConfig{VMName: "mac"}) { + if f.Name != "drop-resolve.js" { + continue + } + rc, err := f.Open() + if err != nil { + t.Fatal(err) + } + data, err := io.ReadAll(rc) + _ = rc.Close() + if err != nil || !bytes.Contains(data, []byte(resolver)) { + t.Fatalf("missing resolver in tools disk files: %v", err) + } + foundResolver = true } - image, err := os.ReadFile(path) - if err != nil || !bytes.Contains(image, []byte(resolver)) { - t.Fatalf("missing resolver in image: %v", err) + if !foundResolver { + t.Fatal("missing drop-resolve.js in tools disk files") } install := string(GuestInstallScript()) agent := string(GuestAgentScript()) diff --git a/internal/guesttools/guesttools_test.go b/internal/guesttools/guesttools_test.go index 4be490a..16c3eec 100644 --- a/internal/guesttools/guesttools_test.go +++ b/internal/guesttools/guesttools_test.go @@ -22,7 +22,6 @@ import ( "testing" "time" - "github.com/Nwflower/reims-go/internal/macos/installer" ) type memClipboard struct { @@ -618,16 +617,23 @@ 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, GuestTimezone: "Etc/GMT+8"} - if err := BuildToolsDiskImage(imgPath, cfg); err != nil { - t.Fatalf("BuildToolsDiskImage: %v", err) + diskFiles := map[string][]byte{} + for _, tf := range ToolsDiskFiles(cfg) { + rc, err := tf.Open() + if err != nil { + t.Fatalf("open %s: %v", tf.Name, err) + } + data, err := io.ReadAll(rc) + _ = rc.Close() + if err != nil { + t.Fatalf("read %s: %v", tf.Name, err) + } + if int64(len(data)) != tf.Size { + t.Fatalf("%s size mismatch: got %d, declared %d", tf.Name, len(data), tf.Size) + } + diskFiles[tf.Name] = data } - f, err := os.Open(imgPath) - if err != nil { - t.Fatal(err) - } - defer f.Close() for _, file := range []struct{ name, content string }{ {"config", "REIMS_VM='macos-tahoe'\n"}, {"guest-tools.sh", fmt.Sprintf(`\"agent_version\":%d,`, CurrentAgentVersion)}, @@ -637,13 +643,12 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) { {"set-timezone.sh", guestTimezoneHelper}, {"Apply-Timezone.command", guestApplyTimezone}, } { - 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, ok := diskFiles[file.name] + if !ok || len(data) == 0 { + t.Fatalf("missing %s in REIMSTOOLS files", file.name) } - 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 !strings.Contains(string(data), file.content) { + t.Errorf("unexpected %s contents", file.name) } if file.name == "config" && strings.Contains(string(data), "REIMS_TIMEZONE=") { t.Error("tools image config contains a build-time timezone") @@ -655,13 +660,9 @@ func TestBuildToolsDiskImageAndScriptSyntax(t *testing.T) { "Disable-Host-DNS.command": guestDisableHostDNS, "active-window-reporter.js": guestWindowReporter, } { - offset, size, err := installer.FindFileInHFSPlusImage(f, name) - if err != nil { - t.Fatal(err) - } - got := make([]byte, size) - if _, err := f.ReadAt(got, offset); err != nil { - t.Fatal(err) + got, ok := diskFiles[name] + if !ok { + t.Fatalf("missing %s in REIMSTOOLS files", name) } if !bytes.Equal(got, bytes.ReplaceAll(script, []byte("\r\n"), []byte("\n"))) { t.Fatalf("unexpected content in %s on REIMSTOOLS", name) diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 2f94364..1cf8f31 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -5,12 +5,8 @@ import ( _ "embed" "fmt" "io" - "os" - "path/filepath" "strconv" "strings" - - "github.com/Nwflower/reims-go/internal/macos/installer" ) func shellSingleQuote(s string) string { @@ -43,13 +39,19 @@ var guestApplyHostDNS []byte //go:embed Disable-Host-DNS.command var guestDisableHostDNS []byte -// BuildToolsDiskImage creates a read-only HFS+ disk image ("REIMSTOOLS") -// containing the per-VM Bearer token config, the POSIX guest agent script, and -// installation, pmset, DNS, and timezone scripts. -func BuildToolsDiskImage(outPath string, cfg VMConfig) error { - if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil { - return err - } +// ToolsDiskFile describes one file to place into the read-only REIMSTOOLS +// disk image without coupling guesttools to a specific disk-image format. +type ToolsDiskFile struct { + Name string + Mode uint16 + Size int64 + Open func() (io.ReadCloser, error) +} + +// ToolsDiskFiles returns the files to package into the read-only REIMSTOOLS +// image: per-VM Bearer token config, POSIX guest agent, and install/pmset/DNS/ +// timezone scripts. +func ToolsDiskFiles(cfg VMConfig) []ToolsDiskFile { confBytes := []byte(fmt.Sprintf("REIMS_HOST_URL='http://10.0.2.2:%d'\nREIMS_HOST_PORT='%d'\nREIMS_TOKEN=%s\nREIMS_VM=%s\n", cfg.Port, cfg.Port, shellSingleQuote(cfg.Token), shellSingleQuote(cfg.VMName))) agentBytes := GuestAgentScript() @@ -58,7 +60,7 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { uninstallBytes := GuestUninstallScript() pmsetBytes := GuestPmsetScript() - files := []installer.HFSFile{ + files := []ToolsDiskFile{ { Name: "config", Mode: 0o100600, @@ -119,14 +121,14 @@ func BuildToolsDiskImage(outPath string, cfg VMConfig) error { } { // The Windows checkout may have CRLF line endings. data := bytes.ReplaceAll(script.data, []byte("\r\n"), []byte("\n")) - files = append(files, installer.HFSFile{ + files = append(files, ToolsDiskFile{ Name: script.name, Mode: 0o100755, Size: int64(len(data)), Open: func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(data)), nil }, }) } - return installer.BuildHFSPlusDiskImage(outPath, ToolsVolumeName, files) + return files } // GuestAgentScript returns the stock-macOS POSIX shell daemon handling diff --git a/internal/host/audio_other.go b/internal/host/audio_other.go deleted file mode 100644 index 36fa470..0000000 --- a/internal/host/audio_other.go +++ /dev/null @@ -1,23 +0,0 @@ -//go:build !windows - -package host - -import "runtime" - -// ProbeAudio returns a non-Windows stub audio report for dev/test hosts. -func ProbeAudio() AudioInfo { - def := "pipewire" - if runtime.GOOS == "darwin" { - def = "coreaudio" - } - return AudioInfo{ - OutputCount: 1, - InputCount: 1, - DefaultBackend: def, - } -} - -// FreeDiskBytesAt returns (0, false) on non-Windows stubs. -func FreeDiskBytesAt(_ string) (uint64, bool) { - return 0, false -} diff --git a/internal/host/close_vm_other.go b/internal/host/close_vm_other.go deleted file mode 100644 index 3533e85..0000000 --- a/internal/host/close_vm_other.go +++ /dev/null @@ -1,22 +0,0 @@ -//go:build !windows - -package host - -import ( - "context" - "errors" - - "github.com/Nwflower/reims-go/internal/i18n" -) - -type VMCloseChoice uint8 - -const ( - VMCloseCancel VMCloseChoice = iota - VMCloseShutdown - VMCloseSuspend -) - -func ConfirmVMClose(context.Context, uintptr, string, i18n.Locale, string, bool) (VMCloseChoice, error) { - return VMCloseCancel, errors.ErrUnsupported -} diff --git a/internal/host/console_other.go b/internal/host/console_other.go deleted file mode 100644 index 4d8d337..0000000 --- a/internal/host/console_other.go +++ /dev/null @@ -1,8 +0,0 @@ -//go:build !windows - -package host - -import "os/exec" - -// HideConsole does nothing: only Windows opens console windows. -func HideConsole(*exec.Cmd) {} diff --git a/internal/host/defender_other.go b/internal/host/defender_other.go deleted file mode 100644 index 5458446..0000000 --- a/internal/host/defender_other.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !windows - -package host - -import "errors" - -func probeDefenderRealtime() bool { return false } - -func OpenWindowsSecurityExclusions() error { - return errors.New("Windows Security is only available on Windows") -} diff --git a/internal/host/display_move_other.go b/internal/host/display_move_other.go deleted file mode 100644 index 4db847a..0000000 --- a/internal/host/display_move_other.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !windows - -package host - -func MoveProcessWindowToDisplay(pid uint32, displayName string, borderless bool) (bool, error) { - return false, nil -} - -func MoveProcessTreeWindowToDisplay(pids []uint32, displayName string, borderless bool) (bool, error) { - return false, nil -} diff --git a/internal/host/display_other.go b/internal/host/display_other.go deleted file mode 100644 index 24a8f33..0000000 --- a/internal/host/display_other.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build !windows - -package host - -func probeDisplays() []DisplayInfo { - return nil -} diff --git a/internal/host/drives_other.go b/internal/host/drives_other.go deleted file mode 100644 index b278b9a..0000000 --- a/internal/host/drives_other.go +++ /dev/null @@ -1,36 +0,0 @@ -//go:build !windows - -package host - -import ( - "os" - "syscall" -) - -// Drive is a disk a data folder could go on. -type Drive struct { - Root string `json:"root"` - FreeGB float64 `json:"free_gb"` - System bool `json:"system"` - External bool `json:"external"` - VolumeGUID string `json:"volume_guid,omitempty"` -} - -// ListDrives returns the home directory's volume on dev/preview hosts. -func ListDrives() []Drive { - home, err := os.UserHomeDir() - if err != nil { - return nil - } - free, _ := FreeGB(home) - return []Drive{{Root: home, FreeGB: free, System: true}} -} - -// FreeGB is the free space on the volume holding path. -func FreeGB(path string) (float64, bool) { - var st syscall.Statfs_t - if err := syscall.Statfs(path, &st); err != nil { - return 0, false - } - return float64(st.Bavail) * float64(st.Bsize) / (1 << 30), true -} diff --git a/internal/host/elevate_other.go b/internal/host/elevate_other.go deleted file mode 100644 index 434486c..0000000 --- a/internal/host/elevate_other.go +++ /dev/null @@ -1,17 +0,0 @@ -//go:build !windows - -package host - -import ( - "context" - "fmt" - "runtime" -) - -// RunElevatedAction is only available on Windows. -func RunElevatedAction(_ context.Context, action, _ string) (ElevationResult, error) { - if _, ok := LookupElevationAction(action); !ok { - return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action) - } - return ElevationResult{Action: action}, fmt.Errorf("elevated actions are a Windows feature (current OS: %s)", runtime.GOOS) -} diff --git a/internal/host/fonts_other.go b/internal/host/fonts_other.go deleted file mode 100644 index 080b58b..0000000 --- a/internal/host/fonts_other.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build !windows - -package host - -import "github.com/Nwflower/reims-go/internal/i18n" - -func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string { - return "" -} diff --git a/internal/host/foreground_other.go b/internal/host/foreground_other.go deleted file mode 100644 index 106bb85..0000000 --- a/internal/host/foreground_other.go +++ /dev/null @@ -1,12 +0,0 @@ -//go:build !windows - -package host - -// ForegroundPID is not implemented off Windows and always reports no owner. -func ForegroundPID() uint32 { return 0 } - -// FocusProcessTreeWindow is not implemented off Windows. -func FocusProcessTreeWindow([]uint32) bool { return false } - -// ForegroundInPIDs is not implemented off Windows and always reports false. -func ForegroundInPIDs([]uint32) bool { return false } diff --git a/internal/host/fullscreen_hotkey_other.go b/internal/host/fullscreen_hotkey_other.go deleted file mode 100644 index c5cea6f..0000000 --- a/internal/host/fullscreen_hotkey_other.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !windows - -package host - -type fullscreenHotkeyHook struct{} - -func startFullscreenHotkeyHook(_ *FullscreenHotkeyService) *fullscreenHotkeyHook { return nil } - -func (h *fullscreenHotkeyHook) Close() {} - -func (h *fullscreenHotkeyHook) active() bool { return false } - -func IsForegroundDisplayWindow(_ uintptr, _ uint32) bool { return false } diff --git a/internal/host/fullscreen_other.go b/internal/host/fullscreen_other.go deleted file mode 100644 index 004cd73..0000000 --- a/internal/host/fullscreen_other.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !windows - -package host - -import "errors" - -// IsProcessTreeWindowFullscreen is not implemented off Windows. -func IsProcessTreeWindowFullscreen([]uint32) bool { return false } - -// ToggleProcessTreeWindowFullscreen is not implemented off Windows. -func ToggleProcessTreeWindowFullscreen([]uint32) (bool, error) { - return false, errors.New("toggling a VM window's full screen mode is only supported on Windows") -} diff --git a/internal/host/host_other.go b/internal/host/host_other.go deleted file mode 100644 index 3a51243..0000000 --- a/internal/host/host_other.go +++ /dev/null @@ -1,50 +0,0 @@ -//go:build !windows - -package host - -import ( - "fmt" - "runtime" -) - -// Inspect returns basic host facts on non-Windows dev machines (e.g., macOS). -func Inspect(dataRoot string) Report { - displays := probeDisplays() - primary := PrimaryDisplayOf(displays) - presets, rec := RecommendDisplayPresets(primary) - return Report{ - OS: runtime.GOOS, - Arch: runtime.GOARCH, - LogicalCPUs: runtime.NumCPU(), - CPUTopology: DefaultCPUTopology(runtime.NumCPU()), - DataRoot: dataRoot, - Timezone: DetectHostTimezone(), - DeepBackingChains: InspectVMDiskChains(dataRoot), - WHPX: WHPXUnsupported, - Displays: displays, - PrimaryDisplay: primary, - RecommendedResolution: rec, - DisplayPresets: presets, - ProcessorScheduling: probeProcessorScheduling(), - Audio: ProbeAudio(), - } -} - -func ConfigureVulkanDrivers() {} - -// ProbeVulkanGPUs returns no adapters on hosts without Windows Vulkan probing. -func ProbeVulkanGPUs() []GPUInfo { - return nil -} - -func SetProcessAffinityMask(pid uint32, mask uint64) error { - return fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS) -} - -func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) { - return 0, 0, fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS) -} - -func DisableProcessPowerThrottling(pid uint32) error { - return fmt.Errorf("process power throttling control is only supported on Windows (current OS: %s)", runtime.GOOS) -} diff --git a/internal/host/hypervisor_other.go b/internal/host/hypervisor_other.go deleted file mode 100644 index 26dae2f..0000000 --- a/internal/host/hypervisor_other.go +++ /dev/null @@ -1,21 +0,0 @@ -//go:build !windows - -package host - -import ( - "context" - "fmt" - "runtime" -) - -func currentBootSession() bootSession { - return bootSession{} -} - -func SetHypervisorBootElevated(_ context.Context, _ bool) error { - return fmt.Errorf("hypervisor boot configuration is only supported on Windows (current OS: %s)", runtime.GOOS) -} - -func OpenWindowsCoreIsolation() error { - return fmt.Errorf("Windows Security Core Isolation is only available on Windows (current OS: %s)", runtime.GOOS) -} diff --git a/internal/host/ime_hook_other.go b/internal/host/ime_hook_other.go deleted file mode 100644 index 52e00dd..0000000 --- a/internal/host/ime_hook_other.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !windows - -package host - -// IMEBridge is a no-op stub on non-Windows hosts. -type IMEBridge struct{} - -func StartIMEBridge(onText func(target IMETarget, text string)) (*IMEBridge, error) { - return &IMEBridge{}, nil -} - -func (b *IMEBridge) SetTargets(targets []IMETarget) {} -func (b *IMEBridge) SetEnabled(enabled bool) {} -func (b *IMEBridge) Close() {} diff --git a/internal/host/input_service_other.go b/internal/host/input_service_other.go deleted file mode 100644 index 2c736f7..0000000 --- a/internal/host/input_service_other.go +++ /dev/null @@ -1,11 +0,0 @@ -//go:build !windows - -package host - -type mouseWheelHook struct{} - -func startMouseWheelHook(_ *InputService) (*mouseWheelHook, error) { - return &mouseWheelHook{}, nil -} - -func (h *mouseWheelHook) Close() {} diff --git a/internal/host/memory_other.go b/internal/host/memory_other.go deleted file mode 100644 index 8c92722..0000000 --- a/internal/host/memory_other.go +++ /dev/null @@ -1,6 +0,0 @@ -//go:build !windows - -package host - -// CommitAvailGB is unknown on dev/preview hosts. -func CommitAvailGB() (float64, bool) { return 0, false } diff --git a/internal/host/open_other.go b/internal/host/open_other.go deleted file mode 100644 index 5ffd264..0000000 --- a/internal/host/open_other.go +++ /dev/null @@ -1,26 +0,0 @@ -//go:build !windows - -package host - -import ( - "fmt" - "os" - "os/exec" - "runtime" -) - -// OpenFolder shows dir in the platform file manager (dev/preview hosts only). -func OpenFolder(dir string) error { - info, err := os.Stat(dir) - if err != nil { - return err - } - if !info.IsDir() { - return fmt.Errorf("not a directory: %s", dir) - } - opener := "xdg-open" - if runtime.GOOS == "darwin" { - opener = "open" - } - return exec.Command(opener, dir).Start() -} diff --git a/internal/host/procwait_other.go b/internal/host/procwait_other.go deleted file mode 100644 index e8a1b08..0000000 --- a/internal/host/procwait_other.go +++ /dev/null @@ -1,16 +0,0 @@ -//go:build !windows - -package host - -import ( - "context" - "errors" -) - -// ErrOtherProcess: the PID now names a process other than the one expected. -var ErrOtherProcess = errors.New("pid belongs to another process") - -// WaitProcessExit is not implemented off Windows; callers fall back to polling. -func WaitProcessExit(ctx context.Context, pid uint32, imageSuffix string) error { - return errors.ErrUnsupported -} diff --git a/internal/host/qemu_aslr_other.go b/internal/host/qemu_aslr_other.go deleted file mode 100644 index 00866ba..0000000 --- a/internal/host/qemu_aslr_other.go +++ /dev/null @@ -1,14 +0,0 @@ -//go:build !windows - -package host - -import ( - "context" - "errors" -) - -func ApplyQEMUASLR(_, _ string) error { - return errors.New("QEMU ASLR requires Windows") -} - -func SyncQEMUASLR(ctx context.Context, _, _ string) error { return ctx.Err() } diff --git a/internal/host/rawdisk_other.go b/internal/host/rawdisk_other.go deleted file mode 100644 index 91edc5d..0000000 --- a/internal/host/rawdisk_other.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build !windows - -package host - -// ListRawPartitions returns eligible unmounted partitions or offline whole disks. -// Currently only Windows raw device passthrough is implemented. -func ListRawPartitions(dataRoot string) ([]RawDiskCandidate, error) { - return nil, nil -} diff --git a/internal/host/scheduling_other.go b/internal/host/scheduling_other.go deleted file mode 100644 index 4837f46..0000000 --- a/internal/host/scheduling_other.go +++ /dev/null @@ -1,18 +0,0 @@ -//go:build !windows - -package host - -import ( - "errors" - "fmt" - "runtime" -) - -// ErrElevationDeclined: the person said no at the UAC prompt. -var ErrElevationDeclined = errors.New("UAC prompt declined") - -func probeProcessorScheduling() string { return "" } - -func OpenPerformanceOptionsElevated() error { - return fmt.Errorf("processor scheduling is a Windows setting (current OS: %s)", runtime.GOOS) -} diff --git a/internal/host/smbios_memory_other.go b/internal/host/smbios_memory_other.go deleted file mode 100644 index 2a796a9..0000000 --- a/internal/host/smbios_memory_other.go +++ /dev/null @@ -1,7 +0,0 @@ -//go:build !windows - -package host - -func probeHostMemorySpec() *HostMemorySpec { - return nil -} diff --git a/internal/host/stats_other.go b/internal/host/stats_other.go deleted file mode 100644 index 39d335c..0000000 --- a/internal/host/stats_other.go +++ /dev/null @@ -1,13 +0,0 @@ -//go:build !windows - -package host - -import "fmt" - -func SampleProcessStats(pid int) (ProcessSample, error) { - return ProcessSample{}, fmt.Errorf("process stats sampling is only supported on Windows") -} - -func fileActualSize(_ string, fallback uint64) uint64 { - return fallback -} diff --git a/internal/host/stubs_hardware_other.go b/internal/host/stubs_hardware_other.go new file mode 100644 index 0000000..4c6d0f8 --- /dev/null +++ b/internal/host/stubs_hardware_other.go @@ -0,0 +1,152 @@ +//go:build !windows + +package host + +import ( + "fmt" + "os" + "path/filepath" + "runtime" + "syscall" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +// Inspect returns basic host facts on non-Windows dev machines (e.g., macOS). +func Inspect(dataRoot string) Report { + displays := probeDisplays() + primary := PrimaryDisplayOf(displays) + presets, rec := RecommendDisplayPresets(primary) + return Report{ + OS: runtime.GOOS, + Arch: runtime.GOARCH, + LogicalCPUs: runtime.NumCPU(), + CPUTopology: DefaultCPUTopology(runtime.NumCPU()), + DataRoot: dataRoot, + Timezone: DetectHostTimezone(), + DeepBackingChains: InspectVMDiskChains(dataRoot), + WHPX: WHPXUnsupported, + Displays: displays, + PrimaryDisplay: primary, + RecommendedResolution: rec, + DisplayPresets: presets, + ProcessorScheduling: probeProcessorScheduling(), + Audio: ProbeAudio(), + } +} + +func ConfigureVulkanDrivers() {} + +// ProbeVulkanGPUs returns no adapters on hosts without Windows Vulkan probing. +func ProbeVulkanGPUs() []GPUInfo { return nil } + +func SetProcessAffinityMask(pid uint32, mask uint64) error { + return fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS) +} + +func GetProcessAffinityMask(pid uint32) (uint64, uint64, error) { + return 0, 0, fmt.Errorf("process CPU affinity is only supported on Windows (current OS: %s)", runtime.GOOS) +} + +func DisableProcessPowerThrottling(pid uint32) error { + return fmt.Errorf("process power throttling control is only supported on Windows (current OS: %s)", runtime.GOOS) +} + +// ProbeAudio returns a non-Windows stub audio report for dev/test hosts. +func ProbeAudio() AudioInfo { + def := "pipewire" + if runtime.GOOS == "darwin" { + def = "coreaudio" + } + return AudioInfo{OutputCount: 1, InputCount: 1, DefaultBackend: def} +} + +// FreeDiskBytesAt returns (0, false) on non-Windows stubs. +func FreeDiskBytesAt(_ string) (uint64, bool) { return 0, false } + +// CommitAvailGB is unknown on dev/preview hosts. +func CommitAvailGB() (float64, bool) { return 0, false } + +func probeHostMemorySpec() *HostMemorySpec { return nil } + +func CheckMissingLocaleFontsForUI(targetLocale string, uiLocale i18n.Locale) string { return "" } + +func SampleProcessStats(pid int) (ProcessSample, error) { + return ProcessSample{}, fmt.Errorf("process stats sampling is only supported on Windows") +} + +func fileActualSize(_ string, fallback uint64) uint64 { return fallback } + +// ListRawPartitions returns eligible unmounted partitions or offline whole disks. +// Currently only Windows raw device passthrough is implemented. +func ListRawPartitions(dataRoot string) ([]RawDiskCandidate, error) { return nil, nil } + +// Drive is a disk a data folder could go on. +type Drive struct { + Root string `json:"root"` + FreeGB float64 `json:"free_gb"` + System bool `json:"system"` + External bool `json:"external"` + VolumeGUID string `json:"volume_guid,omitempty"` +} + +// ListDrives returns the home directory's volume on dev/preview hosts. +func ListDrives() []Drive { + home, err := os.UserHomeDir() + if err != nil { + return nil + } + free, _ := FreeGB(home) + return []Drive{{Root: home, FreeGB: free, System: true}} +} + +// FreeGB is the free space on the volume holding path. +func FreeGB(path string) (float64, bool) { + var st syscall.Statfs_t + if err := syscall.Statfs(path, &st); err != nil { + return 0, false + } + return float64(st.Bavail) * float64(st.Bsize) / (1 << 30), true +} + +func ResolveDirectoryVolume(dir string) (DirectoryVolume, error) { + if invalidDirectoryPath(dir) { + return DirectoryVolume{}, os.ErrInvalid + } + abs, err := filepath.Abs(dir) + if err != nil { + return DirectoryVolume{}, err + } + resolved, err := filepath.EvalSymlinks(abs) + if err != nil { + return DirectoryVolume{}, err + } + info, err := os.Stat(resolved) + if err != nil { + return DirectoryVolume{}, err + } + if !info.IsDir() { + return DirectoryVolume{}, os.ErrInvalid + } + return DirectoryVolume{CanonicalPath: resolved, FixedInternal: true, IsVolumeRoot: filepath.Dir(resolved) == resolved}, nil +} + +// ResolveOpenDirectoryVolume verifies the path still identifies the opened directory. +func ResolveOpenDirectoryVolume(dir string, opened *os.File) (DirectoryVolume, error) { + volume, err := ResolveDirectoryVolume(dir) + if err != nil { + return DirectoryVolume{}, err + } + info, err := os.Stat(volume.CanonicalPath) + if err != nil { + return DirectoryVolume{}, err + } + openedInfo, err := opened.Stat() + if err != nil { + return DirectoryVolume{}, err + } + if !os.SameFile(info, openedInfo) { + return DirectoryVolume{}, os.ErrPermission + } + return volume, nil +} diff --git a/internal/host/stubs_system_other.go b/internal/host/stubs_system_other.go new file mode 100644 index 0000000..c5ba459 --- /dev/null +++ b/internal/host/stubs_system_other.go @@ -0,0 +1,95 @@ +//go:build !windows + +package host + +import ( + "context" + "errors" + "fmt" + "os" + "os/exec" + "runtime" + "strings" + "time" +) + +// HideConsole does nothing: only Windows opens console windows. +func HideConsole(*exec.Cmd) {} + +func probeDefenderRealtime() bool { return false } + +func OpenWindowsSecurityExclusions() error { + return errors.New("Windows Security is only available on Windows") +} + +// RunElevatedAction is only available on Windows. +func RunElevatedAction(_ context.Context, action, _ string) (ElevationResult, error) { + if _, ok := LookupElevationAction(action); !ok { + return ElevationResult{Action: action}, fmt.Errorf("unsupported elevation action %q", action) + } + return ElevationResult{Action: action}, fmt.Errorf("elevated actions are a Windows feature (current OS: %s)", runtime.GOOS) +} + +func currentBootSession() bootSession { return bootSession{} } + +func SetHypervisorBootElevated(_ context.Context, _ bool) error { + return fmt.Errorf("hypervisor boot configuration is only supported on Windows (current OS: %s)", runtime.GOOS) +} + +func OpenWindowsCoreIsolation() error { + return fmt.Errorf("Windows Security Core Isolation is only available on Windows (current OS: %s)", runtime.GOOS) +} + +// OpenFolder shows dir in the platform file manager (dev/preview hosts only). +func OpenFolder(dir string) error { + info, err := os.Stat(dir) + if err != nil { + return err + } + if !info.IsDir() { + return fmt.Errorf("not a directory: %s", dir) + } + opener := "xdg-open" + if runtime.GOOS == "darwin" { + opener = "open" + } + return exec.Command(opener, dir).Start() +} + +// ErrOtherProcess: the PID now names a process other than the one expected. +var ErrOtherProcess = errors.New("pid belongs to another process") + +// WaitProcessExit is not implemented off Windows; callers fall back to polling. +func WaitProcessExit(ctx context.Context, pid uint32, imageSuffix string) error { + return errors.ErrUnsupported +} + +func ApplyQEMUASLR(_, _ string) error { return errors.New("QEMU ASLR requires Windows") } + +func SyncQEMUASLR(ctx context.Context, _, _ string) error { return ctx.Err() } + +// ErrElevationDeclined: the person said no at the UAC prompt. +var ErrElevationDeclined = errors.New("UAC prompt declined") + +func probeProcessorScheduling() string { return "" } + +func OpenPerformanceOptionsElevated() error { + return fmt.Errorf("processor scheduling is a Windows setting (current OS: %s)", runtime.GOOS) +} + +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 "" +} + +func ProcessCPUTime(pid uint32) (time.Duration, bool) { return 0, false } diff --git a/internal/host/stubs_window_other.go b/internal/host/stubs_window_other.go new file mode 100644 index 0000000..2c91354 --- /dev/null +++ b/internal/host/stubs_window_other.go @@ -0,0 +1,76 @@ +//go:build !windows + +package host + +import ( + "context" + "errors" + + "github.com/Nwflower/reims-go/internal/i18n" +) + +type VMCloseChoice uint8 + +const ( + VMCloseCancel VMCloseChoice = iota + VMCloseShutdown + VMCloseSuspend +) + +func ConfirmVMClose(context.Context, uintptr, string, i18n.Locale, string, bool) (VMCloseChoice, error) { + return VMCloseCancel, errors.ErrUnsupported +} + +func probeDisplays() []DisplayInfo { return nil } + +func MoveProcessWindowToDisplay(pid uint32, displayName string, borderless bool) (bool, error) { + return false, nil +} + +func MoveProcessTreeWindowToDisplay(pids []uint32, displayName string, borderless bool) (bool, error) { + return false, nil +} + +// ForegroundPID is not implemented off Windows and always reports no owner. +func ForegroundPID() uint32 { return 0 } + +// FocusProcessTreeWindow is not implemented off Windows. +func FocusProcessTreeWindow([]uint32) bool { return false } + +// ForegroundInPIDs is not implemented off Windows and always reports false. +func ForegroundInPIDs([]uint32) bool { return false } + +// IsProcessTreeWindowFullscreen is not implemented off Windows. +func IsProcessTreeWindowFullscreen([]uint32) bool { return false } + +// ToggleProcessTreeWindowFullscreen is not implemented off Windows. +func ToggleProcessTreeWindowFullscreen([]uint32) (bool, error) { + return false, errors.New("toggling a VM window's full screen mode is only supported on Windows") +} + +type fullscreenHotkeyHook struct{} + +func startFullscreenHotkeyHook(_ *FullscreenHotkeyService) *fullscreenHotkeyHook { return nil } +func (h *fullscreenHotkeyHook) Close() {} +func (h *fullscreenHotkeyHook) active() bool { return false } + +func IsForegroundDisplayWindow(_ uintptr, _ uint32) bool { return false } + +// IMEBridge is a no-op stub on non-Windows hosts. +type IMEBridge struct{} + +func StartIMEBridge(onText func(target IMETarget, text string)) (*IMEBridge, error) { + return &IMEBridge{}, nil +} + +func (b *IMEBridge) SetTargets(targets []IMETarget) {} +func (b *IMEBridge) SetEnabled(enabled bool) {} +func (b *IMEBridge) Close() {} + +type mouseWheelHook struct{} + +func startMouseWheelHook(_ *InputService) (*mouseWheelHook, error) { + return &mouseWheelHook{}, nil +} + +func (h *mouseWheelHook) Close() {} diff --git a/internal/host/timezone_other.go b/internal/host/timezone_other.go deleted file mode 100644 index ef39eeb..0000000 --- a/internal/host/timezone_other.go +++ /dev/null @@ -1,24 +0,0 @@ -//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/volume_other.go b/internal/host/volume_other.go deleted file mode 100644 index e2927c0..0000000 --- a/internal/host/volume_other.go +++ /dev/null @@ -1,50 +0,0 @@ -//go:build !windows - -package host - -import ( - "os" - "path/filepath" -) - -func ResolveDirectoryVolume(dir string) (DirectoryVolume, error) { - if invalidDirectoryPath(dir) { - return DirectoryVolume{}, os.ErrInvalid - } - abs, err := filepath.Abs(dir) - if err != nil { - return DirectoryVolume{}, err - } - resolved, err := filepath.EvalSymlinks(abs) - if err != nil { - return DirectoryVolume{}, err - } - info, err := os.Stat(resolved) - if err != nil { - return DirectoryVolume{}, err - } - if !info.IsDir() { - return DirectoryVolume{}, os.ErrInvalid - } - return DirectoryVolume{CanonicalPath: resolved, FixedInternal: true, IsVolumeRoot: filepath.Dir(resolved) == resolved}, nil -} - -// ResolveOpenDirectoryVolume verifies the path still identifies the opened directory. -func ResolveOpenDirectoryVolume(dir string, opened *os.File) (DirectoryVolume, error) { - volume, err := ResolveDirectoryVolume(dir) - if err != nil { - return DirectoryVolume{}, err - } - info, err := os.Stat(volume.CanonicalPath) - if err != nil { - return DirectoryVolume{}, err - } - openedInfo, err := opened.Stat() - if err != nil { - return DirectoryVolume{}, err - } - if !os.SameFile(info, openedInfo) { - return DirectoryVolume{}, os.ErrPermission - } - return volume, nil -} diff --git a/internal/host/vulkan_driverstore_windows.go b/internal/host/vulkan_driverstore_windows.go index 5046ab3..c471df8 100644 --- a/internal/host/vulkan_driverstore_windows.go +++ b/internal/host/vulkan_driverstore_windows.go @@ -14,6 +14,13 @@ import ( const displayClass = "{4d36e968-e325-11ce-bfc1-08002be10318}" +var displayClassGUID = windows.GUID{ + Data1: 0x4d36e968, + Data2: 0xe325, + Data3: 0x11ce, + Data4: [8]byte{0xbf, 0xc1, 0x08, 0x00, 0x2b, 0xe1, 0x03, 0x18}, +} + var infStoreLocation = windows.NewLazySystemDLL("setupapi.dll").NewProc("SetupGetInfDriverStoreLocationW") // Look only in the installed INF's package. DriverStore can also contain @@ -92,10 +99,7 @@ func isActiveDevNodeStatus(status uint32) bool { } func enumeratePresentDisplayAdapters() []displayAdapterRecord { - guid, err := windows.GUIDFromString(displayClass) - if err != nil { - return nil - } + guid := displayClassGUID devs, err := windows.SetupDiGetClassDevsEx(&guid, "", 0, windows.DIGCF_PRESENT, 0, "") if err != nil { return nil diff --git a/internal/host/whpx_probe_other.go b/internal/host/whpx_probe_other.go deleted file mode 100644 index 54e64db..0000000 --- a/internal/host/whpx_probe_other.go +++ /dev/null @@ -1,9 +0,0 @@ -//go:build !windows - -package host - -import "time" - -func ProcessCPUTime(pid uint32) (time.Duration, bool) { - return 0, false -} diff --git a/internal/macos/installer/pkg_extract.go b/internal/macos/installer/pkg_extract.go index deb7610..c3d1d6c 100644 --- a/internal/macos/installer/pkg_extract.go +++ b/internal/macos/installer/pkg_extract.go @@ -12,8 +12,10 @@ import ( "fmt" "io" "os" + "runtime" "strconv" "strings" + "sync" "unicode/utf16" "github.com/ulikunitz/xz" @@ -260,7 +262,8 @@ func openPayloadStream(r io.Reader) (io.Reader, func(), error) { } switch { case bytes.Equal(magic[:4], []byte("pbzx")): - return newPBZXReader(br), func() {}, nil + pr := newPBZXReader(br) + return pr, pr.Close, nil case magic[0] == 0x1f && magic[1] == 0x8b: gr, err := gzip.NewReader(br) if err != nil { @@ -280,27 +283,138 @@ func openPayloadStream(r io.Reader) (io.Reader, func(), error) { } } -// pbzxReader decodes Apple's PBZX chunked stream into a contiguous CPIO stream. +// Apple payloads use 16 MiB chunks. Allow up to 32 MiB per stored or decoded +// chunk, and limit how many chunks can hold buffers at the same time. +const maxPBZXChunkBytes = 32 << 20 + +// pbzxReader decodes Apple's PBZX chunked stream into a contiguous CPIO stream, +// decompressing independent XZ chunks concurrently across bounded workers while +// preserving strict sequential chunk order. type pbzxReader struct { src io.Reader started bool - cur io.Reader + cur *bytes.Reader + results chan chan pbzxChunkResult + slots chan struct{} + cancel chan struct{} + once sync.Once +} + +type pbzxChunkResult struct { + data []byte + err error } func newPBZXReader(src io.Reader) *pbzxReader { - return &pbzxReader{src: src} + return &pbzxReader{ + src: src, + cancel: make(chan struct{}), + } +} + +func (p *pbzxReader) Close() { + p.once.Do(func() { + close(p.cancel) + }) +} + +func (p *pbzxReader) start() error { + var head [12]byte // "pbzx" (4) + flags (8) + if _, err := io.ReadFull(p.src, head[:]); err != nil { + return fmt.Errorf("read pbzx header: %w", err) + } + if string(head[:4]) != "pbzx" { + return errors.New("invalid pbzx header") + } + workers := min(max(runtime.GOMAXPROCS(0), 1), 4) + p.results = make(chan chan pbzxChunkResult, workers) + p.slots = make(chan struct{}, workers) + + go func() { + defer close(p.results) + for { + select { + case <-p.cancel: + return + case p.slots <- struct{}{}: + } + data, decodedLen, err := p.readChunk() + switch { + case err == io.EOF: + return + case err == nil && len(data) == 0: + <-p.slots + continue + } + ch := make(chan pbzxChunkResult, 1) + select { + case p.results <- ch: + case <-p.cancel: + return + } + if err != nil { + ch <- pbzxChunkResult{err: err} + return + } + if len(data) == decodedLen { + ch <- pbzxChunkResult{data: data} + continue + } + go func() { + decoded, err := decodePBZXXZChunk(data, decodedLen) + ch <- pbzxChunkResult{data: decoded, err: err} + }() + } + }() + p.started = true + return nil +} + +func (p *pbzxReader) readChunk() ([]byte, int, error) { + var header [16]byte + if _, err := io.ReadFull(p.src, header[:]); err != nil { + if err == io.EOF { + return nil, 0, io.EOF + } + return nil, 0, fmt.Errorf("read pbzx chunk header: %w", err) + } + decodedLen := binary.BigEndian.Uint64(header[:8]) + storedLen := binary.BigEndian.Uint64(header[8:]) + if storedLen > maxPBZXChunkBytes || decodedLen > maxPBZXChunkBytes || + (storedLen == 0) != (decodedLen == 0) { + return nil, 0, fmt.Errorf("invalid pbzx chunk lengths: stored %d, decoded %d", storedLen, decodedLen) + } + data := make([]byte, int(storedLen)) + if _, err := io.ReadFull(p.src, data); err != nil { + return nil, 0, fmt.Errorf("read pbzx chunk: %w", err) + } + return data, int(decodedLen), nil +} + +func decodePBZXXZChunk(data []byte, decodedLen int) ([]byte, error) { + xr, err := xz.NewReader(bytes.NewReader(data)) + if err != nil { + return nil, fmt.Errorf("decode pbzx xz chunk: %w", err) + } + decoded := make([]byte, decodedLen) + if _, err := io.ReadFull(xr, decoded); err != nil { + return nil, fmt.Errorf("read pbzx xz chunk: %w", err) + } + var extra [1]byte + if _, err := io.ReadFull(xr, extra[:]); err != io.EOF { + if err == nil { + return nil, errors.New("pbzx xz chunk exceeds declared decoded length") + } + return nil, fmt.Errorf("finish reading pbzx xz chunk: %w", err) + } + return decoded, nil } func (p *pbzxReader) Read(buf []byte) (int, error) { if !p.started { - var head [12]byte // "pbzx" (4) + flags (8) - if _, err := io.ReadFull(p.src, head[:]); err != nil { - return 0, fmt.Errorf("read pbzx header: %w", err) + if err := p.start(); err != nil { + return 0, err } - if string(head[:4]) != "pbzx" { - return 0, errors.New("invalid pbzx header") - } - p.started = true } for { if p.cur != nil { @@ -310,41 +424,22 @@ func (p *pbzxReader) Read(buf []byte) (int, error) { } if err == io.EOF { p.cur = nil + // Keep the slot until the caller has consumed the chunk. + <-p.slots continue } return 0, err } - var chunkHdr [16]byte - if _, err := io.ReadFull(p.src, chunkHdr[:]); err != nil { - if err == io.EOF { - return 0, io.EOF - } - return 0, fmt.Errorf("read pbzx chunk header: %w", err) + ch, ok := <-p.results + if !ok { + return 0, io.EOF } - uncompLen := binary.BigEndian.Uint64(chunkHdr[0:8]) - compLen := binary.BigEndian.Uint64(chunkHdr[8:16]) - if compLen == 0 { - continue - } - limited := io.LimitReader(p.src, int64(compLen)) - if compLen == uncompLen { - p.cur = limited - continue - } - // Compressed PBZX chunks are standalone XZ streams (0xfd 37 7a 58 5a 00). - data, err := io.ReadAll(limited) - if err != nil { - return 0, fmt.Errorf("read pbzx chunk: %w", err) - } - if len(data) >= 6 && bytes.Equal(data[:6], []byte{0xfd, '7', 'z', 'X', 'Z', 0x00}) { - xr, err := xz.NewReader(bytes.NewReader(data)) - if err != nil { - return 0, fmt.Errorf("decode pbzx xz chunk: %w", err) - } - p.cur = xr - } else { - p.cur = bytes.NewReader(data) + res := <-ch + if res.err != nil { + p.Close() + return 0, res.err } + p.cur = bytes.NewReader(res.data) } } diff --git a/internal/macos/installer/pkg_extract_test.go b/internal/macos/installer/pkg_extract_test.go new file mode 100644 index 0000000..452c787 --- /dev/null +++ b/internal/macos/installer/pkg_extract_test.go @@ -0,0 +1,102 @@ +package installer + +import ( + "bytes" + "encoding/binary" + "io" + "strings" + "testing" + + "github.com/ulikunitz/xz" +) + +func TestPBZXReaderMultiChunkConcurrentOrder(t *testing.T) { + var stream bytes.Buffer + stream.WriteString("pbzx") + var flags [8]byte + stream.Write(flags[:]) + + var want bytes.Buffer + for i := range 8 { + chunk := bytes.Repeat([]byte{byte('A' + i)}, 4096+i*137) + want.Write(chunk) + + var payload []byte + if i%3 == 0 { + // Uncompressed chunk (compLen == uncompLen) + payload = chunk + } else { + var comp bytes.Buffer + w, err := xz.NewWriter(&comp) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write(chunk); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + payload = comp.Bytes() + } + var hdr [16]byte + binary.BigEndian.PutUint64(hdr[0:8], uint64(len(chunk))) + binary.BigEndian.PutUint64(hdr[8:16], uint64(len(payload))) + stream.Write(hdr[:]) + stream.Write(payload) + } + + pr := newPBZXReader(bytes.NewReader(stream.Bytes())) + defer pr.Close() + got, err := io.ReadAll(pr) + if err != nil { + t.Fatalf("ReadAll(pbzx): %v", err) + } + if !bytes.Equal(got, want.Bytes()) { + t.Fatalf("pbzx output mismatch: got %d bytes, want %d bytes", len(got), want.Len()) + } +} + +func TestPBZXReaderRejectsInvalidChunkLengths(t *testing.T) { + var compressed bytes.Buffer + w, err := xz.NewWriter(&compressed) + if err != nil { + t.Fatal(err) + } + chunk := bytes.Repeat([]byte("XZ"), 2048) + if _, err := w.Write(chunk); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + + for _, tc := range []struct { + name string + stored, decoded uint64 + data []byte + want string + }{ + {"oversized stored length", maxPBZXChunkBytes + 1, 10, nil, "invalid pbzx chunk lengths"}, + {"oversized decoded length", 10, maxPBZXChunkBytes + 1, nil, "invalid pbzx chunk lengths"}, + {"truncated stored data", 5, 5, []byte("abcd"), "unexpected EOF"}, + {"short decoded output", uint64(compressed.Len()), uint64(len(chunk) + 1), compressed.Bytes(), "unexpected EOF"}, + {"long decoded output", uint64(compressed.Len()), uint64(len(chunk) - 1), compressed.Bytes(), "exceeds declared decoded length"}, + } { + t.Run(tc.name, func(t *testing.T) { + var stream bytes.Buffer + stream.WriteString("pbzx") + var header [24]byte + binary.BigEndian.PutUint64(header[8:16], tc.decoded) + binary.BigEndian.PutUint64(header[16:24], tc.stored) + stream.Write(header[:]) + stream.Write(tc.data) + + r := newPBZXReader(&stream) + defer r.Close() + if _, err := io.ReadAll(r); err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("read pbzx = %v, want %q", err, tc.want) + } + }) + } +} diff --git a/internal/macos/macosdriver/driver.go b/internal/macos/macosdriver/driver.go index b7ba8ca..b3ac31b 100644 --- a/internal/macos/macosdriver/driver.go +++ b/internal/macos/macosdriver/driver.go @@ -193,9 +193,14 @@ func (d *ReimsMacOSDriver) Show(ctx context.Context, name string) (driver.VMInfo det.AutoResolution = vmstart.SupportsAutoResolution(det.Graphics) && vmstart.ReadVMDisplay(det.Directory).AutoResolution marker := startprep.ReadRecoveryMarker(det.Directory) det.RecoveryMode = marker == "on" || marker == "want" - rawBytes, _ := json.Marshal(det) + rawBytes, err := json.Marshal(det) + if err != nil { + return driver.VMInfo{}, fmt.Errorf("encode macOS VM detail: %w", err) + } var data map[string]any - _ = json.Unmarshal(rawBytes, &data) + if err := json.Unmarshal(rawBytes, &data); err != nil { + return driver.VMInfo{}, fmt.Errorf("decode macOS VM detail: %w", err) + } info := driver.VMInfo{ Name: det.Name, DriverID: d.ID(), diff --git a/internal/macos/opencore/image.go b/internal/macos/opencore/image.go index 7f408ee..01cf076 100644 --- a/internal/macos/opencore/image.go +++ b/internal/macos/opencore/image.go @@ -737,7 +737,9 @@ func patchQcow2ViaRawWith(ctx context.Context, qcow2Path, qemuImgPath string, en return false, fmt.Errorf("replace opencore image: %w", berr) } if rerr := os.Rename(qcowTmp, qcow2Path); rerr != nil { - _ = os.Rename(bak, qcow2Path) + if rbErr := os.Rename(bak, qcow2Path); rbErr != nil { + return false, fmt.Errorf("replace opencore image: %w (rollback from %s also failed: %v)", rerr, bak, rbErr) + } return false, fmt.Errorf("replace opencore image: %w", rerr) } _ = os.Remove(bak) diff --git a/internal/packetbridge/bridge.go b/internal/packetbridge/bridge.go index 310cb95..c8e2f5c 100644 --- a/internal/packetbridge/bridge.go +++ b/internal/packetbridge/bridge.go @@ -2,6 +2,7 @@ package packetbridge import ( + "bufio" "bytes" "context" "encoding/binary" @@ -42,8 +43,9 @@ type uplinkHub struct { ctx context.Context cancel context.CancelFunc wg sync.WaitGroup - mu sync.RWMutex - bridges map[*Bridge]bool + mu sync.RWMutex + bridges map[*Bridge]bool + bridgeSnap atomic.Pointer[[]*Bridge] // refs 由 hubRegistry 保护,包含正在创建监听端点、尚未挂载的桥接。 refs int } @@ -159,10 +161,19 @@ func acquireHub(guid string, index int, wirelessOverride *bool) (*uplinkHub, err return h, nil } +func (h *uplinkHub) refreshBridgeSnapshotLocked() { + list := make([]*Bridge, 0, len(h.bridges)) + for b := range h.bridges { + list = append(list, b) + } + h.bridgeSnap.Store(&list) +} + func attachBridge(h *uplinkHub, b *Bridge) { hubRegistry.Lock() h.mu.Lock() h.bridges[b] = true + h.refreshBridgeSnapshotLocked() h.mu.Unlock() hubRegistry.Unlock() } @@ -181,6 +192,7 @@ func releaseBridgeFromHub(h *uplinkHub, b *Bridge) { return } delete(h.bridges, b) + h.refreshBridgeSnapshotLocked() } h.refs-- if h.refs == 0 && hubRegistry.byGUID[h.key] == h { @@ -199,6 +211,9 @@ func releaseBridgeFromHub(h *uplinkHub, b *Bridge) { } func (h *uplinkHub) snapshotBridges() []*Bridge { + if snap := h.bridgeSnap.Load(); snap != nil { + return *snap + } h.mu.RLock() list := make([]*Bridge, 0, len(h.bridges)) for b := range h.bridges { @@ -452,17 +467,19 @@ func (b *Bridge) serveGuest(conn net.Conn) { } func (b *Bridge) readGuest(conn net.Conn) { + br := bufio.NewReaderSize(conn, 64*1024) + frameBuf := make([]byte, 65536) + var size [4]byte for { - var size [4]byte - if _, err := io.ReadFull(conn, size[:]); err != nil { + if _, err := io.ReadFull(br, size[:]); err != nil { return } n := binary.BigEndian.Uint32(size[:]) if n < 14 || n > 65536 { return } - frame := make([]byte, n) - if _, err := io.ReadFull(conn, frame); err != nil { + frame := frameBuf[:n] + if _, err := io.ReadFull(br, frame); err != nil { return } if b.translator == nil || !bytes.Equal(frame[6:12], b.translator.guest) { @@ -500,24 +517,31 @@ func (b *Bridge) enqueue(frame []byte) { func (b *Bridge) writeGuest() { defer b.wg.Done() + writeBuf := make([]byte, 4+65536) for { select { case <-b.ctx.Done(): return case frame := <-b.sendCh: - b.writeFrame(frame) + b.writeFrame(writeBuf, frame) } } } -func (b *Bridge) writeFrame(frame []byte) { +func (b *Bridge) writeFrame(buf, frame []byte) { b.mu.Lock() conn := b.conn b.mu.Unlock() if conn == nil { return } - packet := make([]byte, 4+len(frame)) + needed := 4 + len(frame) + var packet []byte + if needed <= len(buf) { + packet = buf[:needed] + } else { + packet = make([]byte, needed) + } binary.BigEndian.PutUint32(packet, uint32(len(frame))) copy(packet[4:], frame) _ = conn.SetWriteDeadline(time.Now().Add(time.Second)) diff --git a/internal/packetbridge/frame.go b/internal/packetbridge/frame.go index 377e913..918da71 100644 --- a/internal/packetbridge/frame.go +++ b/internal/packetbridge/frame.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/binary" "net" + "net/netip" "sync" ) @@ -12,9 +13,9 @@ const maxLearnedAddresses = 256 type translator struct { guest, host net.HardwareAddr translateMAC bool - mu sync.Mutex - addresses map[string]bool - order []string + mu sync.RWMutex + addresses map[netip.Addr]struct{} + order []netip.Addr } func newTranslator(guest, host net.HardwareAddr, translateMAC bool) *translator { @@ -22,19 +23,25 @@ func newTranslator(guest, host net.HardwareAddr, translateMAC bool) *translator guest: append(net.HardwareAddr(nil), guest...), host: append(net.HardwareAddr(nil), host...), translateMAC: translateMAC, - addresses: map[string]bool{}, + addresses: map[netip.Addr]struct{}{}, } } func (t *translator) learn(ip []byte) { - address := net.IP(ip) - if len(address) == 0 || address.IsUnspecified() || address.IsMulticast() { + addr, ok := netip.AddrFromSlice(ip) + if !ok || addr.IsUnspecified() || addr.IsMulticast() { + return + } + addr = addr.Unmap() + t.mu.RLock() + _, exists := t.addresses[addr] + t.mu.RUnlock() + if exists { return } - key := address.String() t.mu.Lock() defer t.mu.Unlock() - if t.addresses[key] { + if _, exists := t.addresses[addr]; exists { return } if len(t.order) >= maxLearnedAddresses { @@ -42,14 +49,20 @@ func (t *translator) learn(ip []byte) { t.order = t.order[1:] delete(t.addresses, evict) } - t.addresses[key] = true - t.order = append(t.order, key) + t.addresses[addr] = struct{}{} + t.order = append(t.order, addr) } func (t *translator) owns(ip []byte) bool { - t.mu.Lock() - defer t.mu.Unlock() - return t.addresses[net.IP(ip).String()] + addr, ok := netip.AddrFromSlice(ip) + if !ok { + return false + } + addr = addr.Unmap() + t.mu.RLock() + _, exists := t.addresses[addr] + t.mu.RUnlock() + return exists } func frameSum(data []byte) uint16 { @@ -94,7 +107,7 @@ func (t *translator) outbound(frame []byte) ([]byte, bool) { if !validFrameType(frame) { return nil, false } - return append([]byte(nil), frame...), true + return frame, true } f := append([]byte(nil), frame...) copy(f[6:12], t.host) diff --git a/internal/plugin/builtin/bootstrap.go b/internal/plugin/builtin/bootstrap.go new file mode 100644 index 0000000..a716de9 --- /dev/null +++ b/internal/plugin/builtin/bootstrap.go @@ -0,0 +1,104 @@ +package builtin + +import ( + "fmt" + + "github.com/Nwflower/reims-go/internal/driver" + "github.com/Nwflower/reims-go/internal/host" + "github.com/Nwflower/reims-go/internal/i18n" + "github.com/Nwflower/reims-go/internal/plugin" + "github.com/Nwflower/reims-go/internal/version" +) + +// KernelBootstrapOptions configures the shared GUI/CLI plugin-kernel and +// driver-router composition root. +type KernelBootstrapOptions struct { + DataRoot string + DataRootFn func() string + SafeMode bool + LocaleFn func() i18n.Locale + Logger func(source, line string) + HostHandlers func(pluginID string) map[string]plugin.RPCRequestHandler + OnSettingsChanged func(pluginID, vmName string) + OnSidecarStopped func(pluginID string) + VMInventory driver.VMInventory + Callbacks HostCallbacks + RegisterGuest func(reg *plugin.Registry, cb HostCallbacks, desired func(id string, defaultEnabled bool) bool) error + // StrictRegister causes builtin/guest registration errors to abort bootstrap + // instead of logging warnings (used by CLI commands). + StrictRegister bool +} + +// BootstrapKernel creates and wires the plugin manager, driver router, +// built-in extensions, optional guest plugin, and external plugins in one +// canonical order shared by both the desktop app and the CLI. +func BootstrapKernel(opts KernelBootstrapOptions) (*plugin.Manager, *driver.Router, error) { + logf := opts.Logger + if logf == nil { + logf = func(string, string) {} + } + mgr, err := plugin.NewManager(plugin.ManagerOptions{ + DataRoot: opts.DataRoot, + HostVersion: version.Version, + SafeMode: opts.SafeMode, + RedactFn: host.RedactText, + LocaleFn: opts.LocaleFn, + Logger: logf, + HostHandlers: opts.HostHandlers, + OnSettingsChanged: opts.OnSettingsChanged, + OnSidecarStopped: opts.OnSidecarStopped, + SidecarDriverFactory: func(contrib plugin.GuestDriverContribution, sup *plugin.SidecarSupervisor) any { + return driver.NewSidecarDriver(contrib, sup) + }, + }) + if err != nil { + if opts.StrictRegister || mgr == nil { + if mgr != nil { + mgr.Close() + } + return nil, nil, err + } + logf("plugin", "Plugin state warning: "+err.Error()) + } + + dataRootFn := opts.DataRootFn + if dataRootFn == nil { + root := opts.DataRoot + dataRootFn = func() string { return root } + } + router := driver.NewRouter(mgr.Registry(), dataRootFn, opts.VMInventory) + mgr.Registry().SetInUseChecker(router.PluginInUseChecker()) + mgr.Registry().SetBusyChecker(router.PluginBusyChecker()) + + cb := opts.Callbacks + if cb.Log == nil { + cb.Log = logf + } + if cb.GetSetting == nil { + cb.GetSetting = func(pluginID, vmName, key string) (any, bool) { + v, ok := mgr.GetSettings(pluginID, vmName, false)[key] + return v, ok + } + } + + if err := RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil { + if opts.StrictRegister { + mgr.Close() + return nil, nil, err + } + logf("plugin", "Builtin extension register error: "+err.Error()) + } + if opts.RegisterGuest != nil { + if err := opts.RegisterGuest(mgr.Registry(), cb, mgr.DesiredFor); err != nil { + if opts.StrictRegister { + mgr.Close() + return nil, nil, err + } + logf("plugin", "macOS guest plugin register error: "+err.Error()) + } + } + if err := mgr.LoadExternal(); err != nil { + logf("plugin", fmt.Sprintf("External plugin load warning: %v", err)) + } + return mgr, router, nil +} diff --git a/internal/plugin/builtin/builtin_test.go b/internal/plugin/builtin/builtin_test.go index 65065ce..0a23e4b 100644 --- a/internal/plugin/builtin/builtin_test.go +++ b/internal/plugin/builtin/builtin_test.go @@ -241,12 +241,12 @@ func TestNpcapBridgePluginLifecycleZeroResidue(t *testing.T) { t.Fatalf("DispatchBeforeStart: %v", err) } ledger := &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}} - res := plugin.ReconcileStartIntents("-cpu host", ledger, reg.ActivePluginIDs(), intents) + res := plugin.ReconcileStartIntentsForDriver("-cpu host", ledger, reg.ActivePluginIDs(), "", intents) if !strings.Contains(res.ExtraArgs, "addr.type=unix") || !strings.Contains(res.ExtraArgs, "reimsbridge0") || !strings.Contains(res.ExtraArgs, "-cpu host") { t.Fatalf("active npcap-bridge ExtraArgs = %q", res.ExtraArgs) } // Primary bridge NIC (addr=0x3) must always precede guest-tools-network so QEMU never assigns slot 0x3 to reimstools-nic. - withMgmt := plugin.ReconcileStartIntents("-cpu host", &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}, reg.ActivePluginIDs(), append(intents, plugin.StartIntent{ + withMgmt := plugin.ReconcileStartIntentsForDriver("-cpu host", &plugin.ArgLedger{Version: 1, Owners: map[string][]plugin.ArgFragment{}}, reg.ActivePluginIDs(), "", append(intents, plugin.StartIntent{ PluginID: IDGuestTools, Args: []plugin.ArgFragment{{ PluginID: IDGuestTools, @@ -284,7 +284,7 @@ func TestNpcapBridgePluginLifecycleZeroResidue(t *testing.T) { if err != nil { t.Fatalf("DispatchBeforeStart after disable: %v", err) } - resAfter := plugin.ReconcileStartIntents(res.ExtraArgs, ledger, reg.ActivePluginIDs(), intentsAfter) + resAfter := plugin.ReconcileStartIntentsForDriver(res.ExtraArgs, ledger, reg.ActivePluginIDs(), "", intentsAfter) if resAfter.ExtraArgs != "-cpu host" { t.Fatalf("disabled npcap-bridge left residue in ExtraArgs: %q", resAfter.ExtraArgs) } diff --git a/internal/plugin/kernel_test.go b/internal/plugin/kernel_test.go index 38c7d49..5701e5c 100644 --- a/internal/plugin/kernel_test.go +++ b/internal/plugin/kernel_test.go @@ -413,7 +413,7 @@ func TestArgLedgerReconcilePreserveUserArgsAndStripOnDisable(t *testing.T) { }, } - res := ReconcileStartIntents(userArgs, ledger, active, intents) + res := ReconcileStartIntentsForDriver(userArgs, ledger, active, "", intents) if !strings.Contains(res.ExtraArgs, "-device virtio-rng-pci -rtc base=utc") { t.Fatalf("user args lost: %q", res.ExtraArgs) } @@ -446,7 +446,7 @@ func TestArgLedgerReconcilePreserveUserArgsAndStripOnDisable(t *testing.T) { // Disable thirdparty.tweak -> its fragment is stripped cleanly, user + builtin remain. delete(active, "thirdparty.tweak") - after := ReconcileStartIntents(res.ExtraArgs, reloaded, active, intents[:1]) + after := ReconcileStartIntentsForDriver(res.ExtraArgs, reloaded, active, "", intents[:1]) if !after.Changed { t.Fatal("expected change on strip") } diff --git a/internal/plugin/ledger.go b/internal/plugin/ledger.go index 49d86c4..b347b80 100644 --- a/internal/plugin/ledger.go +++ b/internal/plugin/ledger.go @@ -390,16 +390,11 @@ func UserExtraArgs(currentExtraArgs string, ledger *ArgLedger) string { return strings.Join(stripOwnedTokens(qmp.SplitArgs(currentExtraArgs), ledger), " ") } -// ReconcileStartIntents strips previously owned fragments from currentExtraArgs -// (preserving ALL unowned user args), arbitrates conflicts across new intents, -// validates option allowlists & env prefixes, updates the ledger, and returns -// the single merged extra-args string ready for one `reims-ctl set` call (§4.4). -func ReconcileStartIntents(currentExtraArgs string, ledger *ArgLedger, activePlugins map[string]bool, intents []StartIntent) ReconcileResult { - return reconcileStartIntents(currentExtraArgs, ledger, activePlugins, "", intents) -} - -// ReconcileStartIntentsForDriver additionally grants the owning driver control -// of its own VM, without trusting other external plugins by ID prefix. +// ReconcileStartIntentsForDriver strips previously owned fragments from +// currentExtraArgs (preserving ALL unowned user args), arbitrates conflicts +// across new intents, validates option allowlists & env prefixes, updates the +// ledger, and returns the single merged extra-args string ready for one +// `reims-ctl set` call (§4.4), granting driverOwner control of its own VM. func ReconcileStartIntentsForDriver(currentExtraArgs string, ledger *ArgLedger, activePlugins map[string]bool, driverOwner string, intents []StartIntent) ReconcileResult { return reconcileStartIntents(currentExtraArgs, ledger, activePlugins, driverOwner, intents) } diff --git a/internal/plugin/registry.go b/internal/plugin/registry.go index 9de6042..489ada9 100644 --- a/internal/plugin/registry.go +++ b/internal/plugin/registry.go @@ -188,7 +188,7 @@ func (r *Registry) notifyChange() { r.mu.RUnlock() for _, cb := range cbs { if cb != nil { - safeInvoke(cb) + safeInvoke("registry.onChange", cb) } } } diff --git a/internal/plugin/scope.go b/internal/plugin/scope.go index 5667a13..41cd32d 100644 --- a/internal/plugin/scope.go +++ b/internal/plugin/scope.go @@ -1,6 +1,7 @@ package plugin import ( + "log" "sync" ) @@ -42,7 +43,7 @@ func (s *Scope) OnDispose(fn func()) { s.mu.Lock() if s.disposed { s.mu.Unlock() - safeInvoke(fn) + safeInvoke("scope:"+s.pluginID, fn) return } s.disposers = append(s.disposers, fn) @@ -82,7 +83,7 @@ func (s *Scope) Dispose() { s.mu.Unlock() for i := len(fns) - 1; i >= 0; i-- { - safeInvoke(fns[i]) + safeInvoke("scope:"+s.pluginID, fns[i]) } } @@ -93,9 +94,11 @@ func (s *Scope) Disposed() bool { return s.disposed } -func safeInvoke(fn func()) { +func safeInvoke(label string, fn func()) { defer func() { - _ = recover() + if rec := recover(); rec != nil { + log.Printf("[plugin] callback panicked (%s): %v", label, rec) + } }() fn() } diff --git a/internal/selfupdate/takeover_windows.go b/internal/selfupdate/takeover_windows.go index 48778f0..6359b08 100644 --- a/internal/selfupdate/takeover_windows.go +++ b/internal/selfupdate/takeover_windows.go @@ -3,8 +3,10 @@ package selfupdate import ( + "bytes" "context" - "debug/buildinfo" + "debug/pe" + "encoding/binary" "errors" "fmt" "os" @@ -92,7 +94,7 @@ func Takeover(pid uint32, relaunchArgs []string, windowPID func() uint32) (bool, if current, err := os.Stat(source); err != nil || os.SameFile(current, oldFile) { return false, err } - oldBuild, err := buildinfo.ReadFile(target) + oldBuild, err := readPEBuildInfo(target) newBuild, ok := debug.ReadBuildInfo() if err != nil || !ok || oldBuild.Path != newBuild.Path || oldBuild.Main.Path != newBuild.Main.Path { return false, nil @@ -288,3 +290,74 @@ func ReportTakeoverError(err error) { _, _ = windows.MessageBox(0, windows.StringToUTF16Ptr(message+"\n\n"+err.Error()), windows.StringToUTF16Ptr("Reims-Go"), windows.MB_OK|windows.MB_ICONWARNING) } + +var goBuildInfoMagic = []byte("\xff Go buildinf:") + +// readPEBuildInfo reads Go 1.18+ embedded buildinfo directly from a Windows PE +// executable without importing debug/buildinfo (which pulls debug/elf, +// debug/plan9obj, internal/xcoff, debug/dwarf, and internal/zstd into the +// client binary). +func readPEBuildInfo(path string) (*debug.BuildInfo, error) { + f, err := pe.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + + const buildInfoHeaderSize = 32 + for _, sec := range f.Sections { + if sec.Size < buildInfoHeaderSize || sec.Name == ".text" { + continue + } + data, err := sec.Data() + if err != nil { + continue + } + for off := 0; off+buildInfoHeaderSize <= len(data); { + idx := bytes.Index(data[off:], goBuildInfoMagic) + if idx < 0 { + break + } + pos := off + idx + if pos+buildInfoHeaderSize > len(data) { + break + } + if pos%16 != 0 { + off = pos + 1 + continue + } + flags := data[pos+15] + if flags&0x2 == 0 { + return nil, errors.New("unsupported legacy Go buildinfo format") + } + rest := data[pos+buildInfoHeaderSize:] + ver, rest, ok := readVarintString(rest) + if !ok { + return nil, errors.New("malformed Go buildinfo version") + } + mod, _, ok := readVarintString(rest) + if !ok { + return nil, errors.New("malformed Go buildinfo module data") + } + if len(mod) >= 33 && mod[len(mod)-17] == '\n' { + mod = mod[16 : len(mod)-16] + } + bi, err := debug.ParseBuildInfo(mod) + if err != nil { + return nil, err + } + bi.GoVersion = ver + return bi, nil + } + } + return nil, errors.New("Go buildinfo not found in PE executable") +} + +func readVarintString(b []byte) (string, []byte, bool) { + n, read := binary.Uvarint(b) + if read <= 0 || n > uint64(len(b)-read) { + return "", nil, false + } + end := read + int(n) + return string(b[read:end]), b[end:], true +} diff --git a/internal/selfupdate/takeover_windows_test.go b/internal/selfupdate/takeover_windows_test.go index f335cd8..cbe6874 100644 --- a/internal/selfupdate/takeover_windows_test.go +++ b/internal/selfupdate/takeover_windows_test.go @@ -3,6 +3,7 @@ package selfupdate import ( + "os" "runtime/debug" "testing" ) @@ -31,3 +32,21 @@ func TestTakeoverVersionOrdering(t *testing.T) { } } } + +func TestReadPEBuildInfoMatchesRuntime(t *testing.T) { + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + want, ok := debug.ReadBuildInfo() + if !ok { + t.Skip("runtime buildinfo unavailable") + } + got, err := readPEBuildInfo(exe) + if err != nil { + t.Fatalf("readPEBuildInfo(%s): %v", exe, err) + } + if got.Main.Path != want.Main.Path || got.GoVersion != want.GoVersion { + t.Fatalf("readPEBuildInfo = (%q, %q), want (%q, %q)", got.Main.Path, got.GoVersion, want.Main.Path, want.GoVersion) + } +} diff --git a/internal/thumb/preview.go b/internal/thumb/preview.go index 72ca544..4be5fd2 100644 --- a/internal/thumb/preview.go +++ b/internal/thumb/preview.go @@ -4,7 +4,6 @@ import ( "bufio" "fmt" "image" - "image/color" "io" "os" ) @@ -39,7 +38,7 @@ func LoadPreviewFrame(path, format string, maxWidth int) (image.Image, bool, err return nil, false, err } defer f.Close() - r := bufio.NewReader(f) + r := bufio.NewReaderSize(f, 256*1024) size, err := ppmSize(r) if err != nil { return nil, false, err @@ -77,9 +76,14 @@ func LoadPreviewFrame(path, format string, maxWidth int) (image.Image, bool, err sums[x][2] += uint64(blue) } } + rowOff := y * img.Stride for x, sum := range sums { pixels := uint64(((x+1)*w/dw - x*w/dw) * (y1 - y0)) - img.SetRGBA(x, y, color.RGBA{uint8(sum[0] / pixels), uint8(sum[1] / pixels), uint8(sum[2] / pixels), 255}) + off := rowOff + x*4 + img.Pix[off] = uint8(sum[0] / pixels) + img.Pix[off+1] = uint8(sum[1] / pixels) + img.Pix[off+2] = uint8(sum[2] / pixels) + img.Pix[off+3] = 255 } } return img, samples.blank(), nil diff --git a/internal/tray/tray.go b/internal/tray/tray.go index 6d38084..51b646d 100644 --- a/internal/tray/tray.go +++ b/internal/tray/tray.go @@ -27,7 +27,6 @@ func (v VMItem) title() string { // Snapshot holds the live state read each time the user opens the tray menu. type Snapshot struct { Locale i18n.Locale - LocaleZh bool // legacy fallback when Locale is empty CanSuspend bool VMs []VMItem } @@ -111,11 +110,7 @@ type texts struct { func menuTexts(snap Snapshot) texts { loc := snap.Locale if loc == "" { - if snap.LocaleZh { - loc = i18n.ZhCN - } else { - loc = i18n.EnUS - } + loc = i18n.EnUS } return texts{ show: i18n.T(loc, "tray.menu.show"), diff --git a/internal/tray/tray_test.go b/internal/tray/tray_test.go index b08ff95..6049b41 100644 --- a/internal/tray/tray_test.go +++ b/internal/tray/tray_test.go @@ -6,6 +6,8 @@ import ( "image/color" "image/png" "testing" + + "github.com/Nwflower/reims-go/internal/i18n" ) func findEntry(entries []menuEntry, label string) *menuEntry { @@ -18,7 +20,7 @@ func findEntry(entries []menuEntry, label string) *menuEntry { } func TestBuildMenuPerState(t *testing.T) { - menu := buildMenu(Snapshot{LocaleZh: true, CanSuspend: true, VMs: []VMItem{ + menu := buildMenu(Snapshot{Locale: i18n.ZhCN, CanSuspend: true, VMs: []VMItem{ {Name: "macos-tahoe", Label: "日常", State: "running"}, {Name: "macos-dev", State: "stopped"}, {Name: "macos-busy", State: "starting"}, @@ -73,7 +75,7 @@ func TestBuildMenuPerState(t *testing.T) { } func TestSuspendedVMWithoutCompatibleRuntime(t *testing.T) { - menu := buildMenu(Snapshot{LocaleZh: true, VMs: []VMItem{{Name: "macos-sleep", State: "suspended"}}}) + menu := buildMenu(Snapshot{Locale: i18n.ZhCN, VMs: []VMItem{{Name: "macos-sleep", State: "suspended"}}}) vm := findEntry(menu, "macos-sleep\t已挂起") if vm == nil { t.Fatal("suspended VM is missing from the tray menu") diff --git a/internal/version/version.go b/internal/version/version.go index b1eccf8..00da8b7 100644 --- a/internal/version/version.go +++ b/internal/version/version.go @@ -413,14 +413,34 @@ func (s Source) CheckUpdate(ctx context.Context, current, channel string) (Updat if info.PublishedAt == "" { info.PublishedAt = best.rel.CreatedAt } + // Prefer the compressed .zip release archive when it carries a verified + // SHA-256 digest (~62% smaller download than the raw .exe); fall back to + // the raw .exe asset when no verified .zip is published. for _, a := range best.rel.Assets { lower := strings.ToLower(a.Name) - if info.DownloadURL == "" && strings.HasSuffix(lower, ".exe") && !strings.Contains(lower, "-cli-") { - info.AssetName = a.Name - info.AssetSize = a.Size - info.DownloadURL = a.URL - info.AssetSHA256 = parseSHA256Digest(a.Digest) - break + if strings.Contains(lower, "-cli-") { + continue + } + if strings.HasSuffix(lower, ".zip") { + if digest := parseSHA256Digest(a.Digest); digest != "" { + info.AssetName = a.Name + info.AssetSize = a.Size + info.DownloadURL = a.URL + info.AssetSHA256 = digest + break + } + } + } + if info.DownloadURL == "" { + for _, a := range best.rel.Assets { + lower := strings.ToLower(a.Name) + if strings.HasSuffix(lower, ".exe") && !strings.Contains(lower, "-cli-") { + info.AssetName = a.Name + info.AssetSize = a.Size + info.DownloadURL = a.URL + info.AssetSHA256 = parseSHA256Digest(a.Digest) + break + } } } if best.rolling && isSameBaseDevBuild(current, best.ver) {