Skip to content

Commit 77889b5

Browse files
committed
internal: add wrappers for securejoin.Proc*
Signed-off-by: Aleksa Sarai <cyphar@cyphar.com>
1 parent 44a0fcf commit 77889b5

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

internal/pathrs/procfs_pathrslite.go

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,83 @@
1919
package pathrs
2020

2121
import (
22+
"fmt"
2223
"os"
2324

2425
"github.com/cyphar/filepath-securejoin/pathrs-lite"
26+
"github.com/cyphar/filepath-securejoin/pathrs-lite/procfs"
2527
)
2628

29+
func procOpenReopen(openFn func(subpath string) (*os.File, error), subpath string, flags int) (*os.File, error) {
30+
handle, err := openFn(subpath)
31+
if err != nil {
32+
return nil, err
33+
}
34+
defer handle.Close()
35+
36+
f, err := pathrs.Reopen(handle, flags)
37+
if err != nil {
38+
return nil, fmt.Errorf("reopen %s: %w", handle.Name(), err)
39+
}
40+
return f, nil
41+
}
42+
43+
// ProcSelfOpen is a wrapper around [procfs.Handle.OpenSelf] and
44+
// [pathrs.Reopen], to let you one-shot open a procfs file with the given
45+
// flags.
46+
func ProcSelfOpen(subpath string, flags int) (*os.File, error) {
47+
proc, err := procfs.OpenProcRoot()
48+
if err != nil {
49+
return nil, err
50+
}
51+
defer proc.Close()
52+
return procOpenReopen(proc.OpenSelf, subpath, flags)
53+
}
54+
55+
// ProcPidOpen is a wrapper around [procfs.Handle.OpenPid] and [pathrs.Reopen],
56+
// to let you one-shot open a procfs file with the given flags.
57+
func ProcPidOpen(pid int, subpath string, flags int) (*os.File, error) {
58+
proc, err := procfs.OpenProcRoot()
59+
if err != nil {
60+
return nil, err
61+
}
62+
defer proc.Close()
63+
return procOpenReopen(func(subpath string) (*os.File, error) {
64+
return proc.OpenPid(pid, subpath)
65+
}, subpath, flags)
66+
}
67+
68+
// ProcThreadSelfOpen is a wrapper around [procfs.Handle.OpenThreadSelf] and
69+
// [pathrs.Reopen], to let you one-shot open a procfs file with the given
70+
// flags. The returned [procfs.ProcThreadSelfCloser] needs the same handling as
71+
// when using pathrs-lite.
72+
func ProcThreadSelfOpen(subpath string, flags int) (_ *os.File, _ procfs.ProcThreadSelfCloser, Err error) {
73+
proc, err := procfs.OpenProcRoot()
74+
if err != nil {
75+
return nil, nil, err
76+
}
77+
defer proc.Close()
78+
79+
handle, closer, err := proc.OpenThreadSelf(subpath)
80+
if err != nil {
81+
return nil, nil, err
82+
}
83+
if closer != nil {
84+
defer func() {
85+
if Err != nil {
86+
closer()
87+
}
88+
}()
89+
}
90+
defer handle.Close()
91+
92+
f, err := pathrs.Reopen(handle, flags)
93+
if err != nil {
94+
return nil, nil, fmt.Errorf("reopen %s: %w", handle.Name(), err)
95+
}
96+
return f, closer, nil
97+
}
98+
2799
// Reopen is a wrapper around pathrs.Reopen.
28100
func Reopen(file *os.File, flags int) (*os.File, error) {
29101
return pathrs.Reopen(file, flags)

0 commit comments

Comments
 (0)