From 86d2da4a04e0f33f8cf7538e004c3d0971a9eee6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Sun, 29 Nov 2026 09:21:33 -0700 Subject: [PATCH] fix(stability,plugin): fix Windows callback leaks, add WebView2 watchdog, and harden plugin/runtime internals --- docs/plugin-architecture.md | 27 +-- internal/app/app.go | 21 +- internal/app/plugins_flow.go | 20 +- internal/app/thumbnail_flow.go | 2 +- internal/app/ui_health.go | 203 ++++++++++++++++++ internal/cli/plugin.go | 9 +- internal/cli/plugin_test.go | 18 +- internal/guesttools/image.go | 19 +- internal/guesttools/server.go | 28 ++- internal/host/display_windows.go | 157 ++++++++------ internal/host/foreground_windows.go | 45 ++-- internal/host/host_windows.go | 69 +++++- internal/host/host_windows_test.go | 8 + internal/host/input_service.go | 3 +- internal/host/input_service_test.go | 4 +- internal/plugin/blockers_test.go | 19 +- internal/plugin/builtin/builtin.go | 14 +- internal/plugin/builtin/builtin_test.go | 13 -- internal/plugin/bundled/bundled.go | 47 ---- .../plugin/bundled/wheel-invert/plugin.json | 100 --------- internal/plugin/hooks.go | 33 ++- internal/plugin/kernel_test.go | 7 +- internal/plugin/ledger.go | 52 +++-- internal/plugin/manager.go | 31 ++- internal/plugin/package.go | 12 +- internal/plugin/registry.go | 76 ++++++- internal/plugin/rpc.go | 68 ++++-- internal/plugin/sidecar.go | 54 ++++- internal/runtime/runtime.go | 24 ++- main.go | 6 + 30 files changed, 797 insertions(+), 392 deletions(-) create mode 100644 internal/app/ui_health.go delete mode 100644 internal/plugin/bundled/bundled.go delete mode 100644 internal/plugin/bundled/wheel-invert/plugin.json diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 5797ac9..64f82e0 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -104,7 +104,7 @@ flowchart TB ### 3.2 内置功能先插件化 -扩展点先由内置功能使用一遍再对外开放:reims 驱动成为内置 `builtin.driver.reims-macos`,现有启动准备步骤与宿客桥接迁为内置扩展,经同一注册表注册、可独立启停、禁用后零残留。首批示例插件为默认开启的剪贴板互通与默认关闭的滚轮反转(见 §5.4)。 +扩展点先由内置功能使用一遍再对外开放:reims 驱动成为内置 `builtin.driver.reims-macos`,现有启动准备步骤与宿客桥接迁为内置扩展,经同一注册表注册、可独立启停、禁用后零残留。首批示例插件为默认开启的剪贴板互通(见 §5.4)。 --- @@ -247,12 +247,9 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card` #### 首批示例插件 -两个示例分别覆盖「编译期内置扩展」与「声明式插件包」两条路径,并分别演示默认开启与默认关闭: - | 示例 | 形态 | 默认 | 演示的机制 | | :--- | :--- | :--- | :--- | | **剪贴板互通** `builtin.bridge.clipboard` | 内置 Go 扩展 | 开启 | 服务依赖(依赖 Guest Tools 传输服务)、运行中启停与完整拆除、按 VM 设置立即生效、宿主与客体的功能协商、隐私(内容不入日志) | -| **滚轮反转** `reims.input.wheel-invert` | 随主程序附带的 L1 声明式插件包 | 关闭 | 标准插件包格式与清单、按 VM 设置、在宿主热路径上安全扩展(插件只声明策略,不注入代码) | **剪贴板互通** @@ -261,15 +258,6 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card` - 设置:全局开关 + 按 VM 覆盖;方向(双向 / 仅宿主到客体 / 仅客体到宿主);是否同步图片与大小上限;均立即生效。 - `vm.card` 显示连接状态;排障包只记录次数与错误,不记录剪贴板内容。 -**滚轮反转** - -- 背景:macOS 默认开启「自然滚动」,与 Windows 滚轮方向相反。 -- 宿主新增内置「输入服务」,统一持有低级键盘/鼠标钩子(现有 IME 桥的键盘钩子迁入),并开放 `inputFilters` 扩展点。低级钩子回调超时会拖慢整个系统的输入,因此过滤器只能是声明式规则(事件类型、轴向、变换、作用范围),任何插件代码都不得进入该路径。 -- 插件只声明一条规则:前台窗口属于启用该设置的 VM 时,取反垂直(可选水平)滚轮增量。宿主丢弃原事件并以带自身标记的注入事件重发反向增量,识别标记避免重复处理;仅在存在命中 VM 时安装鼠标钩子,插件停用或没有命中 VM 时卸载。 -- 设置按 VM:开关、垂直/水平分别控制,立即生效;渲染在 VM 设置的「键盘与指针」分组。 -- 未采用的备选:经 Guest Tools 客体代理修改 macOS 自然滚动偏好。它依赖客体代理在线,安装器与恢复模式中不可用,可能需重新登录才生效(待验证),并会改变客体全局偏好、停用时还需恢复原值。在 SDL 窗口内改写滚轮属于引擎补丁范畴(§5.5),也不采用。 -- 待验证:VM 窗口捕获鼠标(相对模式/原始输入)时低级钩子丢弃与重发是否仍生效;精确式触控板高分辨率滚动增量取反后的手感。 - #### 其余内置扩展(由现有模块迁入) | 内置扩展 | 对应现有模块 | 使用的扩展点 | @@ -384,7 +372,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card` ## 9. 分发、更新与恢复 - **安装来源**:本地包导入(首批)、市场索引(后续)、开发者模式本地目录链接。 -- **随主程序附带的插件**:以标准插件包形式嵌入 `reims-go.exe`(如滚轮反转),信任等级为 `official`,版本跟随主程序;可启用/停用,不可卸载;用于在不依赖市场的情况下走通完整的清单解析、设置渲染与启停链路。 +- **随主程序附带的插件**:需要时可以标准插件包形式嵌入 `reims-go.exe`,信任等级为 `official`,版本跟随主程序;可启用/停用,不可卸载。 - **事务安装**:下载到 `tmp` → 校验 `SHA256SUMS` 与签名 → 核对包内 `id` / `version` 与预期一致(防偷换)→ 兼容预检 → 原子 rename 到 `pkgs//` → 提交 `state.json`。任一步失败都不改变现状。 - **市场索引**:独立仓库发布静态 `index.json`(GitHub 主源 + GitCode 镜像,复用运行时下载源的回退与代理逻辑),含版本、`engines`、下载地址、SHA-256 与签名者;主程序内嵌兜底副本。 - **更新与回滚**:新旧版本并存、切换指针,保留最近若干版本;插件同样区分 `alpha` / `stable` 通道,默认只取 `stable`。 @@ -438,7 +426,7 @@ flowchart LR | 阶段 | 范围 | 验收标准 | | :--- | :--- | :--- | | **Phase 0** | 注册表与可逆作用域;驱动抽象(reims 为内置驱动);启动准备与宿客桥接迁为内置扩展;Guest Tools 拆出传输服务与**剪贴板互通示例**;输入服务(IME 键盘钩子迁入);参数归属账本;UI 契约 v1(令牌单一来源、部件类名、状态属性) | `go test ./...` 与前端构建通过;存量 VM 零迁移、行为零回归;剪贴板互通可在 VM 运行中开关且关闭后零残留(无残留路由与剪贴板监视);其余内置扩展同样可独立停用且零残留;满足 §8.1 资源预算 | -| **Phase 1** | 插件包与清单、事务安装、`state.json`、安全模式;插件管理页与 `reims-go plugin`;`inputFilters` 与**滚轮反转示例**;令牌主题与样式主题接口;图标、VM 模板、运行时源、规则 Hook | 滚轮反转默认关闭、按 VM 开启即时生效、停用后钩子卸载;以不发布的测试主题验证配色方案、字体、部件样式与状态装饰;损坏包与不兼容包在落盘前被拒绝;仍满足 §8.1 资源预算 | +| **Phase 1** | 插件包与清单、事务安装、`state.json`、安全模式;插件管理页与 `reims-go plugin`;`inputFilters`;令牌主题与样式主题接口;图标、VM 模板、运行时源、规则 Hook | 以不发布的测试主题与示例声明式插件验证配色方案、字体、部件样式、状态装饰与启停零残留;损坏包与不兼容包在落盘前被拒绝;仍满足 §8.1 资源预算 | | **Phase 2** | 运行时种类注册表、`runtime_api` 与 `capabilities`、来源展示 | 第二种运行时与官方运行时并存切换;不兼容组合被拦截并给出提示 | | **Phase 3** | JSON-RPC 协议 v1、进程监管、反向 Host API、权限审批、代码 Hook、插件命令、排障采集、轻量 Go SDK | 死循环或崩溃的示例 Sidecar 不影响主窗口与运行中 VM;退出或禁用后无孤儿进程 | | **Phase 4** | 独立仓库的官方 Linux 驱动 | 不修改主程序源码,经 GUI 与 CLI 完成 Linux VM 创建、WHPX 启动、绑核、截屏、SSH 与快照;真机验证 | @@ -448,8 +436,7 @@ flowchart LR ## 13. 待决事项 -1. **滚轮反转的实现路径**:需在真机上验证 VM 窗口捕获鼠标时低级钩子方案是否可靠;若不可靠,再评估客体侧偏好方案。 -2. **L2 脚本宿主是否需要**:仅当出现 L1 规则无法表达、又不适合要求作者交付原生 exe 的真实需求时引入;届时在纯 Go JS 引擎与 WASM 之间选型。 -3. **市场形态与审核责任**:首批仅本地包导入;社区索引的维护者、审核流程与签名密钥托管方式待定。 -4. **Sidecar 原生沙箱**:AppContainer / 低完整性级别的兼容性与维护成本待评估。 -5. **上游结构化输出**:是否向上游提议 `reims-ctl show --json`,以及非 macOS 客体支持的计划,需核对上游实际进展(待验证)。 +1. **L2 脚本宿主是否需要**:仅当出现 L1 规则无法表达、又不适合要求作者交付原生 exe 的真实需求时引入;届时在纯 Go JS 引擎与 WASM 之间选型。 +2. **市场形态与审核责任**:首批仅本地包导入;社区索引的维护者、审核流程与签名密钥托管方式待定。 +3. **Sidecar 原生沙箱**:AppContainer / 低完整性级别的兼容性与维护成本待评估。 +4. **上游结构化输出**:是否向上游提议 `reims-ctl show --json`,以及非 macOS 客体支持的计划,需核对上游实际进展(待验证)。 diff --git a/internal/app/app.go b/internal/app/app.go index fc3858e..40c4d83 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -83,6 +83,7 @@ type App struct { pluginMgr *plugin.Manager driverRouter *driver.Router runtimeKinds *rt.KindRegistry + uiHealth uiHealthState } // Lifecycle exposes Wails lifecycle callbacks without exporting them as @@ -92,6 +93,8 @@ type Lifecycle struct { OnBeforeClose func(context.Context) bool OnShutdown func(context.Context) OnSecondInstanceLaunch func(options.SecondInstanceData) + OnSuspend func() + OnResume func() } func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) { @@ -110,12 +113,15 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) { pollWake: make(chan struct{}, 1), diskPaths: make(map[string]cachedDiskPath), procSamples: make(map[string]host.ProcessSample), + uiHealth: uiHealthState{windowHidden: launch.Background}, } return a, Lifecycle{ OnStartup: a.startup, OnBeforeClose: a.beforeClose, OnShutdown: a.shutdown, OnSecondInstanceLaunch: a.onSecondInstance, + OnSuspend: a.onSystemSuspend, + OnResume: a.onSystemResume, } } @@ -128,6 +134,7 @@ func (a *App) startup(ctx context.Context) { if a.getInputService() == nil { a.startIMEBridge() } + a.startUIHealthWatchdog(pollCtx) go a.registerExistingGuestTools(pollCtx) go a.pollVMs(pollCtx) a.afterStartup() @@ -153,6 +160,7 @@ func (a *App) beforeClose(ctx context.Context) bool { hasTray := a.trayMgr != nil a.mu.Unlock() if !allow && toTray && hasTray { + a.setWindowHidden(true) wailsRuntime.WindowHide(ctx) return true } @@ -520,6 +528,7 @@ func (a *App) emitLog(source, line string) { } func (a *App) GetState() AppState { + a.noteUIAlive() a.mu.Lock() cfgCopy := *a.cfg trCopy := make(map[string]string, len(a.transitions)) @@ -556,15 +565,6 @@ func (a *App) GetState() AppState { if mgr != nil { safeMode = mgr.SafeMode() crashDetected = mgr.CrashDetected() - if mgr.Registry().Hooks().HasSubscribers(plugin.EventHostPreflight) { - var rtCaps []string - if active != nil { - rtCaps = active.Manifest.EffectiveCapabilities() - } - _ = mgr.Registry().Hooks().DispatchPreflight(context.Background(), plugin.PreflightPayload{ - HostFacts: buildHostFacts(rep, rtCaps), - }) - } } return AppState{ @@ -626,8 +626,10 @@ func (a *App) ShowMainWindow() { if a.ctx == nil { return } + a.setWindowHidden(false) wailsRuntime.WindowUnminimise(a.ctx) wailsRuntime.WindowShow(a.ctx) + a.scheduleUIHealthProbe("window restore", 1500*time.Millisecond) } // RequestClose handles the custom titlebar close button: hides to system tray @@ -641,6 +643,7 @@ func (a *App) RequestClose() { hasTray := a.trayMgr != nil a.mu.Unlock() if toTray && hasTray { + a.setWindowHidden(true) wailsRuntime.WindowHide(a.ctx) return } diff --git a/internal/app/plugins_flow.go b/internal/app/plugins_flow.go index d432ca3..36b3316 100644 --- a/internal/app/plugins_flow.go +++ b/internal/app/plugins_flow.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "strings" + "time" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/driver" @@ -18,7 +19,6 @@ import ( "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" - "github.com/Nwflower/reims-go/internal/plugin/bundled" rt "github.com/Nwflower/reims-go/internal/runtime" "github.com/Nwflower/reims-go/internal/version" "github.com/Nwflower/reims-go/internal/vmstart" @@ -117,6 +117,18 @@ func (a *App) initPlugins() { EnsureGuestTools: func() (*guesttools.Server, int, error) { return a.ensureGuestToolsBridge() }, + 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() + } + }, + ValidateDriveConfig: validatedDriveConfig, OnIMEText: func(target host.IMETarget, text string) { go a.injectRemoteText(target.VMName, target.VMDir, text) }, @@ -137,11 +149,6 @@ func (a *App) initPlugins() { if err := builtin.RegisterAll(mgr.Registry(), cb, mgr.DesiredFor); err != nil { a.emitLog("plugin", "Builtin extension register error: "+err.Error()) } - if bundledList, err := bundled.BundledManifests(); err == nil { - if err := mgr.LoadBundled(bundledList); err != nil { - a.emitLog("plugin", "Bundled plugin load error: "+err.Error()) - } - } if err := mgr.LoadExternal(); err != nil { a.emitLog("plugin", "External plugin load warning: "+err.Error()) } @@ -163,6 +170,7 @@ func (a *App) initPlugins() { a.mu.Unlock() mgr.Registry().Reconcile(context.Background()) + mgr.MarkBootComplete() a.syncInputFilters() a.syncClipboardPolicies() } diff --git a/internal/app/thumbnail_flow.go b/internal/app/thumbnail_flow.go index e5cb20c..6e061ee 100644 --- a/internal/app/thumbnail_flow.go +++ b/internal/app/thumbnail_flow.go @@ -130,7 +130,7 @@ func (a *App) CopyVMScreenshot(name string) error { if err := png.Encode(&buf, img); err != nil { return fmt.Errorf("encode PNG: %w", err) } - if err := (guesttools.OSClipboard{}).WritePNG(buf.Bytes()); err != nil { + if err := (&guesttools.OSClipboard{}).WritePNG(buf.Bytes()); err != nil { return fmt.Errorf("copy image to clipboard: %w", err) } a.emitLog(name, "Copied VM screenshot to clipboard") diff --git a/internal/app/ui_health.go b/internal/app/ui_health.go new file mode 100644 index 0000000..87bca97 --- /dev/null +++ b/internal/app/ui_health.go @@ -0,0 +1,203 @@ +package app + +import ( + "context" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/Nwflower/reims-go/internal/driver/reims" + wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" +) + +const ( + uiHealthInterval = 30 * time.Second + uiHealthStaleAfter = 25 * time.Second + uiHealthPingTimeout = 5 * time.Second + uiReloadCooldown = 20 * time.Second + maxConsecutiveReload = 3 +) + +type uiHealthState struct { + mu sync.Mutex + windowHidden bool + suspended bool + ready bool + lastAliveAt time.Time + lastReloadAt time.Time + consecutiveReload int + probing bool +} + +func (a *App) setWindowHidden(hidden bool) { + a.uiHealth.mu.Lock() + a.uiHealth.windowHidden = hidden + if !hidden { + a.uiHealth.suspended = false + } + a.uiHealth.mu.Unlock() +} + +func (a *App) noteUIAlive() { + a.uiHealth.mu.Lock() + a.uiHealth.ready = true + a.uiHealth.lastAliveAt = time.Now() + a.uiHealth.consecutiveReload = 0 + a.uiHealth.mu.Unlock() +} + +func (a *App) onSystemSuspend() { + a.uiHealth.mu.Lock() + a.uiHealth.suspended = true + a.uiHealth.mu.Unlock() +} + +func (a *App) onSystemResume() { + a.uiHealth.mu.Lock() + a.uiHealth.suspended = false + hidden := a.uiHealth.windowHidden + a.uiHealth.mu.Unlock() + if !hidden { + a.scheduleUIHealthProbe("system resume", 2*time.Second) + } +} + +func (a *App) startUIHealthWatchdog(ctx context.Context) { + if a.ctx == nil { + return + } + wailsRuntime.EventsOn(a.ctx, "reims:ui-pong", func(_ ...any) { + a.noteUIAlive() + }) + wailsRuntime.EventsOn(a.ctx, "reims:ui-error", func(args ...any) { + var parts []string + for _, arg := range args { + if s, ok := arg.(string); ok && strings.TrimSpace(s) != "" { + parts = append(parts, strings.TrimSpace(s)) + } + } + if len(parts) == 0 { + return + } + msg := reims.RedactText(strings.Join(parts, " | ")) + a.emitLog("ui", "Frontend error: "+msg) + a.appendUICrashLog(msg) + }) + go a.watchUIHealth(ctx) +} + +func (a *App) watchUIHealth(ctx context.Context) { + ticker := time.NewTicker(uiHealthInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + a.uiHealth.mu.Lock() + shouldProbe := a.uiHealth.ready && + !a.uiHealth.windowHidden && + !a.uiHealth.suspended && + time.Since(a.uiHealth.lastAliveAt) > uiHealthStaleAfter + a.uiHealth.mu.Unlock() + if shouldProbe { + a.probeUIHealth(ctx, "periodic watchdog") + } + } + } +} + +func (a *App) scheduleUIHealthProbe(reason string, delay time.Duration) { + go func() { + timer := time.NewTimer(delay) + defer timer.Stop() + <-timer.C + a.probeUIHealth(a.baseCtx(), reason) + }() +} + +// probeUIHealth pings the WebView2 frontend and reloads the app if the window is +// visible, unminimized, and completely unresponsive (e.g. WebView2 renderer crash). +func (a *App) probeUIHealth(ctx context.Context, reason string) { + if a.ctx == nil { + return + } + a.uiHealth.mu.Lock() + if !a.uiHealth.ready || a.uiHealth.windowHidden || a.uiHealth.suspended || a.uiHealth.probing { + a.uiHealth.mu.Unlock() + return + } + if time.Since(a.uiHealth.lastReloadAt) < uiReloadCooldown || a.uiHealth.consecutiveReload >= maxConsecutiveReload { + a.uiHealth.mu.Unlock() + return + } + a.uiHealth.probing = true + pingSentAt := time.Now() + a.uiHealth.mu.Unlock() + + defer func() { + a.uiHealth.mu.Lock() + a.uiHealth.probing = false + a.uiHealth.mu.Unlock() + }() + + if wailsRuntime.WindowIsMinimised(a.ctx) { + return + } + wailsRuntime.EventsEmit(a.ctx, "reims:ui-ping", pingSentAt.UnixMilli()) + + timer := time.NewTimer(uiHealthPingTimeout) + defer timer.Stop() + select { + case <-ctx.Done(): + return + case <-timer.C: + } + + if wailsRuntime.WindowIsMinimised(a.ctx) { + return + } + a.uiHealth.mu.Lock() + if a.uiHealth.windowHidden || a.uiHealth.suspended || !a.uiHealth.lastAliveAt.Before(pingSentAt) { + a.uiHealth.mu.Unlock() + return + } + a.uiHealth.lastReloadAt = time.Now() + a.uiHealth.consecutiveReload++ + attempt := a.uiHealth.consecutiveReload + a.uiHealth.mu.Unlock() + + msg := fmt.Sprintf("WebView2 renderer unresponsive (%s, attempt %d/%d); reloading UI", reason, attempt, maxConsecutiveReload) + a.emitLog("ui", msg) + a.appendUICrashLog(msg) + wailsRuntime.WindowReloadApp(a.ctx) +} + +func (a *App) appendUICrashLog(msg string) { + a.mu.Lock() + root := "" + if a.cfg != nil { + root = a.cfg.DataRoot + } + a.mu.Unlock() + if strings.TrimSpace(root) == "" { + return + } + logDir := filepath.Join(root, "logs") + if err := os.MkdirAll(logDir, 0o755); err != nil { + return + } + logPath := filepath.Join(logDir, "ui-health.log") + if st, err := os.Stat(logPath); err == nil && st.Size() >= 1<<20 { + _ = os.Rename(logPath, logPath+".1") + } + f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o644) + if err != nil { + return + } + defer f.Close() + _, _ = fmt.Fprintf(f, "%s %s\n", time.Now().UTC().Format(time.RFC3339), msg) +} diff --git a/internal/cli/plugin.go b/internal/cli/plugin.go index 4aeaee0..70c0f0d 100644 --- a/internal/cli/plugin.go +++ b/internal/cli/plugin.go @@ -15,7 +15,6 @@ import ( "github.com/Nwflower/reims-go/internal/i18n" "github.com/Nwflower/reims-go/internal/plugin" "github.com/Nwflower/reims-go/internal/plugin/builtin" - "github.com/Nwflower/reims-go/internal/plugin/bundled" "github.com/Nwflower/reims-go/internal/version" ) @@ -65,9 +64,6 @@ func openCLIPluginManager(cfg *config.Config, safeMode bool) (*plugin.Manager, * mgr.Close() return nil, nil, err } - if list, err := bundled.BundledManifests(); err == nil { - _ = mgr.LoadBundled(list) - } _ = mgr.LoadExternal() mgr.Registry().Reconcile(context.Background()) @@ -168,7 +164,8 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { if len(args) < 2 { return fmt.Errorf("usage: reims-go plugin disable ") } - mgr, _, err := openCLIPluginManager(cfg, false) + // Load in safeMode so a broken external plugin never prevents disabling it (M9). + mgr, _, err := openCLIPluginManager(cfg, true) if err != nil { return err } @@ -203,7 +200,7 @@ func cmdPlugin(cfg *config.Config, loc i18n.Locale, args []string) error { if len(args) < 2 { return fmt.Errorf("usage: reims-go plugin info ") } - mgr, _, err := openCLIPluginManager(cfg, false) + mgr, _, err := openCLIPluginManager(cfg, true) if err != nil { return err } diff --git a/internal/cli/plugin_test.go b/internal/cli/plugin_test.go index 9bc650d..31caa4f 100644 --- a/internal/cli/plugin_test.go +++ b/internal/cli/plugin_test.go @@ -8,20 +8,20 @@ import ( func TestCLIPluginListEnableDisableAndDoctor(t *testing.T) { dataRoot := t.TempDir() - // `plugin list` should succeed and include builtins + bundled wheel-invert. + // `plugin list` should succeed and include builtins. if code := Main([]string{"--data-root", dataRoot, "plugin", "list", "--json"}); code != 0 { t.Fatalf("plugin list exited %d", code) } - // Enable and disable bundled wheel-invert plugin via CLI. - if code := Main([]string{"--data-root", dataRoot, "plugin", "enable", "reims.input.wheel-invert"}); code != 0 { - t.Fatalf("plugin enable wheel-invert exited %d", code) + // Disable and re-enable builtin clipboard plugin via CLI. + if code := Main([]string{"--data-root", dataRoot, "plugin", "disable", "builtin.bridge.clipboard"}); code != 0 { + t.Fatalf("plugin disable clipboard exited %d", code) } - if code := Main([]string{"--data-root", dataRoot, "plugin", "disable", "reims.input.wheel-invert"}); code != 0 { - t.Fatalf("plugin disable wheel-invert exited %d", code) + if code := Main([]string{"--data-root", dataRoot, "plugin", "enable", "builtin.bridge.clipboard"}); code != 0 { + t.Fatalf("plugin enable clipboard exited %d", code) } - // Builtin/bundled cannot be removed. - if code := Main([]string{"--data-root", dataRoot, "plugin", "remove", "reims.input.wheel-invert"}); code == 0 { - t.Fatal("expected removing bundled plugin to fail") + // Builtin cannot be removed. + if code := Main([]string{"--data-root", dataRoot, "plugin", "remove", "builtin.bridge.clipboard"}); code == 0 { + t.Fatal("expected removing builtin plugin to fail") } // Safe mode window flag round-trips cleanly. w, ok := ParseWindowArgs([]string{"--safe-mode"}) diff --git a/internal/guesttools/image.go b/internal/guesttools/image.go index 94c3c04..bb9fc8e 100644 --- a/internal/guesttools/image.go +++ b/internal/guesttools/image.go @@ -278,6 +278,11 @@ apply_host_config() { cfg_json=$(curl -fsS -m 3 -H "Authorization: Bearer $REIMS_TOKEN" "$REIMS_HOST_URL/v1/config" 2>/dev/null || true) [ -n "$cfg_json" ] || return 0 sync_drive_mounts "$cfg_json" + if printf '%s' "$cfg_json" | grep -q '"clipboard_enabled"[[:space:]]*:[[:space:]]*false'; then + clip_enabled="0" + else + clip_enabled="1" + fi if printf '%s' "$cfg_json" | grep -q '"prevent_sleep"[[:space:]]*:[[:space:]]*true'; then if [ -z "$CAFFEINATE_PID" ] || ! kill -0 "$CAFFEINATE_PID" 2>/dev/null; then if command -v caffeinate >/dev/null 2>&1; then @@ -304,7 +309,7 @@ report_status() { curl -fsS -m 3 -X POST \ -H "Authorization: Bearer $REIMS_TOKEN" \ -H "Content-Type: application/json" \ - -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":4}" \ + -d "{\"mount_mode\":\"$mount_mode\",\"sleep_active\":$sleep_active,\"agent_version\":5}" \ "$REIMS_HOST_URL/v1/status" >/dev/null 2>&1 || true } @@ -355,6 +360,7 @@ write_local_png() { } last_clip_hash="" +clip_enabled="1" tick=0 TAB=$(printf '\t') @@ -405,8 +411,13 @@ sync_clipboard() { elif [ -n "$new_hash" ]; then last_clip_hash="$new_hash" fi + elif [ "$code" = "503" ]; then + # Feature disabled on host: back off instead of busy-looping osascript + curl (M11). + sleep 5 elif [ "$code" = "304" ] && [ -z "$last_clip_hash" ]; then last_clip_hash="$cur_hash" + elif [ "$code" = "000" ]; then + sleep 2 fi } @@ -515,7 +526,11 @@ while :; do apply_host_config report_status fi - sync_clipboard + if [ "$clip_enabled" = "1" ]; then + sync_clipboard + else + sleep 3 + fi if [ "$mount_mode" != "webdav" ] && [ $((tick % 2)) -eq 0 ]; then sync_files fi diff --git a/internal/guesttools/server.go b/internal/guesttools/server.go index 71806f9..153c7c4 100644 --- a/internal/guesttools/server.go +++ b/internal/guesttools/server.go @@ -780,13 +780,6 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { } switch r.Method { case http.MethodGet: - if policy.Direction == ClipboardGuestToHost { - w.WriteHeader(http.StatusNoContent) - return - } - acceptImage := policy.SyncImages && (strings.EqualFold(r.URL.Query().Get("accept"), "image") || - strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")) - since := r.URL.Query().Get("since") waitSec := 0 if rawWait := r.URL.Query().Get("wait"); rawWait != "" { if n, err := strconv.Atoi(rawWait); err == nil && n > 0 { @@ -796,6 +789,27 @@ func (s *Server) handleClipboard(w http.ResponseWriter, r *http.Request) { waitSec = n } } + if policy.Direction == ClipboardGuestToHost { + // Hold the long-poll instead of returning 204 immediately so the + // guest agent loop does not busy-spin CPU in guest-to-host mode (M11). + if waitSec > 0 { + ch := s.clipNotifyChan() + timer := time.NewTimer(time.Duration(waitSec) * time.Second) + select { + case <-ch: + timer.Stop() + case <-timer.C: + case <-r.Context().Done(): + timer.Stop() + return + } + } + w.WriteHeader(http.StatusNoContent) + return + } + acceptImage := policy.SyncImages && (strings.EqualFold(r.URL.Query().Get("accept"), "image") || + strings.Contains(strings.ToLower(r.Header.Get("Accept")), "image/png")) + since := r.URL.Query().Get("since") deadline := time.Now().Add(time.Duration(waitSec) * time.Second) for { diff --git a/internal/host/display_windows.go b/internal/host/display_windows.go index f1226af..e0046de 100644 --- a/internal/host/display_windows.go +++ b/internal/host/display_windows.go @@ -3,6 +3,7 @@ package host import ( + "sync" "syscall" "unsafe" ) @@ -67,75 +68,97 @@ type devModeW struct { Extra [8]uint32 } -func probeDisplays() []DisplayInfo { - var displays []DisplayInfo - cb := syscall.NewCallback(func(hMon uintptr, hdc uintptr, lprc uintptr, data uintptr) uintptr { - var mi monitorInfoExW - mi.Size = uint32(unsafe.Sizeof(mi)) - r, _, _ := procGetMonitorInfoW.Call(hMon, uintptr(unsafe.Pointer(&mi))) - if r == 0 { - return 1 - } - name := syscall.UTF16ToString(mi.Device[:]) - w := int(mi.Monitor.Right - mi.Monitor.Left) - h := int(mi.Monitor.Bottom - mi.Monitor.Top) - refresh := 0 +var ( + displayEnumMu sync.Mutex + displayEnumOnce sync.Once + displayEnumCB uintptr + displayEnumResult *[]DisplayInfo +) - // Query real physical mode dimensions via EnumDisplaySettingsW so DPI - // virtualization never under-reports a 4K/2K display as 1080p. - var dm devModeW - dm.Size = uint16(unsafe.Sizeof(dm)) - if ok, _, _ := procEnumDisplaySettings.Call( - uintptr(unsafe.Pointer(&mi.Device[0])), - uintptr(enumCurrentSettings), - uintptr(unsafe.Pointer(&dm)), - ); ok != 0 && dm.PelsWidth > 0 && dm.PelsHeight > 0 { - w = int(dm.PelsWidth) - h = int(dm.PelsHeight) - refresh = int(dm.DisplayFrequency) - } - - scalePct := 100 - if procGetDpiForMonitor.Find() == nil { - var dpiX, dpiY uint32 - hr, _, _ := procGetDpiForMonitor.Call( - hMon, - uintptr(mdtEffectiveDPI), - uintptr(unsafe.Pointer(&dpiX)), - uintptr(unsafe.Pointer(&dpiY)), - ) - if hr == 0 && dpiX >= 96 { - scalePct = int((dpiX*100 + 48) / 96) - } - } else if hdcScreen, _, _ := procGetDC.Call(0); hdcScreen != 0 { - dpi, _, _ := procGetDeviceCaps.Call(hdcScreen, uintptr(logPixelsX)) - procReleaseDC.Call(0, hdcScreen) - if dpi >= 96 { - scalePct = int((dpi*100 + 48) / 96) - } - } - - if w > 0 && h > 0 { - // The work area in the same units as the monitor rectangle (pixels for a - // DPI-aware process, scaled points otherwise), carried over to w x h. - var workW, workH int - if monW, monH := int(mi.Monitor.Right-mi.Monitor.Left), int(mi.Monitor.Bottom-mi.Monitor.Top); monW > 0 && monH > 0 { - workW = int(mi.Work.Right-mi.Work.Left) * w / monW - workH = int(mi.Work.Bottom-mi.Work.Top) * h / monH - } - displays = append(displays, DisplayInfo{ - Name: name, - Width: w, - Height: h, - ScalePct: scalePct, - RefreshHz: refresh, - Primary: mi.Flags&monitorInfoPrimary != 0, - WorkWidth: workW, - WorkHeight: workH, - }) - } +func enumDisplayMonitorProc(hMon uintptr, _ uintptr, _ uintptr, _ uintptr) uintptr { + out := displayEnumResult + if out == nil { + return 0 + } + var mi monitorInfoExW + mi.Size = uint32(unsafe.Sizeof(mi)) + r, _, _ := procGetMonitorInfoW.Call(hMon, uintptr(unsafe.Pointer(&mi))) + if r == 0 { return 1 + } + name := syscall.UTF16ToString(mi.Device[:]) + w := int(mi.Monitor.Right - mi.Monitor.Left) + h := int(mi.Monitor.Bottom - mi.Monitor.Top) + refresh := 0 + + // Query real physical mode dimensions via EnumDisplaySettingsW so DPI + // virtualization never under-reports a 4K/2K display as 1080p. + var dm devModeW + dm.Size = uint16(unsafe.Sizeof(dm)) + if ok, _, _ := procEnumDisplaySettings.Call( + uintptr(unsafe.Pointer(&mi.Device[0])), + uintptr(enumCurrentSettings), + uintptr(unsafe.Pointer(&dm)), + ); ok != 0 && dm.PelsWidth > 0 && dm.PelsHeight > 0 { + w = int(dm.PelsWidth) + h = int(dm.PelsHeight) + refresh = int(dm.DisplayFrequency) + } + + scalePct := 100 + if procGetDpiForMonitor.Find() == nil { + var dpiX, dpiY uint32 + hr, _, _ := procGetDpiForMonitor.Call( + hMon, + uintptr(mdtEffectiveDPI), + uintptr(unsafe.Pointer(&dpiX)), + uintptr(unsafe.Pointer(&dpiY)), + ) + if hr == 0 && dpiX >= 96 { + scalePct = int((dpiX*100 + 48) / 96) + } + } else if hdcScreen, _, _ := procGetDC.Call(0); hdcScreen != 0 { + dpi, _, _ := procGetDeviceCaps.Call(hdcScreen, uintptr(logPixelsX)) + procReleaseDC.Call(0, hdcScreen) + if dpi >= 96 { + scalePct = int((dpi*100 + 48) / 96) + } + } + + if w > 0 && h > 0 { + // The work area in the same units as the monitor rectangle (pixels for a + // DPI-aware process, scaled points otherwise), carried over to w x h. + var workW, workH int + if monW, monH := int(mi.Monitor.Right-mi.Monitor.Left), int(mi.Monitor.Bottom-mi.Monitor.Top); monW > 0 && monH > 0 { + workW = int(mi.Work.Right-mi.Work.Left) * w / monW + workH = int(mi.Work.Bottom-mi.Work.Top) * h / monH + } + *out = append(*out, DisplayInfo{ + Name: name, + Width: w, + Height: h, + ScalePct: scalePct, + RefreshHz: refresh, + Primary: mi.Flags&monitorInfoPrimary != 0, + WorkWidth: workW, + WorkHeight: workH, + }) + } + return 1 +} + +// probeDisplays enumerates connected monitors reusing a single syscall.NewCallback +// slot for the lifetime of the process (Go's Windows callback table has a fixed +// 2000-slot limit and never frees allocated callbacks). +func probeDisplays() []DisplayInfo { + displayEnumOnce.Do(func() { + displayEnumCB = syscall.NewCallback(enumDisplayMonitorProc) }) - _, _, _ = procEnumDisplayMonitors.Call(0, 0, cb, 0) + displayEnumMu.Lock() + defer displayEnumMu.Unlock() + var displays []DisplayInfo + displayEnumResult = &displays + defer func() { displayEnumResult = nil }() + _, _, _ = procEnumDisplayMonitors.Call(0, 0, displayEnumCB, 0) return displays } diff --git a/internal/host/foreground_windows.go b/internal/host/foreground_windows.go index 1c24c12..f43e568 100644 --- a/internal/host/foreground_windows.go +++ b/internal/host/foreground_windows.go @@ -3,6 +3,7 @@ package host import ( + "sync" "syscall" "unsafe" ) @@ -31,27 +32,43 @@ func ForegroundPID() uint32 { return pid } +var ( + focusEnumMu sync.Mutex + focusEnumOnce sync.Once + focusEnumCB uintptr + focusEnumTargetPID uint32 + focusEnumFound uintptr +) + +func enumFocusWindowProc(hwnd uintptr, _ uintptr) uintptr { + vis, _, _ := procIsWindowVisible.Call(hwnd) + if vis == 0 { + return 1 + } + var winPID uint32 + _, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&winPID))) + if winPID == focusEnumTargetPID { + focusEnumFound = hwnd + return 0 + } + return 1 +} + // FocusProcessWindow finds the primary visible top-level window belonging to // pid, restores it if minimized, and brings it to the foreground. func FocusProcessWindow(pid uint32) bool { if pid == 0 { return false } - var found uintptr - cb := syscall.NewCallback(func(hwnd uintptr, _ uintptr) uintptr { - vis, _, _ := procIsWindowVisible.Call(hwnd) - if vis == 0 { - return 1 - } - var winPID uint32 - _, _, _ = procGetWindowThreadProcessId.Call(hwnd, uintptr(unsafe.Pointer(&winPID))) - if winPID == pid { - found = hwnd - return 0 - } - return 1 + focusEnumOnce.Do(func() { + focusEnumCB = syscall.NewCallback(enumFocusWindowProc) }) - _, _, _ = procEnumWindows.Call(cb, 0) + focusEnumMu.Lock() + focusEnumTargetPID = pid + focusEnumFound = 0 + _, _, _ = procEnumWindows.Call(focusEnumCB, 0) + found := focusEnumFound + focusEnumMu.Unlock() if found == 0 { return false } diff --git a/internal/host/host_windows.go b/internal/host/host_windows.go index 4800674..3e70c0e 100644 --- a/internal/host/host_windows.go +++ b/internal/host/host_windows.go @@ -10,6 +10,7 @@ import ( "runtime" "sort" "strings" + "sync" "syscall" "unsafe" ) @@ -61,23 +62,73 @@ type memoryStatusEx struct { AvailExtendedVirtual uint64 } +type staticHostSnapshot struct { + needsColdReboot bool + gpus []GPUInfo + recGPU *GPUInfo + topo hybridTopology + topoOK bool +} + +var ( + staticHostOnce sync.Once + staticHostData staticHostSnapshot + + whpxCapsMu sync.Mutex + whpxCapsCached bool + whpxCapsVal WHPXCapabilities +) + +func getStaticHostSnapshot() staticHostSnapshot { + staticHostOnce.Do(func() { + gpus := probeVulkanGPUs() + topo, ok := probeHybridTopology() + staticHostData = staticHostSnapshot{ + needsColdReboot: probeNeedsColdRebootWorkaround(), + gpus: gpus, + recGPU: PickRecommendedGPU(gpus), + topo: topo, + topoOK: ok, + } + }) + return staticHostData +} + +func getCachedWHPXCapabilities() WHPXCapabilities { + whpxCapsMu.Lock() + defer whpxCapsMu.Unlock() + if !whpxCapsCached { + whpxCapsVal = probeWHPXCapabilities() + whpxCapsCached = true + } + return whpxCapsVal +} + // Inspect collects Windows host capabilities without requiring administrator privileges. func Inspect(dataRoot string) Report { + st := getStaticHostSnapshot() + gpusCopy := append([]GPUInfo(nil), st.gpus...) + var recGPUCopy *GPUInfo + if st.recGPU != nil { + cp := *st.recGPU + recGPUCopy = &cp + } rep := Report{ OS: "windows", Arch: runtime.GOARCH, LogicalCPUs: runtime.NumCPU(), DataRoot: dataRoot, WHPX: probeWHPX(), - NeedsColdRebootWorkaround: probeNeedsColdRebootWorkaround(), - GPUs: probeVulkanGPUs(), + NeedsColdRebootWorkaround: st.needsColdReboot, + GPUs: gpusCopy, + RecommendedGPU: recGPUCopy, } if rep.WHPX == WHPXReady { - rep.WHPXCaps = probeWHPXCapabilities() + rep.WHPXCaps = getCachedWHPXCapabilities() } - rep.RecommendedGPU = PickRecommendedGPU(rep.GPUs) - if topo, ok := probeHybridTopology(); ok { + if st.topoOK { + topo := st.topo rep.PhysicalCores = topo.phys rep.PCoreCount = topo.pCount rep.ECoreCount = topo.eCount @@ -85,14 +136,14 @@ func Inspect(dataRoot string) Report { rep.HasHybridCores = topo.eCount > 0 || topo.lpeCount > 0 rep.PCoreMask = topo.pMask rep.PCoreMaskHex = fmt.Sprintf("0x%X", topo.pMask) - rep.PCoreLogicalCPUs = topo.pLPs - rep.ECoreLogicalCPUs = topo.eLPs + rep.PCoreLogicalCPUs = append([]int(nil), topo.pLPs...) + rep.ECoreLogicalCPUs = append([]int(nil), topo.eLPs...) if topo.lpeCount > 0 && topo.nonLPEMask > 0 { rep.NonLPEMask = topo.nonLPEMask rep.NonLPEMaskHex = fmt.Sprintf("0x%X", topo.nonLPEMask) - rep.NonLPELogicalCPUs = topo.nonLPELPs + rep.NonLPELogicalCPUs = append([]int(nil), topo.nonLPELPs...) } - rep.CPUTopology = topo.cpus + rep.CPUTopology = append([]LogicalCPUInfo(nil), topo.cpus...) } if len(rep.CPUTopology) == 0 { rep.CPUTopology = DefaultCPUTopology(rep.LogicalCPUs) diff --git a/internal/host/host_windows_test.go b/internal/host/host_windows_test.go index f42fb9f..913fd29 100644 --- a/internal/host/host_windows_test.go +++ b/internal/host/host_windows_test.go @@ -33,3 +33,11 @@ func TestWindowsProcessAffinityAndTopology(t *testing.T) { } } } + +func TestProbeDisplaysNoCallbackLeak(t *testing.T) { + // Go's Windows syscall callback table holds at most 2000 permanent entries. + // Exceeding 2000 iterations verifies probeDisplays reuses a single callback slot. + for i := 0; i < 2100; i++ { + _ = probeDisplays() + } +} diff --git a/internal/host/input_service.go b/internal/host/input_service.go index 47d816b..40793ca 100644 --- a/internal/host/input_service.go +++ b/internal/host/input_service.go @@ -7,8 +7,7 @@ import ( ) // InputFilterRule is a host-evaluated declarative input filter contributed by -// L1 plugins (e.g. reims.input.wheel-invert). No plugin code ever runs inside -// the low-level Win32 hook callback (docs/plugin-architecture.md §5.4). +// L1 plugins. No plugin code ever runs inside the low-level Win32 hook callback. type InputFilterRule struct { ID string `json:"id"` PluginID string `json:"plugin_id"` diff --git a/internal/host/input_service_test.go b/internal/host/input_service_test.go index 6b74a94..db2e48d 100644 --- a/internal/host/input_service_test.go +++ b/internal/host/input_service_test.go @@ -4,8 +4,8 @@ import "testing" func TestEvalWheelFilterAndOnDemandLifecycle(t *testing.T) { rules := []InputFilterRule{{ - ID: "wheel-invert", - PluginID: "reims.input.wheel-invert", + ID: "sample-wheel-filter", + PluginID: "example.input.wheel-filter", Event: "mouse_wheel", Axis: "vertical", Transform: "invert", diff --git a/internal/plugin/blockers_test.go b/internal/plugin/blockers_test.go index 5ce4a48..4f9330a 100644 --- a/internal/plugin/blockers_test.go +++ b/internal/plugin/blockers_test.go @@ -85,16 +85,21 @@ func TestValidateArgFragmentBlocksInjection(t *testing.T) { t.Errorf("ValidateArgFragment(%q) expected error, got nil", toks) } } - good := [][]string{ - {"-machine", "kernel-irqchip=off"}, - {"-no-reboot", "-qmp", "unix:D:/Data/reims-go-reboot.sock,server=on,wait=off"}, - {"-drive", `"id=reimshelp,if=none,format=raw,readonly=on,file=D:/My VMs/reimshelp.img"`, "-device", "usb-storage,id=reimshelp-dev,drive=reimshelp,bus=xhci.0"}, + good := []ArgFragment{ + {Tokens: []string{"-machine", "kernel-irqchip=off"}}, + {Tokens: []string{"-no-reboot"}}, + {Builtin: true, Tokens: []string{"-no-reboot", "-qmp", "unix:D:/Data/reims-go-reboot.sock,server=on,wait=off"}}, + {Builtin: true, Tokens: []string{"-drive", `"id=reimshelp,if=none,format=raw,readonly=on,file=D:/My VMs/reimshelp.img"`, "-device", "usb-storage,id=reimshelp-dev,drive=reimshelp,bus=xhci.0"}}, } - for _, toks := range good { - if err := ValidateArgFragment(ArgFragment{Tokens: toks}); err != nil { - t.Errorf("ValidateArgFragment(%q) unexpected error: %v", toks, err) + for _, f := range good { + if err := ValidateArgFragment(f); err != nil { + t.Errorf("ValidateArgFragment(%+v) unexpected error: %v", f, err) } } + // External (non-builtin) plugin must be rejected from file/socket options (M1). + if err := ValidateArgFragment(ArgFragment{Tokens: []string{"-drive", "file=secret.img"}}); err == nil { + t.Error("expected external -drive to be rejected") + } } func TestBuiltinBeforeStartExemptFromExternalTimeout(t *testing.T) { diff --git a/internal/plugin/builtin/builtin.go b/internal/plugin/builtin/builtin.go index ac3a0e0..0902053 100644 --- a/internal/plugin/builtin/builtin.go +++ b/internal/plugin/builtin/builtin.go @@ -50,8 +50,10 @@ const ( type HostCallbacks struct { GetConfig func() config.Config Log func(source, line string) - EnsureGuestTools func() (*guesttools.Server, int, error) - OnIMEText func(target host.IMETarget, text string) + EnsureGuestTools func() (*guesttools.Server, int, error) + StopGuestTools func() + ValidateDriveConfig func(guesttools.VMConfig) guesttools.VMConfig + OnIMEText func(target host.IMETarget, text string) StartColdReboot func(vmName, qmpAddr string) CancelColdReboot func(vmName string) VMSharedDir func(vmName string) string @@ -182,6 +184,11 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo srv = guesttools.NewTransportServer(nil) } sc.Provide(ServiceGuestToolsTransport, "1.0.0", srv) + sc.OnDispose(func() { + if cb.StopGuestTools != nil { + cb.StopGuestTools() + } + }) sc.Registry().RegisterVMCard(sc, plugin.VMCardContribution{ ID: "guest-tools-transport", @@ -216,6 +223,9 @@ func defGuestTools(ver string, cb HostCallbacks, desiredFn func(string, bool) bo } gtCfg, err := guesttools.LoadOrCreateVMConfig(p.VMDir, p.VMName, sharedDir, port) if err == nil && gtCfg.Token != "" { + if cb.ValidateDriveConfig != nil { + gtCfg = cb.ValidateDriveConfig(gtCfg) + } s.RegisterVM(gtCfg) intent.Env["REIMS_GO_INPUT_URL"] = fmt.Sprintf("http://127.0.0.1:%d/v1/host-text", port) intent.Env["REIMS_GO_INPUT_TOKEN"] = gtCfg.Token diff --git a/internal/plugin/builtin/builtin_test.go b/internal/plugin/builtin/builtin_test.go index 89255b6..9b23cfb 100644 --- a/internal/plugin/builtin/builtin_test.go +++ b/internal/plugin/builtin/builtin_test.go @@ -9,7 +9,6 @@ import ( "github.com/Nwflower/reims-go/internal/guesttools" "github.com/Nwflower/reims-go/internal/host" "github.com/Nwflower/reims-go/internal/plugin" - "github.com/Nwflower/reims-go/internal/plugin/bundled" ) func TestBuiltinClipboardAndInputLifecycleZeroResidue(t *testing.T) { @@ -81,18 +80,6 @@ func TestBuiltinClipboardAndInputLifecycleZeroResidue(t *testing.T) { t.Fatal("expected host.input service removed after disable") } - // Bundled wheel-invert manifest parses cleanly and defaults to disabled. - manifests, err := bundled.BundledManifests() - if err != nil || len(manifests) != 1 { - t.Fatalf("BundledManifests = %d, err=%v", len(manifests), err) - } - if manifests[0].ID != bundled.WheelInvertPluginID || manifests[0].DefaultEnabled { - t.Fatalf("unexpected wheel-invert manifest: %+v", manifests[0]) - } - if manifests[0].InferTier(false) != plugin.TierL1 { - t.Fatalf("wheel-invert tier = %s, want L1", manifests[0].InferTier(false)) - } - // WHPX fallback hook uses runtime capability rather than patch name substring. intents, err := reg.Hooks().DispatchBeforeStart(context.Background(), plugin.BeforeStartPayload{ VMName: "mac1", diff --git a/internal/plugin/bundled/bundled.go b/internal/plugin/bundled/bundled.go deleted file mode 100644 index cbefb64..0000000 --- a/internal/plugin/bundled/bundled.go +++ /dev/null @@ -1,47 +0,0 @@ -// Package bundled embeds official L1 plugin packages shipped inside reims-go.exe -// (docs/plugin-architecture.md §5.4, §9). They exercise the exact same manifest -// parsing, permission checking, settings rendering, and enable/disable lifecycle -// as external packages, with trust=official and removable=false. -package bundled - -import ( - "embed" - "encoding/json" - "fmt" - "strings" - - "github.com/Nwflower/reims-go/internal/plugin" - "github.com/Nwflower/reims-go/internal/version" -) - -//go:embed wheel-invert/plugin.json -var bundledFS embed.FS - -// WheelInvertPluginID is the ID of the bundled mouse-wheel inversion L1 plugin. -const WheelInvertPluginID = "reims.input.wheel-invert" - -// BundledManifests returns all official bundled L1 plugin manifests embedded in -// the binary, with version aligned to the host application version. -func BundledManifests() ([]plugin.Manifest, error) { - paths := []string{ - "wheel-invert/plugin.json", - } - out := make([]plugin.Manifest, 0, len(paths)) - appVer := strings.TrimPrefix(strings.TrimSpace(version.Version), "v") - if appVer == "" || appVer == "dev" { - appVer = "0.2.6" - } - for _, p := range paths { - raw, err := bundledFS.ReadFile(p) - if err != nil { - return nil, fmt.Errorf("read bundled manifest %s: %w", p, err) - } - var m plugin.Manifest - if err := json.Unmarshal(raw, &m); err != nil { - return nil, fmt.Errorf("parse bundled manifest %s: %w", p, err) - } - m.Version = appVer - out = append(out, m) - } - return out, nil -} diff --git a/internal/plugin/bundled/wheel-invert/plugin.json b/internal/plugin/bundled/wheel-invert/plugin.json deleted file mode 100644 index 70539ca..0000000 --- a/internal/plugin/bundled/wheel-invert/plugin.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "schema": 1, - "id": "reims.input.wheel-invert", - "version": "1.0.0", - "name": { - "zh-CN": "滚轮方向反转", - "en-US": "Mouse wheel invert" - }, - "description": { - "zh-CN": "针对 macOS 自然滚动方向,在前台为目标虚拟机窗口时反转鼠标滚轮增量", - "en-US": "Invert mouse wheel scroll deltas when a target macOS VM window is focused" - }, - "publisher": "Reims-Go", - "license": "Apache-2.0", - "homepage": "https://github.com/Nwflower/reims-go", - "engines": { - "pluginApi": "^1.0.0" - }, - "platforms": ["windows-x64"], - "permissions": ["input:filter"], - "activation": ["onStartup"], - "defaultEnabled": false, - "contributes": { - "inputFilters": [ - { - "id": "wheel-invert-rule", - "event": "mouse_wheel", - "axis": "vertical", - "transform": "invert", - "scope": "vm_foreground", - "settingKey": "enabled", - "verticalKey": "vertical", - "horizontalKey": "horizontal", - "name": { - "zh-CN": "反转滚轮", - "en-US": "Invert wheel" - } - } - ], - "settingsPages": [ - { - "id": "wheel-invert-vm-settings", - "title": { - "zh-CN": "滚轮反转", - "en-US": "Wheel invert" - }, - "group": "keyboard", - "scope": "vm" - } - ] - }, - "settings": { - "title": { - "zh-CN": "滚轮反转", - "en-US": "Wheel invert" - }, - "x-group": "keyboard", - "x-scope": "vm", - "x-order": ["enabled", "vertical", "horizontal"], - "properties": { - "enabled": { - "type": "boolean", - "title": { - "zh-CN": "为此虚拟机反转滚轮方向", - "en-US": "Invert mouse wheel for this VM" - }, - "description": { - "zh-CN": "仅在前台窗口属于该虚拟机时生效,停用后立即卸载钩子", - "en-US": "Active only while this VM window is focused; hook unloads when disabled" - }, - "default": false, - "x-effect": "immediate", - "x-scope": "vm", - "x-group": "keyboard" - }, - "vertical": { - "type": "boolean", - "title": { - "zh-CN": "反转垂直滚轮", - "en-US": "Invert vertical scroll" - }, - "default": true, - "x-effect": "immediate", - "x-scope": "vm", - "x-group": "keyboard" - }, - "horizontal": { - "type": "boolean", - "title": { - "zh-CN": "反转水平滚轮", - "en-US": "Invert horizontal scroll" - }, - "default": false, - "x-effect": "immediate", - "x-scope": "vm", - "x-group": "keyboard" - } - } - } -} diff --git a/internal/plugin/hooks.go b/internal/plugin/hooks.go index e3caf25..a3496d8 100644 --- a/internal/plugin/hooks.go +++ b/internal/plugin/hooks.go @@ -286,6 +286,10 @@ func (b *HookBus) DispatchBeforeStart(ctx context.Context, payload BeforeStartPa defer extChainCancel() } + var ( + extPayload BeforeStartPayload + extPayloadInit bool + ) var intents []StartIntent for _, hr := range subs { var ( @@ -298,7 +302,13 @@ func (b *HookBus) DispatchBeforeStart(ctx context.Context, payload BeforeStartPa if extChainCtx.Err() != nil { break } - res, err = b.invokeWithTimeout(extChainCtx, hr, payload, 2*time.Second) + // Never leak raw host paths, raw ExtraArgs (may contain MACs), or + // sensitive HostFacts to external plugins (§1.2, M3). + if !extPayloadInit { + extPayload = redactBeforeStartPayload(payload) + extPayloadInit = true + } + res, err = b.invokeWithTimeout(extChainCtx, hr, extPayload, 2*time.Second) } if err != nil { continue @@ -317,6 +327,12 @@ func (b *HookBus) DispatchBeforeStart(ctx context.Context, payload BeforeStartPa continue } intent.PluginID = hr.PluginID + // Enforce vm:intent permission for external plugins producing start intents (§7.1, M2). + if !hr.Builtin && b.reg != nil && (len(intent.Args) > 0 || len(intent.Env) > 0 || len(intent.PostStart) > 0 || intent.BlockReason != "") { + if !b.reg.PluginHasPermission(hr.PluginID, "vm:intent") { + continue + } + } if intent.BlockReason != "" && hr.Blocking && hr.BlockingAllowed { return intents, fmt.Errorf("blocked by %s: %s", hr.PluginID, intent.BlockReason) } @@ -407,6 +423,21 @@ func (b *HookBus) runLogBatcher(ch <-chan LogLineEvent) { } } +// redactBeforeStartPayload removes host paths, raw ExtraArgs, and sensitive +// keys before handing a BeforeStartPayload to any external plugin (§1.2, M3). +func redactBeforeStartPayload(p BeforeStartPayload) BeforeStartPayload { + return BeforeStartPayload{ + VMName: p.VMName, + DriverID: p.DriverID, + HasInstaller: p.HasInstaller, + RuntimeKind: p.RuntimeKind, + RuntimeCaps: append([]string(nil), p.RuntimeCaps...), + HostFacts: StripSensitiveFields(p.HostFacts), + VMCaps: append([]string(nil), p.VMCaps...), + State: p.State, + } +} + // invokeBuiltin runs a trusted built-in handler synchronously on parent ctx // (with panic recovery) so I/O-heavy prep steps never time out or race QEMU. func (b *HookBus) invokeBuiltin(ctx context.Context, hr *HookRegistration, payload any) (val any, err error) { diff --git a/internal/plugin/kernel_test.go b/internal/plugin/kernel_test.go index 9379b6a..10c2b41 100644 --- a/internal/plugin/kernel_test.go +++ b/internal/plugin/kernel_test.go @@ -248,7 +248,7 @@ func TestHookBusOrderingTimeoutDegradeAndBlocking(t *testing.T) { // Blocking guard honored only when Blocking && BlockingAllowed. _ = reg.Register(PluginDef{ - Manifest: Manifest{ID: "guard.block", Version: "1.0.0"}, + Manifest: Manifest{ID: "guard.block", Version: "1.0.0", Permissions: []string{"vm:intent"}}, Source: SourceLocal, Desired: true, Activate: func(_ context.Context, sc *Scope) error { @@ -370,8 +370,9 @@ func TestL1RuleHooks(t *testing.T) { reg := NewRegistry(nil) _ = reg.Register(PluginDef{ Manifest: Manifest{ - ID: "l1.rule.sample", - Version: "1.0.0", + ID: "l1.rule.sample", + Version: "1.0.0", + Permissions: []string{"vm:intent"}, Contributes: Contributes{ RuleHooks: []RuleHook{{ ID: "rtc-rule", diff --git a/internal/plugin/ledger.go b/internal/plugin/ledger.go index 3eb6392..731739a 100644 --- a/internal/plugin/ledger.go +++ b/internal/plugin/ledger.go @@ -12,24 +12,31 @@ import ( const ArgLedgerFileName = ".reims-go-arg-ledger.json" -// AllowedQEMUOptionFamilies lists the QEMU argument families plugins are -// allowed to contribute via StartIntent (§4.4). +// AllowedQEMUOptionFamilies lists the QEMU argument families external plugins +// are allowed to contribute via StartIntent (§4.4, M1). File/socket/host-memory +// options (-drive, -chardev, -qmp, -fw_cfg, -object, -global) are restricted to +// compiled-in builtins via BuiltinOnlyQEMUOptionFamilies. var AllowedQEMUOptionFamilies = map[string]bool{ - "-drive": true, - "-device": true, - "-machine": true, - "-qmp": true, - "-no-reboot": true, - "-chardev": true, - "-netdev": true, - "-audiodev": true, - "-display": true, - "-usb": true, - "-fw_cfg": true, - "-smbios": false, // never allow overriding SMBIOS - "-rtc": true, - "-global": true, - "-object": true, + "-device": true, + "-machine": true, + "-no-reboot": true, + "-netdev": true, + "-audiodev": true, + "-display": true, + "-usb": true, + "-smbios": false, // never allow overriding SMBIOS + "-rtc": true, +} + +// BuiltinOnlyQEMUOptionFamilies lists QEMU option families permitted ONLY for +// compiled-in builtins (M1). +var BuiltinOnlyQEMUOptionFamilies = map[string]bool{ + "-drive": true, + "-chardev": true, + "-qmp": true, + "-fw_cfg": true, + "-global": true, + "-object": true, } // AllowedHostEnvVars lists non-namespaced environment variables permitted in @@ -224,7 +231,7 @@ func ValidateArgFragment(frag ArgFragment) error { flagName = flagName[:eq] } allowed, exists := AllowedQEMUOptionFamilies[flagName] - if !exists || !allowed { + if (!exists || !allowed) && !(frag.Builtin && BuiltinOnlyQEMUOptionFamilies[flagName]) { return fmt.Errorf("QEMU option %q is not in plugin allowlist", flagName) } // Value-taking flags without '=' must carry their argument value in this fragment. @@ -478,14 +485,21 @@ func stripOwnedTokens(tokens []string, ledger *ArgLedger) []string { return tokens } // Match longest sequences first so composite fragments don't partially match. + // Remove AT MOST ONE occurrence per recorded fragment so a user's hand-written + // duplicate flag (e.g. `-no-reboot`) is preserved (M13). sort.Slice(seqs, func(i, j int) bool { return len(seqs[i]) > len(seqs[j]) }) + used := make([]bool, len(seqs)) out := make([]string, 0, len(tokens)) for i := 0; i < len(tokens); { matched := false - for _, seq := range seqs { + for idx, seq := range seqs { + if used[idx] { + continue + } if i+len(seq) <= len(tokens) && tokensEqual(tokens[i:i+len(seq)], seq) { + used[idx] = true i += len(seq) matched = true break diff --git a/internal/plugin/manager.go b/internal/plugin/manager.go index 6a4db69..93db6b7 100644 --- a/internal/plugin/manager.go +++ b/internal/plugin/manager.go @@ -176,7 +176,6 @@ func (m *Manager) LoadExternal() error { if !safe { _ = BeginStartupInit(m.layout.Root) - defer EndStartupInit(m.layout.Root) } for _, item := range entries { @@ -628,17 +627,29 @@ func (m *Manager) Disable(ctx context.Context, id string) error { return err } +// MarkBootComplete clears the plugin startup crash sentinel AFTER Reconcile +// has activated plugins cleanly (M8, §9). +func (m *Manager) MarkBootComplete() { + EndStartupInit(m.layout.Root) +} + // Remove uninstalls a removable external plugin (refusing builtins/bundled or in-use plugins). +// Also allows removing orphaned/failed records present only in state.json (M8). func (m *Manager) Remove(ctx context.Context, id string, purgeData bool) error { - info, ok := m.registry.Info(id) - if !ok { - return fmt.Errorf("plugin %q not found", id) - } - if !info.Removable { - return fmt.Errorf("plugin %q is built-in or bundled and cannot be uninstalled (disable it instead)", id) - } - if err := m.registry.Unregister(ctx, id); err != nil { - return err + if info, ok := m.registry.Info(id); ok { + if !info.Removable { + return fmt.Errorf("plugin %q is built-in or bundled and cannot be uninstalled (disable it instead)", id) + } + if err := m.registry.Unregister(ctx, id); err != nil { + return err + } + } else { + m.mu.RLock() + existsInState := m.state != nil && m.state.Plugins[id] != nil + m.mu.RUnlock() + if !existsInState { + return fmt.Errorf("plugin %q not found", id) + } } m.mu.Lock() if m.state == nil { diff --git a/internal/plugin/package.go b/internal/plugin/package.go index da45a86..9156f41 100644 --- a/internal/plugin/package.go +++ b/internal/plugin/package.go @@ -307,11 +307,15 @@ func InstallArchive(layout PluginsLayout, archivePath string, opts PackageInstal trust := TrustCommunity sigPath := filepath.Join(stageDir, "SHA256SUMS.sig") if sigRaw, sigErr := os.ReadFile(sigPath); sigErr == nil { - t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, opts.Keyring) - if vErr != nil { - return nil, fmt.Errorf("invalid package signature: %w", vErr) + if len(opts.Keyring) > 0 { + t, vErr := verifyEd25519Signature(sumsRaw, sigRaw, opts.Keyring) + if vErr != nil { + return nil, fmt.Errorf("invalid package signature: %w", vErr) + } + trust = t + } else if !opts.AllowUnsigned { + return nil, errors.New("package signature present but no trusted keyring configured") } - trust = t } else if !errors.Is(sigErr, os.ErrNotExist) { return nil, sigErr } else if !opts.AllowUnsigned && len(opts.Keyring) > 0 { diff --git a/internal/plugin/registry.go b/internal/plugin/registry.go index 80fcd80..3882859 100644 --- a/internal/plugin/registry.go +++ b/internal/plugin/registry.go @@ -76,7 +76,8 @@ type RegisteredDiagnostics struct { // Registry is the single unified extension-point and lifecycle kernel for both // compiled-in builtins and external/bundled plugins (§3.1, §4.1, §4.2). type Registry struct { - mu sync.RWMutex + reconcileMu sync.Mutex // serializes Reconcile passes (M7) + mu sync.RWMutex entries map[string]*pluginEntry services map[string]serviceRecord // serviceName -> record @@ -176,8 +177,16 @@ func (r *Registry) Register(def PluginDef) error { if def.Manifest.Version == "" { def.Manifest.Version = "0.0.0" } + var oldScope *Scope r.mu.Lock() if existing, ok := r.entries[def.Manifest.ID]; ok { + // If upgrading an already-active plugin, mark for reload by tearing down + // the old scope so Reconcile activates the new definition cleanly (M7). + if existing.scope != nil && (existing.def.Manifest.Version != def.Manifest.Version || existing.def.InstallDir != def.InstallDir || existing.def.EntryHash != def.EntryHash) { + oldScope = existing.scope + existing.scope = nil + existing.state = StateOff + } existing.def = def existing.updatedAt = time.Now() } else { @@ -188,6 +197,9 @@ func (r *Registry) Register(def PluginDef) error { } } r.mu.Unlock() + if oldScope != nil { + oldScope.Dispose() + } return nil } @@ -233,6 +245,10 @@ func (r *Registry) SetDesired(ctx context.Context, id string, enabled bool) erro } e.def.Desired = enabled if enabled { + // Allow retrying a previously failed plugin on explicit re-enable (M7). + if e.state == StateFailed { + e.state = StateOff + } e.errMsg = "" e.degradedReason = "" e.consecutiveErrs = 0 @@ -270,26 +286,47 @@ func (r *Registry) Reconcile(ctx context.Context) { if ctx == nil { ctx = context.Background() } + r.reconcileMu.Lock() + defer r.reconcileMu.Unlock() // Phase 1: Close-first fixed point. - // Dispose any active/degraded plugin that is no longer desired OR whose - // required services are no longer satisfied (cascade unload). + // Dispose leaves first (plugins that no other active plugin depends on) so + // dependent consumers always unload BEFORE their service providers (M7, §4.1). for { var toDispose []*pluginEntry r.mu.RLock() + dependedOn := make(map[string]bool) + for _, e := range r.entries { + if e.scope == nil { + continue + } + for _, req := range e.def.Manifest.Requires { + if svc, ok := r.services[req.Service]; ok && svc.pluginID != e.def.Manifest.ID { + dependedOn[svc.pluginID] = true + } + } + } + var allDue []*pluginEntry for _, e := range r.entries { if e.scope == nil { continue } if !e.def.Desired || !r.requirementsSatisfiedLocked(e.def.Manifest.Requires) { - toDispose = append(toDispose, e) + allDue = append(allDue, e) + if !dependedOn[e.def.Manifest.ID] { + toDispose = append(toDispose, e) + } } } + // Break cycles if every due plugin is mutually depended upon. + if len(toDispose) == 0 && len(allDue) > 0 { + toDispose = allDue + } r.mu.RUnlock() if len(toDispose) == 0 { break } - // Deterministic reverse-ID order for disposal. + // Deterministic reverse-ID order within the same topological wave. sort.Slice(toDispose, func(i, j int) bool { return toDispose[i].def.Manifest.ID > toDispose[j].def.Manifest.ID }) @@ -500,6 +537,35 @@ func (r *Registry) registerManifestContributions(sc *Scope, m Manifest) { rules := append([]RuleHook(nil), m.Contributes.RuleHooks...) r.registerRuleHooks(sc, pid, rules) } + // Register declarative services declared in external Manifest.Provides (M7). + for _, pr := range m.Provides { + if pr.Service == "" { + continue + } + if _, exists := r.LookupService(pr.Service); !exists { + ver := pr.Version + if ver == "" { + ver = m.Version + } + sc.Provide(pr.Service, ver, pid) + } + } +} + +// PluginHasPermission reports whether pluginID declares perm (M2). +func (r *Registry) PluginHasPermission(pluginID, perm string) bool { + r.mu.RLock() + defer r.mu.RUnlock() + e, ok := r.entries[pluginID] + if !ok { + return false + } + for _, p := range e.def.Manifest.Permissions { + if p == perm { + return true + } + } + return false } // MarkDegraded marks an active plugin as degraded with a reason (§4.3). diff --git a/internal/plugin/rpc.go b/internal/plugin/rpc.go index bc78143..991a775 100644 --- a/internal/plugin/rpc.go +++ b/internal/plugin/rpc.go @@ -47,24 +47,26 @@ type RPCConn struct { closeCh chan struct{} closeOnce sync.Once - nextID atomic.Uint64 - mu sync.Mutex - pending map[string]chan rpcEnvelope - handlers map[string]RPCRequestHandler - closed bool - doneCh chan struct{} + nextID atomic.Uint64 + mu sync.Mutex + pending map[string]chan rpcEnvelope + handlers map[string]RPCRequestHandler + inboundSem chan struct{} + closed bool + doneCh chan struct{} } // NewRPCConn starts reader and single-writer goroutines over r and w. func NewRPCConn(r io.Reader, w io.Writer) *RPCConn { c := &RPCConn{ - r: bufio.NewReaderSize(r, 64*1024), - w: w, - writeCh: make(chan []byte, 64), - closeCh: make(chan struct{}), - pending: make(map[string]chan rpcEnvelope), - handlers: make(map[string]RPCRequestHandler), - doneCh: make(chan struct{}), + r: bufio.NewReaderSize(r, 64*1024), + w: w, + writeCh: make(chan []byte, 64), + closeCh: make(chan struct{}), + pending: make(map[string]chan rpcEnvelope), + handlers: make(map[string]RPCRequestHandler), + inboundSem: make(chan struct{}, 32), + doneCh: make(chan struct{}), } go c.writeLoop() go c.readLoop() @@ -208,8 +210,17 @@ func (c *RPCConn) readLoop() { continue } if env.Method != "" { - // Inbound request or notification from peer. - go c.dispatchInbound(env) + // Bounded inbound concurrency so a misbehaving sidecar cannot spawn + // unbounded goroutines in the host (M10). + select { + case c.inboundSem <- struct{}{}: + go func(e rpcEnvelope) { + defer func() { <-c.inboundSem }() + c.dispatchInbound(e) + }(env) + case <-c.closeCh: + return + } continue } if len(env.ID) > 0 { @@ -282,13 +293,30 @@ func (c *RPCConn) Close() { } func readContentLengthFrame(r *bufio.Reader) ([]byte, error) { + const ( + maxHeaderLines = 64 + maxHeaderBytes = 8 * 1024 + ) contentLen := -1 - for { - line, err := r.ReadString('\n') - if err != nil { - return nil, err + for lines := 0; ; lines++ { + if lines >= maxHeaderLines { + return nil, errors.New("RPC header line limit exceeded") } - line = strings.TrimRight(line, "\r\n") + var rawLine []byte + for { + chunk, isPrefix, err := r.ReadLine() + if err != nil { + return nil, err + } + if len(rawLine)+len(chunk) > maxHeaderBytes { + return nil, errors.New("RPC header line exceeds 8 KiB limit") + } + rawLine = append(rawLine, chunk...) + if !isPrefix { + break + } + } + line := string(rawLine) if line == "" { break } diff --git a/internal/plugin/sidecar.go b/internal/plugin/sidecar.go index ef5c2b0..1b2bce7 100644 --- a/internal/plugin/sidecar.go +++ b/internal/plugin/sidecar.go @@ -112,6 +112,20 @@ func (s *SidecarSupervisor) EnsureStarted(ctx context.Context) error { inst, caps, err := s.spawnInstance(ctx) if err != nil { + // Count start/handshake failures toward circuit breaker so broken sidecars + // don't spin infinitely on every hook call (M10). + s.mu.Lock() + if !s.stopped { + s.crashCount++ + s.lastCrash = time.Now() + crashes := s.crashCount + s.mu.Unlock() + if crashes >= s.opts.MaxRestarts && s.opts.Registry != nil { + s.opts.Registry.MarkFailed(s.opts.PluginID, fmt.Sprintf("sidecar failed to start %d times: %v", crashes, err)) + } + } else { + s.mu.Unlock() + } return err } @@ -192,13 +206,41 @@ func (s *SidecarSupervisor) spawnInstance(ctx context.Context) (*sidecarInstance exited: make(chan struct{}), } - // Collect stderr into rotated plugin audit log (§8). + // Collect stderr into rotated plugin audit log using bufio.Reader so lines + // >64 KiB are truncated and drained instead of wedging the pipe (M10, §8). go func() { - sc := bufio.NewScanner(stderr) - sc.Buffer(make([]byte, 0, 16*1024), 64*1024) - for sc.Scan() { - if s.opts.Broker != nil { - s.opts.Broker.Audit(s.opts.PluginID, "STDERR", sc.Text()) + const maxLineBytes = 8 * 1024 + br := bufio.NewReaderSize(stderr, 16*1024) + var buf []byte + truncated := false + for { + chunk, isPrefix, err := br.ReadLine() + if len(chunk) > 0 { + if len(buf) < maxLineBytes { + remain := maxLineBytes - len(buf) + if len(chunk) > remain { + buf = append(buf, chunk[:remain]...) + truncated = true + } else { + buf = append(buf, chunk...) + } + } else { + truncated = true + } + } + if !isPrefix && (len(buf) > 0 || err != nil) { + if len(buf) > 0 && s.opts.Broker != nil { + line := string(buf) + if truncated { + line += "…(truncated)" + } + s.opts.Broker.Audit(s.opts.PluginID, "STDERR", line) + } + buf = buf[:0] + truncated = false + } + if err != nil { + return } } }() diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index 76c37c1..f2d9bdc 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -290,7 +290,13 @@ func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, err } kind := m.EffectiveKind() - if m.Origin == "third-party" { + if !isSafeRuntimeSegment(kind) { + return nil, fmt.Errorf("invalid runtime kind %q in manifest.json", kind) + } + if !isSafeRuntimeSegment(m.Commit) { + return nil, fmt.Errorf("invalid runtime commit %q in manifest.json", m.Commit) + } + if kind != DefaultKind || m.Origin == "third-party" { if err := ValidateThirdPartyProvenance(m); err != nil { return nil, err } @@ -316,6 +322,22 @@ func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, err }, nil } +// isSafeRuntimeSegment guards filepath.Join + os.RemoveAll against manifest +// path traversal in kind or commit (M6). +func isSafeRuntimeSegment(s string) bool { + if len(s) == 0 || len(s) > 64 || strings.Contains(s, "..") { + return false + } + for i := 0; i < len(s); i++ { + c := s[i] + ok := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' + if !ok { + return false + } + } + return true +} + func readManifest(path string) (Manifest, error) { var m Manifest raw, err := os.ReadFile(path) diff --git a/main.go b/main.go index 82753be..8fcbe3a 100644 --- a/main.go +++ b/main.go @@ -57,6 +57,12 @@ func main() { Theme: windows.Dark, WebviewIsTransparent: false, WindowIsTranslucent: false, + // Disable WebView2's GPU process: Reims-Go's desktop UI is a lightweight + // control panel, and software compositing avoids WebView2 GPU process crashes, + // DXGI surface loss on sleep/resume, and VRAM/TDR contention with reims-vgpu. + WebviewGpuIsDisabled: true, + OnSuspend: hooks.OnSuspend, + OnResume: hooks.OnResume, CustomTheme: &windows.ThemeSettings{ DarkModeTitleBar: windows.RGB(28, 28, 30), DarkModeTitleText: windows.RGB(245, 245, 247),