File: fd_linux.go

package info (click to toggle)
rust-pathrs 0.2.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,912 kB
  • sloc: python: 1,138; sh: 371; ansic: 259; makefile: 151
file content (75 lines) | stat: -rw-r--r-- 2,219 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//go:build linux

// SPDX-License-Identifier: MPL-2.0
/*
 * libpathrs: safe path resolution on Linux
 * Copyright (C) 2019-2025 Aleksa Sarai <cyphar@cyphar.com>
 * Copyright (C) 2019-2025 SUSE LLC
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

// Package fdutils contains a few helper methods when dealing with *os.File and
// file descriptors.
package fdutils

import (
	"fmt"
	"os"

	"golang.org/x/sys/unix"

	"cyphar.com/go-pathrs/internal/libpathrs"
)

// DupFd makes a duplicate of the given fd.
func DupFd(fd uintptr, name string) (*os.File, error) {
	newFd, err := unix.FcntlInt(fd, unix.F_DUPFD_CLOEXEC, 0)
	if err != nil {
		return nil, fmt.Errorf("fcntl(F_DUPFD_CLOEXEC): %w", err)
	}
	return os.NewFile(uintptr(newFd), name), nil
}

// WithFileFd is a more ergonomic wrapper around file.SyscallConn().Control().
func WithFileFd[T any](file *os.File, fn func(fd uintptr) (T, error)) (T, error) {
	conn, err := file.SyscallConn()
	if err != nil {
		return *new(T), err
	}
	var (
		ret      T
		innerErr error
	)
	if err := conn.Control(func(fd uintptr) {
		ret, innerErr = fn(fd)
	}); err != nil {
		return *new(T), err
	}
	return ret, innerErr
}

// DupFile makes a duplicate of the given file.
func DupFile(file *os.File) (*os.File, error) {
	return WithFileFd(file, func(fd uintptr) (*os.File, error) {
		return DupFd(fd, file.Name())
	})
}

// MkFile creates a new *os.File from the provided file descriptor. However,
// unlike os.NewFile, the file's Name is based on the real path (provided by
// /proc/self/fd/$n).
func MkFile(fd uintptr) (*os.File, error) {
	fdPath := fmt.Sprintf("fd/%d", fd)
	fdName, err := libpathrs.ProcReadlinkat(libpathrs.ProcDefaultRootFd, libpathrs.ProcThreadSelf, fdPath)
	if err != nil {
		_ = unix.Close(int(fd))
		return nil, fmt.Errorf("failed to fetch real name of fd %d: %w", fd, err)
	}
	// TODO: Maybe we should prefix this name with something to indicate to
	// users that they must not use this path as a "safe" path. Something like
	// "//pathrs-handle:/foo/bar"?
	return os.NewFile(fd, fdName), nil
}