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

832 lines
24 KiB
Go

package runtime
import (
"archive/tar"
"archive/zip"
"context"
"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/filelock"
"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 provenance fields: upstream commits, applied patches, build channel, and source archive.
VendorQemuCommit string `json:"vendor_qemu_commit,omitempty"`
SuspendCompatID string `json:"suspend_compat_id,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.
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 unmarshals integer byte counts as well as whole-number JSON floats
// emitted by older PowerShell runtime packaging scripts.
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/<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: (specForKind(kind).Builtin && commit == cfg.ActiveRuntime) || kind+"/"+commit == cfg.ActiveRuntime,
Manifest: m,
Spec: specForKind(kind),
})
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: (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)
}
if _, err := os.Stat(cfg.RuntimesDir()); errors.Is(err, os.ErrNotExist) {
return nil, fmt.Errorf("%w: %s", ErrNotFound, want)
}
release, err := lockRuntimeDirectories(cfg.RuntimesDir())
if err != nil {
return nil, err
}
defer release()
// Activation takes the same directory lock. Include any selection published
// while this process waited, and leave both runtimes intact upon read errors.
current := *cfg
if err := RefreshSelection(&current); err != nil {
return nil, err
}
list, err := List(&current)
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)
}
active, err := ResolveActive(&current)
if err != nil && !errors.Is(err, ErrNoActiveRuntime) {
return nil, err
}
if 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 an environment isolated under cfg.DataRoot for invoking runtime tools.
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(),
"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)
}
release, err := lockRuntimeDirectories(cfg.RuntimesDir())
if err != nil {
return nil, err
}
defer release()
if err := replaceRuntimeDirectory(bundleDir, finalDir); err != nil {
return nil, err
}
return &Installed{
Kind: kind,
Commit: m.Commit,
Dir: finalDir,
Active: spec.Builtin,
Manifest: m,
Spec: spec,
}, nil
}
func lockRuntimeDirectories(runtimesDir string) (func(), error) {
return lockRuntimeDirectoriesContext(context.Background(), runtimesDir)
}
func lockRuntimeDirectoriesContext(ctx context.Context, runtimesDir string) (func(), error) {
if err := os.MkdirAll(runtimesDir, 0o755); err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
return filelock.Acquire(ctx, filepath.Join(runtimesDir, ".reims-go-runtime.lock"), 0)
}
// replaceRuntimeDirectory publishes an already verified bundle. The caller
// holds the runtime directory lock. List ignores the backup's .tmp suffix.
func replaceRuntimeDirectory(bundleDir, finalDir string) error {
backupDir := finalDir + ".replace.tmp"
_, finalErr := os.Lstat(finalDir)
hadRuntime := finalErr == nil
if !hadRuntime && !errors.Is(finalErr, os.ErrNotExist) {
return fmt.Errorf("inspect installed runtime: %w", finalErr)
}
if _, err := os.Lstat(backupDir); err == nil {
if hadRuntime {
if err := os.RemoveAll(backupDir); err != nil {
return fmt.Errorf("clean previous runtime backup: %w", err)
}
} else {
if err := os.Rename(backupDir, finalDir); err != nil {
return fmt.Errorf("recover previous runtime from %s: %w", backupDir, err)
}
hadRuntime = true
}
} else if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("inspect runtime backup: %w", err)
}
if hadRuntime {
if err := os.Rename(finalDir, backupDir); err != nil {
return fmt.Errorf("%w: move installed runtime to backup: %w", ErrRuntimeInUse, err)
}
}
if err := os.Rename(bundleDir, finalDir); err != nil {
activateErr := fmt.Errorf("activate runtime dir: %w", err)
if hadRuntime {
if restoreErr := os.Rename(backupDir, finalDir); restoreErr != nil {
return errors.Join(activateErr, fmt.Errorf("restore previous runtime from %s: %w", backupDir, restoreErr))
}
}
return activateErr
}
if hadRuntime {
_ = os.RemoveAll(backupDir)
}
return nil
}
// isSafeRuntimeSegment guards filepath.Join + os.RemoveAll against manifest
// path traversal in kind or commit.
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
}