| 1 | package host |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "os" |
| 6 | "path" |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/carlosframework/platform/internal/rootstate" |
| 10 | "github.com/carlosframework/platform/internal/safefile" |
| 11 | "golang.org/x/sys/unix" |
| 12 | ) |
| 13 | |
| 14 | func claimPredecessorGroup(group string) (rootstate.FileIdentity, bool, error) { |
| 15 | var zero rootstate.FileIdentity |
| 16 | if !claimPredecessorPlacement(path.Base(group), group) { |
| 17 | return zero, false, os.ErrPermission |
| 18 | } |
| 19 | dir, err := safefile.OpenDir("/sys/fs/cgroup/" + group) |
| 20 | if errors.Is(err, os.ErrNotExist) { |
| 21 | return zero, false, nil |
| 22 | } |
| 23 | if err != nil { |
| 24 | return zero, false, err |
| 25 | } |
| 26 | defer dir.Close() |
| 27 | var st unix.Statfs_t |
| 28 | if err = unix.Fstatfs(int(dir.Fd()), &st); err != nil { |
| 29 | return zero, false, err |
| 30 | } |
| 31 | if st.Type != unix.CGROUP2_SUPER_MAGIC { |
| 32 | return zero, false, os.ErrPermission |
| 33 | } |
| 34 | id, err := rootstate.Identity(dir) |
| 35 | if err != nil { |
| 36 | return zero, false, err |
| 37 | } |
| 38 | fd, err := unix.Openat(int(dir.Fd()), "cgroup.events", unix.O_RDONLY|unix.O_CLOEXEC|unix.O_NOFOLLOW, 0) |
| 39 | if err != nil { |
| 40 | return zero, false, err |
| 41 | } |
| 42 | file := os.NewFile(uintptr(fd), "cgroup.events") |
| 43 | defer file.Close() |
| 44 | var buf [1024]byte |
| 45 | n, err := file.Read(buf[:]) |
| 46 | if err != nil { |
| 47 | return zero, false, err |
| 48 | } |
| 49 | if n == len(buf) { |
| 50 | return zero, false, os.ErrPermission |
| 51 | } |
| 52 | for _, line := range strings.Split(string(buf[:n]), "\n") { |
| 53 | if line == "populated 0" { |
| 54 | return id, false, nil |
| 55 | } |
| 56 | if line == "populated 1" { |
| 57 | return id, true, nil |
| 58 | } |
| 59 | } |
| 60 | return zero, false, os.ErrPermission |
| 61 | } |
| 62 | |
| 63 | func claimUnitBoot() (string, error) { |
| 64 | raw, err := os.ReadFile("/proc/sys/kernel/random/boot_id") |
| 65 | if err != nil { |
| 66 | return "", err |
| 67 | } |
| 68 | boot := strings.TrimSpace(string(raw)) |
| 69 | if boot == "" { |
| 70 | return "", os.ErrPermission |
| 71 | } |
| 72 | return boot, nil |
| 73 | } |
| 74 | |