diff options
| author | Ophestra <cat@gensokyo.uk> | 2025-03-17 02:55:36 +0900 |
|---|---|---|
| committer | Ophestra <cat@gensokyo.uk> | 2025-03-17 02:55:36 +0900 |
| commit | 24618ab9a1524e8b8986a9bf67667288e642fcf1 (patch) | |
| tree | b3f2a71a2c9bedf937d0fec00092ad9133cb3ec9 /sandbox/params.go | |
| parent | 9ce4706a0766880c072cccd2643d66f614a6a16b (diff) | |
sandbox: move out of internal
Signed-off-by: Ophestra <cat@gensokyo.uk>
Diffstat (limited to 'sandbox/params.go')
| -rw-r--r-- | sandbox/params.go | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/sandbox/params.go b/sandbox/params.go new file mode 100644 index 00000000..5b698747 --- /dev/null +++ b/sandbox/params.go @@ -0,0 +1,47 @@ +package sandbox + +import ( + "encoding/gob" + "errors" + "os" + "strconv" +) + +var ( + ErrNotSet = errors.New("environment variable not set") + ErrInvalid = errors.New("bad file descriptor") +) + +// Setup appends the read end of a pipe for setup params transmission and returns its fd. +func Setup(extraFiles *[]*os.File) (int, *gob.Encoder, error) { + if r, w, err := os.Pipe(); err != nil { + return -1, nil, err + } else { + fd := 3 + len(*extraFiles) + *extraFiles = append(*extraFiles, r) + return fd, gob.NewEncoder(w), nil + } +} + +// Receive retrieves setup fd from the environment and receives params. +func Receive(key string, e any, v **os.File) (func() error, error) { + var setup *os.File + + if s, ok := os.LookupEnv(key); !ok { + return nil, ErrNotSet + } else { + if fd, err := strconv.Atoi(s); err != nil { + return nil, err + } else { + setup = os.NewFile(uintptr(fd), "setup") + if setup == nil { + return nil, ErrInvalid + } + if v != nil { + *v = setup + } + } + } + + return setup.Close, gob.NewDecoder(setup).Decode(e) +} |
