Debian Codegraph @

contrib/bindings/python/pathrs/procfs.py

raw symbols SCIP
1 #!/usr/bin/python3
2 # SPDX-License-Identifier: MPL-2.0
3 #
4 # libpathrs: safe path resolution on Linux
5 # Copyright (C) 2019-2025 SUSE LLC
6 # Copyright (C) 2026 Aleksa Sarai <[email protected]>
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 import typing
13 from typing import Any, IO, cast
14
15 # TODO: Remove this once we only support Python >= 3.11.
16 from typing_extensions import Self, TypeAlias
17
18 from ._internal import (
19 # File type helpers.
20 WrappedFd,
21 _convert_mode,
22 # Error API.
23 PathrsError,
24 _is_pathrs_err,
25 INTERNAL_ERROR,
26 # CFFI helpers.
27 _cstr,
28 _cbuffer,
29 )
30 from ._libpathrs_cffi import lib as libpathrs_so
31
32 if typing.TYPE_CHECKING:
33 # mypy apparently cannot handle the "ffi: cffi.api.FFI" definition in
34 # _libpathrs_cffi/__init__.pyi so we need to explicitly reference the type
35 # from cffi here.
36 import cffi
37
38 ffi = cffi.FFI()
39 CString: TypeAlias = cffi.FFI.CData
40 CBuffer: TypeAlias = cffi.FFI.CData
41 else:
42 from ._libpathrs_cffi import ffi
43
44 CString: TypeAlias = ffi.CData
45 CBuffer: TypeAlias = ffi.CData
46
47 __all__ = [
48 "PROC_ROOT",
49 "PROC_SELF",
50 "PROC_THREAD_SELF",
51 "PROC_PID",
52 "ProcfsHandle",
53 # Shorthand for ProcfsHandle.cached().<foo>.
54 "open",
55 "open_raw",
56 "readlink",
57 ]
58
59 # TODO: Switch to "type ..." syntax once we switch to Python >= 3.12...?
60 ProcfsBase: TypeAlias = int
61
62 #: Resolve proc_* operations relative to the /proc root. Note that this mode
63 #: may be more expensive because we have to take steps to try to avoid leaking
64 #: unmasked procfs handles, so you should use PROC_SELF if you can.
65 PROC_ROOT: ProcfsBase = libpathrs_so.PATHRS_PROC_ROOT
66
67 #: Resolve proc_* operations relative to /proc/self. For most programs, this is
68 #: the standard choice.
69 PROC_SELF: ProcfsBase = libpathrs_so.PATHRS_PROC_SELF
70
71 #: Resolve proc_* operations relative to /proc/thread-self. In multi-threaded
72 #: programs where one thread has a different CLONE_FS, it is possible for
73 #: /proc/self to point the wrong thread and so /proc/thread-self may be
74 #: necessary.
75 PROC_THREAD_SELF: ProcfsBase = libpathrs_so.PATHRS_PROC_THREAD_SELF
76
77
78 def PROC_PID(pid: int) -> ProcfsBase:
79 """
80 Resolve proc_* operations relative to /proc/<pid>. Be aware that due to PID
81 recycling, using this is generally not safe except in certain
82 circumstances. Namely:
83
84 * PID 1 (the init process), as that PID cannot ever get recycled.
85 * Your current PID (though you should just use PROC_SELF).
86 * PIDs of child processes (as long as you are sure that no other part of
87 your program incorrectly catches or ignores SIGCHLD, and that you do it
88 *before* you call wait(2)or any equivalent method that could reap
89 zombies).
90 """
91 if pid & libpathrs_so.__PATHRS_PROC_TYPE_MASK:
92 raise ValueError(f"invalid PROC_PID value {pid}")
93 return libpathrs_so.__PATHRS_PROC_TYPE_PID | pid
94
95
96 class ProcfsHandle(WrappedFd):
97 """ """
98
99 _PROCFS_OPEN_HOW_TYPE = "pathrs_procfs_open_how *"
100
101 @classmethod
102 def cached(cls) -> Self:
103 """
104 Returns a cached version of ProcfsHandle that will always remain valid
105 and cannot be closed. This is the recommended usage of ProcfsHandle.
106 """
107 return cls.from_raw_fd(libpathrs_so.PATHRS_PROC_DEFAULT_ROOTFD)
108
109 @classmethod
110 def new(cls, /, *, unmasked: bool = False) -> Self:
111 """
112 Create a new procfs handle with the requested configuration settings.
113
114 Note that the requested configuration might be eligible for caching, in
115 which case the ProcfsHandle.fileno() will contain a special sentinel
116 value that cannot be used like a regular file descriptor.
117 """
118
119 # TODO: Is there a way to have ProcfsOpenHow actually subclass CData so
120 # that we don't need to do any of these ugly casts?
121 how = cast("libpathrs_so.ProcfsOpenHow", ffi.new(cls._PROCFS_OPEN_HOW_TYPE))
122 how_size = ffi.sizeof(cast("Any", how))
123
124 if unmasked:
125 how.flags = libpathrs_so.PATHRS_PROCFS_NEW_UNMASKED
126
127 fd = libpathrs_so.pathrs_procfs_open(how, how_size)
128 if _is_pathrs_err(fd):
129 raise PathrsError._fetch(fd) or INTERNAL_ERROR
130 return cls.from_raw_fd(fd)
131
132 def open_raw(self, base: ProcfsBase, path: str, flags: int, /) -> WrappedFd:
133 """
134 Open a procfs file using Unix open flags.
135
136 This function returns a WrappedFd file handle.
137
138 base indicates what the path should be relative to. Valid values
139 include PROC_{ROOT,SELF,THREAD_SELF}.
140
141 path is a relative path to base indicating which procfs file you wish
142 to open.
143
144 flags is the set of O_* flags you wish to pass to the open operation.
145 If you do not intend to open a symlink, you should pass O_NOFOLLOW to
146 flags to let libpathrs know that it can be more strict when opening the
147 path.
148 """
149 # TODO: Should we default to O_NOFOLLOW or put a separate argument for it?
150 fd = libpathrs_so.pathrs_proc_openat(self.fileno(), base, _cstr(path), flags)
151 if _is_pathrs_err(fd):
152 raise PathrsError._fetch(fd) or INTERNAL_ERROR
153 return WrappedFd(fd)
154
155 def open(
156 self, base: ProcfsBase, path: str, mode: str = "r", /, *, extra_flags: int = 0
157 ) -> IO[Any]:
158 """
159 Open a procfs file using Pythonic mode strings.
160
161 This function returns an os.fdopen() file handle.
162
163 base indicates what the path should be relative to. Valid values
164 include PROC_{ROOT,SELF,THREAD_SELF}.
165
166 path is a relative path to base indicating which procfs file you wish
167 to open.
168
169 mode is a Python mode string, and extra_flags can be used to indicate
170 extra O_* flags you wish to pass to the open operation. If you do not
171 intend to open a symlink, you should pass O_NOFOLLOW to extra_flags to
172 let libpathrs know that it can be more strict when opening the path.
173 """
174 flags = _convert_mode(mode) | extra_flags
175 with self.open_raw(base, path, flags) as file:
176 return file.fdopen(mode)
177
178 def readlink(self, base: ProcfsBase, path: str, /) -> str:
179 """
180 Fetch the target of a procfs symlink.
181
182 Note that some procfs symlinks are "magic-links" where the returned
183 string from readlink() is not how they are actually resolved.
184
185 base indicates what the path should be relative to. Valid values
186 include PROC_{ROOT,SELF,THREAD_SELF}.
187
188 path is a relative path to base indicating which procfs file you wish
189 to open.
190 """
191 # TODO: See if we can merge this with Root.readlink.
192 cpath = _cstr(path)
193 linkbuf_size = 128
194 while True:
195 linkbuf = _cbuffer(linkbuf_size)
196 n = libpathrs_so.pathrs_proc_readlinkat(
197 self.fileno(), base, cpath, linkbuf, linkbuf_size
198 )
199 if _is_pathrs_err(n):
200 raise PathrsError._fetch(n) or INTERNAL_ERROR
201 elif n <= linkbuf_size:
202 buf = typing.cast(bytes, ffi.buffer(linkbuf, linkbuf_size)[:n])
203 return buf.decode("latin1")
204 else:
205 # The contents were truncated. Unlike readlinkat, pathrs
206 # returns the size of the link when it checked. So use the
207 # returned size as a basis for the reallocated size (but in
208 # order to avoid a DoS where a magic-link is growing by a
209 # single byte each iteration, make sure we are a fair bit
210 # larger).
211 linkbuf_size += n
212
213
214 #: Open a procfs file (with unix open flags).
215 #: Shorthand for ProcfsHandle.cached().open(...).
216 open = ProcfsHandle.cached().open
217
218 #: Open a procfs file (with Pythonic mode strings).
219 #: Shorthand for ProcfsHandle.cached().open_raw(...).
220 open_raw = ProcfsHandle.cached().open_raw
221
222 #: Fetch the target of a procfs symlink.
223 #: Shorthand for ProcfsHandle.cached().readlink(...).
224 readlink = ProcfsHandle.cached().readlink