From e6b36494e703c0570f983b79fc06b8b0ddaf49c3 Mon Sep 17 00:00:00 2001 From: Elara6331 Date: Sun, 14 Apr 2024 11:46:43 -0700 Subject: [PATCH] Prevent operations on a file once it's closed --- infinitime/fs.go | 18 +++++++++++++++++- internal/fsproto/errors.go | 1 + internal/fusefs/syscallerr.go | 2 ++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/infinitime/fs.go b/infinitime/fs.go index 6d6ec11..5470154 100644 --- a/infinitime/fs.go +++ b/infinitime/fs.go @@ -266,6 +266,7 @@ type File struct { offset uint32 size uint32 readOnly bool + closed bool ProgressFunc func(transferred, total uint32) } @@ -294,6 +295,10 @@ func (ifs *FS) Create(path string, size uint32) (*File, error) { // Write writes data from the byte slice b to the file. // It returns the number of bytes written and an error, if any. func (fl *File) Write(b []byte) (int, error) { + if fl.closed { + return 0, fsproto.ErrFileClosed + } + if fl.readOnly { return 0, fsproto.ErrFileReadOnly } @@ -384,6 +389,10 @@ func (fl *File) Write(b []byte) (int, error) { // Read reads data from the file into the byte slice b. // It returns the number of bytes read and an error, if any. func (fl *File) Read(b []byte) (int, error) { + if fl.closed { + return 0, fsproto.ErrFileClosed + } + fl.fs.mtx.Lock() defer fl.fs.mtx.Unlock() @@ -504,6 +513,10 @@ func (fl *File) Stat() (fs.FileInfo, error) { // // Seek returns the new offset and an error, if any. func (fl *File) Seek(offset int64, whence int) (int64, error) { + if fl.closed { + return 0, fsproto.ErrFileClosed + } + if offset > math.MaxUint32 { return 0, fsproto.ErrInvalidOffset } @@ -534,8 +547,11 @@ func (fl *File) Seek(offset int64, whence int) (int64, error) { return int64(fl.offset), nil } -// Close always returns nil +// Close closes the file for future operations func (fl *File) Close() error { + fl.fs.mtx.Lock() + defer fl.fs.mtx.Unlock() + fl.closed = true return nil } diff --git a/internal/fsproto/errors.go b/internal/fsproto/errors.go index 9c91ba7..6a8de3a 100644 --- a/internal/fsproto/errors.go +++ b/internal/fsproto/errors.go @@ -11,6 +11,7 @@ var ( ErrFileWriteOnly = errors.New("file is write only") ErrInvalidOffset = errors.New("offset out of range") ErrNoRemoveRoot = errors.New("refusing to remove root directory") + ErrFileClosed = errors.New("cannot perform operation on a closed file") ) // Error represents an error returned by BLE FS diff --git a/internal/fusefs/syscallerr.go b/internal/fusefs/syscallerr.go index b7f20e6..ae91624 100644 --- a/internal/fusefs/syscallerr.go +++ b/internal/fusefs/syscallerr.go @@ -61,6 +61,8 @@ func syscallErr(err error) syscall.Errno { return syscall.EINVAL case fsproto.ErrNoRemoveRoot: // refusing to remove root directory return syscall.EPERM + case fsproto.ErrFileClosed: // cannot perform operation on closed file + return syscall.EBADF default: return syscall.EINVAL }