diff --git a/connection.go b/connection.go index 429a3b7c..ca89ecc2 100644 --- a/connection.go +++ b/connection.go @@ -16,6 +16,7 @@ package fuse import ( "context" + "errors" "fmt" "io" "log" @@ -29,6 +30,7 @@ import ( "github.com/jacobsa/fuse/internal/buffer" "github.com/jacobsa/fuse/internal/freelist" "github.com/jacobsa/fuse/internal/fusekernel" + "github.com/jacobsa/fuse/internal/operror" ) type contextKeyType uint64 @@ -438,10 +440,13 @@ func (c *Connection) writeOutMessage(outMsg *buffer.OutMessage) error { return err } +// syscallWrite is syscall.Write. Tests replace it to make a reply write fail. +var syscallWrite = syscall.Write + // Write the supplied message to the kernel. func (c *Connection) writeMessage(msg []byte) error { // Avoid the retry loop in os.File.Write. - n, err := syscall.Write(int(c.dev.Fd()), msg) + n, err := syscallWrite(int(c.dev.Fd()), msg) if err != nil { return err } @@ -519,21 +524,24 @@ func (c *Connection) shouldLogError( return false } + // Judge the errno that kernelResponse sends, not any errno in the chain. + errno, _ := operror.Errno(err) + switch op.(type) { case *fuseops.LookUpInodeOp: // It is totally normal for the kernel to ask to look up an inode by name // and find the name doesn't exist. For example, this happens when linking // a new file. - if err == syscall.ENOENT { + if errno == syscall.ENOENT { return false } case *fuseops.GetXattrOp, *fuseops.ListXattrOp: - if err == syscall.ENOSYS || err == syscall.ENODATA || err == syscall.ERANGE { + if errno == syscall.ENOSYS || errno == syscall.ENODATA || errno == syscall.ERANGE { return false } case *unknownOp: // Don't bother the user with methods we intentionally don't support. - if err == syscall.ENOSYS { + if errno == syscall.ENOSYS { return false } } @@ -546,6 +554,10 @@ var writeLock sync.Mutex // Reply replies to an op previously read using ReadOp, with the supplied error // (or nil if successful). The context must be the context returned by ReadOp. // +// The kernel receives the first syscall.Errno in opErr's chain, or EIO when +// the chain has none. A reply the kernel refuses with ENOENT, because the +// request is gone, is not an error. +// // LOCKS_EXCLUDED(c.mu) func (c *Connection) Reply(ctx context.Context, opErr error) error { // Extract the state we stuffed in earlier. @@ -585,7 +597,7 @@ func (c *Connection) Reply(ctx context.Context, opErr error) error { c.debugLog(fuseID, 1, "-> %s", describeResponse(op)) } else { if !logError { - c.debugLog(fuseID, 1, "-> Error: %q", opErr.Error()) + c.debugLog(fuseID, 1, "-> Error: %q", opErr) } } } @@ -600,7 +612,10 @@ func (c *Connection) Reply(ctx context.Context, opErr error) error { if !noResponse { err := c.writeOutMessage(outMsg) - if err != nil { + // The kernel answers a reply to a request it no longer tracks with + // ENOENT. libfuse leaves it out of its error output, and Reply neither + // logs nor returns it. + if err != nil && !errors.Is(err, syscall.ENOENT) { writeErrMsg := fmt.Sprintf("writeMessage: %v %v", err, outMsg.OutHeaderBytes()) if c.errorLogger != nil { c.errorLogger.Print(writeErrMsg) diff --git a/connection_test.go b/connection_test.go index c1a4f013..694bc78c 100644 --- a/connection_test.go +++ b/connection_test.go @@ -15,12 +15,212 @@ package fuse import ( + "bytes" + "context" + "encoding/binary" + "errors" + "fmt" + "io" + "log" + "os" "strings" + "syscall" "testing" + "unsafe" + "github.com/jacobsa/fuse/fuseops" "github.com/jacobsa/fuse/internal/buffer" + "github.com/jacobsa/fuse/internal/fusekernel" ) +// A nil *os.PathError panics when errors.As or errors.Is unwraps it. +var nilPathErr error = (*os.PathError)(nil) + +// newReplyTestConnection returns a Connection that reads one unknown op from +// a pipe. Its reply writes return writeErr. +func newReplyTestConnection(t *testing.T, writeErr error) *Connection { + t.Helper() + + message := make([]byte, unsafe.Sizeof(fusekernel.InHeader{})) + binary.NativeEndian.PutUint32(message[0:4], uint32(len(message))) + binary.NativeEndian.PutUint64(message[8:16], 7) + + r, w, err := os.Pipe() + if err != nil { + t.Fatalf("Pipe: %v", err) + } + t.Cleanup(func() { r.Close() }) + if _, err := w.Write(message); err != nil { + t.Fatalf("Write: %v", err) + } + w.Close() + + oldWrite := syscallWrite + syscallWrite = func(fd int, p []byte) (int, error) { + if writeErr != nil { + return 0, writeErr + } + return len(p), nil + } + t.Cleanup(func() { syscallWrite = oldWrite }) + + return &Connection{ + cfg: MountConfig{OpContext: context.Background()}, + dev: r, + cancelFuncs: make(map[uint64]func()), + inMessageBufSize: buffer.GetPageSize(), + } +} + +func TestKernelResponseKeepsWrappedErrno(t *testing.T) { + tests := []struct { + name string + opErr error + want syscall.Errno + }{ + {"bare errno", syscall.ENOENT, syscall.ENOENT}, + {"wrapped errno", fmt.Errorf("lookup: %w", syscall.ENOENT), syscall.ENOENT}, + {"path error", &os.PathError{Op: "open", Path: "f", Err: syscall.EACCES}, syscall.EACCES}, + {"no errno", errors.New("lookup failed"), syscall.EIO}, + {"EIO before ENOENT", fmt.Errorf("lookup: %w (cleanup: %w)", syscall.EIO, syscall.ENOENT), syscall.EIO}, + {"joined EACCES and ENOENT", errors.Join(syscall.EACCES, syscall.ENOENT), syscall.EACCES}, + {"nil path error", nilPathErr, syscall.EIO}, + {"wrapped nil path error", fmt.Errorf("lookup: %w", nilPathErr), syscall.EIO}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var c Connection + var m buffer.OutMessage + m.Reset() + c.kernelResponse(&m, 1, &fuseops.LookUpInodeOp{}, tt.opErr) + if got := m.OutHeader().Error; got != -int32(tt.want) { + t.Errorf("reply error = %d, want %d", got, -int32(tt.want)) + } + }) + } +} + +func TestShouldLogErrorMatchesWrappedErrno(t *testing.T) { + wrap := func(errno syscall.Errno) error { return fmt.Errorf("op: %w", errno) } + tests := []struct { + name string + op interface{} + err error + want bool + }{ + {"lookup ENOENT", &fuseops.LookUpInodeOp{}, wrap(syscall.ENOENT), false}, + {"getxattr ENODATA", &fuseops.GetXattrOp{}, wrap(syscall.ENODATA), false}, + {"listxattr ERANGE", &fuseops.ListXattrOp{}, wrap(syscall.ERANGE), false}, + {"getxattr ENOSYS", &fuseops.GetXattrOp{}, wrap(syscall.ENOSYS), false}, + {"unknown op ENOSYS", &unknownOp{}, wrap(syscall.ENOSYS), false}, + {"lookup EIO", &fuseops.LookUpInodeOp{}, wrap(syscall.EIO), true}, + {"lookup EIO before ENOENT", &fuseops.LookUpInodeOp{}, fmt.Errorf("lookup: %w (cleanup: %w)", syscall.EIO, syscall.ENOENT), true}, + {"lookup joined EACCES and ENOENT", &fuseops.LookUpInodeOp{}, errors.Join(syscall.EACCES, syscall.ENOENT), true}, + {"lookup no errno", &fuseops.LookUpInodeOp{}, errors.New("lookup failed"), true}, + {"lookup nil path error", &fuseops.LookUpInodeOp{}, nilPathErr, true}, + {"lookup wrapped nil path error", &fuseops.LookUpInodeOp{}, fmt.Errorf("lookup: %w", nilPathErr), true}, + } + c := &Connection{errorLogger: log.New(io.Discard, "", 0)} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := c.shouldLogError(tt.op, tt.err); got != tt.want { + t.Errorf("shouldLogError = %v, want %v", got, tt.want) + } + }) + } +} + +// The kernel answers a reply to a request it no longer tracks with ENOENT. +func TestReplyTreatsENOENTWriteAsBenign(t *testing.T) { + tests := []struct { + name string + writeErr error + wantErr bool + }{ + {"ENOENT", syscall.ENOENT, false}, + {"EIO", syscall.EIO, true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var logged bytes.Buffer + c := newReplyTestConnection(t, tt.writeErr) + c.errorLogger = log.New(&logged, "", 0) + ctx, _, err := c.ReadOp() + if err != nil { + t.Fatalf("ReadOp: %v", err) + } + + err = c.Reply(ctx, syscall.ENOSYS) + if (err != nil) != tt.wantErr { + t.Errorf("Reply = %v, want error: %v", err, tt.wantErr) + } + if (logged.Len() != 0) != tt.wantErr { + t.Errorf("logged %q, want a log: %v", logged.String(), tt.wantErr) + } + }) + } +} + +func TestFormatWireLogEntryStatus(t *testing.T) { + tests := []struct { + name string + opErr error + want int + }{ + {"wrapped errno", fmt.Errorf("lookup: %w", syscall.ENOENT), int(syscall.ENOENT)}, + {"no errno", errors.New("lookup failed"), 0}, + {"nil path error", nilPathErr, 0}, + {"wrapped nil path error", fmt.Errorf("lookup: %w", nilPathErr), 0}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + wlog := NewWireLogRecord() + if _, err := formatWireLogEntry(&fuseops.LookUpInodeOp{}, tt.opErr, wlog); err != nil { + t.Fatalf("formatWireLogEntry: %v", err) + } + if wlog.Status != tt.want { + t.Errorf("Status = %d, want %d", wlog.Status, tt.want) + } + }) + } +} + +// fmt recovers from a panic in Error when it formats the error value itself. +func TestReplyDebugLogsOpError(t *testing.T) { + tests := []struct { + name string + opErr error + errorLogger bool + want string + }{ + {"ordinary error", errors.New("lookup failed"), false, `-> Error: "lookup failed"`}, + {"nil path error", nilPathErr, false, "-> Error: "}, + {"suppressed errno joined with nil path error", errors.Join(syscall.ENOSYS, nilPathErr), true, + "-> Error: %!q(PANIC=Error method: runtime error: invalid memory address or nil pointer dereference)"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var debugged bytes.Buffer + c := newReplyTestConnection(t, nil) + c.debugLogger = log.New(&debugged, "", 0) + if tt.errorLogger { + c.errorLogger = log.New(io.Discard, "", 0) + } + ctx, _, err := c.ReadOp() + if err != nil { + t.Fatalf("ReadOp: %v", err) + } + + if err := c.Reply(ctx, tt.opErr); err != nil { + t.Errorf("Reply: %v", err) + } + if !strings.HasSuffix(debugged.String(), "] "+tt.want+"\n") { + t.Errorf("debug log = %q, want it to end with %q", debugged.String(), tt.want) + } + }) + } +} + func TestSanitizeMaxPagesAndWrite(t *testing.T) { pageSize := uint32(buffer.GetPageSize()) defaultMaxWrite := uint32(buffer.MaxWriteSize) diff --git a/conversions.go b/conversions.go index a7c5a4fd..8ce05c90 100644 --- a/conversions.go +++ b/conversions.go @@ -27,6 +27,7 @@ import ( "github.com/jacobsa/fuse/fuseops" "github.com/jacobsa/fuse/internal/buffer" "github.com/jacobsa/fuse/internal/fusekernel" + "github.com/jacobsa/fuse/internal/operror" ) //////////////////////////////////////////////////////////////////////// @@ -805,7 +806,7 @@ func (c *Connection) kernelResponse( if !handled { m.OutHeader().Error = -int32(syscall.EIO) - if errno, ok := opErr.(syscall.Errno); ok { + if errno, ok := operror.Errno(opErr); ok { m.OutHeader().Error = -int32(errno) } diff --git a/fuseutil/file_system.go b/fuseutil/file_system.go index b1c27f56..50eb4c50 100644 --- a/fuseutil/file_system.go +++ b/fuseutil/file_system.go @@ -21,6 +21,7 @@ import ( "github.com/jacobsa/fuse" "github.com/jacobsa/fuse/fuseops" + "github.com/jacobsa/fuse/internal/operror" ) // An interface with a method for each op type in the fuseops package. This can @@ -155,20 +156,7 @@ func (s *fileSystemServer) handleOp( err = s.fs.ForgetInode(ctx, typed) case *fuseops.BatchForgetOp: - err = s.fs.BatchForget(ctx, typed) - if err == fuse.ENOSYS { - // Handle as a series of single-inode forget operations - for _, entry := range typed.Entries { - err = s.fs.ForgetInode(ctx, &fuseops.ForgetInodeOp{ - Inode: entry.Inode, - N: entry.N, - OpContext: typed.OpContext, - }) - if err != nil { - break - } - } - } + err = s.batchForget(ctx, typed) case *fuseops.MkDirOp: err = s.fs.MkDir(ctx, typed) @@ -248,3 +236,23 @@ func (s *fileSystemServer) handleOp( c.Reply(ctx, err) } + +func (s *fileSystemServer) batchForget( + ctx context.Context, + op *fuseops.BatchForgetOp) error { + err := s.fs.BatchForget(ctx, op) + if errno, _ := operror.Errno(err); errno == fuse.ENOSYS { + // Handle as a series of single-inode forget operations + for _, entry := range op.Entries { + err = s.fs.ForgetInode(ctx, &fuseops.ForgetInodeOp{ + Inode: entry.Inode, + N: entry.N, + OpContext: op.OpContext, + }) + if err != nil { + break + } + } + } + return err +} diff --git a/fuseutil/file_system_test.go b/fuseutil/file_system_test.go new file mode 100644 index 00000000..b6dbdcd6 --- /dev/null +++ b/fuseutil/file_system_test.go @@ -0,0 +1,77 @@ +// Copyright 2026 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package fuseutil + +import ( + "context" + "errors" + "fmt" + "os" + "slices" + "syscall" + "testing" + + "github.com/jacobsa/fuse" + "github.com/jacobsa/fuse/fuseops" +) + +type forgetRecorder struct { + NotImplementedFileSystem + batchErr error + forgotten []fuseops.InodeID +} + +func (fs *forgetRecorder) BatchForget(context.Context, *fuseops.BatchForgetOp) error { + return fs.batchErr +} + +func (fs *forgetRecorder) ForgetInode(_ context.Context, op *fuseops.ForgetInodeOp) error { + fs.forgotten = append(fs.forgotten, op.Inode) + return nil +} + +func TestBatchForgetFallsBackToForgetInodeOnENOSYS(t *testing.T) { + eioBeforeENOSYS := fmt.Errorf("batch forget: %w (cleanup: %w)", syscall.EIO, fuse.ENOSYS) + // A nil *os.PathError panics when errors.As or errors.Is unwraps it. + var nilPathErr error = (*os.PathError)(nil) + wrappedNilPathErr := fmt.Errorf("batch forget: %w", nilPathErr) + tests := []struct { + name string + batchErr error + wantErr error + want []fuseops.InodeID + }{ + {"bare ENOSYS", fuse.ENOSYS, nil, []fuseops.InodeID{2, 3}}, + {"wrapped ENOSYS", fmt.Errorf("batch forget: %w", fuse.ENOSYS), nil, []fuseops.InodeID{2, 3}}, + {"implemented", nil, nil, nil}, + {"other error", syscall.EIO, syscall.EIO, nil}, + {"EIO before ENOSYS", eioBeforeENOSYS, eioBeforeENOSYS, nil}, + {"nil path error", nilPathErr, nilPathErr, nil}, + {"wrapped nil path error", wrappedNilPathErr, wrappedNilPathErr, nil}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fs := &forgetRecorder{batchErr: tt.batchErr} + s := &fileSystemServer{fs: fs} + op := &fuseops.BatchForgetOp{Entries: []fuseops.BatchForgetEntry{{Inode: 2, N: 1}, {Inode: 3, N: 1}}} + if err := s.batchForget(context.Background(), op); !errors.Is(err, tt.wantErr) { + t.Errorf("batchForget = %v, want %v", err, tt.wantErr) + } + if !slices.Equal(fs.forgotten, tt.want) { + t.Errorf("forgotten inodes = %v, want %v", fs.forgotten, tt.want) + } + }) + } +} diff --git a/internal/operror/operror.go b/internal/operror/operror.go new file mode 100644 index 00000000..e1656b2b --- /dev/null +++ b/internal/operror/operror.go @@ -0,0 +1,35 @@ +// Copyright 2026 Google Inc. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package operror finds the errno in the error a file system returns for an +// op. +package operror + +import ( + "errors" + "syscall" +) + +// Errno returns the first syscall.Errno in err's chain. It reports false when +// the chain holds none, or when unwrapping the chain panics, as it does for a +// nil *os.PathError. +func Errno(err error) (errno syscall.Errno, ok bool) { + defer func() { + if recover() != nil { + errno, ok = 0, false + } + }() + ok = errors.As(err, &errno) + return errno, ok +} diff --git a/wirelog.go b/wirelog.go index 2ce7ab12..40cdf6fa 100644 --- a/wirelog.go +++ b/wirelog.go @@ -16,13 +16,12 @@ package fuse import ( "encoding/json" - "errors" "reflect" "slices" - "syscall" "time" "github.com/jacobsa/fuse/fuseops" + "github.com/jacobsa/fuse/internal/operror" ) // NewWireLogRecord creates a new empty WireLogRecord. @@ -58,10 +57,9 @@ func formatWireLogEntry(op any, opErr error, wlog *WireLogRecord) ([]byte, error wlog.Duration = time.Since(wlog.StartTime) // Result of the operation - var errno syscall.Errno if opErr == nil { wlog.Status = 0 - } else if errors.As(opErr, &errno) { + } else if errno, ok := operror.Errno(opErr); ok { wlog.Status = int(errno) }