File size: 1,879 Bytes
9d4a3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Expand the projected standalone runtime without accepting archive links."""

from __future__ import annotations

import os
import shutil
import stat
import tarfile
from pathlib import Path, PurePosixPath


ROOT = Path(__file__).resolve().parent
ARCHIVE = ROOT / "standalone.tar.gz"
DESTINATION = ROOT / "standalone"


def target_for(name: str) -> Path:
    relative = PurePosixPath(name)
    if relative.is_absolute() or not relative.parts or any(
        part in {"", ".", ".."} for part in relative.parts
    ):
        raise RuntimeError(f"unsafe standalone archive member: {name!r}")
    return DESTINATION.joinpath(*relative.parts)


if DESTINATION.exists():
    raise RuntimeError("standalone destination already exists")
DESTINATION.mkdir(mode=0o700)
try:
    with tarfile.open(ARCHIVE, mode="r:gz") as archive:
        for member in archive:
            target = target_for(member.name)
            if member.isdir():
                target.mkdir(parents=True, exist_ok=True)
                target.chmod(stat.S_IMODE(member.mode) | 0o500)
                continue
            if not member.isfile() or member.issym() or member.islnk():
                raise RuntimeError(
                    f"non-regular standalone archive member: {member.name!r}"
                )
            target.parent.mkdir(parents=True, exist_ok=True)
            source = archive.extractfile(member)
            if source is None:
                raise RuntimeError(f"unreadable archive member: {member.name!r}")
            with source, target.open("xb") as destination:
                shutil.copyfileobj(source, destination, length=1024 * 1024)
                destination.flush()
                os.fsync(destination.fileno())
            target.chmod(stat.S_IMODE(member.mode))
except BaseException:
    shutil.rmtree(DESTINATION, ignore_errors=True)
    raise