package runtime import ( "archive/zip" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "os" "os/exec" "path/filepath" "runtime" "sort" "strings" "github.com/Nwflower/reims-go/internal/config" ) 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"` // candidate | stable SourcePackage string `json:"source_package,omitempty"` // file name of the matching source archive } // 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 { Commit string `json:"commit"` Dir string `json:"dir"` Active bool `json:"active"` Manifest Manifest `json:"manifest"` } func (r Installed) ReimsCtlPath() string { name := "reims-ctl" if runtime.GOOS == "windows" { name += ".exe" } return filepath.Join(r.Dir, "bin", name) } func (r Installed) ReimsUtilPath() string { name := "reims-util" if runtime.GOOS == "windows" { name += ".exe" } return filepath.Join(r.Dir, "bin", name) } 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(). 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()) m, err := readManifest(filepath.Join(dir, "manifest.json")) if err != nil { continue } commit := m.Commit if commit == "" { commit = e.Name() } out = append(out, Installed{ Commit: commit, Dir: dir, Active: commit == cfg.ActiveRuntime, Manifest: m, }) } 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 runtime. func ResolveActive(cfg *config.Config) (*Installed, error) { list, err := List(cfg) if err != nil { return nil, err } for i := range list { if list[i].Commit == cfg.ActiveRuntime { return &list[i], nil } } if len(list) == 1 { return &list[0], nil } return nil, errors.New("no active runtime installed") } // 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") overrides := map[string]string{ "XDG_CONFIG_HOME": cfg.XDGConfigDir(), "XDG_DATA_HOME": cfg.XDGDataDir(), "XDG_CACHE_HOME": cfg.XDGCacheDir(), "REIMS_CTL_QEMU": rt.QemuPath(), } 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) } } finalDir := filepath.Join(cfg.RuntimesDir(), m.Commit) _ = os.RemoveAll(finalDir) if err := os.Rename(bundleDir, finalDir); err != nil { return nil, fmt.Errorf("activate runtime dir: %w", err) } return &Installed{ Commit: m.Commit, Dir: finalDir, Active: true, Manifest: m, }, nil } 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")) err = json.Unmarshal(raw, &m) return m, err } 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) { f, err := os.Open(path) if err != nil { return "", err } defer f.Close() h := sha256.New() if _, err := io.Copy(h, f); err != nil { return "", err } return hex.EncodeToString(h.Sum(nil)), nil } // tarCommand is Windows' own bsdtar (System32/tar.exe, Windows 10 1803+), // which reads .tar.zst directly and takes "D:\..." paths. A bare "tar" can // resolve to GNU tar from Git or MSYS2, which does neither. func tarCommand() string { if runtime.GOOS == "windows" { if root := os.Getenv("SystemRoot"); root != "" { p := filepath.Join(root, "System32", "tar.exe") if _, err := os.Stat(p); err == nil { return p } } } return "tar" } func extractTarZst(archivePath, destDir string) error { tarBin := tarCommand() cmd := exec.Command(tarBin, "-xf", archivePath, "-C", destDir) configureCmd(cmd) out, err := cmd.CombinedOutput() if err == nil { return nil } // Fallback for a tar without zstd: decompress to a temporary .tar first. // (Piping zstd into tar deadlocked when tar exited early: zstd blocked on a // full pipe nobody read.) zstdBin := findZstd() if zstdBin == "" { return fmt.Errorf("tar -xf failed (%v: %s) and zstd was not found", err, strings.TrimSpace(string(out))) } tmpTar := filepath.Join(destDir, ".extract.tar") defer os.Remove(tmpTar) z := exec.Command(zstdBin, "-d", "-q", "-f", archivePath, "-o", tmpTar) configureCmd(z) if zOut, zErr := z.CombinedOutput(); zErr != nil { return fmt.Errorf("zstd -d failed: %v (%s)", zErr, strings.TrimSpace(string(zOut))) } t := exec.Command(tarBin, "-xf", tmpTar, "-C", destDir) configureCmd(t) if tOut, tErr := t.CombinedOutput(); tErr != nil { return fmt.Errorf("tar extract failed: %v (%s)", tErr, strings.TrimSpace(string(tOut))) } return nil } func findZstd() string { for _, c := range []string{"zstd", `D:\DevTools\msys64\usr\bin\zstd.exe`, `D:\DevTools\msys64\clang64\bin\zstd.exe`} { if p, err := exec.LookPath(c); err == nil { return p } } return "" } 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 }