Files
Reims-Go/internal/runtime/runtime.go
T

503 lines
14 KiB
Go

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"` // 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"`
}
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().
// Legacy layout `runtimes/<commit>/` is treated as kind "reims-vgpu" (zero
// migration); additional runtime kinds live under `runtimes/<kind>/<version>/`.
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: kind == DefaultKind && commit == cfg.ActiveRuntime,
Manifest: m,
})
continue
}
// Check nested kind directory: runtimes/<kind>/<version>/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: (kind == DefaultKind && commit == cfg.ActiveRuntime) || (kind+"/"+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 reims-vgpu runtime.
func ResolveActive(cfg *config.Config) (*Installed, error) {
return ResolveForKind(cfg, DefaultKind)
}
// 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\<non-ASCII>\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(),
"REIMS_CTL_QEMU": rt.QemuPath(),
"TEMP": tmpDir,
"TMP": tmpDir,
"TMPDIR": tmpDir,
}
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)
}
if kind != DefaultKind || m.Origin == "third-party" {
if err := ValidateThirdPartyProvenance(m); err != nil {
return nil, err
}
}
finalDir := filepath.Join(cfg.RuntimesDir(), m.Commit)
if kind != DefaultKind {
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: kind == DefaultKind,
Manifest: m,
}, 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"))
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
}