Skip to content

Commit

Permalink
Fix closing file descriptors twice (#62)
Browse files Browse the repository at this point in the history
Closing the fd's in this code after using them to create new os.File objects results in the fd being closed twice with disastrous results in multi-threaded code.  os.File already arranges for its finalizer to close the fd.

Found via restic tests.
  • Loading branch information
gco authored Feb 2, 2022
1 parent 27812d2 commit 492d80d
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions xattr_solaris.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,14 @@ const (
)

func getxattr(path string, name string, data []byte) (int, error) {
fd, err := unix.Open(path, unix.O_RDONLY, 0)
f, err := os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
return 0, err
}
defer func() {
_ = unix.Close(fd)
_ = f.Close()
}()
return fgetxattr(os.NewFile(uintptr(fd), path), name, data)
return fgetxattr(f, name, data)
}

func lgetxattr(path string, name string, data []byte) (int, error) {
Expand All @@ -49,15 +49,16 @@ func fgetxattr(f *os.File, name string, data []byte) (int, error) {
}

func setxattr(path string, name string, data []byte, flags int) error {
fd, err := unix.Open(path, unix.O_RDONLY, 0)
f, err := os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
return err
}
if err = fsetxattr(os.NewFile(uintptr(fd), path), name, data, flags); err != nil {
_ = unix.Close(fd)
err = fsetxattr(f, name, data, flags)
if err != nil {
_ = f.Close()
return err
}
return unix.Close(fd)
return f.Close()
}

func lsetxattr(path string, name string, data []byte, flags int) error {
Expand Down Expand Up @@ -89,10 +90,11 @@ func removexattr(path string, name string) error {
if err != nil {
return err
}
f := os.NewFile(uintptr(fd), path);
defer func() {
_ = unix.Close(fd)
_ = f.Close()
}()
return fremovexattr(os.NewFile(uintptr(fd), path), name)
return fremovexattr(f, name)
}

func lremovexattr(path string, name string) error {
Expand All @@ -111,14 +113,14 @@ func fremovexattr(f *os.File, name string) error {
}

func listxattr(path string, data []byte) (int, error) {
fd, err := unix.Open(path, unix.O_RDONLY, 0)
f, err := os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
return 0, err
}
defer func() {
_ = unix.Close(fd)
_ = f.Close()
}()
return flistxattr(os.NewFile(uintptr(fd), path), data)
return flistxattr(f, data)
}

func llistxattr(path string, data []byte) (int, error) {
Expand All @@ -130,10 +132,11 @@ func flistxattr(f *os.File, data []byte) (int, error) {
if err != nil {
return 0, err
}
xf := os.NewFile(uintptr(fd), f.Name())
defer func() {
_ = unix.Close(fd)
_ = xf.Close()
}()
names, err := os.NewFile(uintptr(fd), f.Name()).Readdirnames(-1)
names, err := xf.Readdirnames(-1)
if err != nil {
return 0, err
}
Expand Down

0 comments on commit 492d80d

Please sign in to comment.