| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
|
| 3 |
//go:build linux |
| 4 |
|
| 5 |
// Copyright (C) 2024-2025 Aleksa Sarai <[email protected]> |
| 6 |
// Copyright (C) 2024-2025 SUSE LLC |
| 7 |
// |
| 8 |
// This Source Code Form is subject to the terms of the Mozilla Public |
| 9 |
// License, v. 2.0. If a copy of the MPL was not distributed with this |
| 10 |
// file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 11 |
|
| 12 |
package fd |
| 13 |
|
| 14 |
import ( |
| 15 |
"fmt" |
| 16 |
"os" |
| 17 |
"runtime" |
| 18 |
|
| 19 |
"golang.org/x/sys/unix" |
| 20 |
|
| 21 |
"github.com/cyphar/filepath-securejoin/pathrs-lite/internal" |
| 22 |
) |
| 23 |
|
| 24 |
// DupWithName creates a new file descriptor referencing the same underlying |
| 25 |
// file, but with the provided name instead of fd.Name(). |
| 26 |
func DupWithName(fd Fd, name string) (*os.File, error) { |
| 27 |
fd2, err := unix.FcntlInt(fd.Fd(), unix.F_DUPFD_CLOEXEC, 0) |
| 28 |
if err != nil { |
| 29 |
return nil, os.NewSyscallError("fcntl(F_DUPFD_CLOEXEC)", err) |
| 30 |
} |
| 31 |
runtime.KeepAlive(fd) |
| 32 |
return os.NewFile(uintptr(fd2), name), nil |
| 33 |
} |
| 34 |
|
| 35 |
// Dup creates a new file description referencing the same underlying file. |
| 36 |
func Dup(fd Fd) (*os.File, error) { |
| 37 |
return DupWithName(fd, fd.Name()) |
| 38 |
} |
| 39 |
|
| 40 |
// Fstat is an [Fd]-based wrapper around unix.Fstat. |
| 41 |
func Fstat(fd Fd) (unix.Stat_t, error) { |
| 42 |
var stat unix.Stat_t |
| 43 |
if err := unix.Fstat(int(fd.Fd()), &stat); err != nil { |
| 44 |
return stat, &os.PathError{Op: "fstat", Path: fd.Name(), Err: err} |
| 45 |
} |
| 46 |
runtime.KeepAlive(fd) |
| 47 |
return stat, nil |
| 48 |
} |
| 49 |
|
| 50 |
// Fstatfs is an [Fd]-based wrapper around unix.Fstatfs. |
| 51 |
func Fstatfs(fd Fd) (unix.Statfs_t, error) { |
| 52 |
var statfs unix.Statfs_t |
| 53 |
if err := unix.Fstatfs(int(fd.Fd()), &statfs); err != nil { |
| 54 |
return statfs, &os.PathError{Op: "fstatfs", Path: fd.Name(), Err: err} |
| 55 |
} |
| 56 |
runtime.KeepAlive(fd) |
| 57 |
return statfs, nil |
| 58 |
} |
| 59 |
|
| 60 |
// IsDeadInode detects whether the file has been unlinked from a filesystem and |
| 61 |
// is thus a "dead inode" from the kernel's perspective. |
| 62 |
func IsDeadInode(file Fd) error { |
| 63 |
// If the nlink of a file drops to 0, there is an attacker deleting |
| 64 |
// directories during our walk, which could result in weird /proc values. |
| 65 |
// It's better to error out in this case. |
| 66 |
stat, err := Fstat(file) |
| 67 |
if err != nil { |
| 68 |
return fmt.Errorf("check for dead inode: %w", err) |
| 69 |
} |
| 70 |
if stat.Nlink == 0 { |
| 71 |
err := internal.ErrDeletedInode |
| 72 |
if stat.Mode&unix.S_IFMT == unix.S_IFDIR { |
| 73 |
err = internal.ErrInvalidDirectory |
| 74 |
} |
| 75 |
return fmt.Errorf("%w %q", err, file.Name()) |
| 76 |
} |
| 77 |
return nil |
| 78 |
} |