package runtime import ( "archive/tar" "archive/zip" "encoding/json" "errors" "fmt" "io" "os" "path" "path/filepath" "runtime" "sort" "strings" "time" "github.com/Nwflower/reims-go/internal/config" "github.com/Nwflower/reims-go/internal/fetch" "github.com/Nwflower/reims-go/internal/host" "github.com/klauspost/compress/zstd" ) type Manifest struct { SchemaVersion int `json:"schema_version"` Name string `json:"name"` Platform string `json:"platform"` UpstreamRepo string `json:"upstream_repo"` Commit string `json:"commit"` FullCommit string `json:"full_commit"` QemuVersion string `json:"qemu_version"` UtilVersion string `json:"util_version"` BuiltAt string `json:"built_at"` FileCount int `json:"file_count"` DLLCount int `json:"dll_count"` RawBytes ByteCount `json:"raw_bytes"` SHA256 map[string]string `json:"sha256"` // Schema 2 (docs/portable-runtime-spec.md §3.1, §5, §7): what the package // was really built from. A package with patches is not "pure upstream". VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"` UtilCommit string `json:"util_commit,omitempty"` MetalCommit string `json:"metal2vulkan_commit,omitempty"` Patches []Patch `json:"patches,omitempty"` Channel string `json:"channel,omitempty"` // channel at build time: alpha (older packages: candidate) SourcePackage string `json:"source_package,omitempty"` // file name of the matching source archive // Schema 2+ plugin runtime extensions (docs/plugin-architecture.md §5.2). Kind string `json:"kind,omitempty"` // defaults to "reims-vgpu" RuntimeAPI string `json:"runtime_api,omitempty"` // CLI/driver contract version, e.g. "1.0.0" Capabilities []string `json:"capabilities,omitempty"` // explicit feature/patch capability IDs License string `json:"license,omitempty"` // SPDX or license summary Publisher string `json:"publisher,omitempty"` // official or third-party publisher Origin string `json:"origin,omitempty"` // "official" | "third-party" } // ByteCount is an integer that also accepts a whole-number float ("962466926.0"), // which PowerShell 7 wrote into manifests before pack-runtime.ps1 cast it. type ByteCount int64 func (b *ByteCount) UnmarshalJSON(data []byte) error { var f float64 if err := json.Unmarshal(data, &f); err != nil { return err } *b = ByteCount(f) return nil } // Patch is one local patch applied on top of upstream. type Patch struct { Name string `json:"name"` Target string `json:"target"` // e.g. "vendor/qemu" SHA256 string `json:"sha256"` } type Installed struct { Kind string `json:"kind,omitempty"` Commit string `json:"commit"` Dir string `json:"dir"` Active bool `json:"active"` Manifest Manifest `json:"manifest"` Spec KindSpec `json:"-"` } func specForKind(kind string) KindSpec { spec, _ := NewKindRegistry().Get(kind) if spec.Kind == "" { spec.Kind = kind } return spec } func executablePath(dir, subdir, name string) string { if name == "" { return "" } if runtime.GOOS == "windows" && !strings.HasSuffix(strings.ToLower(name), ".exe") { name += ".exe" } return filepath.Join(dir, subdir, name) } func (r Installed) runtimeSpec() KindSpec { if r.Spec.Kind != "" || r.Spec.ControlExecutable != "" { return r.Spec } kind := r.Kind if kind == "" { kind = r.Manifest.EffectiveKind() } return specForKind(kind) } func (r Installed) ControlPath() string { return executablePath(r.Dir, "bin", r.runtimeSpec().ControlExecutable) } func (r Installed) UtilityPath() string { return executablePath(r.Dir, "bin", r.runtimeSpec().UtilityExecutable) } // ReimsCtlPath and ReimsUtilPath are compatibility wrappers for the built-in driver. func (r Installed) ReimsCtlPath() string { return r.ControlPath() } func (r Installed) ReimsUtilPath() string { return r.UtilityPath() } func (r Installed) QemuPath() string { name := "qemu-system-x86_64" if runtime.GOOS == "windows" { name += ".exe" } return filepath.Join(r.Dir, "qemu", "bin", name) } func (r Installed) QemuImgPath() string { name := "qemu-img" if runtime.GOOS == "windows" { name += ".exe" } return filepath.Join(r.Dir, "qemu", "bin", name) } // List returns all valid portable runtimes installed under cfg.RuntimesDir(). // Legacy layout `runtimes//` is treated as kind "reims-vgpu" (zero // migration); additional runtime kinds live under `runtimes///`. func List(cfg *config.Config) ([]Installed, error) { entries, err := os.ReadDir(cfg.RuntimesDir()) if err != nil { if errors.Is(err, os.ErrNotExist) { return nil, nil } return nil, err } var out []Installed for _, e := range entries { if !e.IsDir() || strings.HasSuffix(e.Name(), ".tmp") { continue } dir := filepath.Join(cfg.RuntimesDir(), e.Name()) if m, err := readManifest(filepath.Join(dir, "manifest.json")); err == nil { commit := m.Commit if commit == "" { commit = e.Name() } kind := m.EffectiveKind() out = append(out, Installed{ Kind: kind, Commit: commit, Dir: dir, Active: specForKind(kind).Builtin && commit == cfg.ActiveRuntime, Manifest: m, Spec: specForKind(kind), }) continue } // Check nested kind directory: runtimes///manifest.json subEntries, subErr := os.ReadDir(dir) if subErr != nil { continue } for _, sub := range subEntries { if !sub.IsDir() || strings.HasSuffix(sub.Name(), ".tmp") { continue } subDir := filepath.Join(dir, sub.Name()) m, err := readManifest(filepath.Join(subDir, "manifest.json")) if err != nil { continue } commit := m.Commit if commit == "" { commit = sub.Name() } kind := m.EffectiveKind() if m.Kind == "" { kind = e.Name() m.Kind = kind } out = append(out, Installed{ Kind: kind, Commit: commit, Dir: subDir, Active: (specForKind(kind).Builtin && commit == cfg.ActiveRuntime) || (kind+"/"+commit) == cfg.ActiveRuntime, Manifest: m, Spec: specForKind(kind), }) } } sort.Slice(out, func(i, j int) bool { return out[i].Manifest.BuiltAt > out[j].Manifest.BuiltAt }) return out, nil } // ResolveActive returns the currently active installed reims-vgpu runtime. func ResolveActive(cfg *config.Config) (*Installed, error) { return ResolveForKind(cfg, DefaultKind) } var ( ErrNotFound = errors.New("runtime not found") ErrRemoveActive = errors.New("cannot remove active runtime") ErrRuntimeInUse = errors.New("runtime files are in use") ) // Remove deletes an installed non-active portable runtime directory from // cfg.RuntimesDir(). It renames the directory to a .tmp sibling first so an // open executable/DLL handle on Windows aborts cleanly without leaving a // half-deleted runtime behind. func Remove(cfg *config.Config, commit string) (*Installed, error) { want := strings.TrimSpace(commit) if want == "" { return nil, fmt.Errorf("%w: %s", ErrNotFound, commit) } list, err := List(cfg) if err != nil { return nil, err } var match *Installed for i := range list { item := list[i] if item.Commit == want || (item.Kind+"/"+item.Commit) == want { if match == nil || item.Spec.Builtin { cp := item match = &cp } } } if match == nil { return nil, fmt.Errorf("%w: %s", ErrNotFound, want) } if match.Active { return nil, fmt.Errorf("%w: %s", ErrRemoveActive, match.Commit) } if active, err := ResolveActive(cfg); err == nil && active != nil && samePath(active.Dir, match.Dir) { return nil, fmt.Errorf("%w: %s", ErrRemoveActive, match.Commit) } baseAbs, err := filepath.Abs(cfg.RuntimesDir()) if err != nil { return nil, err } dirAbs, err := filepath.Abs(match.Dir) if err != nil { return nil, err } rel, err := filepath.Rel(baseAbs, dirAbs) if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) { return nil, fmt.Errorf("refusing to remove directory outside runtimes root: %s", match.Dir) } staging := fmt.Sprintf("%s.%d.tmp", dirAbs, time.Now().UnixNano()) if err := os.Rename(dirAbs, staging); err != nil { return nil, fmt.Errorf("%w: %v", ErrRuntimeInUse, err) } if err := os.RemoveAll(staging); err != nil { _ = os.Rename(staging, dirAbs) return nil, fmt.Errorf("%w: %v", ErrRuntimeInUse, err) } return match, nil } func samePath(a, b string) bool { aa, errA := filepath.Abs(a) bb, errB := filepath.Abs(b) if errA != nil || errB != nil { return filepath.Clean(a) == filepath.Clean(b) } if runtime.GOOS == "windows" { return strings.EqualFold(filepath.Clean(aa), filepath.Clean(bb)) } return filepath.Clean(aa) == filepath.Clean(bb) } // BuildChildEnv returns a clean, D-drive-isolated environment for invoking reims-ctl. func BuildChildEnv(cfg *config.Config, rt Installed) []string { binDir := filepath.Join(rt.Dir, "bin") tmpDir := cfg.TempDir() _ = os.MkdirAll(tmpDir, 0o755) // Redirect TEMP/TMP/TMPDIR into DataRoot so QEMU's snapshot=on temporary // overlay does not write into C:\Users\\AppData\Local\Temp // (MinGW QEMU's open() fails with ENOENT on non-ASCII Windows usernames). overrides := map[string]string{ "XDG_CONFIG_HOME": cfg.XDGConfigDir(), "XDG_DATA_HOME": cfg.XDGDataDir(), "XDG_CACHE_HOME": cfg.XDGCacheDir(), "TEMP": tmpDir, "TMP": tmpDir, "TMPDIR": tmpDir, } if envName := rt.runtimeSpec().ControlQemuEnv; envName != "" { overrides[envName] = rt.QemuPath() } host.ConfigureVulkanDrivers() env := os.Environ() out := make([]string, 0, len(env)+len(overrides)) seenPath := false for _, kv := range env { idx := strings.IndexByte(kv, '=') if idx <= 0 { continue } k := kv[:idx] v := kv[idx+1:] if strings.EqualFold(k, "PATH") { out = append(out, k+"="+binDir+string(os.PathListSeparator)+v) seenPath = true continue } skip := false for ok := range overrides { if strings.EqualFold(k, ok) { skip = true break } } if !skip { out = append(out, kv) } } if !seenPath { out = append(out, "PATH="+binDir) } for k, v := range overrides { out = append(out, k+"="+v) } return out } // InstallFromArchive verifies and atomically extracts a .tar.zst or .zip runtime archive. func InstallFromArchive(cfg *config.Config, archivePath string) (*Installed, error) { if err := cfg.EnsureDirs(); err != nil { return nil, err } if err := verifySidecarSHA256(archivePath); err != nil { return nil, err } tmpDir, err := os.MkdirTemp(cfg.RuntimesDir(), "install-*.tmp") if err != nil { return nil, err } defer os.RemoveAll(tmpDir) low := strings.ToLower(archivePath) switch { case strings.HasSuffix(low, ".tar.zst"): if err := extractTarZst(archivePath, tmpDir); err != nil { return nil, err } case strings.HasSuffix(low, ".zip"): if err := extractZip(archivePath, tmpDir); err != nil { return nil, err } default: return nil, fmt.Errorf("unsupported archive format: %s (expected .tar.zst or .zip)", archivePath) } bundleDir, err := findBundleRoot(tmpDir) if err != nil { return nil, err } m, err := readManifest(filepath.Join(bundleDir, "manifest.json")) if err != nil { return nil, fmt.Errorf("read manifest.json: %w", err) } if m.Commit == "" { return nil, errors.New("manifest.json missing commit") } for rel, expected := range m.SHA256 { fp := filepath.Join(bundleDir, filepath.FromSlash(rel)) got, err := fileSHA256(fp) if err != nil { return nil, fmt.Errorf("hash %s: %w", rel, err) } if !strings.EqualFold(got, expected) { return nil, fmt.Errorf("SHA256 mismatch for %s: expected %s, got %s", rel, expected, got) } } kind := m.EffectiveKind() 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) } spec := specForKind(kind) if !spec.Builtin || m.Origin == "third-party" { if err := ValidateThirdPartyProvenance(m); err != nil { return nil, err } } finalDir := filepath.Join(cfg.RuntimesDir(), m.Commit) if !spec.Builtin { kindDir := filepath.Join(cfg.RuntimesDir(), kind) if err := os.MkdirAll(kindDir, 0o755); err != nil { return nil, err } finalDir = filepath.Join(kindDir, m.Commit) } _ = os.RemoveAll(finalDir) if err := os.Rename(bundleDir, finalDir); err != nil { return nil, fmt.Errorf("activate runtime dir: %w", err) } return &Installed{ Kind: kind, Commit: m.Commit, Dir: finalDir, Active: spec.Builtin, Manifest: m, Spec: spec, }, 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) if err != nil { return m, err } // Strip UTF-8 BOM if written by Windows PowerShell Set-Content -Encoding utf8. raw = []byte(strings.TrimPrefix(string(raw), "\uFEFF")) if err = json.Unmarshal(raw, &m); err != nil { return m, err } var keys map[string]json.RawMessage if err = json.Unmarshal(raw, &keys); err != nil { return m, err } if _, declared := keys["capabilities"]; !declared { m.Capabilities = legacyCapabilities(m) } return m, nil } func findBundleRoot(dir string) (string, error) { if _, err := os.Stat(filepath.Join(dir, "manifest.json")); err == nil { return dir, nil } entries, err := os.ReadDir(dir) if err != nil { return "", err } for _, e := range entries { if e.IsDir() { sub := filepath.Join(dir, e.Name()) if _, err := os.Stat(filepath.Join(sub, "manifest.json")); err == nil { return sub, nil } } } return "", errors.New("manifest.json not found in extracted runtime archive") } func verifySidecarSHA256(archivePath string) error { sidecar := archivePath + ".sha256" raw, err := os.ReadFile(sidecar) if err != nil { if errors.Is(err, os.ErrNotExist) { return nil } return err } fields := strings.Fields(string(raw)) if len(fields) == 0 { return nil } got, err := fileSHA256(archivePath) if err != nil { return err } if !strings.EqualFold(got, fields[0]) { return fmt.Errorf("archive SHA256 mismatch: expected %s, got %s", fields[0], got) } return nil } func fileSHA256(path string) (string, error) { return fetch.FileSHA256(path) } // extractTarZst decompresses and extracts a .tar.zst runtime archive in pure Go // (no dependency on Windows tar.exe libzstd support or an external zstd binary). func extractTarZst(archivePath, destDir string) error { f, err := os.Open(archivePath) if err != nil { return fmt.Errorf("open archive: %w", err) } defer f.Close() zr, err := zstd.NewReader(f) if err != nil { return fmt.Errorf("init zstd reader: %w", err) } defer zr.Close() cleanDest := filepath.Clean(destDir) realDest, err := filepath.EvalSymlinks(cleanDest) if err != nil { realDest = cleanDest } tr := tar.NewReader(zr) for { hdr, err := tr.Next() if errors.Is(err, io.EOF) { break } if err != nil { return fmt.Errorf("read tar.zst entry: %w", err) } switch hdr.Typeflag { case tar.TypeXHeader, tar.TypeXGlobalHeader, tar.TypeGNULongName, tar.TypeGNULongLink: continue } target, isRoot, err := safeExtractPath(cleanDest, hdr.Name) if err != nil { return err } switch hdr.Typeflag { case tar.TypeDir: if isRoot { continue } if err := ensureWithinDest(realDest, filepath.Dir(target), hdr.Name); err != nil { return err } if err := os.MkdirAll(target, 0o755); err != nil { return err } case tar.TypeReg, tar.TypeRegA: if isRoot { return fmt.Errorf("illegal tar file path: %s", hdr.Name) } if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { return err } if err := ensureWithinDest(realDest, filepath.Dir(target), hdr.Name); err != nil { return err } mode := (os.FileMode(hdr.Mode) & 0o777) | 0o600 if err := writeTarFile(target, tr, mode); err != nil { return err } case tar.TypeLink: if isRoot { return fmt.Errorf("illegal tar hardlink path: %s", hdr.Name) } linkTarget, linkIsRoot, err := safeExtractPath(cleanDest, hdr.Linkname) if err != nil || linkIsRoot { return fmt.Errorf("illegal tar hardlink target %q for %s", hdr.Linkname, hdr.Name) } if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { return err } if err := ensureWithinDest(realDest, filepath.Dir(target), hdr.Name); err != nil { return err } if err := ensureWithinDest(realDest, filepath.Dir(linkTarget), hdr.Linkname); err != nil { return err } _ = os.Remove(target) if err := os.Link(linkTarget, target); err != nil { return fmt.Errorf("create hardlink %s -> %s: %w", hdr.Name, hdr.Linkname, err) } case tar.TypeSymlink: if isRoot { return fmt.Errorf("illegal tar symlink path: %s", hdr.Name) } normLink := strings.ReplaceAll(hdr.Linkname, "\\", "/") if normLink == "" || strings.HasPrefix(normLink, "/") || filepath.IsAbs(hdr.Linkname) || filepath.VolumeName(hdr.Linkname) != "" || filepath.VolumeName(normLink) != "" { return fmt.Errorf("illegal tar symlink target %q for %s", hdr.Linkname, hdr.Name) } if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { return err } realParent, err := evalWithinDest(realDest, filepath.Dir(target), hdr.Name) if err != nil { return err } resolved := filepath.Clean(filepath.Join(realParent, filepath.FromSlash(normLink))) if !isWithinDir(realDest, resolved) { return fmt.Errorf("illegal tar symlink target %q for %s", hdr.Linkname, hdr.Name) } _ = os.Remove(target) if err := os.Symlink(filepath.FromSlash(normLink), target); err != nil { // Windows without Developer Mode or admin rights denies os.Symlink; // fall back to copying if the target is an already-extracted regular file. if runtime.GOOS == "windows" { if copyErr := copyFileIfRegular(resolved, target); copyErr == nil { continue } } return fmt.Errorf("create symlink %s -> %s: %w", hdr.Name, hdr.Linkname, err) } default: return fmt.Errorf("unsupported tar entry type %q for %s", hdr.Typeflag, hdr.Name) } } return nil } func safeExtractPath(cleanDest, rawName string) (target string, isRoot bool, err error) { norm := strings.ReplaceAll(rawName, "\\", "/") if norm == "" || strings.HasPrefix(norm, "/") || filepath.IsAbs(rawName) || filepath.VolumeName(rawName) != "" || filepath.VolumeName(norm) != "" { return "", false, fmt.Errorf("illegal tar path: %s", rawName) } clean := path.Clean(norm) if clean == "." { return cleanDest, true, nil } if clean == ".." || strings.HasPrefix(clean, "../") { return "", false, fmt.Errorf("illegal tar path: %s", rawName) } target = filepath.Join(cleanDest, filepath.FromSlash(clean)) if !isWithinDir(cleanDest, filepath.Clean(target)) { return "", false, fmt.Errorf("illegal tar path: %s", rawName) } return target, false, nil } func isWithinDir(baseDir, candidate string) bool { base := filepath.Clean(baseDir) cand := filepath.Clean(candidate) if cand == base { return true } return strings.HasPrefix(cand, base+string(os.PathSeparator)) } func evalWithinDest(realDest, dir, entryName string) (string, error) { realDir, err := filepath.EvalSymlinks(dir) if err != nil { return "", err } if !isWithinDir(realDest, realDir) { return "", fmt.Errorf("illegal tar path (symlink escape): %s", entryName) } return realDir, nil } func ensureWithinDest(realDest, dir, entryName string) error { _, err := evalWithinDest(realDest, dir, entryName) return err } func writeTarFile(target string, r io.Reader, mode os.FileMode) error { _ = os.Remove(target) out, err := os.OpenFile(target, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, mode) if err != nil { return err } _, copyErr := io.Copy(out, r) closeErr := out.Close() if copyErr != nil { return copyErr } return closeErr } func copyFileIfRegular(src, dst string) error { info, err := os.Stat(src) if err != nil || !info.Mode().IsRegular() { return errors.New("not a regular file") } in, err := os.Open(src) if err != nil { return err } defer in.Close() return writeTarFile(dst, in, (info.Mode()&0o777)|0o600) } func extractZip(archivePath, destDir string) error { r, err := zip.OpenReader(archivePath) if err != nil { return err } defer r.Close() for _, f := range r.File { target := filepath.Join(destDir, f.Name) if !strings.HasPrefix(filepath.Clean(target), filepath.Clean(destDir)+string(os.PathSeparator)) { return fmt.Errorf("illegal zip path: %s", f.Name) } if f.FileInfo().IsDir() { if err := os.MkdirAll(target, 0o755); err != nil { return err } continue } if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { return err } rc, err := f.Open() if err != nil { return err } out, err := os.Create(target) if err != nil { rc.Close() return err } _, copyErr := io.Copy(out, rc) rc.Close() closeErr := out.Close() if copyErr != nil { return copyErr } if closeErr != nil { return closeErr } } return nil }