Debian Codegraph @

contrib/bindings/python/pathrs/_pathrs.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 os
13
14 import typing
15 from typing import Any, IO, Union, cast
16 import warnings
17
18 # TODO: Remove this once we only support Python >= 3.11.
19 from typing_extensions import TypeAlias
20
21 from ._internal import (
22 # Generic helpers.
23 SingletonClass,
24 # File type helpers.
25 FileLike,
26 WrappedFd,
27 _convert_mode,
28 # Error API.
29 PathrsError,
30 _is_pathrs_err,
31 INTERNAL_ERROR,
32 # CFFI helpers.
33 _cstr,
34 _pystr,
35 _cbuffer,
36 )
37 from ._libpathrs_cffi import lib as libpathrs_so
38
39 if typing.TYPE_CHECKING:
40 # mypy apparently cannot handle the "ffi: cffi.api.FFI" definition in
41 # _libpathrs_cffi/__init__.pyi so we need to explicitly reference the type
42 # from cffi here.
43 import cffi
44
45 ffi = cffi.FFI()
46 CString: TypeAlias = cffi.FFI.CData
47 CBuffer: TypeAlias = cffi.FFI.CData
48 else:
49 from ._libpathrs_cffi import ffi
50
51 CString: TypeAlias = ffi.CData
52 CBuffer: TypeAlias = ffi.CData
53
54 __all__ = [
55 # Core api.
56 "Root",
57 "Handle",
58 "library_version",
59 # Error api (re-export).
60 "PathrsError",
61 ]
62
63
64 class VersionInfo(metaclass=SingletonClass):
65 """Stores information about the runtime version of libpathrs.so."""
66
67 _VERSION_INFO_TYPE = "pathrs_version_info_t *"
68
69 version_string: str
70
71 def __init__(self): # type: ignore[no-untyped-def] # TODO: mypy appears to struggle with metaclasses.
72 info = cast("libpathrs_so.VersionInfo", ffi.new(self._VERSION_INFO_TYPE))
73 info_size = ffi.sizeof(cast("Any", info))
74
75 size = libpathrs_so.pathrs_version(info, info_size)
76 if _is_pathrs_err(size):
77 raise PathrsError._fetch(size) or INTERNAL_ERROR
78 if size > 0:
79 # TODO: We should also output a warning if the size of
80 # pathrs_version_info_t is bigger than the number of fields in the
81 # python-native VersionInfo. Otherwise a rebuild will mask that
82 # Python callers cannot see any new fields.
83 warnings.warn(
84 f"pathrs_version returned extra data we could not parse (need {size} bytes but buffer was only {info_size})"
85 )
86
87 self.version_string = _pystr(info.version_string)
88
89
90 def library_version() -> VersionInfo:
91 """
92 Returns information about the runtime version of libpathrs.so.
93 This is just shorthand for VersionInfo().
94 """
95 return VersionInfo() # type: ignore[no-untyped-call] # TODO: mypy appears to struggle with metaclasses.
96
97
98 class Handle(WrappedFd):
99 "A handle to a filesystem object, usually resolved using Root.resolve()."
100
101 def reopen(self, mode: str = "r", /, *, extra_flags: int = 0) -> IO[Any]:
102 """
103 Upgrade a Handle to a os.fdopen() file handle.
104
105 mode is a Python mode string, and extra_flags can be used to indicate
106 extra O_* flags you wish to pass to the reopen operation.
107
108 The returned file handle is independent to the original Handle, and you
109 can freely call Handle.reopen() on the same Handle multiple times.
110 """
111 flags = _convert_mode(mode) | extra_flags
112 with self.reopen_raw(flags) as file:
113 return file.fdopen(mode)
114
115 def reopen_raw(self, flags: int, /) -> WrappedFd:
116 """
117 Upgrade a Handle to a WrappedFd file handle.
118
119 flags is the set of O_* flags you wish to pass to the open operation.
120
121 The returned file handle is independent to the original Handle, and you
122 can freely call Handle.reopen() on the same Handle multiple times.
123 """
124 fd = libpathrs_so.pathrs_reopen(self.fileno(), flags)
125 if _is_pathrs_err(fd):
126 raise PathrsError._fetch(fd) or INTERNAL_ERROR
127 return WrappedFd(fd)
128
129
130 class Root(WrappedFd):
131 """
132 A handle to a filesystem root, which filesystem operations are all done
133 relative to.
134 """
135
136 def __init__(self, file_or_path: Union[FileLike, str], /):
137 """
138 Create a handle from a file-like object or a path to a directory.
139
140 Note that creating a Root in an attacker-controlled directory can allow
141 for an attacker to trick you into allowing breakouts. If file_or_path
142 is a path string, be aware there are no protections against rename race
143 attacks when opening the Root directory handle itself.
144 """
145 if isinstance(file_or_path, str):
146 path = _cstr(file_or_path)
147 fd = libpathrs_so.pathrs_open_root(path)
148 if _is_pathrs_err(fd):
149 raise PathrsError._fetch(fd) or INTERNAL_ERROR
150 file: FileLike = fd
151 else:
152 file = file_or_path
153
154 # XXX: Is this necessary?
155 super().__init__(file)
156
157 def resolve(self, path: str, /, *, follow_trailing: bool = True) -> Handle:
158 """
159 Resolve the given path inside the Root and return a Handle.
160
161 follow_trailing indicates what resolve should do if the final component
162 of the path is a symlink. The default is to continue resolving it, if
163 follow_trailing=False then a handle to the symlink itself is returned.
164 This has some limited uses, but most users should use the default.
165
166 A pathrs.Error is raised if the path doesn't exist.
167 """
168 if follow_trailing:
169 fd = libpathrs_so.pathrs_inroot_resolve(self.fileno(), _cstr(path))
170 else:
171 fd = libpathrs_so.pathrs_inroot_resolve_nofollow(self.fileno(), _cstr(path))
172 if _is_pathrs_err(fd):
173 raise PathrsError._fetch(fd) or INTERNAL_ERROR
174 return Handle(fd)
175
176 def open(
177 self,
178 path: str,
179 mode: str = "r",
180 /,
181 *,
182 follow_trailing: bool = True,
183 extra_flags: int = 0,
184 ) -> IO[Any]:
185 """
186 Resolve and open a path inside the Root and return an os.fdopen() file
187 handle.
188
189 This is effectively shorthand for Root.resolve(path).reopen(...), but
190 for the openat2-based resolver this is slightly more efficient if you
191 just want to open a file and don't need to do multiple reopens of the
192 Handle.
193
194 mode is a Python mode string, and extra_flags can be used to indicate
195 extra O_* flags you wish to pass to the open operation.
196
197 follow_trailing has the same behaviour as Root.resolve(), and is
198 equivalent to passing os.O_NOFOLLOW to extra_flags.
199 """
200 flags = _convert_mode(mode) | extra_flags
201 if not follow_trailing:
202 flags |= os.O_NOFOLLOW
203 with self.open_raw(path, flags) as file:
204 return file.fdopen(mode)
205
206 def open_raw(self, path: str, flags: int, /) -> WrappedFd:
207 """
208 Resolve and open a path inside the Root and return a WrappedFd file
209 handle.
210
211 This is effectively shorthand for Root.resolve(path).reopen_raw(flags),
212 but for the openat2-based resolver this is slightly more efficient if
213 you just want to open a file and don't need to do multiple reopens of
214 the Handle.
215
216 If flags contains os.O_NOFOLLOW, then the resolution is done as if you
217 passed follow_trailing=False to Root.resolve().
218 """
219 fd = libpathrs_so.pathrs_inroot_open(self.fileno(), _cstr(path), flags)
220 if _is_pathrs_err(fd):
221 raise PathrsError._fetch(fd) or INTERNAL_ERROR
222 return WrappedFd(fd)
223
224 def readlink(self, path: str, /) -> str:
225 """
226 Fetch the target of a symlink at the given path in the Root.
227
228 A pathrs.Error is raised if the path is not a symlink or doesn't exist.
229 """
230 cpath = _cstr(path)
231 linkbuf_size = 128
232 while True:
233 linkbuf = _cbuffer(linkbuf_size)
234 n = libpathrs_so.pathrs_inroot_readlink(
235 self.fileno(), cpath, linkbuf, linkbuf_size
236 )
237 if _is_pathrs_err(n):
238 raise PathrsError._fetch(n) or INTERNAL_ERROR
239 elif n <= linkbuf_size:
240 buf = typing.cast(bytes, ffi.buffer(linkbuf, linkbuf_size)[:n])
241 return buf.decode("latin1")
242 else:
243 # The contents were truncated. Unlike readlinkat, pathrs returns
244 # the size of the link when it checked. So use the returned size
245 # as a basis for the reallocated size (but in order to avoid a DoS
246 # where a magic-link is growing by a single byte each iteration,
247 # make sure we are a fair bit larger).
248 linkbuf_size += n
249
250 def creat(
251 self, path: str, mode: str = "r", filemode: int = 0o644, /, extra_flags: int = 0
252 ) -> IO[Any]:
253 """
254 Atomically create-and-open a new file at the given path in the Root,
255 a-la O_CREAT.
256
257 This method returns an os.fdopen() file handle.
258
259 filemode is the Unix DAC mode you wish the new file to be created with.
260 This mode might not be the actual mode of the created file due to a
261 variety of external factors (umask, setgid bits, POSIX ACLs).
262
263 mode is a Python mode string, and extra_flags can be used to indicate
264 extra O_* flags you wish to pass to the reopen operation. If you wish
265 to ensure the new file was created *by you* then you may wish to add
266 O_EXCL to extra_flags.
267 """
268 flags = _convert_mode(mode) | extra_flags
269 fd = libpathrs_so.pathrs_inroot_creat(
270 self.fileno(), _cstr(path), flags, filemode
271 )
272 if _is_pathrs_err(fd):
273 raise PathrsError._fetch(fd) or INTERNAL_ERROR
274 return os.fdopen(fd, mode)
275
276 def creat_raw(self, path: str, flags: int, filemode: int = 0o644, /) -> WrappedFd:
277 """
278 Atomically create-and-open a new file at the given path in the Root,
279 a-la O_CREAT.
280
281 This method returns a WrappedFd handle.
282
283 filemode is the Unix DAC mode you wish the new file to be created with.
284 This mode might not be the actual mode of the created file due to a
285 variety of external factors (umask, setgid bits, POSIX ACLs).
286
287 flags is the set of O_* flags you wish to pass to the open operation. If
288 you do not intend to open a symlink, you should pass O_NOFOLLOW to flags to
289 let libpathrs know that it can be more strict when opening the path.
290 """
291 fd = libpathrs_so.pathrs_inroot_creat(
292 self.fileno(), _cstr(path), flags, filemode
293 )
294 if _is_pathrs_err(fd):
295 raise PathrsError._fetch(fd) or INTERNAL_ERROR
296 return WrappedFd(fd)
297
298 def rename(self, src: str, dst: str, flags: int = 0, /) -> None:
299 """
300 Rename a path from src to dst within the Root.
301
302 flags can be any renameat2(2) flags you wish to use, which can change
303 the behaviour of this method substantially. For instance,
304 RENAME_EXCHANGE will turn this into an atomic swap operation.
305 """
306 # TODO: Should we have a separate Root.swap() operation?
307 err = libpathrs_so.pathrs_inroot_rename(
308 self.fileno(), _cstr(src), self.fileno(), _cstr(dst), flags
309 )
310 if _is_pathrs_err(err):
311 raise PathrsError._fetch(err) or INTERNAL_ERROR
312
313 def rmdir(self, path: str, /) -> None:
314 """
315 Remove an empty directory at the given path within the Root.
316
317 To remove non-empty directories recursively, you can use
318 Root.remove_all().
319 """
320 err = libpathrs_so.pathrs_inroot_rmdir(self.fileno(), _cstr(path))
321 if _is_pathrs_err(err):
322 raise PathrsError._fetch(err) or INTERNAL_ERROR
323
324 def unlink(self, path: str, /) -> None:
325 """
326 Remove a non-directory inode at the given path within the Root.
327
328 To remove empty directories, you can use Root.remove_all(). To remove
329 files and non-empty directories recursively, you can use
330 Root.remove_all().
331 """
332 err = libpathrs_so.pathrs_inroot_unlink(self.fileno(), _cstr(path))
333 if _is_pathrs_err(err):
334 raise PathrsError._fetch(err) or INTERNAL_ERROR
335
336 def remove_all(self, path: str, /) -> None:
337 """
338 Remove the file or directory (empty or non-empty) at the given path
339 within the Root.
340 """
341 err = libpathrs_so.pathrs_inroot_remove_all(self.fileno(), _cstr(path))
342 if _is_pathrs_err(err):
343 raise PathrsError._fetch(err) or INTERNAL_ERROR
344
345 def mkdir(self, path: str, mode: int, /) -> None:
346 """
347 Create a directory at the given path within the Root.
348
349 mode is the Unix DAC mode you wish the new directory to be created
350 with. This mode might not be the actual mode of the created file due to
351 a variety of external factors (umask, setgid bits, POSIX ACLs).
352
353 A pathrs.Error will be raised if the parent directory doesn't exist, or
354 the path already exists. To create a directory and all of its parent
355 directories (or just reuse an existing directory) you can use
356 Root.mkdir_all().
357 """
358 err = libpathrs_so.pathrs_inroot_mkdir(self.fileno(), _cstr(path), mode)
359 if _is_pathrs_err(err):
360 raise PathrsError._fetch(err) or INTERNAL_ERROR
361
362 def mkdir_all(self, path: str, mode: int, /) -> Handle:
363 """
364 Recursively create a directory and all of its parents at the given path
365 within the Root (or reuse an existing directory if the path already
366 exists).
367
368 This method returns a Handle to the created directory.
369
370 mode is the Unix DAC mode you wish any new directories to be created
371 with. This mode might not be the actual mode of the created file due to
372 a variety of external factors (umask, setgid bits, POSIX ACLs). If the
373 full path already exists, this mode is ignored and the existing
374 directory mode is kept.
375 """
376 fd = libpathrs_so.pathrs_inroot_mkdir_all(self.fileno(), _cstr(path), mode)
377 if _is_pathrs_err(fd):
378 raise PathrsError._fetch(fd) or INTERNAL_ERROR
379 return Handle(fd)
380
381 def mknod(self, path: str, mode: int, device: int = 0, /) -> None:
382 """
383 Create a new inode at the given path within the Root.
384
385 mode both indicates the file type (it must contain a valid bit from
386 S_IFMT to indicate what kind of file to create) and what the mode of
387 the newly created file should have. This mode might not be the actual
388 mode of the created file due to a variety of external factors (umask,
389 setgid bits, POSIX ACLs).
390
391 dev is the the (major, minor) device number used for the new inode if
392 the mode contains S_IFCHR or S_IFBLK. You can construct the device
393 number from a (major, minor) using os.makedev().
394
395 A pathrs.Error is raised if the path already exists.
396 """
397 err = libpathrs_so.pathrs_inroot_mknod(self.fileno(), _cstr(path), mode, device)
398 if _is_pathrs_err(err):
399 raise PathrsError._fetch(err) or INTERNAL_ERROR
400
401 def hardlink(self, target: str, linkname: str, /) -> None:
402 """
403 Create a hardlink between two paths inside the Root.
404
405 linkname is the path to the *new* hardlink, and target is a path to
406 the *existing* file.
407
408 A pathrs.Error is raised if the path for the new hardlink already
409 exists.
410 """
411 err = libpathrs_so.pathrs_inroot_hardlink(
412 self.fileno(), _cstr(target), self.fileno(), _cstr(linkname), 0
413 )
414 if _is_pathrs_err(err):
415 raise PathrsError._fetch(err) or INTERNAL_ERROR
416
417 def symlink(self, target: str, linkname: str, /) -> None:
418 """
419 Create a symlink at the given path in the Root.
420
421 linkname is the path to the *new* symlink, and target is what the
422 symlink will point to. Note that symlink contents are not verified on
423 Linux, so there are no restrictions on what target you put.
424
425 A pathrs.Error is raised if the path for the new symlink already
426 exists.
427 """
428 err = libpathrs_so.pathrs_inroot_symlink(
429 _cstr(target), self.fileno(), _cstr(linkname)
430 )
431 if _is_pathrs_err(err):
432 raise PathrsError._fetch(err) or INTERNAL_ERROR