carlos / platform Public

Clone
git clone https://amadan.net/carlos/platform

Plain git — no account needed to clone.

Download

Download this file

1package rootstate
2
3import (
4 "os"
5 "path/filepath"
6
7 "golang.org/x/sys/unix"
8)
9
10func EnsurePublicDir(path string) error {
11 if !filepath.IsAbs(path) || filepath.Clean(path) != path || os.Geteuid() != 0 {
12 return os.ErrPermission
13 }
14 parent, err := Open(filepath.Dir(path), true, true)
15 if err != nil {
16 return err
17 }
18 defer parent.Close()
19 return ensurePublicChild(parent.(*directory), filepath.Base(path))
20}
21
22func ensurePublicChild(parent *directory, name string) error {
23 if !component(name) || parent.check() != nil {
24 return os.ErrPermission
25 }
26 fd := int(parent.file.Fd())
27 if err := unix.Mkdirat(fd, name, 0755); err != nil && err != unix.EEXIST {
28 return err
29 }
30 child, err := unix.Openat(fd, name, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0)
31 if err != nil {
32 return err
33 }
34 defer unix.Close(child)
35 if err := trusted(child, parent.owner, unix.S_IFDIR); err != nil {
36 return err
37 }
38 var st unix.Stat_t
39 if err := unix.Fstat(child, &st); err != nil {
40 return err
41 }
42 if st.Gid != 0 || st.Mode&07777 != 0700 && st.Mode&07777 != 0755 {
43 return os.ErrPermission
44 }
45 if st.Mode&07777 == 0700 {
46 if err := unix.Fchmod(child, 0755); err != nil {
47 return err
48 }
49 }
50 if err := unix.Fsync(child); err != nil {
51 return err
52 }
53 return unix.Fsync(fd)
54}
55