Debian Codegraph @

contrib/bindings/go/internal/fdutils/fd_linux.go

raw symbols SCIP
1 //go:build linux
2
3 // SPDX-License-Identifier: MPL-2.0
4 /*
5 * libpathrs: safe path resolution on Linux
6 * Copyright (C) 2019-2025 SUSE LLC
7 * Copyright (C) 2026 Aleksa Sarai <[email protected]>
8 *
9 * This Source Code Form is subject to the terms of the Mozilla Public
10 * License, v. 2.0. If a copy of the MPL was not distributed with this
11 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
12 */
13
14 // Package fdutils contains a few helper methods when dealing with *os.File and
15 // file descriptors.
16 package fdutils
17
18 import (
19 "fmt"
20 "os"
21
22 "golang.org/x/sys/unix"
23
24 "cyphar.com/go-pathrs/internal/libpathrs"
25 )
26
27 // DupFd makes a duplicate of the given fd.
28 func DupFd(fd uintptr, name string) (*os.File, error) {
29 newFd, err := unix.FcntlInt(fd, unix.F_DUPFD_CLOEXEC, 0)
30 if err != nil {
31 return nil, fmt.Errorf("fcntl(F_DUPFD_CLOEXEC): %w", err)
32 }
33 return os.NewFile(uintptr(newFd), name), nil
34 }
35
36 // WithFileFd is a more ergonomic wrapper around file.SyscallConn().Control().
37 func WithFileFd[T any](file *os.File, fn func(fd uintptr) (T, error)) (T, error) {
38 conn, err := file.SyscallConn()
39 if err != nil {
40 return *new(T), err
41 }
42 var (
43 ret T
44 innerErr error
45 )
46 if err := conn.Control(func(fd uintptr) {
47 ret, innerErr = fn(fd)
48 }); err != nil {
49 return *new(T), err
50 }
51 return ret, innerErr
52 }
53
54 // DupFile makes a duplicate of the given file.
55 func DupFile(file *os.File) (*os.File, error) {
56 return WithFileFd(file, func(fd uintptr) (*os.File, error) {
57 return DupFd(fd, file.Name())
58 })
59 }
60
61 // MkFile creates a new *os.File from the provided file descriptor. However,
62 // unlike os.NewFile, the file's Name is based on the real path (provided by
63 // /proc/self/fd/$n).
64 func MkFile(fd uintptr) (*os.File, error) {
65 fdPath := fmt.Sprintf("fd/%d", fd)
66 fdName, err := libpathrs.ProcReadlinkat(libpathrs.ProcDefaultRootFd, libpathrs.ProcThreadSelf, fdPath)
67 if err != nil {
68 _ = unix.Close(int(fd))
69 return nil, fmt.Errorf("failed to fetch real name of fd %d: %w", fd, err)
70 }
71 // TODO: Maybe we should prefix this name with something to indicate to
72 // users that they must not use this path as a "safe" path. Something like
73 // "//pathrs-handle:/foo/bar"?
74 return os.NewFile(fd, fdName), nil
75 }