2024-09-04 01:20:12 +09:00
|
|
|
package state
|
2024-07-16 14:19:43 +09:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/gob"
|
|
|
|
"errors"
|
|
|
|
"io/fs"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"path"
|
|
|
|
"strconv"
|
2024-09-17 13:48:42 +09:00
|
|
|
|
|
|
|
"git.ophivana.moe/cat/fortify/internal"
|
2024-07-16 14:19:43 +09:00
|
|
|
)
|
|
|
|
|
2024-09-04 01:20:12 +09:00
|
|
|
// SaveProcess called after process start, before wait
|
2024-09-17 13:48:42 +09:00
|
|
|
func SaveProcess(uid string, cmd *exec.Cmd, runDirPath string, command []string, enablements internal.Enablements) (string, error) {
|
2024-09-16 20:31:15 +09:00
|
|
|
statePath := path.Join(runDirPath, uid, strconv.Itoa(cmd.Process.Pid))
|
2024-07-16 14:19:43 +09:00
|
|
|
state := launcherState{
|
2024-09-08 02:24:01 +09:00
|
|
|
PID: cmd.Process.Pid,
|
|
|
|
Launcher: cmd.Path,
|
|
|
|
Argv: cmd.Args,
|
|
|
|
Command: command,
|
2024-09-16 20:31:15 +09:00
|
|
|
Capability: enablements,
|
2024-07-16 14:19:43 +09:00
|
|
|
}
|
|
|
|
|
2024-09-16 20:31:15 +09:00
|
|
|
if err := os.Mkdir(path.Join(runDirPath, uid), 0700); err != nil && !errors.Is(err, fs.ErrExist) {
|
|
|
|
return statePath, err
|
2024-07-16 14:19:43 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
if f, err := os.OpenFile(statePath, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600); err != nil {
|
2024-09-16 20:31:15 +09:00
|
|
|
return statePath, err
|
2024-07-16 14:19:43 +09:00
|
|
|
} else {
|
|
|
|
defer func() {
|
|
|
|
if f.Close() != nil {
|
|
|
|
// unreachable
|
|
|
|
panic("state file closed prematurely")
|
|
|
|
}
|
|
|
|
}()
|
2024-09-16 20:31:15 +09:00
|
|
|
return statePath, gob.NewEncoder(f).Encode(state)
|
2024-07-16 14:19:43 +09:00
|
|
|
}
|
|
|
|
}
|