aboutsummaryrefslogtreecommitdiffhomepage
path: root/sandbox/path.go
blob: 5a28bdf96bbf0922cc709affce2667724fe06559 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package sandbox

import (
	"errors"
	"fmt"
	"io/fs"
	"os"
	"path"
	"strconv"
	"strings"
	"syscall"
)

const (
	hostPath    = "/" + hostDir
	hostDir     = "host"
	sysrootPath = "/" + sysrootDir
	sysrootDir  = "sysroot"
)

func toSysroot(name string) string {
	name = strings.TrimLeftFunc(name, func(r rune) bool { return r == '/' })
	return path.Join(sysrootPath, name)
}

func toHost(name string) string {
	name = strings.TrimLeftFunc(name, func(r rune) bool { return r == '/' })
	return path.Join(hostPath, name)
}

func createFile(name string, perm os.FileMode, content []byte) error {
	if err := os.MkdirAll(path.Dir(name), 0755); err != nil {
		return msg.WrapErr(err, err.Error())
	}
	f, err := os.OpenFile(name, syscall.O_CREAT|syscall.O_EXCL|syscall.O_WRONLY, perm)
	if err != nil {
		return msg.WrapErr(err, err.Error())
	}
	if content != nil {
		_, err = f.Write(content)
		if err != nil {
			err = msg.WrapErr(err, err.Error())
		}
	}
	return errors.Join(f.Close(), err)
}

func ensureFile(name string, perm os.FileMode) error {
	fi, err := os.Stat(name)
	if err != nil {
		if !os.IsNotExist(err) {
			return err
		}
		return createFile(name, perm, nil)
	}

	if mode := fi.Mode(); mode&fs.ModeDir != 0 || mode&fs.ModeSymlink != 0 {
		err = msg.WrapErr(syscall.EISDIR,
			fmt.Sprintf("path %q is a directory", name))
	}
	return err
}

var hostProc = newProcPats(hostPath)

func newProcPats(prefix string) *procPaths {
	return &procPaths{prefix, prefix + "/self", prefix + "/self/mountinfo"}
}

type procPaths struct {
	prefix    string
	self      string
	mountinfo string
}

func (p *procPaths) stdout() string   { return p.self + "/fd/1" }
func (p *procPaths) fd(fd int) string { return p.self + "/fd/" + strconv.Itoa(fd) }