Datasets:
File size: 21,843 Bytes
196f3aa ec5da4b 196f3aa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 | """Make a delivered file out of an upstream file: take a member out of a zip or tar archive, decompress, turn a hex
dump or a uuencoded file back into bytes, recompress.
Standard library only, so it can sit next to fetch.py and to_pool.py and be imported by both.
A transform is a list of steps, applied in order:
unzip:<member> the member with exactly this name inside a zip archive (a directory entry is refused)
bunzip2 decompress bzip2 (several concatenated streams are read as one)
gunzip decompress gzip (several concatenated members are read as one)
unxz decompress xz (several concatenated streams are read as one)
untar:<member> the member with exactly this name inside an uncompressed tar archive (put unxz, gunzip or
bunzip2 before it for a compressed one); it must be a regular file, read at its full size
when it is stored sparse; a member that is a link, a directory or a device is refused, and
so is a name that is absolute, has a .. part, or is found more than once in the archive
unxxd turn a hex dump written by xxd (or xxd -a) back into bytes, without running xxd; see below
uudecode turn a uuencoded file back into bytes, without running uudecode; see below
uncompress decompress a .Z file written by Unix compress (LZW), without running uncompress; see below
gzip compress with gzip at level 9, modification time 0 and no file name in the header;
allowed once, as the last step
validate(steps) checks a list of steps and raises ValueError for anything else.
apply(src_path, steps, out_path) writes the result to out_path (atomically: a temporary file in the same
directory, renamed at the end) and returns {"sha256", "bytes", "content_sha256"}: the sha256 and size of the
written file, and the sha256 of the bytes before a final gzip step (equal to sha256 when the last step is not
gzip). The gzip bytes depend on the zlib build, so compare content_sha256 to check a transform made elsewhere.
Only the named member is read out of an archive, and the result is written only to out_path: no name found
inside an archive is ever used as a path.
The output of unxz, untar, unxxd, uudecode and uncompress may be at most max_bytes (a keyword of apply; default
MAX_BYTES, 256,000,000 bytes; None for no limit): apply stops as soon as it passes and raises TooLarge, a ValueError.
A tar member whose size, counted at its expanded size when it is stored sparse, is more than the limit is refused
before it is read. The other steps have no limit.
unxxd reads only the default layout of xxd: each line is an offset of 8 lowercase hex digits, a colon and a
space, 16 bytes in groups of two bytes (4 lowercase hex digits) parted by one space, two spaces and the text
column. The text column is not compared with the bytes; it must hold one character per byte. The first line has
offset 0 and each line starts where the one before it ended. Only the last line may hold fewer than 16 bytes;
its hex part is padded with spaces to the full width. A line holding only * (written by xxd -a) means that the
bytes from the end of the line before it up to the offset of the line after it are all zero: the line before it
must hold 16 zero bytes, the line after it must be a line of bytes, and the zero bytes it stands for must be a
whole number of 16-byte lines, at least one. Every line ends with a newline (a carriage return is refused), and
an empty file gives an empty output. Anything else is refused: nothing is guessed. The whole dump is read and
checked, and the length of the output counted, before anything is written, so a dump that is bad anywhere or
whose output would pass max_bytes writes nothing.
uudecode decodes the lines between the first line of the form "begin <mode> <name>" (mode in octal digits) and
the first line "end" after it, each with binascii.a2b_uu; lines before the begin line and after the end line are
skipped. The name on the begin line is never used: the output goes only to out_path. A file with no begin line,
with a second begin line, with no end line after the begin line, or with a line between them that does not decode
is refused. A line may end with a carriage return before its newline.
uncompress reads the .Z format of Unix compress: the magic bytes 1f 9d, a flags byte whose low five bits are the
maximum code width (9 to 16 bits) and whose high bit is block mode (code 256 then clears the table), and then LZW
codes of 9 bits up to that width, packed from the low bit up. Codes are read in groups of eight, as the original
compress writes them: when the width grows, or after a clear code, the remaining codes of the current group are
skipped and the next group starts at the new width. As in the original compress (and in gzip -d), with a maximum
width of 9 the codes still grow to 10 bits once the table is full, so a file written by ncompress -b 9 does not
decode here, as it does not with ncompress or gzip either. Bits at the end too few for one more code are ignored.
A wrong magic, a maximum width outside 9 to 16, a first code that is not a byte, and a code that is not yet in the
table (other than the next one to be added, the KwKwK case) are refused. The output is written as it is decoded.
Bad archives, a missing member and corrupt compressed data raise ValueError; reading or writing errors (a
missing source file, a full disk) raise OSError.
Deletes: the step outputs .transform-*.part that apply made with tempfile.mkstemp next to the output (listed one by
one in its temps list), once the last one is renamed to the output or a step fails: temporary files.
"""
from __future__ import annotations
import binascii
import bz2
import gzip
import hashlib
import lzma
import os
import re
import tarfile
import tempfile
import unicodedata
import zipfile
import zlib
UNZIP = "unzip:"
UNTAR = "untar:"
SIMPLE = ("bunzip2", "gunzip", "unxz", "unxxd", "uudecode", "uncompress", "gzip")
MAX_BYTES = 256_000_000
GZIP_LEVEL = 9
CHUNK = 1 << 20
XXD_WIDTH = 16
_XXD_LINE = re.compile(r"([0-9a-f]{8}): ([0-9a-f ]{39}) ([ -~]*)")
_XXD_HEX = re.compile(r"(?:[0-9a-f]{4} ){0,7}(?:[0-9a-f]{4}|[0-9a-f]{2})")
_XXD_LINE_MAX = 128
_UU_BEGIN = re.compile(rb"begin [0-7]{1,6} +\S.*")
_UU_LINE_MAX = 1024
_Z_MAGIC = b"\x1f\x9d"
_Z_BLOCK_MODE = 0x80
_Z_BITS_MASK = 0x1f
_Z_INIT_BITS = 9
_Z_MAX_BITS = 16
_Z_CLEAR = 256
_Z_KEEP = 256
_ZEROS = bytes(CHUNK)
_DATA_ERRORS = (OSError, EOFError, zlib.error, zipfile.BadZipFile, RuntimeError, NotImplementedError,
lzma.LZMAError, tarfile.TarError)
class TooLarge(ValueError):
"""The output of a step passed max_bytes."""
def _tar_name_problem(member: str):
if re.match(r"[/\\]|[A-Za-z]:", member):
return "is an absolute path"
if ".." in re.split(r"[/\\]", member):
return "has a .. part"
return None
def validate(steps) -> list:
"""-> the steps as a new list; ValueError unless steps is a non-empty list of known steps with gzip only last."""
if not isinstance(steps, (list, tuple)) or not steps:
raise ValueError(f"transform must be a non-empty list of steps, got {steps!r}")
out = []
for i, s in enumerate(steps):
if not isinstance(s, str):
raise ValueError(f"step {i + 1} must be a string, got {s!r}")
if s.startswith(UNZIP):
member = s[len(UNZIP):]
if not member or member.endswith("/"):
raise ValueError(f"step {i + 1}: unzip needs a file member name: {s!r}")
if any(unicodedata.category(c) == "Cc" for c in member):
raise ValueError(f"step {i + 1}: member name has a control character: {s!r}")
elif s.startswith(UNTAR):
member = s[len(UNTAR):]
if not member or member.endswith("/"):
raise ValueError(f"step {i + 1}: untar needs a file member name: {s!r}")
if any(unicodedata.category(c) == "Cc" for c in member):
raise ValueError(f"step {i + 1}: member name has a control character: {s!r}")
why = _tar_name_problem(member)
if why:
raise ValueError(f"step {i + 1}: member name {why}: {s!r}")
elif s not in SIMPLE:
raise ValueError(f"step {i + 1}: unknown step {s!r} "
"(use unzip:<member>, untar:<member>, bunzip2, gunzip, unxz, unxxd, uudecode, uncompress "
"or gzip)")
if s == "gzip" and i != len(steps) - 1:
raise ValueError(f"step {i + 1}: gzip is allowed only as the last step")
out.append(s)
return out
def _copy(fin, fout, h=None, limit=None) -> None:
n = 0
while True:
b = fin.read(CHUNK)
if not b:
return
n += len(b)
if limit is not None and n > limit:
raise TooLarge(f"output passes the limit of {limit} bytes")
if h is not None:
h.update(b)
fout.write(b)
def _unzip(src: str, member: str, fout) -> None:
with zipfile.ZipFile(src) as zf:
try:
info = zf.getinfo(member)
except KeyError:
raise ValueError(f"no member {member!r} in the zip archive") from None
if info.is_dir():
raise ValueError(f"member {member!r} is a directory")
with zf.open(info) as fin:
_copy(fin, fout)
def _untar(src: str, member: str, fout, limit) -> None:
with tarfile.open(src, "r:") as tf:
found = [m for m in tf.getmembers() if m.name == member]
if not found:
raise ValueError(f"no member {member!r} in the tar archive")
if len(found) > 1:
raise ValueError(f"member {member!r} is in the tar archive {len(found)} times")
info = found[0]
if info.issym() or info.islnk():
raise ValueError(f"member {member!r} is a link")
if not info.isfile():
raise ValueError(f"member {member!r} is not a regular file")
if limit is not None and info.size > limit:
raise TooLarge(f"member {member!r} is {info.size} bytes"
f"{' when expanded' if info.sparse else ''}, more than the limit of {limit} bytes")
fin = tf.extractfile(info)
_copy(fin, fout, limit=limit)
def _xxd_parts(fin):
"""Yield the bytes a hex dump stands for, in order: a bytes object per line, an int (that many zero bytes) per *
line. Raises ValueError at the first thing that does not fit the layout."""
pos = 0
last = None
n = 0
while True:
raw = fin.readline(_XXD_LINE_MAX)
if not raw:
break
n += 1
if not raw.endswith(b"\n"):
raise ValueError(f"line {n}: " + ("too long" if len(raw) >= _XXD_LINE_MAX else "no newline at the end"))
try:
line = raw[:-1].decode("ascii")
except UnicodeDecodeError:
raise ValueError(f"line {n}: not ASCII") from None
if line == "*":
if last is None:
raise ValueError(f"line {n}: a * line cannot come first")
if last == "*":
raise ValueError(f"line {n}: two * lines in a row")
if len(last) != XXD_WIDTH or any(last):
raise ValueError(f"line {n}: the line before a * line must hold {XXD_WIDTH} zero bytes")
last = "*"
continue
m = _XXD_LINE.fullmatch(line)
hexpart = m.group(2).rstrip(" ") if m else ""
if not m or not _XXD_HEX.fullmatch(hexpart):
raise ValueError(f"line {n}: not a line of xxd output: {line[:80]!r}")
data = bytes.fromhex(hexpart)
if len(m.group(3)) != len(data):
raise ValueError(f"line {n}: the text column has {len(m.group(3))} characters for {len(data)} bytes")
if isinstance(last, bytes) and len(last) < XXD_WIDTH:
raise ValueError(f"line {n - 1}: only the last line may hold fewer than {XXD_WIDTH} bytes")
off = int(m.group(1), 16)
if last == "*":
gap = off - pos
if gap <= 0:
raise ValueError(f"line {n}: offset {off:08x} after a * line does not pass {pos:08x}")
if gap % XXD_WIDTH:
raise ValueError(f"line {n}: the * line before it stands for {gap} bytes, "
f"not a whole number of {XXD_WIDTH}-byte lines")
yield gap
pos = off
elif off != pos:
raise ValueError(f"line {n}: offset {off:08x}, expected {pos:08x}")
yield data
pos += len(data)
last = data
if last == "*":
raise ValueError("the dump ends with a * line")
def _unxxd(src: str, fout, limit) -> None:
with open(src, "rb") as fin:
total = 0
for part in _xxd_parts(fin):
total += part if isinstance(part, int) else len(part)
if limit is not None and total > limit:
raise TooLarge(f"output would pass the limit of {limit} bytes")
fin.seek(0)
for part in _xxd_parts(fin):
if isinstance(part, int):
while part:
k = min(part, CHUNK)
fout.write(_ZEROS[:k] if k < CHUNK else _ZEROS)
part -= k
else:
fout.write(part)
def _uu_lines(fin):
"""Yield (line number, line without its line end) for each line of fin; a line of _UU_LINE_MAX bytes or more
is read to its end and yielded as None, so it never matches a begin or end line and never decodes."""
n = 0
while True:
raw = fin.readline(_UU_LINE_MAX)
if not raw:
return
n += 1
if len(raw) >= _UU_LINE_MAX and not raw.endswith(b"\n"):
while raw and not raw.endswith(b"\n"):
raw = fin.readline(CHUNK)
yield n, None
continue
line = raw[:-1] if raw.endswith(b"\n") else raw
if line.endswith(b"\r"):
line = line[:-1]
yield n, line
def _uudecode(src: str, fout, limit) -> None:
with open(src, "rb") as fin:
state = "before"
total = 0
for n, line in _uu_lines(fin):
is_begin = line is not None and _UU_BEGIN.fullmatch(line) is not None
if state == "before":
if is_begin:
state = "body"
continue
if is_begin:
raise ValueError(f"line {n}: a second begin line")
if state == "after":
continue
if line == b"end":
state = "after"
continue
if line is None:
raise ValueError(f"line {n}: too long for a uuencoded line")
try:
data = binascii.a2b_uu(line)
except binascii.Error as e:
raise ValueError(f"line {n}: does not decode: {e}") from None
total += len(data)
if limit is not None and total > limit:
raise TooLarge(f"output passes the limit of {limit} bytes")
fout.write(data)
if state == "before":
raise ValueError("no begin line")
if state == "body":
raise ValueError("no end line after the begin line")
def _uncompress(src: str, fout, limit) -> None:
with open(src, "rb") as fin:
head = fin.read(3)
if len(head) < 3 or head[:2] != _Z_MAGIC:
raise ValueError("not a .Z file (no 1f 9d magic)")
maxbits = head[2] & _Z_BITS_MASK
block = bool(head[2] & _Z_BLOCK_MODE)
if not _Z_INIT_BITS <= maxbits <= _Z_MAX_BITS:
raise ValueError(f"maximum code width {maxbits} is outside {_Z_INIT_BITS} to {_Z_MAX_BITS}")
maxmaxcode = 1 << maxbits
# an entry is kept as bytes when it is at most _Z_KEEP bytes long, else as its prefix code and last byte
strs = [bytes([i]) for i in range(256)] + [None] * (maxmaxcode - 256)
pre = [0] * maxmaxcode
suf = [0] * maxmaxcode
n_bits = _Z_INIT_BITS
maxcode = (1 << n_bits) - 1
free_ent = 257 if block else 256
oldcode = -1
prev = b""
total = 0
buf = bytearray()
while True:
group = fin.read(n_bits)
if not group:
break
v = int.from_bytes(group, "little")
mask = (1 << n_bits) - 1
for k in range(len(group) * 8 // n_bits):
code = (v >> (k * n_bits)) & mask
if oldcode == -1:
if code >= 256:
raise ValueError(f"first code {code} is not a byte")
oldcode = code
prev = strs[code]
out = prev
elif code == _Z_CLEAR and block:
free_ent = 256
n_bits = _Z_INIT_BITS
maxcode = (1 << n_bits) - 1
break
else:
if code > free_ent:
raise ValueError(f"code {code} is not in the table (next entry is {free_ent})")
if code == free_ent:
out = prev + prev[:1]
else:
out = strs[code]
if out is None:
tail = []
c = code
while out is None:
tail.append(suf[c])
c = pre[c]
out = strs[c]
tail.reverse()
out = out + bytes(tail)
if free_ent < maxmaxcode:
if len(prev) < _Z_KEEP:
strs[free_ent] = prev + out[:1]
else:
strs[free_ent] = None
pre[free_ent] = oldcode
suf[free_ent] = out[0]
free_ent += 1
oldcode = code
prev = out
total += len(out)
if limit is not None and total > limit:
raise TooLarge(f"output passes the limit of {limit} bytes")
buf += out
if len(buf) >= CHUNK:
fout.write(buf)
buf.clear()
if free_ent > maxcode:
n_bits += 1
maxcode = maxmaxcode if n_bits == maxbits else (1 << n_bits) - 1
break
fout.write(buf)
def _step(src: str, step: str, fout, content, limit=None) -> None:
if step.startswith(UNZIP):
_unzip(src, step[len(UNZIP):], fout)
elif step.startswith(UNTAR):
_untar(src, step[len(UNTAR):], fout, limit)
elif step == "unxz":
with lzma.open(src, "rb", format=lzma.FORMAT_XZ) as fin:
_copy(fin, fout, limit=limit)
elif step == "unxxd":
_unxxd(src, fout, limit)
elif step == "uudecode":
_uudecode(src, fout, limit)
elif step == "uncompress":
_uncompress(src, fout, limit)
elif step == "bunzip2":
with bz2.open(src, "rb") as fin:
_copy(fin, fout)
elif step == "gunzip":
with gzip.open(src, "rb") as fin:
_copy(fin, fout)
else:
with open(src, "rb") as fin, gzip.GzipFile(filename="", mode="wb", fileobj=fout,
compresslevel=GZIP_LEVEL, mtime=0) as gz:
_copy(fin, gz, content)
def _sha256_file(path: str) -> tuple:
h = hashlib.sha256()
n = 0
with open(path, "rb") as f:
while True:
b = f.read(CHUNK)
if not b:
return h.hexdigest(), n
h.update(b)
n += len(b)
def apply(src_path, steps, out_path, *, max_bytes: int | None = MAX_BYTES) -> dict:
"""Apply steps to src_path, write out_path -> {"sha256", "bytes", "content_sha256"}. max_bytes limits the
output of unxz, untar, unxxd, uudecode and uncompress (TooLarge when it passes)."""
steps = validate(steps)
src = os.fspath(src_path)
out = os.path.abspath(os.fspath(out_path))
if not os.path.isfile(src):
raise FileNotFoundError(src)
d = os.path.dirname(out)
os.makedirs(d, exist_ok=True)
temps = []
cur = src
content = None
try:
for i, step in enumerate(steps):
fd, tmp = tempfile.mkstemp(dir=d, prefix=".transform-", suffix=".part")
temps.append(tmp)
if step == "gzip":
content = hashlib.sha256()
with os.fdopen(fd, "wb") as fout:
limited = step in ("unxz", "unxxd", "uudecode", "uncompress") or step.startswith(UNTAR)
try:
_step(cur, step, fout, content, max_bytes if limited else None)
except ValueError as e:
kind = TooLarge if isinstance(e, TooLarge) else ValueError
raise kind(f"step {i + 1} ({step}): {e}") from None
except _DATA_ERRORS as e:
if isinstance(e, OSError) and e.errno is not None:
raise
raise ValueError(f"step {i + 1} ({step}): {type(e).__name__}: {e}") from e
cur = tmp
sha, n = _sha256_file(cur)
os.chmod(cur, 0o644)
os.replace(cur, out)
temps.remove(cur)
finally:
for t in temps:
try:
os.unlink(t)
except OSError:
pass
return {"sha256": sha, "bytes": n, "content_sha256": content.hexdigest() if content is not None else sha}
|