| 1 | package receiver |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io/fs" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "strconv" |
| 9 | "syscall" |
| 10 | |
| 11 | "github.com/gokrazy/rsync" |
| 12 | "golang.org/x/sys/unix" |
| 13 | ) |
| 14 | |
| 15 | func (rt *Transfer) createDevice(f *File, st fs.FileInfo) error { |
| 16 | base := filepath.Base(f.Name) |
| 17 | parentDir, err := rt.DestRoot.OpenFile(filepath.Dir(f.Name), 0, 0) |
| 18 | if err != nil { |
| 19 | return fmt.Errorf("Open(parent(%s)): %v", f.Name, err) |
| 20 | } |
| 21 | defer parentDir.Close() |
| 22 | perm := fs.FileMode(f.Mode) & os.ModePerm |
| 23 | mode := f.Mode & rsync.S_IFMT |
| 24 | switch mode { |
| 25 | case rsync.S_IFCHR: |
| 26 | if st != nil && st.Mode().Type()&os.ModeCharDevice != 0 { |
| 27 | return nil // file of correct type exists |
| 28 | } |
| 29 | return unix.Mknodat(int(parentDir.Fd()), base, uint32(perm)|syscall.S_IFCHR, int(f.Rdev)) |
| 30 | |
| 31 | case rsync.S_IFBLK: |
| 32 | if st != nil && (st.Mode().Type()&os.ModeDevice != 0 || |
| 33 | st.Mode().Type()&os.ModeCharDevice != 0) { |
| 34 | return nil // file of correct type exists |
| 35 | } |
| 36 | |
| 37 | return unix.Mknodat(int(parentDir.Fd()), base, uint32(perm)|syscall.S_IFBLK, int(f.Rdev)) |
| 38 | |
| 39 | case rsync.S_IFSOCK: |
| 40 | if st != nil && st.Mode().Type()&os.ModeSocket != 0 { |
| 41 | return nil // file of correct type exists |
| 42 | } |
| 43 | |
| 44 | fd, err := unix.Socket(unix.AF_UNIX, unix.SOCK_DGRAM, 0) |
| 45 | if err != nil { |
| 46 | return err |
| 47 | } |
| 48 | |
| 49 | // The parent dir is safely resolved through *os.Root, |
| 50 | // so we skip path resolution by constructing a path |
| 51 | // from a known-safe prefix (/proc/self/fd/<parent-dir-fd>) |
| 52 | // and a basename (not a path!). |
| 53 | local := filepath.Join("/proc/self/fd", strconv.Itoa(int(parentDir.Fd())), base) |
| 54 | if err := unix.Bind(fd, &unix.SockaddrUnix{Name: local}); err != nil { |
| 55 | return err |
| 56 | } |
| 57 | |
| 58 | if err := unix.Close(fd); err != nil { |
| 59 | return err |
| 60 | } |
| 61 | return nil |
| 62 | |
| 63 | case rsync.S_IFIFO: |
| 64 | if st != nil && st.Mode().Type()&os.ModeNamedPipe != 0 { |
| 65 | return nil // file of correct type exists |
| 66 | } |
| 67 | |
| 68 | return unix.Mkfifoat(int(parentDir.Fd()), base, uint32(perm)) |
| 69 | } |
| 70 | return nil |
| 71 | } |