| """ |
| Extract package to directory, with checks against tar members extracting outside |
| the target directory. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import os |
| import tarfile |
| from collections.abc import Generator |
| from errno import ELOOP |
| from pathlib import Path |
|
|
| from . import exceptions, package_streaming |
|
|
| __all__ = ["extract_stream", "extract"] |
| HAS_TAR_FILTER = hasattr(tarfile, "tar_filter") |
|
|
|
|
| def extract_stream( |
| stream: Generator[tuple[tarfile.TarFile, tarfile.TarInfo]], |
| dest_dir: Path | str, |
| tar_filter: str | None = None, |
| ): |
| """ |
| Pipe ``stream_conda_component`` output here to extract every member into |
| dest_dir. |
| |
| For ``.conda`` will need to be called twice (for info and pkg components); |
| for ``.tar.bz2`` every member is extracted. |
| """ |
| dest_dir = os.path.realpath(dest_dir) |
|
|
| def is_within_dest_dir(name): |
| abs_target = os.path.realpath(os.path.join(dest_dir, name)) |
| prefix = os.path.commonpath((dest_dir, abs_target)) |
| return prefix == dest_dir |
|
|
| for tar_file, _ in stream: |
| |
| def checked_members(): |
| |
| for member in tar_file: |
| if not is_within_dest_dir(member.name): |
| raise exceptions.SafetyError(f"contains unsafe path: {member.name}") |
| yield member |
|
|
| try: |
| |
| |
| |
| tar_args = {"path": dest_dir, "members": checked_members()} |
| if HAS_TAR_FILTER: |
| tar_args["filter"] = tar_filter or "fully_trusted" |
| tar_file.extractall(**tar_args) |
| except OSError as e: |
| if e.errno == ELOOP: |
| raise exceptions.CaseInsensitiveFileSystemError() from e |
| raise |
|
|
| |
| stream.close() |
|
|
|
|
| def extract(filename, dest_dir=None, fileobj=None): |
| """ |
| Extract all components of conda package to dest_dir. |
| |
| fileobj: must be seekable if provided, if a ``.conda`` package. |
| """ |
| assert dest_dir, "dest_dir is required" |
| if str(filename).endswith(".conda"): |
| components = [ |
| package_streaming.CondaComponent.pkg, |
| package_streaming.CondaComponent.info, |
| ] |
| else: |
| components = [package_streaming.CondaComponent.pkg] |
|
|
| closefd = False |
| if not fileobj: |
| fileobj = open(filename, "rb") |
| closefd = True |
|
|
| try: |
| for component in components: |
| stream = package_streaming.stream_conda_component( |
| filename, fileobj, component=component |
| ) |
| extract_stream(stream, dest_dir) |
| finally: |
| if closefd: |
| fileobj.close() |
|
|