Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-16 19:59:57 +03:00
1 parent 818d391022
commit 639362fbf5
40 files changed
+6701 -429

No files matched your search

+273
View File
@@ -0,0 +1,273 @@
#!/usr/bin/env python3
"""Collect deterministic license notices from an installed npm dependency tree."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import re
import shutil
import stat
import sys
import tempfile
from typing import Any
from urllib.parse import quote
NOTICE_FILE_PATTERN = re.compile(
r"^(?:licen[cs]e|copying|notice|copyright)(?:$|[._-].*)",
re.IGNORECASE,
)
class CollectionError(RuntimeError):
"""Raised when dependency metadata cannot produce a trustworthy notice."""
def is_package_root(package_json: Path, node_modules: Path) -> bool:
relative_parts = package_json.parent.relative_to(node_modules).parts
node_modules_indices = [
index
for index, component in enumerate(relative_parts)
if component == "node_modules"
]
package_start = node_modules_indices[-1] + 1 if node_modules_indices else 0
package_parts = relative_parts[package_start:]
if len(package_parts) == 1:
return not package_parts[0].startswith("@")
return (
len(package_parts) == 2
and package_parts[0].startswith("@")
and len(package_parts[0]) > 1
)
def package_json_files(node_modules: Path) -> list[Path]:
def fail_walk(error: OSError) -> None:
raise CollectionError(f"cannot scan {error.filename}: {error.strerror}")
package_files: list[Path] = []
for directory, child_directories, filenames in os.walk(
node_modules, followlinks=False, onerror=fail_walk
):
child_directories.sort()
filenames.sort()
if "package.json" not in filenames:
continue
candidate = Path(directory, "package.json")
if not stat.S_ISREG(candidate.lstat().st_mode):
continue
if is_package_root(candidate, node_modules):
package_files.append(candidate)
return package_files
def require_metadata_text(metadata: dict[str, Any], field: str, source: Path) -> str:
value = metadata.get(field)
if not isinstance(value, str) or not value.strip():
raise CollectionError(f"{source}: {field!r} must be a non-empty string")
value = value.strip()
if any(ord(character) < 32 or ord(character) == 127 for character in value):
raise CollectionError(f"{source}: {field!r} contains control characters")
return value
def require_plain_text(value: Any, description: str, source: Path) -> str:
if not isinstance(value, str) or not value.strip():
raise CollectionError(f"{source}: {description} must be a non-empty string")
value = value.strip()
if any(ord(character) < 32 or ord(character) == 127 for character in value):
raise CollectionError(f"{source}: {description} contains control characters")
return value
def validate_package_name(name: str, source: Path) -> None:
components = name.split("/")
valid_scope = (
len(components) == 2
and components[0].startswith("@")
and len(components[0]) > 1
)
if not (len(components) == 1 and not name.startswith("@")) and not valid_scope:
raise CollectionError(f"{source}: invalid npm package name {name!r}")
if any(component in {"", ".", ".."} for component in components):
raise CollectionError(f"{source}: invalid npm package name {name!r}")
if "\\" in name:
raise CollectionError(f"{source}: invalid npm package name {name!r}")
def describe_license_entry(value: Any, source: Path) -> str:
if isinstance(value, str):
return require_plain_text(value, "license", source)
if isinstance(value, dict):
description = require_plain_text(
value.get("type"), "license object type", source
)
license_url = value.get("url")
if license_url is not None:
description += (
f" ({require_plain_text(license_url, 'license URL', source)})"
)
return description
raise CollectionError(f"{source}: license metadata has an unsupported form")
def declared_license(metadata: dict[str, Any], source: Path) -> str:
if "license" in metadata:
return describe_license_entry(metadata["license"], source)
legacy_licenses = metadata.get("licenses")
if not isinstance(legacy_licenses, list) or not legacy_licenses:
raise CollectionError(f"{source}: package has no declared license")
descriptions = sorted(
{describe_license_entry(value, source) for value in legacy_licenses}
)
return "; ".join(descriptions)
def notice_files(package_root: Path) -> dict[str, bytes]:
notices: dict[str, bytes] = {}
with os.scandir(package_root) as entries:
for entry in sorted(entries, key=lambda candidate: candidate.name):
if not NOTICE_FILE_PATTERN.match(entry.name):
continue
if not entry.is_file(follow_symlinks=False):
continue
notices[entry.name] = Path(entry.path).read_bytes()
return notices
def output_component(value: str, *, safe: str) -> str:
return quote(value, safe=safe)
def collect(node_modules: Path, destination: Path) -> int:
if not node_modules.is_dir():
raise CollectionError(f"node_modules directory does not exist: {node_modules}")
packages: dict[tuple[str, str], tuple[str, dict[str, bytes], Path]] = {}
for package_file in package_json_files(node_modules):
try:
metadata = json.loads(package_file.read_text(encoding="utf-8"))
except (OSError, UnicodeError, json.JSONDecodeError) as error:
raise CollectionError(f"cannot read {package_file}: {error}") from error
if not isinstance(metadata, dict):
raise CollectionError(f"{package_file}: package metadata must be an object")
name = require_metadata_text(metadata, "name", package_file)
version = require_metadata_text(metadata, "version", package_file)
validate_package_name(name, package_file)
license_description = declared_license(metadata, package_file)
notices = notice_files(package_file.parent)
key = (name, version)
previous = packages.get(key)
if previous is not None:
previous_license, previous_notices, previous_source = previous
if previous_license != license_description or previous_notices != notices:
raise CollectionError(
f"conflicting contents for {name}@{version}: "
f"{previous_source} and {package_file}"
)
continue
packages[key] = (license_description, notices, package_file)
if not packages:
raise CollectionError(f"no npm packages found below {node_modules}")
destination_parent = destination.parent
destination_parent.mkdir(parents=True, exist_ok=True)
temporary = Path(
tempfile.mkdtemp(prefix=f".{destination.name}.", dir=destination_parent)
)
try:
temporary.chmod(0o755)
notice_lines = [
"Echoion frontend third-party notices",
"",
"Generated from the installed npm dependency tree.",
"Packages are sorted by name and version.",
"",
]
output_directories: set[str] = set()
for (name, version), (license_description, notices, _) in sorted(
packages.items()
):
directory_name = (
output_component(name, safe="@._+-")
+ "@"
+ output_component(version, safe="._+-")
)
if directory_name in output_directories:
raise CollectionError(
f"output-name collision while collecting {name}@{version}"
)
output_directories.add(directory_name)
package_destination = temporary / directory_name
package_destination.mkdir(mode=0o755)
package_destination.chmod(0o755)
copied_files: list[str] = []
for filename, contents in sorted(notices.items()):
output_name = output_component(filename, safe="._+-")
target = package_destination / output_name
target.write_bytes(contents)
target.chmod(0o644)
copied_files.append(f"{directory_name}/{output_name}")
notice_lines.append(f"Package: {name}@{version}")
notice_lines.append(f"Declared license: {license_description}")
if copied_files:
notice_lines.append("Notice files:")
notice_lines.extend(f" {filename}" for filename in copied_files)
else:
notice_lines.append("Notice files: none published at package root")
notice_lines.append("")
notices_path = temporary / "THIRD-PARTY-NOTICES.txt"
notices_path.write_text("\n".join(notice_lines), encoding="utf-8", newline="\n")
notices_path.chmod(0o644)
if destination.is_symlink() or (
destination.exists() and not destination.is_dir()
):
raise CollectionError(
f"destination is not a regular directory: {destination}"
)
if destination.exists():
shutil.rmtree(destination)
os.replace(temporary, destination)
except BaseException:
shutil.rmtree(temporary, ignore_errors=True)
raise
return len(packages)
def parse_arguments() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="collect npm dependency licenses for an Echoion release"
)
parser.add_argument("--node-modules", required=True, type=Path)
parser.add_argument("--output", required=True, type=Path)
return parser.parse_args()
def main() -> int:
arguments = parse_arguments()
try:
count = collect(
arguments.node_modules.resolve(),
Path(os.path.abspath(arguments.output)),
)
except (CollectionError, OSError) as error:
print(f"collect-frontend-licenses: {error}", file=sys.stderr)
return 2
print(f"Collected notices for {count} frontend npm packages.")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 BUILD_DIR" >&2
exit 2
fi
cache=$(realpath -e -- "$1/CMakeCache.txt")
compiler=
while IFS= read -r line; do
case $line in
CMAKE_CXX_COMPILER:FILEPATH=* | CMAKE_CXX_COMPILER:STRING=*)
[[ -z $compiler ]] || {
echo "duplicate CMAKE_CXX_COMPILER entries in $cache" >&2
exit 2
}
compiler=${line#*=}
;;
esac
done <"$cache"
[[ $compiler == /* && -x $compiler ]] || {
echo "CMake cache has no executable absolute C++ compiler: $cache" >&2
exit 2
}
realpath -e -- "$compiler"
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env python3
"""Generate Echoion's deterministic v2 immutable-payload manifest."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import re
import stat
import tempfile
VERSION_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
IMMUTABLE_ROOTS = ("bin", "lib", "service", "share")
UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
for block in iter(lambda: source.read(1024 * 1024), b""):
digest.update(block)
return digest.hexdigest()
def safe_symlink_target(root: Path, path: Path) -> str:
target = os.readlink(path)
target_path = PurePosixPath(target)
target_components = target.split("/")
if (
not target
or target_path.is_absolute()
or any(component in ("", ".", "..") for component in target_components)
):
raise ValueError(f"unsafe symlink target for {path}: {target!r}")
try:
resolved = path.resolve(strict=True)
resolved.relative_to(root)
except (FileNotFoundError, RuntimeError, ValueError) as error:
raise ValueError(f"symlink escapes the payload or is dangling: {path}") from error
return target
def reject_unsafe_writable_mode(path: Path, metadata: os.stat_result) -> None:
if metadata.st_mode & UNSAFE_WRITABLE_MODE:
raise ValueError(f"immutable payload path is group- or world-writable: {path}")
def collect_entries(root: Path) -> list[dict[str, object]]:
entries: list[dict[str, object]] = []
root_metadata = root.lstat()
if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink():
raise ValueError(f"immutable payload root is not a directory: {root}")
reject_unsafe_writable_mode(root, root_metadata)
pending = [root / name for name in IMMUTABLE_ROOTS]
for directory in pending:
try:
metadata = directory.lstat()
except FileNotFoundError as error:
raise ValueError(
f"missing immutable payload directory: {directory}"
) from error
if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink():
raise ValueError(f"missing immutable payload directory: {directory}")
reject_unsafe_writable_mode(directory, metadata)
while pending:
directory = pending.pop()
with os.scandir(directory) as iterator:
children = sorted(iterator, key=lambda item: item.name)
for child in children:
path = Path(child.path)
relative = path.relative_to(root).as_posix()
metadata = path.lstat()
if stat.S_ISLNK(metadata.st_mode):
entries.append(
{
"path": relative,
"type": "symlink",
"target": safe_symlink_target(root, path),
}
)
elif stat.S_ISDIR(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
pending.append(path)
elif stat.S_ISREG(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
if metadata.st_size > (1 << 53) - 1:
raise ValueError(f"payload file is too large for the manifest: {path}")
entries.append(
{
"path": relative,
"type": "file",
"size": metadata.st_size,
"sha256": sha256(path),
"mode": f"{stat.S_IMODE(metadata.st_mode):04o}",
}
)
else:
raise ValueError(f"unsupported special file in payload: {path}")
entries.sort(key=lambda entry: str(entry["path"]))
return entries
def write_manifest(root: Path, version: str, output: Path) -> None:
entries = collect_entries(root)
regular_files = {
str(entry["path"]) for entry in entries if entry["type"] == "file"
}
executable = "bin/echoiond"
core = "lib/Echoion.ts"
web_index = "share/echoion/web/index.html"
for description, required in (
("executable", executable),
("Core library", core),
("web dashboard entry point", web_index),
):
if required not in regular_files:
raise ValueError(f"manifest {description} is missing: {required}")
if not os.access(root / executable, os.X_OK):
raise ValueError(f"manifest executable is not executable: {executable}")
manifest = {
"schemaVersion": 2,
"version": version,
"executable": executable,
"core": core,
"files": entries,
}
output.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{output.name}.", dir=output.parent
)
try:
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
json.dump(manifest, stream, ensure_ascii=False, indent=2)
stream.write("\n")
os.chmod(temporary_name, 0o644)
os.replace(temporary_name, output)
except BaseException:
try:
os.unlink(temporary_name)
except FileNotFoundError:
pass
raise
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--root", required=True, type=Path)
parser.add_argument("--version", required=True)
parser.add_argument("--output", type=Path)
arguments = parser.parse_args()
if not VERSION_PATTERN.fullmatch(arguments.version):
parser.error("version must contain only letters, digits, dot, underscore, or dash")
root = arguments.root.resolve(strict=True)
output = arguments.output or root / "manifest.json"
write_manifest(root, arguments.version, output)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 6 ]]; then
echo "usage: $0 STAGE ARTIFACT_BASE SOURCE_DATE_EPOCH ARCHIVE INSTALLER WORK_DIR" >&2
exit 2
fi
stage=$(realpath -e -- "$1")
artifact_base=$2
source_date_epoch=$3
archive=$(realpath -m -- "$4")
installer=$(realpath -m -- "$5")
work_dir=$(realpath -m -- "$6")
[[ $artifact_base =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$ ]] || {
echo "invalid artifact base: $artifact_base" >&2
exit 2
}
[[ $source_date_epoch =~ ^[0-9]+$ ]] || {
echo "SOURCE_DATE_EPOCH must be a non-negative integer" >&2
exit 2
}
[[ -x $stage/install.sh && -x $stage/uninstall.sh ]] || {
echo "stage is missing executable installer helpers" >&2
exit 2
}
[[ -f $stage/manifest.json && -x $stage/bin/echoiond && -f $stage/lib/Echoion.ts ]] || {
echo "stage is missing required Echoion payload files" >&2
exit 2
}
mkdir -p -- "$(dirname -- "$archive")" "$(dirname -- "$installer")" "$work_dir"
archive_tmp="$(dirname -- "$archive")/.$(basename -- "$archive").tmp.$$"
installer_tmp="$(dirname -- "$installer")/.$(basename -- "$installer").tmp.$$"
gzip_payload="$work_dir/$artifact_base.tar.gz.$$"
header="$work_dir/$artifact_base.run-header.$$"
cleanup() {
rm -f -- "$archive_tmp" "$installer_tmp" "$gzip_payload" "$header"
}
trap cleanup EXIT
tar_options=(
--sort=name
"--mtime=@$source_date_epoch"
--owner=0
--group=0
--numeric-owner
--format=posix
'--pax-option=delete=atime,delete=ctime'
)
tar -C "$stage" "${tar_options[@]}" \
--transform="s,^\\.$,$artifact_base," \
--transform="s,^\\./,$artifact_base/," \
-cf - . |
zstd -T1 -19 --no-progress -o "$archive_tmp"
mv -f -- "$archive_tmp" "$archive"
tar -C "$stage" "${tar_options[@]}" -cf - . | gzip -n -9 >"$gzip_payload"
cat >"$header" <<'RUN_HEADER'
#!/bin/sh
set -eu
self=$0
case $self in
/*) ;;
*) self=$(pwd)/$self ;;
esac
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-installer.XXXXXX")
cleanup() {
rm -rf -- "$temporary"
}
trap cleanup EXIT HUP INT TERM
payload_line=$(awk '/^__ECHOION_PAYLOAD_BELOW__$/ { print NR + 1; exit }' "$self")
if [ -z "$payload_line" ]; then
echo "Echoion installer payload marker is missing" >&2
exit 2
fi
tail -n "+$payload_line" "$self" |
tar --same-permissions --no-same-owner -xzf - -C "$temporary"
"$temporary/install.sh" "$@"
status=$?
exit "$status"
__ECHOION_PAYLOAD_BELOW__
RUN_HEADER
cat "$header" "$gzip_payload" >"$installer_tmp"
chmod 0755 "$installer_tmp"
mv -f -- "$installer_tmp" "$installer"
trap - EXIT
+354
View File
@@ -0,0 +1,354 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<'EOF'
usage: scripts/release.sh --version VERSION [options]
Options:
--build-dir DIR Clean build directory (default: build-release)
--dist-dir DIR Release output directory (default: dist)
--jobs N Parallel build jobs
--skip-tests Skip CTest and frontend tests
--no-clean Reuse the configured build directory
--container Build with containers/release.Dockerfile (the default)
--host Explicitly build directly on this host
-h, --help Show this help
The release process never starts echoiond. Runtime validation uses readelf.
EOF
}
die() {
echo "release: $*" >&2
exit 2
}
script_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
source_dir=$(cd -- "$script_dir/.." && pwd -P)
version=
build_dir="$source_dir/build-release"
dist_dir="$source_dir/dist"
jobs=
run_tests=1
clean_build=1
use_container=1
while (($#)); do
case $1 in
--version)
(($# >= 2)) || die "--version requires a value"
version=$2
shift 2
;;
--build-dir)
(($# >= 2)) || die "--build-dir requires a value"
build_dir=$2
shift 2
;;
--dist-dir)
(($# >= 2)) || die "--dist-dir requires a value"
dist_dir=$2
shift 2
;;
--jobs)
(($# >= 2)) || die "--jobs requires a value"
jobs=$2
shift 2
;;
--skip-tests)
run_tests=0
shift
;;
--no-clean)
clean_build=0
shift
;;
--container)
use_container=1
shift
;;
--host)
use_container=0
shift
;;
-h|--help)
usage
exit 0
;;
*)
die "unknown argument: $1"
;;
esac
done
[[ $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]] ||
die "--version must contain only letters, digits, dot, underscore, or dash"
if [[ -n $jobs && ! $jobs =~ ^[1-9][0-9]*$ ]]; then
die "--jobs must be a positive integer"
fi
build_dir=$(realpath -m -- "$build_dir")
dist_dir=$(realpath -m -- "$dist_dir")
container_path() {
local path=$1
case $path in
"$source_dir") echo /workspace ;;
"$source_dir"/*) echo "/workspace/${path#"$source_dir"/}" ;;
*) die "container build and dist directories must be inside $source_dir" ;;
esac
}
if ((use_container)); then
command -v docker >/dev/null || die "docker is required for --container"
container_build_dir=$(container_path "$build_dir")
container_dist_dir=$(container_path "$dist_dir")
image="echoion-release-builder:gcc-16.1.0"
docker build \
--platform linux/amd64 \
--file "$source_dir/containers/release.Dockerfile" \
--tag "$image" \
"$source_dir"
container_args=(
--rm
--user "$(id -u):$(id -g)"
--volume "$source_dir:/workspace"
--workdir /workspace
--env HOME=/tmp/echoion-release-home
--env npm_config_cache=/tmp/echoion-npm-cache
)
if [[ -n ${SOURCE_DATE_EPOCH:-} ]]; then
container_args+=(--env "SOURCE_DATE_EPOCH=$SOURCE_DATE_EPOCH")
fi
release_args=(
--host
--version "$version"
--build-dir "$container_build_dir"
--dist-dir "$container_dist_dir"
)
[[ -n $jobs ]] && release_args+=(--jobs "$jobs")
((run_tests)) || release_args+=(--skip-tests)
((clean_build)) || release_args+=(--no-clean)
docker run --platform linux/amd64 "${container_args[@]}" "$image" \
bash scripts/release.sh "${release_args[@]}"
exit
fi
case "$(uname -s)/$(uname -m)" in
Linux/x86_64|Linux/amd64) ;;
*) die "host release builds require Linux x86_64; use the amd64 container builder" ;;
esac
required_commands=(
cmake ninja npm python3 patchelf readelf tar zstd gzip sha256sum
dpkg-query ldconfig
)
for command_name in "${required_commands[@]}"; do
command -v "$command_name" >/dev/null || die "required command not found: $command_name"
done
[[ -x $source_dir/packaging/install.sh ]] ||
die "installer source is missing: packaging/install.sh"
[[ -x $source_dir/packaging/uninstall.sh ]] ||
die "uninstaller source is missing: packaging/uninstall.sh"
[[ -f $source_dir/packaging/service/echoion.service.in ]] ||
die "service template is missing: packaging/service/echoion.service.in"
if [[ -z ${SOURCE_DATE_EPOCH:-} ]]; then
SOURCE_DATE_EPOCH=$(git -C "$source_dir" log -1 --format=%ct 2>/dev/null || true)
[[ $SOURCE_DATE_EPOCH =~ ^[0-9]+$ ]] || SOURCE_DATE_EPOCH=0
fi
export SOURCE_DATE_EPOCH
safe_remove_tree() {
local path=$1
case $path in
"$source_dir"/build*|/tmp/*) ;;
*) die "refusing to clean non-build path outside source build*/ or /tmp: $path" ;;
esac
rm -rf -- "$path"
}
if ((clean_build)); then
safe_remove_tree "$build_dir"
fi
mkdir -p "$build_dir"
configure_args=(--preset linux-release -B "$build_dir")
npm --prefix "$source_dir/EchoionWeb/frontend" ci --no-audit --no-fund
cmake -E rm -rf "$source_dir/EchoionWeb/frontend/web-dist"
(
cd "$source_dir"
cmake "${configure_args[@]}"
)
build_args=(--build "$build_dir" --config Release)
[[ -n $jobs ]] && build_args+=(--parallel "$jobs")
cmake "${build_args[@]}"
if ((run_tests)); then
ctest --test-dir "$build_dir" --build-config Release --output-on-failure
npm --prefix "$source_dir/EchoionWeb/frontend" test
npm --prefix "$source_dir/EchoionWeb/frontend" run i18n:check
fi
stage="$build_dir/runtime-stage"
safe_remove_tree "$stage"
cmake --install "$build_dir" \
--config Release \
--component Runtime \
--prefix "$stage"
mapfile -t library_directories < <(
find "$build_dir" -type f \( -name '*.so' -o -name '*.so.*' -o -name '*.ts' \) \
-printf '%h\n' | LC_ALL=C sort -u
)
library_directories+=("$stage/lib")
cxx_compiler=$("$source_dir/scripts/configured-cxx-compiler.sh" "$build_dir")
compiler_runtime_files=()
for runtime_name in libstdc++.so.6 libgcc_s.so.1; do
runtime_path=$(
"$cxx_compiler" -print-file-name="$runtime_name"
) || die "cannot locate $runtime_name with $cxx_compiler"
[[ $runtime_path == /* && -f $runtime_path ]] ||
die "$cxx_compiler did not return an existing absolute path for $runtime_name"
compiler_runtime_files+=("$runtime_path")
library_directories+=("$(dirname -- "$runtime_path")")
done
search_directories=$(IFS=';'; echo "${library_directories[*]}")
compiler_runtimes=$(IFS=';'; echo "${compiler_runtime_files[*]}")
cmake \
"-DBUNDLE_ROOT=$stage" \
"-DBUNDLE_RESOLVER_EXECUTABLE=$build_dir/bin/echoiond" \
"-DBUNDLE_RESOLVER_LIBRARIES=$build_dir/lib/Echoion.ts" \
"-DBUNDLE_SEARCH_DIRECTORIES=$search_directories" \
"-DBUNDLE_SEED_FILES=$compiler_runtimes" \
"-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \
-P "$source_dir/cmake/BundleRuntimeDependencies.cmake"
dependency_report="$build_dir/dependency-report.txt"
python3 "$source_dir/scripts/validate-release-elf.py" \
--root "$stage" \
--max-glibc 2.35 \
--report "$dependency_report"
collect_licenses() {
local destination=$1
local candidate relative package_name license_name digest target package source_path soname
local -a license_roots=(
"$source_dir/EchoionApi"
"$source_dir/EchoionCore"
"$source_dir/EchoionHost"
"$source_dir/EchoionStandalone"
"$source_dir/EchoionWeb"
"$build_dir/_deps"
)
if [[ -n ${GCC_ROOT:-} && -d $GCC_ROOT/share/licenses ]]; then
license_roots+=("$GCC_ROOT/share/licenses")
fi
if [[ -n ${BOOST_ROOT:-} && -d $BOOST_ROOT/share/licenses ]]; then
license_roots+=("$BOOST_ROOT/share/licenses")
fi
if [[ -n ${FFMPEG_ROOT:-} && -d $FFMPEG_ROOT/share/licenses ]]; then
license_roots+=("$FFMPEG_ROOT/share/licenses")
fi
mkdir -p "$destination"
for source_path in "${license_roots[@]}"; do
[[ -d $source_path ]] || continue
while IFS= read -r -d '' candidate; do
relative=${candidate#"$source_path"/}
if [[ $relative == */* ]]; then
package_name=${relative%%/*}
else
package_name=$(basename -- "$source_path")
fi
license_name=$(basename -- "$candidate")
package_name=${package_name//[^A-Za-z0-9._+-]/_}
license_name=${license_name//[^A-Za-z0-9._+-]/_}
digest=$(sha256sum "$candidate" | cut -c1-12)
target="$destination/${package_name}--${license_name}--${digest}"
install -m 0644 -- "$candidate" "$target"
done < <(
find "$source_path" -maxdepth 5 -type f \
\( -iname 'LICENSE' -o -iname 'LICENSE.txt' -o \
-iname 'LICENSE.md' -o -iname 'LICENSE.rst' -o \
-iname 'LICENSE-*' -o -iname 'LICENSE_*' -o \
-iname 'COPYING' -o -iname 'COPYING.*' -o \
-iname 'NOTICE' -o -iname 'NOTICE.*' -o \
-iname 'COPYRIGHT' -o -iname 'COPYRIGHT.*' \) \
-not -path '*/node_modules/*' -not -path '*/.git/*' \
-print0 | LC_ALL=C sort -z
)
done
if command -v dpkg-query >/dev/null && command -v ldconfig >/dev/null; then
while IFS= read -r soname; do
[[ -n $soname ]] || continue
source_path=$(ldconfig -p 2>/dev/null |
awk -v name="$soname" '
$1 == name && !path { path = $NF }
END { if (path) print path }
')
[[ -n $source_path ]] || continue
package=$(dpkg-query -S "$(readlink -f -- "$source_path")" 2>/dev/null |
sed -n '1s/: .*//p') || package=
[[ -n $package ]] || continue
package=${package%%:*}
candidate="/usr/share/doc/${package}/copyright"
[[ -f $candidate ]] || continue
install -m 0644 -- "$candidate" "$destination/${package}--copyright"
done < <(
find "$stage/lib" -maxdepth 1 \( -type f -o -type l \) \
-printf '%f\n' | LC_ALL=C sort -u
)
fi
}
collect_licenses "$stage/share/echoion/licenses"
python3 "$source_dir/scripts/collect-frontend-licenses.py" \
--node-modules "$source_dir/EchoionWeb/frontend/node_modules" \
--output "$stage/share/echoion/licenses/frontend"
python3 "$source_dir/scripts/generate-release-manifest.py" \
--root "$stage" \
--version "$version" \
--output "$stage/manifest.json"
# Installer helpers are mutable prefix-level files and intentionally are not
# included in manifest.files. They are added only after the immutable manifest.
install -m 0755 "$source_dir/packaging/install.sh" "$stage/install.sh"
install -m 0755 "$source_dir/packaging/uninstall.sh" "$stage/uninstall.sh"
mkdir -p "$dist_dir"
artifact_base="echoion-${version}-linux-x86_64"
archive="$dist_dir/$artifact_base.tar.zst"
installer="$dist_dir/$artifact_base.run"
external_manifest="$dist_dir/$artifact_base.manifest.json"
external_report="$dist_dir/$artifact_base.dependencies.txt"
rm -f -- \
"$archive" "$archive.tmp" \
"$installer" "$installer.tmp" \
"$external_manifest" "$external_report" \
"$dist_dir/SHA256SUMS"
bash "$source_dir/scripts/package-release-payload.sh" \
"$stage" "$artifact_base" "$SOURCE_DATE_EPOCH" \
"$archive" "$installer" "$build_dir"
install -m 0644 "$stage/manifest.json" "$external_manifest"
install -m 0644 "$dependency_report" "$external_report"
(
cd "$dist_dir"
sha256sum \
"$(basename "$archive")" \
"$(basename "$installer")" \
"$(basename "$external_manifest")" \
"$(basename "$external_report")" >SHA256SUMS
)
echo "Release created without starting Echoion:"
echo " $archive"
echo " $installer"
echo " $external_manifest"
echo " $external_report"
echo " $dist_dir/SHA256SUMS"
+211 -32
View File
@@ -1,63 +1,242 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -lt 4 || $# -gt 5 ]]; then
echo "usage: $0 RELEASE_ROOT VERSION ECHOIOND ECHOION_CORE [MANIFEST]" >&2
if [[ $# -lt 3 || $# -gt 4 ]]; then
echo "usage: $0 RELEASE_ROOT VERSION BUNDLE_ROOT [MANIFEST]" >&2
exit 2
fi
release_root=$1
release_root=$(realpath -m -- "$1")
version=$2
executable=$3
core=$4
manifest=${5:-"$release_root/pending-release.json"}
bundle_root=$(realpath -e -- "$3")
manifest=${4:-"$release_root/pending-release.json"}
manifest=$(realpath -m -- "$manifest")
if [[ ! $version =~ ^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$ ]]; then
echo "invalid release version: $version" >&2
exit 2
fi
if [[ ! -x $executable ]]; then
echo "echoiond is missing or not executable: $executable" >&2
if [[ $bundle_root == "$release_root" ||
$bundle_root == "$release_root"/* ||
$release_root == "$bundle_root"/* ]]; then
echo "bundle root and release root must not overlap" >&2
exit 2
fi
if [[ ! -f $core ]]; then
echo "Core library is missing: $core" >&2
if [[ $(dirname -- "$manifest") != "$release_root" ]]; then
echo "pending manifest must be written directly below the release root" >&2
exit 2
fi
if [[ ! -x $bundle_root/bin/echoiond ]]; then
echo "echoiond is missing or not executable: $bundle_root/bin/echoiond" >&2
exit 2
fi
if [[ ! -f $bundle_root/lib/Echoion.ts ]]; then
echo "Core library is missing: $bundle_root/lib/Echoion.ts" >&2
exit 2
fi
if [[ ! -f $bundle_root/manifest.json ]]; then
echo "v2 release manifest is missing: $bundle_root/manifest.json" >&2
exit 2
fi
mkdir -p "$release_root" "$(dirname "$manifest")"
mkdir -p -- "$release_root" "$(dirname -- "$manifest")"
staging="$release_root/.staging-$version-$$"
destination="$release_root/$version"
trap 'rm -rf -- "$staging"' EXIT
manifest_tmp="$(dirname -- "$manifest")/.$(basename -- "$manifest").tmp.$$"
version_lock="$release_root/.stage-$version.lock"
destination_created=0
manifest_published=0
lock_acquired=0
cleanup() {
rm -rf -- "$staging"
rm -f -- "$manifest_tmp"
if ((destination_created && !manifest_published)); then
rm -rf -- "$destination"
fi
if ((lock_acquired)); then
rmdir -- "$version_lock" 2>/dev/null || true
fi
}
trap cleanup EXIT
if ! mkdir -- "$version_lock"; then
echo "release staging is already active for version $version" >&2
exit 2
fi
lock_acquired=1
if [[ -e $destination ]]; then
echo "release already exists: $destination" >&2
exit 2
fi
mkdir "$staging"
install -m 0755 "$executable" "$staging/echoiond"
install -m 0644 "$core" "$staging/Echoion.ts"
mkdir -m 0755 -- "$staging"
cp -a -- "$bundle_root/." "$staging/"
executable_hash=$(sha256sum "$staging/echoiond" | cut -d' ' -f1)
core_hash=$(sha256sum "$staging/Echoion.ts" | cut -d' ' -f1)
mv "$staging" "$destination"
python3 - "$staging" "$version" "$manifest_tmp" <<'PY'
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import stat
import sys
manifest_tmp="$manifest.tmp.$$"
trap 'rm -rf -- "$staging"; rm -f -- "$manifest_tmp"' EXIT
printf '%s\n' \
'{' \
" \"version\": \"$version\"," \
" \"executable\": \"$version/echoiond\"," \
" \"core\": \"$version/Echoion.ts\"," \
' "sha256": {' \
" \"executable\": \"$executable_hash\"," \
" \"core\": \"$core_hash\"" \
' }' \
'}' > "$manifest_tmp"
chmod 0644 "$manifest_tmp"
mv -f "$manifest_tmp" "$manifest"
IMMUTABLE_ROOTS = ("bin", "lib", "service", "share")
UNSAFE_WRITABLE_MODE = stat.S_IWGRP | stat.S_IWOTH
def reject_unsafe_writable_mode(path, metadata):
if metadata.st_mode & UNSAFE_WRITABLE_MODE:
raise SystemExit(
f"immutable payload path is group- or world-writable: {path}"
)
root = Path(sys.argv[1]).resolve(strict=True)
version = sys.argv[2]
output = Path(sys.argv[3])
source = root / "manifest.json"
with source.open("r", encoding="utf-8") as stream:
manifest = json.load(stream)
if manifest.get("schemaVersion") != 2:
raise SystemExit("release manifest must use schemaVersion 2")
if manifest.get("version") != version:
raise SystemExit(
f"release version mismatch: expected {version!r}, got {manifest.get('version')!r}"
)
entries = manifest.get("files")
if not isinstance(entries, list):
raise SystemExit("release manifest files must be an array")
root_metadata = root.lstat()
if not stat.S_ISDIR(root_metadata.st_mode) or root.is_symlink():
raise SystemExit(f"immutable payload root is not a directory: {root}")
reject_unsafe_writable_mode(root, root_metadata)
actual = set()
pending_directories = [root / name for name in IMMUTABLE_ROOTS]
for directory in pending_directories:
try:
metadata = directory.lstat()
except FileNotFoundError:
raise SystemExit(f"missing immutable payload directory: {directory}")
if not stat.S_ISDIR(metadata.st_mode) or directory.is_symlink():
raise SystemExit(f"missing immutable payload directory: {directory}")
reject_unsafe_writable_mode(directory, metadata)
while pending_directories:
directory = pending_directories.pop()
with os.scandir(directory) as iterator:
children = sorted(iterator, key=lambda item: item.name)
for child in children:
path = Path(child.path)
relative = path.relative_to(root).as_posix()
metadata = path.lstat()
if stat.S_ISDIR(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
pending_directories.append(path)
elif stat.S_ISREG(metadata.st_mode) or stat.S_ISLNK(metadata.st_mode):
if stat.S_ISREG(metadata.st_mode):
reject_unsafe_writable_mode(path, metadata)
actual.add(relative)
else:
raise SystemExit(f"unsupported special file in payload: {path}")
seen = set()
entry_types = {}
for entry in entries:
if not isinstance(entry, dict) or not isinstance(entry.get("path"), str):
raise SystemExit("invalid release manifest file entry")
relative = PurePosixPath(entry["path"])
if (
relative.is_absolute()
or not relative.parts
or relative.as_posix() != entry["path"]
or any(component in ("", ".", "..") for component in entry["path"].split("/"))
):
raise SystemExit(f"unsafe manifest path: {entry['path']!r}")
if entry["path"] in seen:
raise SystemExit(f"duplicate manifest path: {entry['path']}")
if relative.parts[0] not in IMMUTABLE_ROOTS:
raise SystemExit(
f"manifest path is outside immutable payload roots: {entry['path']}"
)
seen.add(entry["path"])
entry_types[entry["path"]] = entry.get("type")
path = root.joinpath(*relative.parts)
metadata = path.lstat()
if entry.get("type") == "file":
if not stat.S_ISREG(metadata.st_mode):
raise SystemExit(f"manifest regular file is missing: {entry['path']}")
digest = hashlib.sha256(path.read_bytes()).hexdigest()
if digest != entry.get("sha256") or metadata.st_size != entry.get("size"):
raise SystemExit(f"manifest file verification failed: {entry['path']}")
mode = f"{stat.S_IMODE(metadata.st_mode):04o}"
if mode != entry.get("mode"):
raise SystemExit(f"manifest mode verification failed: {entry['path']}")
reject_unsafe_writable_mode(path, metadata)
elif entry.get("type") == "symlink":
if not stat.S_ISLNK(metadata.st_mode):
raise SystemExit(f"manifest symlink is missing: {entry['path']}")
target = entry.get("target")
if not isinstance(target, str):
raise SystemExit(f"invalid manifest symlink target: {entry['path']}")
target_path = PurePosixPath(target)
if (
target_path.is_absolute()
or any(component in ("", ".", "..") for component in target.split("/"))
):
raise SystemExit(f"unsafe manifest symlink target: {entry['path']}")
if os.readlink(path) != target:
raise SystemExit(f"manifest symlink verification failed: {entry['path']}")
try:
path.resolve(strict=True).relative_to(root)
except (FileNotFoundError, RuntimeError, ValueError):
raise SystemExit(f"manifest symlink escapes release root: {entry['path']}")
else:
raise SystemExit(f"invalid manifest entry type: {entry.get('type')!r}")
if seen != actual:
undeclared = sorted(actual - seen)
missing = sorted(seen - actual)
details = []
if undeclared:
details.append("undeclared=" + ",".join(undeclared))
if missing:
details.append("missing=" + ",".join(missing))
raise SystemExit("immutable payload coverage mismatch: " + "; ".join(details))
required_files = {
"executable": "bin/echoiond",
"core": "lib/Echoion.ts",
"web dashboard": "share/echoion/web/index.html",
}
for description, required in required_files.items():
if description in ("executable", "core") and manifest.get(description) != required:
raise SystemExit(f"manifest {description} has a non-canonical path")
if required not in seen or entry_types.get(required) != "file":
raise SystemExit(f"manifest {description} is not declared as a file")
prefix = f"{version}/"
pending = dict(manifest)
pending["executable"] = prefix + manifest["executable"]
pending["core"] = prefix + manifest["core"]
pending["files"] = [dict(entry, path=prefix + entry["path"]) for entry in entries]
with output.open("w", encoding="utf-8", newline="\n") as stream:
json.dump(pending, stream, ensure_ascii=False, indent=2)
stream.write("\n")
os.chmod(output, 0o644)
PY
mv -T -- "$staging" "$destination"
destination_created=1
mv -f -- "$manifest_tmp" "$manifest"
manifest_published=1
rmdir -- "$version_lock"
lock_acquired=0
trap - EXIT
echo "staged release $version"
echo "payload: $destination"
echo "manifest: $manifest"
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 SOURCE_ROOT" >&2
exit 2
fi
source_root=$(realpath -e -- "$1")
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-frontend-licenses.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
node_modules="$temporary/node_modules"
mkdir -p \
"$node_modules/plain/docs" \
"$node_modules/@scope/example" \
"$node_modules/parent/node_modules/duplicate" \
"$node_modules/second/node_modules/duplicate" \
"$node_modules/no-notice"
printf '%s\n' \
'{"name":"plain","version":"1.2.3","license":"MIT"}' \
>"$node_modules/plain/package.json"
printf '%s\n' 'plain license' >"$node_modules/plain/LICENSE"
printf '%s\n' 'ignored nested file' >"$node_modules/plain/docs/LICENSE"
printf '%s\n' '{"name":"not-a-package-root"}' \
>"$node_modules/plain/docs/package.json"
printf '%s\n' \
'{"name":"@scope/example","version":"2.0.0-beta.1","license":"Apache-2.0"}' \
>"$node_modules/@scope/example/package.json"
printf '%s\n' 'scoped license' >"$node_modules/@scope/example/LICENCE.md"
printf '%s\n' 'scoped notice' >"$node_modules/@scope/example/NOTICE-extra"
for package_root in \
"$node_modules/parent/node_modules/duplicate" \
"$node_modules/second/node_modules/duplicate"; do
printf '%s\n' \
'{"name":"duplicate","version":"3.4.5","licenses":[{"type":"BSD-2-Clause"}]}' \
>"$package_root/package.json"
printf '%s\n' 'duplicate copying' >"$package_root/COPYING.txt"
done
printf '%s\n' \
'{"name":"no-notice","version":"4.0.0","license":"ISC"}' \
>"$node_modules/no-notice/package.json"
output_one="$temporary/output-one"
output_two="$temporary/output-two"
(
umask 077
python3 "$source_root/scripts/collect-frontend-licenses.py" \
--node-modules "$node_modules" \
--output "$output_one"
)
python3 "$source_root/scripts/collect-frontend-licenses.py" \
--node-modules "$node_modules" \
--output "$output_two"
diff -r -- "$output_one" "$output_two"
[[ -f $output_one/plain@1.2.3/LICENSE ]]
[[ ! -e $output_one/plain@1.2.3/docs ]]
[[ -f $output_one/@scope%2Fexample@2.0.0-beta.1/LICENCE.md ]]
[[ -f $output_one/@scope%2Fexample@2.0.0-beta.1/NOTICE-extra ]]
[[ -f $output_one/duplicate@3.4.5/COPYING.txt ]]
[[ -d $output_one/no-notice@4.0.0 ]]
if find "$output_one" -type d ! -perm 0755 -print -quit | grep -q .; then
echo "license collection created a directory with an unstable mode" >&2
exit 1
fi
if find "$output_one" -type f ! -perm 0644 -print -quit | grep -q .; then
echo "license collection created a file with an unstable mode" >&2
exit 1
fi
python3 - "$output_one/THIRD-PARTY-NOTICES.txt" <<'PY'
from pathlib import Path
import sys
contents = Path(sys.argv[1]).read_text(encoding="utf-8")
packages = [
line.removeprefix("Package: ")
for line in contents.splitlines()
if line.startswith("Package: ")
]
assert packages == sorted(packages)
assert packages == [
"@scope/example@2.0.0-beta.1",
"duplicate@3.4.5",
"no-notice@4.0.0",
"plain@1.2.3",
]
assert contents.count("Package: duplicate@3.4.5") == 1
assert "Declared license: BSD-2-Clause" in contents
assert "Notice files: none published at package root" in contents
assert "@scope%2Fexample@2.0.0-beta.1/NOTICE-extra" in contents
PY
mkdir -p "$temporary/malformed/node_modules/bad"
printf '%s\n' '{"name":"bad","version":"1.0.0"}' \
>"$temporary/malformed/node_modules/bad/package.json"
error_file="$temporary/malformed.error"
if python3 "$source_root/scripts/collect-frontend-licenses.py" \
--node-modules "$temporary/malformed/node_modules" \
--output "$temporary/malformed-output" \
>/dev/null 2>"$error_file"; then
echo "package without license metadata unexpectedly passed" >&2
exit 1
fi
grep -Fq 'package has no declared license' "$error_file"
mkdir -p \
"$temporary/conflict/node_modules/first/node_modules/same" \
"$temporary/conflict/node_modules/second/node_modules/same"
for package_root in \
"$temporary/conflict/node_modules/first/node_modules/same" \
"$temporary/conflict/node_modules/second/node_modules/same"; do
printf '%s\n' \
'{"name":"same","version":"1.0.0","license":"MIT"}' \
>"$package_root/package.json"
done
printf '%s\n' first \
>"$temporary/conflict/node_modules/first/node_modules/same/LICENSE"
printf '%s\n' second \
>"$temporary/conflict/node_modules/second/node_modules/same/LICENSE"
if python3 "$source_root/scripts/collect-frontend-licenses.py" \
--node-modules "$temporary/conflict/node_modules" \
--output "$temporary/conflict-output" >/dev/null 2>&1; then
echo "conflicting duplicate package contents unexpectedly passed" >&2
exit 1
fi
echo "frontend npm license collection regressions passed"
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 SOURCE_ROOT" >&2
exit 2
fi
source_root=$(realpath -e -- "$1")
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-release-archive.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
stage="$temporary/stage"
mkdir -p "$stage/bin" "$stage/lib"
install -m 0755 /bin/true "$stage/bin/echoiond"
install -m 0644 /bin/true "$stage/lib/Echoion.ts"
printf '%s\n' '{}' >"$stage/manifest.json"
cat >"$stage/install.sh" <<'INSTALL'
#!/bin/sh
set -eu
payload_root=$(CDPATH= cd -P -- "$(dirname -- "$0")" && pwd -P)
[ "$(stat -c '%a' -- "$payload_root/bin/echoiond")" = 755 ]
[ "$(stat -c '%a' -- "$payload_root/lib/Echoion.ts")" = 644 ]
[ "$1" = --record ]
record=$2
shift 2
printf '%s\n' "$@" >"$record"
INSTALL
printf '%s\n' '#!/bin/sh' 'exit 0' >"$stage/uninstall.sh"
chmod 0755 "$stage/install.sh" "$stage/uninstall.sh"
base=echoion-1.2.3-linux-x86_64
archive_one="$temporary/one.tar.zst"
installer_one="$temporary/one.run"
archive_two="$temporary/two.tar.zst"
installer_two="$temporary/two.run"
bash "$source_root/scripts/package-release-payload.sh" \
"$stage" "$base" 1700000000 "$archive_one" "$installer_one" "$temporary"
bash "$source_root/scripts/package-release-payload.sh" \
"$stage" "$base" 1700000000 "$archive_two" "$installer_two" "$temporary"
cmp "$archive_one" "$archive_two"
cmp "$installer_one" "$installer_two"
mapfile -t members < <(tar --zstd -tf "$archive_one")
((${#members[@]} > 0))
for member in "${members[@]}"; do
[[ $member == "$base" || $member == "$base/"* ]] || {
echo "archive member escaped top-level directory: $member" >&2
exit 1
}
done
printf '%s\n' "${members[@]}" | grep -Fx "$base/bin/echoiond"
record="$temporary/installer-arguments"
(
umask 077
"$installer_one" --record "$record" alpha 'two words'
)
printf '%s\n' alpha 'two words' >"$temporary/expected-arguments"
cmp "$temporary/expected-arguments" "$record"
echo "release archive layout and .run regressions passed"
+207
View File
@@ -0,0 +1,207 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 SOURCE_ROOT" >&2
exit 2
fi
source_root=$(realpath -e -- "$1")
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-release-packaging.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
bundle="$temporary/bundle"
mkdir -p \
"$bundle/bin" \
"$bundle/lib" \
"$bundle/service" \
"$bundle/share/echoion/web"
install -m 0755 /bin/true "$bundle/bin/echoiond"
install -m 0644 /bin/true "$bundle/lib/Echoion.ts"
printf '%s\n' '<!doctype html><title>Echoion</title>' \
>"$bundle/share/echoion/web/index.html"
printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in"
ln -s Echoion.ts "$bundle/lib/Echoion-current.ts"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$bundle" --version 1.2.3
cp "$bundle/manifest.json" "$temporary/manifest.first.json"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$bundle" --version 1.2.3
cmp "$temporary/manifest.first.json" "$bundle/manifest.json"
unsafe_file_mode="$temporary/unsafe-file-mode"
cp -a "$bundle" "$unsafe_file_mode"
chmod 0666 "$unsafe_file_mode/lib/Echoion.ts"
if python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$unsafe_file_mode" --version 1.2.3 >/dev/null 2>&1; then
echo "world-writable payload file unexpectedly entered manifest" >&2
exit 1
fi
unsafe_directory_mode="$temporary/unsafe-directory-mode"
cp -a "$bundle" "$unsafe_directory_mode"
chmod 0777 "$unsafe_directory_mode/lib"
if python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$unsafe_directory_mode" --version 1.2.3 >/dev/null 2>&1; then
echo "world-writable payload directory unexpectedly entered manifest" >&2
exit 1
fi
python3 - "$bundle/manifest.json" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as stream:
manifest = json.load(stream)
assert manifest["schemaVersion"] == 2
assert manifest["version"] == "1.2.3"
assert manifest["executable"] == "bin/echoiond"
assert manifest["core"] == "lib/Echoion.ts"
paths = [entry["path"] for entry in manifest["files"]]
assert paths == sorted(paths)
assert "share/echoion/web/index.html" in paths
link = next(entry for entry in manifest["files"] if entry["path"].endswith("current.ts"))
assert link == {
"path": "lib/Echoion-current.ts",
"type": "symlink",
"target": "Echoion.ts",
}
for entry in manifest["files"]:
if entry["type"] == "file":
assert set(entry) == {"path", "type", "size", "sha256", "mode"}
assert len(entry["sha256"]) == 64
assert len(entry["mode"]) == 4
PY
printf '%s\n' '#!/bin/sh' 'exit 0' >"$bundle/install.sh"
printf '%s\n' '#!/bin/sh' 'exit 0' >"$bundle/uninstall.sh"
chmod 0755 "$bundle/install.sh" "$bundle/uninstall.sh"
for overlapping_release_root in "$bundle" "$bundle/releases"; do
if bash "$source_root/scripts/stage-release.sh" \
"$overlapping_release_root" 1.2.3 "$bundle" >/dev/null 2>&1; then
echo "overlapping bundle/release roots unexpectedly staged" >&2
exit 1
fi
done
overlap_parent="$temporary/overlap-parent"
mkdir "$overlap_parent"
cp -a "$bundle" "$overlap_parent/bundle"
if bash "$source_root/scripts/stage-release.sh" \
"$overlap_parent" 1.2.3 "$overlap_parent/bundle" >/dev/null 2>&1; then
echo "release root containing bundle root unexpectedly staged" >&2
exit 1
fi
release_root="$temporary/releases"
bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.3 "$bundle"
[[ -x $release_root/1.2.3/bin/echoiond ]]
[[ -L $release_root/1.2.3/lib/Echoion-current.ts ]]
[[ -x $release_root/1.2.3/install.sh ]]
python3 - "$release_root/pending-release.json" <<'PY'
import json
import sys
with open(sys.argv[1], encoding="utf-8") as stream:
manifest = json.load(stream)
assert manifest["executable"] == "1.2.3/bin/echoiond"
assert manifest["core"] == "1.2.3/lib/Echoion.ts"
assert all(entry["path"].startswith("1.2.3/") for entry in manifest["files"])
assert not any(entry["path"].endswith("install.sh") for entry in manifest["files"])
PY
tampered="$temporary/tampered"
cp -a "$bundle" "$tampered"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$tampered" --version 1.2.4
printf '%s\n' tampered >>"$tampered/lib/Echoion.ts"
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.4 "$tampered" >/dev/null 2>&1; then
echo "tampered payload unexpectedly staged" >&2
exit 1
fi
rogue="$temporary/rogue"
cp -a "$bundle" "$rogue"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$rogue" --version 1.2.6
printf '%s\n' rogue >"$rogue/lib/rogue.so"
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.6 "$rogue" >/dev/null 2>&1; then
echo "undeclared immutable payload file unexpectedly staged" >&2
exit 1
fi
[[ ! -e $release_root/1.2.6 ]]
outside_entry="$temporary/outside-entry"
cp -a "$bundle" "$outside_entry"
python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$outside_entry" --version 1.2.8
printf '%s\n' outside >"$outside_entry/outside.dat"
python3 - "$outside_entry/manifest.json" "$outside_entry/outside.dat" <<'PY'
import hashlib
import json
from pathlib import Path
import stat
import sys
manifest_path = Path(sys.argv[1])
outside = Path(sys.argv[2])
with manifest_path.open(encoding="utf-8") as stream:
manifest = json.load(stream)
metadata = outside.stat()
manifest["files"].append(
{
"path": "outside.dat",
"type": "file",
"size": metadata.st_size,
"sha256": hashlib.sha256(outside.read_bytes()).hexdigest(),
"mode": f"{stat.S_IMODE(metadata.st_mode):04o}",
}
)
with manifest_path.open("w", encoding="utf-8", newline="\n") as stream:
json.dump(manifest, stream, indent=2)
stream.write("\n")
PY
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.8 "$outside_entry" >/dev/null 2>&1; then
echo "manifest entry outside immutable roots unexpectedly staged" >&2
exit 1
fi
[[ ! -e $release_root/1.2.8 ]]
mkdir "$release_root/.stage-1.2.7.lock"
lock_error="$temporary/stage-lock.error"
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" 1.2.7 "$bundle" > /dev/null 2>"$lock_error"; then
echo "concurrent same-version staging unexpectedly acquired the lock" >&2
exit 1
fi
grep -q 'release staging is already active' "$lock_error"
[[ ! -e $release_root/1.2.7 ]]
rmdir "$release_root/.stage-1.2.7.lock"
if find "$release_root" -mindepth 2 -name '.staging-*' | grep -q .; then
echo "staging directory was nested below a published release" >&2
exit 1
fi
unsafe="$temporary/unsafe"
cp -a "$bundle" "$unsafe"
rm "$unsafe/lib/Echoion-current.ts"
ln -s ../bin/echoiond "$unsafe/lib/Echoion-current.ts"
if python3 "$source_root/scripts/generate-release-manifest.py" \
--root "$unsafe" --version 1.2.5 >/dev/null 2>&1; then
echo "unsafe symlink unexpectedly entered manifest" >&2
exit 1
fi
if bash "$source_root/scripts/stage-release.sh" \
"$release_root" '../unsafe' "$bundle" >/dev/null 2>&1; then
echo "unsafe version unexpectedly staged" >&2
exit 1
fi
echo "release manifest and staging regressions passed"
+237
View File
@@ -0,0 +1,237 @@
#!/usr/bin/env bash
set -euo pipefail
if [[ $# != 1 ]]; then
echo "usage: $0 SOURCE_ROOT" >&2
exit 2
fi
source_root=$(realpath -e -- "$1")
for command_name in cc cmake patchelf readelf python3; do
command -v "$command_name" >/dev/null || {
echo "missing test command: $command_name" >&2
exit 2
}
done
temporary=$(mktemp -d "${TMPDIR:-/tmp}/echoion-runtime-deps.XXXXXX")
trap 'rm -rf -- "$temporary"' EXIT
configured_build="$temporary/configured-build"
mkdir -p "$configured_build"
configured_compiler=$(realpath -e -- "$(command -v c++)")
printf 'CMAKE_CXX_COMPILER:FILEPATH=%s\n' "$configured_compiler" \
>"$configured_build/CMakeCache.txt"
queried_compiler=$(CXX=/bin/false \
"$source_root/scripts/configured-cxx-compiler.sh" "$configured_build")
[[ $queried_compiler == "$configured_compiler" ]] || {
echo "runtime compiler query followed CXX instead of the configured cache" >&2
exit 1
}
preferred_lib="$temporary/preferred-lib"
other_lib="$temporary/other-lib"
bundle="$temporary/bundle"
resolver="$temporary/resolver"
seed_lib="$temporary/seed-lib"
mkdir -p \
"$preferred_lib" \
"$other_lib" \
"$resolver" \
"$seed_lib" \
"$bundle/bin" \
"$bundle/lib" \
"$bundle/service" \
"$bundle/share/echoion/web"
cat >"$temporary/dependency.c" <<'C'
int echoion_dependency(void) { return 42; }
__attribute__((used, section(".echoion_variant")))
static const char echoion_variant[] = ECHOION_VARIANT;
C
cat >"$temporary/core.c" <<'C'
extern int echoion_dependency(void);
extern int echoion_compiler_runtime(void);
int echoion_core(void) {
return echoion_dependency() + echoion_compiler_runtime();
}
C
cat >"$temporary/main.c" <<'C'
int main(void) { return 0; }
C
cat >"$temporary/compiler-runtime.c" <<'C'
int echoion_compiler_runtime(void) { return 7; }
__attribute__((used, section(".echoion_compiler_variant")))
static const char echoion_compiler_variant[] = ECHOION_VARIANT;
C
for variant in preferred other; do
case $variant in
preferred) variant_lib=$preferred_lib ;;
other) variant_lib=$other_lib ;;
esac
cc -fPIC -shared "$temporary/dependency.c" \
'-DECHOION_VARIANT="'"$variant"'-runtime"' \
-Wl,-soname,libechoion-dependency.so.1 \
-o "$variant_lib/libechoion-dependency.so.1.2.3"
ln -s libechoion-dependency.so.1.2.3 \
"$variant_lib/libechoion-dependency.so.1"
ln -s libechoion-dependency.so.1 \
"$variant_lib/libechoion-dependency.so"
done
for variant in seeded resolver; do
case $variant in
seeded)
variant_lib=$seed_lib
variant_version=100
;;
resolver)
variant_lib=$preferred_lib
variant_version=200
;;
esac
cc -fPIC -shared "$temporary/compiler-runtime.c" \
'-DECHOION_VARIANT="'"$variant"'-compiler-runtime"' \
-Wl,-soname,libstdc++.so.6 \
-o "$variant_lib/libstdc++.so.6.0.$variant_version"
ln -s "libstdc++.so.6.0.$variant_version" \
"$variant_lib/libstdc++.so.6"
done
resolver_core="$resolver/Echoion.ts"
cc -fPIC -shared "$temporary/core.c" \
-L"$preferred_lib" -lechoion-dependency \
-Wl,-l:libstdc++.so.6 \
-Wl,-soname,Echoion.ts \
-Wl,-rpath,"$preferred_lib" \
-o "$resolver_core"
install -m 0644 "$resolver_core" "$bundle/lib/Echoion.ts"
patchelf --set-rpath "\$ORIGIN" "$bundle/lib/Echoion.ts"
cc "$temporary/main.c" -o "$bundle/bin/echoiond"
printf '%s\n' '[Service]' >"$bundle/service/echoion.service.in"
printf '%s\n' '<!doctype html><title>Echoion</title>' \
>"$bundle/share/echoion/web/index.html"
cmake \
"-DBUNDLE_ROOT=$bundle" \
"-DBUNDLE_RESOLVER_LIBRARIES=$resolver_core" \
"-DBUNDLE_SEARCH_DIRECTORIES=$other_lib" \
"-DBUNDLE_SEED_FILES=$seed_lib/libstdc++.so.6" \
"-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \
-P "$source_root/cmake/BundleRuntimeDependencies.cmake"
python3 - "$source_root/scripts/validate-release-elf.py" <<'PY'
import importlib.util
from pathlib import Path
import sys
module_path = Path(sys.argv[1])
spec = importlib.util.spec_from_file_location("validate_release_elf", module_path)
assert spec is not None and spec.loader is not None
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
fixture = """
Version needs section '.gnu.version_r' contains 2 entries:
000000: Version: 1 File: libm.so.6 Cnt: 1
0x0010: Name: GLIBC_9.99 Flags: none Version: 4
0x0020: Version: 1 File: libc.so.6 Cnt: 3
0x0030: Name: GLIBC_2.17 Flags: none Version: 3
0x0040: Name: GLIBC_2.36 Flags: none Version: 2
0x0050: Name: GLIBC_ABI_DT_RELR Flags: none Version: 1
"""
assert module.required_glibc_versions(fixture) == {(2, 17), (2, 36), (9, 99)}
assert module.parse_version("2.35") == (2, 35)
assert module.is_system_dependency("libc.so.6")
assert module.is_system_dependency("libm.so.6")
assert not module.is_system_dependency("libc.so.evil")
assert not module.is_system_dependency("libm.so.99")
unknown_abi = """
Version needs section '.gnu.version_r' contains 1 entry:
000000: Version: 1 File: libc.so.6 Cnt: 1
0x0010: Name: GLIBC_ABI_FUTURE Flags: none Version: 1
"""
try:
module.required_glibc_versions(unknown_abi)
except ValueError as error:
assert "unknown GLIBC ABI requirement" in str(error)
else:
raise AssertionError("unknown GLIBC ABI requirement was accepted")
PY
evil_bundle="$temporary/evil-bundle"
evil_build="$temporary/evil-build"
cp -a -- "$bundle" "$evil_bundle"
mkdir "$evil_build"
cat >"$temporary/evil-dependency.c" <<'C'
int echoion_evil_dependency(void) { return 13; }
C
cat >"$temporary/evil-user.c" <<'C'
extern int echoion_evil_dependency(void);
int echoion_evil_user(void) { return echoion_evil_dependency(); }
C
cc -fPIC -shared "$temporary/evil-dependency.c" \
-Wl,-soname,libc.so.evil -o "$evil_build/libc.so.evil"
cc -fPIC -shared "$temporary/evil-user.c" \
-L"$evil_build" -Wl,-l:libc.so.evil -Wl,-rpath,"$evil_build" \
-o "$evil_build/libevil-user.so"
rm "$evil_build/libc.so.evil"
if cmake \
"-DBUNDLE_ROOT=$evil_bundle" \
"-DBUNDLE_RESOLVER_LIBRARIES=$evil_build/libevil-user.so" \
"-DBUNDLE_SEARCH_DIRECTORIES=$other_lib" \
"-DBUNDLE_SEED_FILES=$seed_lib/libstdc++.so.6" \
"-DPATCHELF_EXECUTABLE=$(command -v patchelf)" \
-P "$source_root/cmake/BundleRuntimeDependencies.cmake" \
>/dev/null 2>&1; then
echo "fake glibc-like SONAME was treated as a system dependency" >&2
exit 1
fi
report="$temporary/dependencies.txt"
python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" --max-glibc 2.35 --report "$report"
grep -F $'NEEDED\tlib/Echoion.ts\tlibechoion-dependency.so.1\tbundled' "$report"
grep -F $'NEEDED\tbin/echoiond\tlibc.so.6\tsystem' "$report"
[[ -L $bundle/lib/libechoion-dependency.so.1 ]]
[[ $(readlink "$bundle/lib/libechoion-dependency.so.1") != /* ]]
[[ -f $bundle/lib/libechoion-dependency.so.1.2.3 ]]
readelf -p .echoion_variant \
"$bundle/lib/libechoion-dependency.so.1.2.3" | grep -F preferred-runtime
if readelf -p .echoion_variant \
"$bundle/lib/libechoion-dependency.so.1.2.3" | grep -Fq other-runtime; then
echo "search-directory runtime replaced the exact build resolver runtime" >&2
exit 1
fi
readelf -p .echoion_compiler_variant \
"$bundle/lib/libstdc++.so.6.0.100" | grep -F seeded-compiler-runtime
if find "$bundle/lib" -maxdepth 1 -name 'libstdc++.so.6.0.200' | grep -q .; then
echo "resolver compiler runtime leaked beside the exact seed" >&2
exit 1
fi
if find "$bundle/lib" -maxdepth 1 -name 'libc.so*' | grep -q .; then
echo "glibc was unexpectedly bundled" >&2
exit 1
fi
patchelf --set-rpath /tmp/unsafe-build-path "$bundle/lib/Echoion.ts"
if python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" >/dev/null 2>&1; then
echo "absolute Core RUNPATH unexpectedly passed validation" >&2
exit 1
fi
patchelf --set-rpath "\$ORIGIN" "$bundle/lib/Echoion.ts"
python3 - "$bundle/lib/Echoion.ts" <<'PY'
import sys
with open(sys.argv[1], "r+b") as stream:
stream.seek(18)
stream.write(b"\xb7\x00") # EM_AARCH64 in a little-endian ELF header.
PY
if python3 "$source_root/scripts/validate-release-elf.py" \
--root "$bundle" >/dev/null 2>&1; then
echo "non-x86-64 Core unexpectedly passed validation" >&2
exit 1
fi
echo "runtime dependency bundling regressions passed"
+249
View File
@@ -0,0 +1,249 @@
#!/usr/bin/env python3
"""Validate a relocatable Linux ELF closure without executing its binaries."""
from __future__ import annotations
import argparse
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import subprocess
import tempfile
SYSTEM_DEPENDENCIES = tuple(
re.compile(pattern)
for pattern in (
r"^linux-vdso\.so\.1$",
r"^ld-linux-x86-64\.so\.2$",
r"^libc\.so\.6$",
r"^libm\.so\.6$",
r"^libmvec\.so\.1$",
r"^libdl\.so\.2$",
r"^libpthread\.so\.0$",
r"^librt\.so\.1$",
r"^libresolv\.so\.2$",
r"^libutil\.so\.1$",
r"^libanl\.so\.1$",
r"^libBrokenLocale\.so\.1$",
r"^libthread_db\.so\.1$",
)
)
NEEDED_PATTERN = re.compile(r"\(NEEDED\).*Shared library: \[([^]]+)]")
RUNPATH_PATTERN = re.compile(r"\((?:RPATH|RUNPATH)\).*Library r(?:un)?path: \[([^]]*)]")
INTERPRETER_PATTERN = re.compile(r"Requesting program interpreter: ([^]]+)]")
GLIBC_NAME_PATTERN = re.compile(r"\bName: (GLIBC_[A-Za-z0-9_.]+)\b")
GLIBC_VERSION_PATTERN = re.compile(r"^GLIBC_(\d+)\.(\d+)(?:\.(\d+))?$")
GLIBC_ABI_MINIMUMS = {"GLIBC_ABI_DT_RELR": (2, 36)}
def parse_version(value: str) -> tuple[int, ...]:
if not re.fullmatch(r"\d+(?:\.\d+){1,2}", value):
raise ValueError(f"invalid ABI version: {value!r}")
return tuple(int(component) for component in value.split("."))
def required_glibc_versions(version_info: str) -> set[tuple[int, ...]]:
versions: set[tuple[int, ...]] = set()
in_needs = False
for line in version_info.splitlines():
if line.startswith("Version needs section"):
in_needs = True
continue
if in_needs and line.startswith("Version "):
break
if not in_needs:
continue
name_match = GLIBC_NAME_PATTERN.search(line)
if name_match is None:
continue
name = name_match.group(1)
if name in GLIBC_ABI_MINIMUMS:
versions.add(GLIBC_ABI_MINIMUMS[name])
elif name.startswith("GLIBC_ABI_"):
raise ValueError(f"unknown GLIBC ABI requirement: {name}")
elif version_match := GLIBC_VERSION_PATTERN.fullmatch(name):
versions.add(
tuple(
int(component)
for component in version_match.groups()
if component is not None
)
)
return versions
def command_output(arguments: list[str]) -> str:
environment = os.environ.copy()
environment["LC_ALL"] = "C"
completed = subprocess.run(
arguments,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
env=environment,
)
if completed.returncode != 0:
message = completed.stderr.strip() or completed.stdout.strip()
raise ValueError(f"{' '.join(arguments)} failed: {message}")
return completed.stdout
def is_elf(path: Path) -> bool:
with path.open("rb") as stream:
return stream.read(4) == b"\x7fELF"
def is_system_dependency(name: str) -> bool:
return any(pattern.fullmatch(name) for pattern in SYSTEM_DEPENDENCIES)
def ensure_inside(path: Path, directory: Path, description: str) -> None:
try:
path.resolve(strict=True).relative_to(directory)
except (FileNotFoundError, RuntimeError, ValueError) as error:
raise ValueError(f"{description} escapes the bundle or is dangling: {path}") from error
def validate_symlinks(library_dir: Path) -> None:
for path in sorted(library_dir.iterdir()):
if not path.is_symlink():
continue
target = os.readlink(path)
pure_target = PurePosixPath(target)
if not target or pure_target.is_absolute() or ".." in pure_target.parts:
raise ValueError(f"unsafe library symlink: {path.name} -> {target}")
ensure_inside(path, library_dir, "library symlink")
def validate(root: Path, maximum_glibc: tuple[int, ...] | None = None) -> list[str]:
executable = root / "bin/echoiond"
core = root / "lib/Echoion.ts"
library_dir = (root / "lib").resolve(strict=True)
for required in (executable, core):
if not required.is_file() or required.is_symlink() or not is_elf(required):
raise ValueError(f"missing regular ELF payload: {required}")
validate_symlinks(library_dir)
elf_files: list[Path] = [executable]
for path in sorted(library_dir.iterdir()):
if path.is_symlink():
continue
if not path.is_file() or not is_elf(path):
raise ValueError(f"unexpected non-ELF entry in lib/: {path}")
elf_files.append(path)
report: list[str] = []
for path in elf_files:
relative = path.relative_to(root).as_posix()
header = command_output(["readelf", "-hW", os.fspath(path)])
if not re.search(r"^\s*Class:\s+ELF64\s*$", header, re.MULTILINE):
raise ValueError(f"{relative} is not a 64-bit ELF")
if not re.search(
r"^\s*Machine:\s+Advanced Micro Devices X86-64\s*$",
header,
re.MULTILINE,
):
raise ValueError(f"{relative} is not an x86-64 ELF")
dynamic = command_output(["readelf", "-dW", os.fspath(path)])
runpaths = RUNPATH_PATTERN.findall(dynamic)
expected_runpath = "$ORIGIN/../lib" if path == executable else "$ORIGIN"
if runpaths != [expected_runpath]:
raise ValueError(
f"{relative} RUNPATH must be {expected_runpath!r}, got {runpaths!r}"
)
report.append(f"ELF\t{relative}\tRUNPATH={expected_runpath}")
for needed in NEEDED_PATTERN.findall(dynamic):
if "/" in needed or needed in ("", ".", ".."):
raise ValueError(f"unsafe DT_NEEDED entry in {relative}: {needed!r}")
if is_system_dependency(needed):
location = "system"
else:
dependency = library_dir / needed
if not dependency.exists():
raise ValueError(f"unresolved DT_NEEDED in {relative}: {needed}")
ensure_inside(dependency, library_dir, "DT_NEEDED dependency")
location = "bundled"
report.append(f"NEEDED\t{relative}\t{needed}\t{location}")
version_info = command_output(
["readelf", "--version-info", "-W", os.fspath(path)]
)
glibc_versions = required_glibc_versions(version_info)
if maximum_glibc is not None:
incompatible = sorted(
version for version in glibc_versions if version > maximum_glibc
)
if incompatible:
rendered = ", ".join(
".".join(map(str, version)) for version in incompatible
)
maximum = ".".join(map(str, maximum_glibc))
raise ValueError(
f"{relative} requires GLIBC newer than {maximum}: {rendered}"
)
if glibc_versions:
newest = ".".join(map(str, max(glibc_versions)))
report.append(f"ABI\t{relative}\tGLIBC_MAX={newest}")
program_headers = command_output(["readelf", "-lW", os.fspath(executable)])
interpreter_match = INTERPRETER_PATTERN.search(program_headers)
if interpreter_match is None:
raise ValueError("echoiond has no ELF interpreter")
interpreter = interpreter_match.group(1)
if not re.fullmatch(
r"/(?:[^/]+/)*(?:ld-linux[^/]*\.so[^/]*|ld64\.so[^/]*)",
interpreter,
):
raise ValueError(f"unexpected ELF interpreter: {interpreter}")
report.append(f"INTERPRETER\tbin/echoiond\t{interpreter}\tsystem")
return sorted(report)
def write_report(lines: list[str], output: Path) -> None:
output.parent.mkdir(parents=True, exist_ok=True)
descriptor, temporary_name = tempfile.mkstemp(
prefix=f".{output.name}.", dir=output.parent
)
try:
with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream:
stream.write("# Echoion runtime dependency report\n")
stream.write("# Generated with readelf; no payload executable was run.\n")
for line in lines:
stream.write(f"{line}\n")
os.chmod(temporary_name, 0o644)
os.replace(temporary_name, output)
except BaseException:
try:
os.unlink(temporary_name)
except FileNotFoundError:
pass
raise
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--root", required=True, type=Path)
parser.add_argument("--report", type=Path)
parser.add_argument("--max-glibc", type=parse_version)
arguments = parser.parse_args()
if shutil.which("readelf") is None:
parser.error("readelf is required")
try:
root = arguments.root.resolve(strict=True)
report = validate(root, arguments.max_glibc)
except (OSError, ValueError) as error:
parser.error(str(error))
if arguments.report:
write_report(report, arguments.report)
else:
print("\n".join(report))
return 0
if __name__ == "__main__":
raise SystemExit(main())