Debian Codegraph @

contrib/bindings/python/pathrs/_internal.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 io
13 import os
14 import sys
15 import copy
16 import errno
17 import fcntl
18
19 import typing
20 from types import TracebackType
21 from typing import Any, Dict, IO, Optional, TextIO, Type, TypeVar, Union
22
23 # TODO: Remove this once we only support Python >= 3.11.
24 from typing_extensions import Self, TypeAlias
25
26 from ._libpathrs_cffi import lib as libpathrs_so
27
28 if typing.TYPE_CHECKING:
29 # mypy apparently cannot handle the "ffi: cffi.api.FFI" definition in
30 # _libpathrs_cffi/__init__.pyi so we need to explicitly reference the type
31 # from cffi here.
32 import cffi
33
34 ffi = cffi.FFI()
35 CString: TypeAlias = cffi.FFI.CData
36 CBuffer: TypeAlias = cffi.FFI.CData
37 else:
38 from ._libpathrs_cffi import ffi
39
40 CString: TypeAlias = ffi.CData
41 CBuffer: TypeAlias = ffi.CData
42
43
44 def _cstr(pystr: str) -> CString:
45 return ffi.new("char[]", pystr.encode("utf8"))
46
47
48 def _pystr(cstr: CString) -> str:
49 s = ffi.string(cstr)
50 assert isinstance(s, bytes) # typing
51 return s.decode("utf8")
52
53
54 def _cbuffer(size: int) -> CBuffer:
55 return ffi.new("char[%d]" % (size,))
56
57
58 def _is_pathrs_err(ret: int) -> bool:
59 return ret < libpathrs_so.__PATHRS_MAX_ERR_VALUE
60
61
62 class PathrsError(Exception):
63 """
64 Represents a libpathrs error. All libpathrs errors have a description
65 (PathrsError.message) and errors that were caused by an underlying OS error
66 (or can be translated to an OS error) also include the errno value
67 (PathrsError.errno).
68 """
69
70 message: str
71 errno: Optional[int]
72 strerror: Optional[str]
73
74 def __init__(self, message: str, /, *, errno: Optional[int] = None):
75 # Construct Exception.
76 super().__init__(message)
77
78 # Basic arguments.
79 self.message = message
80 self.errno = errno
81
82 # Pre-format the errno.
83 self.strerror = None
84 if errno is not None:
85 try:
86 self.strerror = os.strerror(errno)
87 except ValueError:
88 self.strerror = str(errno)
89
90 @classmethod
91 def _fetch(cls, err_id: int, /) -> Optional[Self]:
92 if err_id >= 0:
93 return None
94
95 err = libpathrs_so.pathrs_errorinfo(err_id)
96 if err == ffi.NULL: # type: ignore[comparison-overlap,unused-ignore] # TODO: Make this check nicer...
97 return None
98
99 description = _pystr(err.description)
100 errno = err.saved_errno or None
101
102 # TODO: Should we use ffi.gc()? mypy doesn't seem to like our types...
103 libpathrs_so.pathrs_errorinfo_free(err)
104 del err
105
106 return cls(description, errno=errno)
107
108 def __str__(self) -> str:
109 if self.errno is None:
110 return self.message
111 else:
112 return "%s (%s)" % (self.message, self.strerror)
113
114 def __repr__(self) -> str:
115 return "Error(%r, errno=%r)" % (self.message, self.errno)
116
117 def pprint(self, out: TextIO = sys.stdout) -> None:
118 "Pretty-print the error to the given @out file."
119 # Basic error information.
120 if self.errno is None:
121 print("pathrs error:", file=out)
122 else:
123 print("pathrs error [%s]:" % (self.strerror,), file=out)
124 print(" %s" % (self.message,), file=out)
125
126
127 INTERNAL_ERROR = PathrsError("tried to fetch libpathrs error but no error found")
128
129
130 class FilenoFile(typing.Protocol):
131 def fileno(self) -> int: ...
132
133
134 FileLike = Union[FilenoFile, int]
135
136
137 def _fileno(file: FileLike) -> int:
138 if isinstance(file, int):
139 # file is a plain fd
140 return file
141 else:
142 # Assume there is a fileno method.
143 return file.fileno()
144
145
146 def _clonefile(file: FileLike) -> int:
147 return fcntl.fcntl(_fileno(file), fcntl.F_DUPFD_CLOEXEC)
148
149
150 # TODO: Switch to def foo[T](...): ... syntax with Python >= 3.12.
151 Fd = TypeVar("Fd", bound="WrappedFd")
152
153
154 class WrappedFd(object):
155 """
156 Represents a file descriptor that allows for manual lifetime management,
157 unlike os.fdopen() which are tracked by the GC with no way of "leaking" the
158 file descriptor for FFI purposes.
159
160 pathrs will return WrappedFds for most operations that return an fd.
161 """
162
163 _fd: Optional[int]
164
165 def __init__(self, file: FileLike, /):
166 """
167 Construct a WrappedFd from any file-like object.
168
169 For most cases, the WrappedFd will take ownership of the lifetime of
170 the file handle. This means you should So a raw file descriptor must
171 only be turned into a WrappedFd *once* (unless you make sure to use
172 WrappedFd.leak() to ensure there is only ever one owner of the handle
173 at a given time).
174
175 However, for os.fdopen() (or similar Pythonic file objects that are
176 tracked by the GC), we have to create a clone and so the WrappedFd is a
177 copy.
178 """
179 # TODO: Maybe we should always clone to make these semantics less
180 # confusing...?
181 fd = _fileno(file)
182 if isinstance(file, io.IOBase):
183 # If this is a regular open file, we need to make a copy because
184 # you cannot leak files and so the GC might close it from
185 # underneath us.
186 fd = _clonefile(fd)
187 self._fd = fd
188
189 def fileno(self) -> int:
190 """
191 Return the file descriptor number of this WrappedFd.
192
193 Note that the file can still be garbage collected by Python after this
194 call, so the file descriptor number might become invalid (or worse, be
195 reused for an unrelated file).
196
197 If you want to convert a WrappedFd to a file descriptor number and stop
198 the GC from the closing the file, use WrappedFd.into_raw_fd().
199 """
200 if self._fd is None:
201 raise OSError(errno.EBADF, "Closed file descriptor")
202 return self._fd
203
204 def leak(self) -> None:
205 """
206 Clears this WrappedFd without closing the underlying file, to stop GC
207 from closing the file.
208
209 Note that after this operation, all operations on this WrappedFd will
210 return an error. If you want to get the underlying file handle and then
211 leak the WrappedFd, just use WrappedFd.into_raw_fd() which does both
212 for you.
213 """
214 if self._fd is not None and self._fd >= 0:
215 self._fd = None
216
217 def fdopen(self, mode: str = "r") -> IO[Any]:
218 """
219 Convert this WrappedFd into an os.fileopen() handle.
220
221 This operation implicitly calls WrappedFd.leak(), so the WrappedFd will
222 no longer be useful and you should instead use the returned os.fdopen()
223 handle.
224 """
225 fd = self.fileno()
226 try:
227 file = os.fdopen(fd, mode)
228 self.leak()
229 return file
230 except:
231 # "Unleak" the file if there was an error.
232 self._fd = fd
233 raise
234
235 @classmethod
236 def from_raw_fd(cls: Type[Fd], fd: int, /) -> Fd:
237 "Shorthand for WrappedFd(fd)."
238 return cls(fd)
239
240 @classmethod
241 def from_file(cls: Type[Fd], file: FileLike, /) -> Fd:
242 "Shorthand for WrappedFd(file)."
243 return cls(file)
244
245 def into_raw_fd(self) -> int:
246 """
247 Convert this WrappedFd into a raw file descriptor that GC won't touch.
248
249 This is just shorthand for WrappedFd.fileno() to get the fileno,
250 followed by WrappedFd.leak().
251 """
252 fd = self.fileno()
253 self.leak()
254 return fd
255
256 def isclosed(self) -> bool:
257 """
258 Returns whether the underlying file descriptor is closed or the
259 WrappedFd has been leaked.
260 """
261 return self._fd is None
262
263 def close(self) -> None:
264 """
265 Manually close the underlying file descriptor for this WrappedFd.
266
267 WrappedFds are garbage collected, so this is usually unnecessary unless
268 you really care about the point where a file is closed.
269 """
270 if not self.isclosed():
271 assert self._fd is not None # typing
272 if self._fd >= 0:
273 os.close(self._fd)
274 self._fd = None
275
276 def clone(self) -> Self:
277 "Create a clone of this WrappedFd that has a separate lifetime."
278 if self.isclosed():
279 raise ValueError("cannot clone closed file")
280 assert self._fd is not None # typing
281 newfd = self._fd
282 if self._fd >= 0:
283 newfd = _clonefile(self._fd)
284 return self.__class__.from_raw_fd(newfd)
285
286 def __copy__(self) -> Self:
287 "Identical to WrappedFd.clone()"
288 # A "shallow copy" of a file is the same as a deep copy.
289 return copy.deepcopy(self)
290
291 def __deepcopy__(self, memo: Dict[int, Any]) -> Self:
292 "Identical to WrappedFd.clone()"
293 return self.clone()
294
295 def __del__(self) -> None:
296 "Identical to WrappedFd.close()"
297 self.close()
298
299 def __enter__(self) -> Self:
300 return self
301
302 def __exit__(
303 self,
304 exc_type: Optional[Type[BaseException]],
305 exc_value: Optional[BaseException],
306 exc_traceback: Optional[TracebackType],
307 ) -> None:
308 self.close()
309
310
311 # XXX: This is _super_ ugly but so is the one in CPython.
312 def _convert_mode(mode: str) -> int:
313 mode_set = set(mode)
314 flags = os.O_CLOEXEC
315
316 # We don't support O_CREAT or O_EXCL with libpathrs -- use creat().
317 if "x" in mode_set:
318 raise ValueError("pathrs doesn't support mode='x', use Root.creat()")
319 # Basic sanity-check to make sure we don't accept garbage modes.
320 if len(mode_set & {"r", "w", "a"}) > 1:
321 raise ValueError("must have exactly one of read/write/append mode")
322
323 read = False
324 write = False
325
326 if "+" in mode_set:
327 read = True
328 write = True
329 if "r" in mode_set:
330 read = True
331 if "w" in mode_set:
332 write = True
333 flags |= os.O_TRUNC
334 if "a" in mode_set:
335 write = True
336 flags |= os.O_APPEND
337
338 if read and write:
339 flags |= os.O_RDWR
340 elif write:
341 flags |= os.O_WRONLY
342 else:
343 flags |= os.O_RDONLY
344
345 # We don't care about "b" or "t" since that's just a Python thing.
346 return flags
347
348
349 class SingletonClass(type):
350 """Metaclass used to create singleton classes."""
351
352 _instances: dict[type, Type[Any]] = {}
353
354 def __call__(cls, *args, **kwargs): # type: ignore[no-untyped-def] # TODO: Not clear what annotations to use, and mypy appears to be confused by metaclasses.
355 if cls not in cls._instances:
356 cls._instances[cls] = super(SingletonClass, cls).__call__(*args, **kwargs)
357 return cls._instances[cls]