Debian Codegraph @

conda_package_streaming/extract.py

raw
1 """
2 Extract package to directory, with checks against tar members extracting outside
3 the target directory.
4 """
5
6 from __future__ import annotations
7
8 import os
9 import tarfile
10 from collections.abc import Generator
11 from errno import ELOOP
12 from pathlib import Path
13
14 from . import exceptions, package_streaming
15
16 __all__ = ["extract_stream", "extract"]
17 HAS_TAR_FILTER = hasattr(tarfile, "tar_filter")
18
19
20 def extract_stream(
21 stream: Generator[tuple[tarfile.TarFile, tarfile.TarInfo]],
22 dest_dir: Path | str,
23 tar_filter: str | None = None,
24 ):
25 """
26 Pipe ``stream_conda_component`` output here to extract every member into
27 dest_dir.
28
29 For ``.conda`` will need to be called twice (for info and pkg components);
30 for ``.tar.bz2`` every member is extracted.
31 """
32 dest_dir = os.path.realpath(dest_dir)
33
34 def is_within_dest_dir(name):
35 abs_target = os.path.realpath(os.path.join(dest_dir, name))
36 prefix = os.path.commonpath((dest_dir, abs_target))
37 return prefix == dest_dir
38
39 for tar_file, _ in stream:
40 # careful not to seek backwards
41 def checked_members():
42 # from conda_package_handling
43 for member in tar_file:
44 if not is_within_dest_dir(member.name):
45 raise exceptions.SafetyError(f"contains unsafe path: {member.name}")
46 yield member
47
48 try:
49 # Drop checked_members() when HAS_TAR_FILTER once we are 100%
50 # certain the stdlib filter maintains same permissions as
51 # checked_members().
52 tar_args = {"path": dest_dir, "members": checked_members()}
53 if HAS_TAR_FILTER:
54 tar_args["filter"] = tar_filter or "fully_trusted"
55 tar_file.extractall(**tar_args)
56 except OSError as e:
57 if e.errno == ELOOP:
58 raise exceptions.CaseInsensitiveFileSystemError() from e
59 raise
60
61 # next iteraton of for loop raises GeneratorExit in stream
62 stream.close()
63
64
65 def extract(filename, dest_dir=None, fileobj=None):
66 """
67 Extract all components of conda package to dest_dir.
68
69 fileobj: must be seekable if provided, if a ``.conda`` package.
70 """
71 assert dest_dir, "dest_dir is required"
72 if str(filename).endswith(".conda"):
73 components = [
74 package_streaming.CondaComponent.pkg,
75 package_streaming.CondaComponent.info,
76 ]
77 else: # .tar.bz2 doesn't filter by component
78 components = [package_streaming.CondaComponent.pkg]
79
80 closefd = False
81 if not fileobj:
82 fileobj = open(filename, "rb")
83 closefd = True
84
85 try:
86 for component in components:
87 stream = package_streaming.stream_conda_component(
88 filename, fileobj, component=component
89 )
90 extract_stream(stream, dest_dir)
91 finally:
92 if closefd:
93 fileobj.close()