375 lines
13 KiB
Python
375 lines
13 KiB
Python
import argparse
|
|
import gzip
|
|
import json
|
|
import os
|
|
import re
|
|
import subprocess
|
|
import tarfile
|
|
import zlib
|
|
from contextlib import contextmanager
|
|
from contextvars import ContextVar
|
|
from dataclasses import dataclass, field
|
|
from pathlib import Path, PurePosixPath
|
|
from shutil import copyfileobj
|
|
|
|
from .domain_names import canonical_domain
|
|
from .mail_node import MailboxSpec
|
|
|
|
MAX_METADATA_SIZE = 8 * 1024 * 1024
|
|
ZSTD_MAGIC = b"\x28\xb5\x2f\xfd"
|
|
HOME_ARCHIVES = {"home.tar", "home.tar.gz", "home.tar.zst"}
|
|
DOCUMENT_ROOTS = ("public_html", "private_html")
|
|
EXPANSION_LIMIT = ContextVar("directadmin_expansion_limit", default=None)
|
|
MAX_WEB_IMPORT_MEMBERS = 500_000
|
|
|
|
|
|
class BackupTarInfo(tarfile.TarInfo):
|
|
@classmethod
|
|
def fromtarfile(cls, archive):
|
|
try:
|
|
return super().fromtarfile(archive)
|
|
except (tarfile.InvalidHeaderError, tarfile.SubsequentHeaderError):
|
|
raise tarfile.ReadError("Invalid backup tar header.") from None
|
|
|
|
def _proc_pax(self, archive):
|
|
self.check_extension_size()
|
|
return super()._proc_pax(archive)
|
|
|
|
def _proc_gnulong(self, archive):
|
|
self.check_extension_size()
|
|
return super()._proc_gnulong(archive)
|
|
|
|
def check_extension_size(self):
|
|
if EXPANSION_LIMIT.get() is not None and not (
|
|
0 <= self.size <= MAX_METADATA_SIZE
|
|
):
|
|
raise ValueError("A tar header extension exceeds the size limit.")
|
|
|
|
|
|
@contextmanager
|
|
def limit_backup_expansion(maximum):
|
|
"""Bound both expanded tar bytes and declared member sizes."""
|
|
token = EXPANSION_LIMIT.set(maximum)
|
|
try:
|
|
yield
|
|
finally:
|
|
EXPANSION_LIMIT.reset(token)
|
|
|
|
|
|
class BoundedArchiveStream:
|
|
def __init__(self, stream, remaining):
|
|
self.stream = stream
|
|
self.remaining = remaining
|
|
|
|
def read(self, size):
|
|
data = self.stream.read(min(size, self.remaining + 1))
|
|
self.remaining -= len(data)
|
|
if self.remaining < 0:
|
|
raise ValueError("The expanded backup exceeds the size limit.")
|
|
return data
|
|
|
|
|
|
@dataclass
|
|
class DomainInventory:
|
|
website_files: int = 0
|
|
dns_zone: bool = False
|
|
mailboxes: set[str] = field(default_factory=set)
|
|
mail_files: int = 0
|
|
unrecognized_mailbox_entries: int = 0
|
|
|
|
def report(self, name):
|
|
return {
|
|
"name": name,
|
|
"website_files": self.website_files,
|
|
"dns_zone": self.dns_zone,
|
|
"mailboxes": sorted(self.mailboxes),
|
|
"mail_files": self.mail_files,
|
|
"unrecognized_mailbox_entries": self.unrecognized_mailbox_entries,
|
|
}
|
|
|
|
|
|
@dataclass
|
|
class BackupInventory:
|
|
username: str | None = None
|
|
primary_domain: str | None = None
|
|
domains: dict[str, DomainInventory] = field(default_factory=dict)
|
|
databases: set[str] = field(default_factory=set)
|
|
home_archive: bool = False
|
|
skipped_non_regular_entries: int = 0
|
|
metadata_paths: set[tuple[str, ...]] = field(default_factory=set)
|
|
|
|
def domain(self, value):
|
|
inventory = self.domains.get(value)
|
|
if inventory is None:
|
|
inventory = self.domains.setdefault(
|
|
canonical_domain(value), DomainInventory()
|
|
)
|
|
return inventory
|
|
|
|
def visit(self, archive, member):
|
|
parts = member_path(member)
|
|
if not member.isreg():
|
|
if not member.isdir():
|
|
self.skipped_non_regular_entries += 1
|
|
return
|
|
|
|
match parts:
|
|
case ("backup", "user.conf"):
|
|
settings = read_account_settings(
|
|
self.read_metadata(archive, member, parts)
|
|
)
|
|
self.username = settings["username"]
|
|
if settings["domain"]:
|
|
self.primary_domain = canonical_domain(settings["domain"])
|
|
self.domain(self.primary_domain)
|
|
case ("backup", "domains.list"):
|
|
for line in self.read_metadata(
|
|
archive, member, parts
|
|
).splitlines():
|
|
if line.strip():
|
|
self.domain(line.strip())
|
|
case ("backup", filename):
|
|
if match := re.fullmatch(
|
|
r"([a-zA-Z0-9_]{1,64})\.sql", filename
|
|
):
|
|
self.databases.add(match[1])
|
|
if filename in HOME_ARCHIVES:
|
|
self.home_archive = True
|
|
case ("backup", domain, filename) if filename == f"{domain}.db":
|
|
self.domain(domain).dns_zone = True
|
|
case ("backup", domain, filename) if filename == f"{domain}.conf":
|
|
self.domain(domain)
|
|
case ("backup", domain, "email", "passwd"):
|
|
lines = self.read_metadata(archive, member, parts)
|
|
self.visit_mailboxes(domain, lines)
|
|
case ("backup", domain, "email", "data", "imap", *tail) if (
|
|
tail and tail != [".direct_imap_backup"]
|
|
):
|
|
self.domain(domain).mail_files += 1
|
|
case (
|
|
"domains",
|
|
domain,
|
|
"public_html" | "private_html",
|
|
*tail,
|
|
) if tail:
|
|
self.domain(domain).website_files += 1
|
|
case ("domains", domain, "domain.conf"):
|
|
self.domain(domain)
|
|
case ("imap", domain, *tail) if tail:
|
|
self.domain(domain).mail_files += 1
|
|
|
|
def read_metadata(self, archive, member, parts):
|
|
if parts in self.metadata_paths:
|
|
raise ValueError(
|
|
"The archive contains duplicate account or mailbox metadata."
|
|
)
|
|
self.metadata_paths.add(parts)
|
|
if not 0 <= member.size <= MAX_METADATA_SIZE:
|
|
raise ValueError(
|
|
"An account or mailbox metadata file exceeds the size limit."
|
|
)
|
|
with archive.extractfile(member) as stream:
|
|
return stream.read().decode("utf-8", errors="replace")
|
|
|
|
def visit_mailboxes(self, domain, text):
|
|
inventory = self.domain(domain)
|
|
for line in text.splitlines():
|
|
if not line.strip():
|
|
continue
|
|
local_part, separator, _ = line.partition(":")
|
|
try:
|
|
if not separator:
|
|
raise ValueError
|
|
mailbox = MailboxSpec(domain, local_part)
|
|
except ValueError:
|
|
inventory.unrecognized_mailbox_entries += 1
|
|
else:
|
|
inventory.mailboxes.add(mailbox.address)
|
|
|
|
def report(self):
|
|
if self.username is None:
|
|
raise ValueError(
|
|
"Expected a DirectAdmin account backup with backup/user.conf."
|
|
)
|
|
return {
|
|
"version": 1,
|
|
"kind": "directadmin_backup_inventory",
|
|
"username": self.username,
|
|
"primary_domain": self.primary_domain,
|
|
"domains": [
|
|
inventory.report(name)
|
|
for name, inventory in sorted(self.domains.items())
|
|
],
|
|
"databases": sorted(self.databases),
|
|
"home_archive": self.home_archive,
|
|
"skipped_non_regular_entries": self.skipped_non_regular_entries,
|
|
}
|
|
|
|
|
|
def read_account_settings(text):
|
|
settings = {}
|
|
for line in text.splitlines():
|
|
key, separator, value = line.partition("=")
|
|
if separator and key in {"username", "domain"}:
|
|
if key in settings:
|
|
raise ValueError(
|
|
"The account metadata repeats an identity field."
|
|
)
|
|
settings[key] = value.strip()
|
|
username = settings.get("username", "")
|
|
if not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}", username):
|
|
raise ValueError(
|
|
"The account metadata is missing a valid DirectAdmin username."
|
|
)
|
|
return {"username": username, "domain": settings.get("domain")}
|
|
|
|
|
|
@contextmanager
|
|
def archive_stream(path):
|
|
with path.open("rb", buffering=0) as source:
|
|
magic = source.read(4)
|
|
source.seek(0)
|
|
if magic.startswith(b"\x1f\x8b"):
|
|
with gzip.GzipFile(fileobj=source) as stream:
|
|
yield stream
|
|
elif magic == ZSTD_MAGIC:
|
|
try:
|
|
decoder = subprocess.Popen(
|
|
["zstd", "--decompress", "--stdout", "--quiet"],
|
|
stdin=source,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.DEVNULL,
|
|
)
|
|
except FileNotFoundError:
|
|
raise ValueError(
|
|
"Install zstd to inspect Zstandard backups."
|
|
) from None
|
|
with decoder:
|
|
try:
|
|
yield decoder.stdout
|
|
except BaseException:
|
|
decoder.kill()
|
|
raise
|
|
if decoder.wait():
|
|
raise ValueError(
|
|
"The Zstandard backup is damaged or incomplete."
|
|
)
|
|
else:
|
|
yield source
|
|
|
|
|
|
def check_tar_padding(archive):
|
|
size = 0
|
|
while chunk := archive.fileobj.read(64 * 1024):
|
|
if chunk.strip(b"\0"):
|
|
raise ValueError(
|
|
"Unexpected data after the end of the tar archive."
|
|
)
|
|
size += len(chunk)
|
|
if size < tarfile.BLOCKSIZE:
|
|
raise ValueError("The tar archive is missing its end marker.")
|
|
|
|
|
|
def member_path(member):
|
|
path = PurePosixPath(member.name)
|
|
if path.is_absolute() or ".." in path.parts:
|
|
raise ValueError("The archive contains an unsafe member path.")
|
|
return path.parts
|
|
|
|
|
|
@contextmanager
|
|
def open_backup(path):
|
|
try:
|
|
with archive_stream(path) as stream:
|
|
limit = EXPANSION_LIMIT.get()
|
|
if limit is not None:
|
|
stream = BoundedArchiveStream(stream, limit)
|
|
with tarfile.open(
|
|
fileobj=stream, mode="r|", tarinfo=BackupTarInfo
|
|
) as archive:
|
|
yield archive
|
|
except (
|
|
EOFError,
|
|
tarfile.TarError,
|
|
zlib.error,
|
|
gzip.BadGzipFile,
|
|
RecursionError,
|
|
):
|
|
raise ValueError(
|
|
"The backup is not a readable or complete tar archive."
|
|
) from None
|
|
|
|
|
|
def backup_members(archive):
|
|
limit = EXPANSION_LIMIT.get()
|
|
declared_bytes = members = 0
|
|
while (member := archive.next()) is not None:
|
|
if limit is not None:
|
|
declared_bytes += member.size
|
|
members += 1
|
|
if (
|
|
not 0 <= member.size <= limit
|
|
or declared_bytes > limit
|
|
or members > MAX_WEB_IMPORT_MEMBERS
|
|
):
|
|
raise ValueError("The expanded backup exceeds the size limit.")
|
|
yield member
|
|
# Forward-only reads do not need tarfile's member cache.
|
|
archive.members.clear()
|
|
check_tar_padding(archive)
|
|
|
|
|
|
def copy_member(archive, member, target):
|
|
if member.size < 0:
|
|
raise ValueError("A file in the backup has an invalid size.")
|
|
target.parent.mkdir(parents=True, exist_ok=True)
|
|
with target.open("xb") as output, archive.extractfile(member) as source:
|
|
os.fchmod(output.fileno(), 0o600)
|
|
copyfileobj(source, output, length=1024 * 1024)
|
|
if output.tell() != member.size:
|
|
raise ValueError("A file in the backup is incomplete.")
|
|
|
|
|
|
def inspect_backup(path):
|
|
inventory = BackupInventory()
|
|
with open_backup(path) as archive:
|
|
for member in backup_members(archive):
|
|
inventory.visit(archive, member)
|
|
return inventory.report()
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(prog="coulobre-directadmin")
|
|
commands = parser.add_subparsers(dest="command", required=True)
|
|
inspect = commands.add_parser(
|
|
"inspect", help="Inventory a DirectAdmin account backup."
|
|
)
|
|
inspect.add_argument("backup", type=Path)
|
|
stage = commands.add_parser(
|
|
"stage-website",
|
|
help="Stage one DirectAdmin website in a new local directory.",
|
|
)
|
|
stage.add_argument("backup", type=Path)
|
|
stage.add_argument("domain")
|
|
stage.add_argument("destination", type=Path)
|
|
stage.add_argument(
|
|
"--source-root", choices=DOCUMENT_ROOTS, default="public_html"
|
|
)
|
|
args = parser.parse_args(argv)
|
|
try:
|
|
if args.command == "stage-website":
|
|
from .directadmin_website import stage_website
|
|
|
|
report = stage_website(
|
|
args.backup,
|
|
args.domain,
|
|
args.destination,
|
|
source_root=args.source_root,
|
|
)
|
|
else:
|
|
report = inspect_backup(args.backup)
|
|
except (OSError, ValueError) as error:
|
|
parser.exit(1, f"coulobre-directadmin: {error}\n")
|
|
print(json.dumps(report, indent=2))
|
|
return 0
|