Battam's picture
regenerate the index pages only (generator 46a2db14, templates 908e82ff) [run publish-20261028T213235Z]
ec5da4b verified
Raw History Blame Contribute Delete
9.07 kB
"""Unpacking an archive the pool uses as a folder: one rule, one function, one set of limits.
The rule (expand_decision, rule name EXPAND_RULE): a unit is unpacked when the format table
(archive_formats.tsv, read by archive_formats.place) classes it as a multi-member archive, that is an archive meant
to be used as a folder whose members are the material (zip, tar and its compressed forms, 7z, rar and the like).
Single-file compression (.gz, .bz2, .xz, .zst around one file) and zip-based containers read by their own library
(npz, xlsx, docx, epub, jar, whl and the like) are files, not folders, and are not unpacked.
The function (expand) and its limits, those of the pool format: every file and every
unpacked folder is at most MAX_UNIT_BYTES = 20,000,000 bytes, and a source holds at most MAX_SOURCE_FILES = 400,000
files, counted across all its archives (SourceFiles). The limits are counted while unpacking, on the bytes actually
written, and unpacking stops at the first excess; nothing is unpacked in full and measured afterwards. Unsafe member
paths, links and other non-regular members, nested archives and formats this function cannot unpack are refused
with a reason. Unpacking goes to a work folder next to the target and is moved into place only when it succeeds;
on failure nothing is left behind and the archive stays a file unit.
Both pool builders call expand: tools/to_pool.py (artpool/public_to_pool.py) and artpool/pool/build.py.
Standard library only (a zstd decoder is used for .tar.zst when one is present).
Deletes: the work folder <dest>.expanding (or the caller's work) before unpacking and on a failure: a temporary
folder expand writes.
Deletes: an earlier dest folder, replaced by the new unpacking: recomputable, by expand from the archive, which stays
in the pool as a file unit.
"""
from __future__ import annotations
import importlib
import shutil
import stat
import tarfile
import zipfile
from pathlib import Path
try:
from .facts import archive_formats as AF
except ImportError:
import archive_formats as AF
EXPAND_RULE = "multi_member_archive_as_folder"
MAX_UNIT_BYTES = 20_000_000
MAX_SOURCE_FILES = 400_000
SKIP_IN_ARCHIVE = frozenset({"__MACOSX", ".DS_Store", ".git"})
_CHUNK = 1 << 16
_TAR_MODES = {"tar": "r|", "tar.gz": "r|gz", "tar.bz2": "r|bz2", "tar.xz": "r|xz", "tar.zst": "r|"}
class Refused(ValueError):
pass
def expand_decision(path, head: bytes | None = None) -> dict:
"""The one rule for whether a unit is unpacked into _expanded/. path is the unit's pool path; head is the file's
first bytes when the file is at hand. -> {"expand": bool, "expand_rule": EXPAND_RULE, "format": table format or ""}."""
pl = AF.place(path, head)
return {"expand": pl.cls == AF.ARCHIVE, "expand_rule": EXPAND_RULE, "format": pl.format}
class SourceFiles:
"""The file count of one source against its limit; shared by every archive of that source."""
def __init__(self, used: int = 0, limit: int = MAX_SOURCE_FILES):
self.used, self.limit = used, limit
@classmethod
def of_dir(cls, folder, limit: int = MAX_SOURCE_FILES) -> "SourceFiles":
folder = Path(folder)
n = sum(1 for p in folder.rglob("*") if p.is_file()) if folder.is_dir() else 0
return cls(n, limit)
@property
def room(self) -> int:
return max(self.limit - self.used, 0)
def _member_parts(name: str) -> list | None:
"""Path parts of a member, None for a skipped member (macOS metadata, .git); unsafe paths are refused."""
if (not name or name.startswith("/") or "\\" in name or any(ord(c) < 32 or ord(c) == 127 for c in name)
or (len(name) > 1 and name[1] == ":")):
raise Refused(f"unsafe member path {name!r}")
parts = [p for p in name.split("/") if p not in ("", ".")]
if ".." in parts:
raise Refused(f"unsafe member path {name!r}")
if not parts or any(p in SKIP_IN_ARCHIVE for p in parts):
return None
return parts
def _zstd_stream(raw):
try:
return importlib.import_module("compression.zstd").ZstdFile(raw)
except ImportError:
pass
try:
zstandard = importlib.import_module("zstandard")
except ImportError:
raise Refused("no zstd decoder in this Python for tar.zst") from None
return zstandard.ZstdDecompressor().stream_reader(raw, read_across_frames=True)
def _members(archive: Path, fmt: str, stack: list):
"""Yield (name, declared size, reader opener) per regular member; directories are passed over, links and other
non-regular members are refused."""
if fmt == "zip":
z = zipfile.ZipFile(archive)
stack.append(z)
for info in z.infolist():
if info.is_dir():
continue
mode = info.external_attr >> 16
# mode bits with no file type (as Python's writestr writes them) count as a regular file
if stat.S_ISLNK(mode) or (stat.S_IFMT(mode) and not stat.S_ISREG(mode)):
raise Refused(f"link or special member {info.filename!r}")
if info.flag_bits & 0x1:
raise Refused(f"encrypted member {info.filename!r}")
yield info.filename, info.file_size, (lambda i=info: z.open(i))
return
if fmt not in _TAR_MODES:
raise Refused(f"no extractor for format {fmt}")
raw = open(archive, "rb")
stack.append(raw)
src = _zstd_stream(raw) if fmt == "tar.zst" else raw
if src is not raw:
stack.append(src)
tf = tarfile.open(fileobj=src, mode=_TAR_MODES[fmt])
stack.append(tf)
for m in tf:
if m.isdir():
continue
if not m.isfile():
raise Refused(f"link or special member {m.name!r}")
yield m.name, m.size, (lambda m=m: tf.extractfile(m))
def expand(archive, dest, *, files: SourceFiles | None = None, max_bytes: int = MAX_UNIT_BYTES,
work=None) -> dict:
"""Unpack archive into the new folder dest within the limits: every file and the whole folder at most
max_bytes, the source's file count (files, shared across its archives) at most its limit. Stops at the first
excess. -> {"status": "ok", "format", "files", "bytes", "skipped"} or {"status": "failed", "reason"}; on failure
nothing is left at dest or in the work folder, and files is unchanged."""
archive, dest = Path(archive), Path(dest)
files = files if files is not None else SourceFiles()
work = Path(work) if work is not None else dest.parent / (dest.name + ".expanding")
shutil.rmtree(work, ignore_errors=True)
total, n, skipped, stack, fmt = 0, 0, 0, [], ""
try:
pl = AF.place_file(archive)
fmt = pl.format
if not pl.cls:
raise Refused("unknown format: not in the format table")
if pl.cls != AF.ARCHIVE:
raise Refused(f"{pl.format} is {pl.cls}, not a multi-member archive")
work.mkdir(parents=True)
for name, declared, opener in _members(archive, fmt, stack):
parts = _member_parts(name)
if parts is None:
skipped += 1
continue
if AF.place(name).cls == AF.ARCHIVE:
raise Refused(f"nested archive {name!r}")
n += 1
if n > files.room:
raise Refused(f"the source would hold more than its limit of {files.limit:,} files")
if declared > max_bytes or total + declared > max_bytes:
raise Refused(f"over the {max_bytes:,} byte limit at member {name!r}")
t = work.joinpath(*parts)
if t.exists():
raise Refused(f"member {name!r} appears twice")
t.parent.mkdir(parents=True, exist_ok=True)
with opener() as src, open(t, "wb") as out:
while True:
b = src.read(min(_CHUNK, max_bytes - total + 1))
if not b:
break
total += len(b)
if total > max_bytes:
raise Refused(f"over the {max_bytes:,} byte limit while unpacking member {name!r}")
out.write(b)
if AF.place_file(t).cls == AF.ARCHIVE:
raise Refused(f"nested archive {name!r}")
if n == 0:
raise Refused("the archive holds no files")
except (Refused, OSError, EOFError, RuntimeError, zipfile.BadZipFile, tarfile.TarError, ValueError) as e:
for s in reversed(stack):
try:
s.close()
except Exception: # closing a half-read stream may raise again; the failure is already recorded
pass
shutil.rmtree(work, ignore_errors=True)
return {"status": "failed", "reason": f"cannot expand: {e}"}
for s in reversed(stack):
s.close()
if dest.exists():
shutil.rmtree(dest)
dest.parent.mkdir(parents=True, exist_ok=True)
work.replace(dest)
files.used += n
return {"status": "ok", "format": fmt, "files": n, "bytes": total, "skipped": skipped}