commit 0cf4829fa5304a8e5dda5f6bb2418ee6f906acd4 Author: Liam Waldron Date: Thu Oct 29 09:15:34 2026 -0400 glacier-ng 4.0.0 diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..f7077ee --- /dev/null +++ b/Makefile @@ -0,0 +1,7 @@ +include config.mk + +all: + @echo "Run 'make install' to install Glacier." + +install: + diff --git a/bin/gbuild b/bin/gbuild new file mode 100755 index 0000000..616eef8 --- /dev/null +++ b/bin/gbuild @@ -0,0 +1,791 @@ +#!/bin/bash +# gbuild - Glacier Package Builder +# Compiles a source directory and produces a glacier-compliant .gpkg bundle +# (compiled binary tree + .gpm.cfg manifest) + +set -euo pipefail + +# --------------------------------------------------------------------------- +# Colour / logging helpers — matches glacier lg_printf() in log.c +# LG_INFO = 0 -> [i] blue +# LG_WARN = 1 -> [!] yellow +# LG_ERR = 2 -> [x] red +# LG_SUCCESS = 3 -> [✓] green (falls back to [*] if not UTF-8) +# --------------------------------------------------------------------------- +_COL_RESET="\033[0m" +_COL_BLUE="\033[0;34m" +_COL_YELLOW="\033[0;33m" +_COL_RED="\033[0;31m" +_COL_GREEN="\033[0;32m" +_COL_BOLD="\033[1m" + +# Check UTF-8 support once at startup +if [[ "$(locale charmap 2>/dev/null)" == "UTF-8" ]]; then + _CHECK="\xe2\x9c\x93" # ✓ +else + _CHECK="*" +fi + +log_info() { printf "${_COL_BLUE}[i]${_COL_RESET} $*\n"; } +log_warn() { printf "${_COL_YELLOW}[!]${_COL_RESET} $*\n"; } +log_err() { printf "${_COL_RED}[x]${_COL_RESET} $*\n" >&2; } +log_success() { printf "${_COL_GREEN}[${_CHECK}]${_COL_RESET} $*\n"; } +log_step() { printf "\n${_COL_BOLD}==> $*${_COL_RESET}\n"; } + +die() { + log_err "$*" + exit 1 +} + +# --------------------------------------------------------------------------- +# Usage +# --------------------------------------------------------------------------- +usage() { + local prog="$0" + printf "%s: Build and package source code into a Glacier-compliant .gpkg\n" "$prog" + printf "usage: %s [-hvs] [-n NAME] [-V VER] [-d DESC] [-m MAINT] [-c COPY]\n" "$prog" + printf " %s [-b CMD] [-i CMD] [-o DIR] [-p DIR] [-j N]\n" "$prog" + printf " %s [-D name:ver] [-C name:ver] \n\n" "$prog" + printf "%-35s %s\n" "{-h --help}" "Show this message" + printf "%-35s %s\n\n" "{-v --version}" "Show the current version" + printf "%-35s %s\n" "{-n --name} NAME" "Package name (default: basename of SOURCE_DIR)" + printf "%-35s %s\n" "{-V --ver} VERSION" "Semantic version (default: 0.1.0)" + printf "%-35s %s\n" "{-d --desc} DESC" "Short description (prompted if omitted)" + printf "%-35s %s\n" "{-m --maint} MAINT" "Maintainer e-mail (prompted if omitted)" + printf "%-35s %s\n" "{-c --copy} COPYRIGHT" "Copyright string (default: MIT)" + printf "%-35s %s\n" "{-g --repo} REPO" "Package repo (default: local — e.g. base, core, community, nonfree)" + printf "%-35s %s\n" "{-D --dep} name:ver" "Add a dependency, e.g. libfoo:1.0.0" + printf "%-35s %s\n" "{-C --conf} name:ver" "Add a conflict, e.g. old-foo:0.9.0" + printf "%-35s %s\n" "{-b --build} CMD" "Build command (default: autodetected)" + printf "%-35s %s\n" "{-i --install} CMD" "Install command populating \$DESTDIR" + printf "%-35s %s\n" "{-o --output} DIR" "Output directory for finished .gpkg (default: .)" + printf "%-35s %s\n" "{-p --stage} DIR" "Staging DESTDIR to inspect after build" + printf "%-35s %s\n" "{-j --jobs} N" "Parallel build jobs (default: nproc)" + printf "%-35s %s\n" "{-F --flags} FLAGS" "Extra compiler flags, e.g. \"-O2 -fstack-protector-strong\"" + printf "%-35s %s\n" "{-t --toolchain} DIR" "Path to toolchain bin directory, e.g. ~/x86_64-linux-musl-cross/bin" + printf "%-35s %s\n" "{-x --cross-prefix} P" "Toolchain prefix, e.g. x86_64-linux-musl (default: autodetected)" + printf "%-35s %s\n" "{-u --url} URL" "Git repository URL to clone" + printf "%-35s %s\n" "{-r --ref} REF" "Git tag, branch, or commit to check out (default: default branch)" + printf "%-35s %s\n" "{-k --key} KEY.sec" "Sign the sidecar with this secret key (writes .sha256.sig)" + printf "%-35s %s\n\n" "{--verbose}" "Log events more verbosely" + printf "This program is free software.\n" + printf "See the GNU GPL version 3 for details.\n" +} + +# --------------------------------------------------------------------------- +# Defaults +# --------------------------------------------------------------------------- +PKG_NAME="" +PKG_VER="0.1.0" +PKG_DESC="" +PKG_MAINT="" +PKG_COPYRIGHT="MIT" +PKG_REPO="local" +BUILD_CMD="" +INSTALL_CMD="" +OUTPUT_DIR="." +STAGE_DIR="" +JOBS="$(nproc 2>/dev/null || echo 4)" +SKIP_BUILD=0 +VERBOSE=0 +DEPS=() +CONFS=() +EXTRA_CFLAGS="" +TOOLCHAIN_DIR="" +TOOLCHAIN_PREFIX="" +REPO_URL="" +REPO_REF="" +SIGN_KEY="" + +# --------------------------------------------------------------------------- +# Parse options — convert longopts to shortopts before getopts runs +# --------------------------------------------------------------------------- + +# Map of --longopt -> shortopt +declare -A _LONGOPTS=( + [--repo]="-g" + [--help]="-h" + [--version]="-v" + [--name]="-n" + [--ver]="-V" + [--desc]="-d" + [--maint]="-m" + [--copy]="-c" + [--dep]="-D" + [--conf]="-C" + [--build]="-b" + [--install]="-i" + [--output]="-o" + [--stage]="-p" + [--jobs]="-j" + [--flags]="-F" + [--toolchain]="-t" + [--cross-prefix]="-x" + [--skip]="-s" + [--verbose]="-e" + [--url]="-u" + [--ref]="-r" + [--key]="-k" +) + +# Rewrite argv replacing any --long-opt[=val] with -s [val] +_args=() +for _arg in "$@"; do + if [[ "$_arg" == --*=* ]]; then + # --key=value -> -s value + _key="${_arg%%=*}" + _val="${_arg#*=}" + _short="${_LONGOPTS[$_key]:-}" + [[ -z "$_short" ]] && die "Unknown option: $_key" + _args+=("$_short" "$_val") + elif [[ "$_arg" == --* ]]; then + # --key -> -s + _short="${_LONGOPTS[$_arg]:-}" + [[ -z "$_short" ]] && die "Unknown option: $_arg" + _args+=("$_short") + else + _args+=("$_arg") + fi +done +set -- "${_args[@]+"${_args[@]}"}" + +# -v is --version (as documented); verbose is long-only (--verbose), mapped +# to the otherwise unused -e above. +while getopts ":n:V:d:m:c:g:D:C:b:i:o:p:j:F:t:x:u:r:k:svhe" opt; do + case $opt in + n) PKG_NAME="$OPTARG" ;; + V) PKG_VER="$OPTARG" ;; + d) PKG_DESC="$OPTARG" ;; + m) PKG_MAINT="$OPTARG" ;; + c) PKG_COPYRIGHT="$OPTARG" ;; + g) PKG_REPO="$OPTARG" ;; + D) DEPS+=("$OPTARG") ;; + C) CONFS+=("$OPTARG") ;; + b) BUILD_CMD="$OPTARG" ;; + i) INSTALL_CMD="$OPTARG" ;; + o) OUTPUT_DIR="$OPTARG" ;; + p) STAGE_DIR="$OPTARG" ;; + j) JOBS="$OPTARG" ;; + F) EXTRA_CFLAGS="$OPTARG" ;; + t) TOOLCHAIN_DIR="$OPTARG" ;; + x) TOOLCHAIN_PREFIX="$OPTARG" ;; + u) REPO_URL="$OPTARG" ;; + r) REPO_REF="$OPTARG" ;; + k) SIGN_KEY="$OPTARG" ;; + s) SKIP_BUILD=1 ;; + v) + echo "v4.0.0" + exit 0 + ;; + e) VERBOSE=1 ;; + h) + usage + exit 0 + ;; + :) die "Option -$OPTARG requires an argument." ;; + \?) die "Unknown option: -$OPTARG" ;; + esac +done +shift $((OPTIND - 1)) + +# --------------------------------------------------------------------------- +# Locate gsha256sum (and gsign, for -k) +# +# Resolution order (shown for gsha256sum; gsign's variable is $GSIGN_BIN): +# 1. $GSHA256SUM_BIN, if the caller set it explicitly +# 2. relative to this script's own location — ../bin/gsha256sum, which +# is where `make install` puts it relative to $PREFIX/gbuild if +# gbuild itself is being run from $PREFIX. This is what makes a +# project-local, non-PATH PREFIX (e.g. PREFIX=~/Projects/glacier-ng) +# work without the caller having to export PATH themselves. +# 3. bare `gsha256sum` on PATH, same as how git/tar/make are already +# invoked elsewhere in this script — the fallback for a real +# system-wide install where $PREFIX/bin IS on PATH. +# +# Resolved here (after option parsing, so -h/--help never needs this; +# before any clone/build work, so a missing gsha256sum fails fast rather +# than after minutes of building something that can't be hashed at the +# end anyway) once, so every later call site just uses $GSHA256SUM. +# --------------------------------------------------------------------------- +resolve_tool() { + local tool="$1" var="$2" + local explicit="${!var:-}" + if [[ -n "$explicit" ]]; then + if [[ ! -x "$explicit" ]]; then + die "\$$var is set to '$explicit' but that isn't executable." + fi + echo "$explicit" + return + fi + + local script_dir + script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + # gbuild runs from the source checkout, NOT from inside $PREFIX — + # $PREFIX is arbitrary and unrelated to where this script lives. + # What IS guaranteed by the Makefile is that `make` (before any + # `make install`) drops the freshly-built binary at build/bin/ + # right next to this script, in the same source tree. + local candidate="$script_dir/build/bin/$tool" + if [[ -x "$candidate" ]]; then + echo "$candidate" + return + fi + + if command -v "$tool" >/dev/null 2>&1; then + echo "$tool" + return + fi + + die "Could not find $tool (checked \$$var, $candidate, and PATH). Run 'make install' first, or set $var explicitly." +} + +GSHA256SUM="$(resolve_tool gsha256sum GSHA256SUM_BIN)" || exit 1 +GSIGN="" +if [[ -n "$SIGN_KEY" ]]; then + GSIGN="$(resolve_tool gsign GSIGN_BIN)" || exit 1 + # Fail before building, not after: sign a throwaway file now. + _probe="$(mktemp)" || die "Cannot create a temporary file." + _out="$("$GSIGN" -S -s "$SIGN_KEY" -m "$_probe" -x "$_probe.sig" 2>&1)" || + { rm -f "$_probe" "$_probe.sig"; printf '%s\n' "$_out" >&2; exit 1; } + rm -f "$_probe" "$_probe.sig" +fi + +[[ $# -lt 1 ]] && [[ -z "$REPO_URL" ]] && { + log_err "usage: $0 [-hvs] [-nVdmcDCbiojpur] " + exit 1 +} + +if [[ -z "$REPO_URL" ]]; then + SOURCE_DIR="${1%/}" + [[ -d "$SOURCE_DIR" ]] || die "Source directory '$SOURCE_DIR' does not exist." + SOURCE_DIR="$(realpath "$SOURCE_DIR")" +fi + +# --------------------------------------------------------------------------- +# Fill in defaults that depend on SOURCE_DIR +# --------------------------------------------------------------------------- +[[ -z "$PKG_NAME" ]] && [[ -n "$SOURCE_DIR" ]] && PKG_NAME="$(basename "$SOURCE_DIR")" +[[ -z "$PKG_NAME" ]] && [[ -n "$REPO_URL" ]] && PKG_NAME="$(basename "$REPO_URL" .git)" + +# --------------------------------------------------------------------------- +# Validate semver format +# --------------------------------------------------------------------------- +validate_semver() { + local v="$1" + # strip optional pre-release tag (e.g. 1.2.3-alpha) + local core="${v%%-*}" + [[ "$core" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || + die "Version '$v' is not valid semver (expected MAJOR.MINOR.PATCH[-tag])." +} +validate_semver "$PKG_VER" + +# --------------------------------------------------------------------------- +# Interactive prompts for missing required fields +# --------------------------------------------------------------------------- +prompt_if_empty() { + local varname="$1" + local prompt_text="$2" + local default="$3" + local current + current="${!varname}" + if [[ -z "$current" ]]; then + if [[ -t 0 ]]; then + read -rp "$(printf "${_COL_BLUE}[i]${_COL_RESET} ${prompt_text} [${default}]: ")" val + val="${val:-$default}" + else + val="$default" + fi + printf -v "$varname" '%s' "$val" + fi +} + +prompt_if_empty PKG_DESC "Short description" "A Glacier package" +prompt_if_empty PKG_MAINT "Maintainer e-mail" "unknown@localhost" + +# --------------------------------------------------------------------------- +# Dependency / conflict format validation: name:MAJOR.MINOR.PATCH +# --------------------------------------------------------------------------- +parse_dep_or_conf() { + local raw="$1" + local label="$2" # "dependency" or "conflict" + local name ver + name="${raw%%:*}" + ver="${raw#*:}" + [[ "$name" =~ ^[a-zA-Z0-9_-]+$ ]] || + die "Invalid $label name in '$raw'. Use alphanumeric/hyphen/underscore." + validate_semver "$ver" 2>/dev/null || + die "Invalid $label version in '$raw'. Expected name:MAJOR.MINOR.PATCH." + echo "$name $ver" +} + +# --------------------------------------------------------------------------- +# Toolchain setup +# If -t is given, locate the compiler in that directory. +# If -x is also given, use it as the prefix (e.g. x86_64-linux-musl). +# If -x is omitted, autodetect by scanning the toolchain bin dir for *-gcc. +# If neither is given, fall back to the system CC/CXX. +# --------------------------------------------------------------------------- +setup_toolchain() { + if [[ -z "$TOOLCHAIN_DIR" ]]; then + # No toolchain specified — use system compiler + CC="${CC:-cc}" + CXX="${CXX:-c++}" + AR="${AR:-ar}" + export CC CXX AR + log_info "Toolchain: system (${CC})" + return + fi + + [[ -d "$TOOLCHAIN_DIR" ]] || + die "Toolchain directory '$TOOLCHAIN_DIR' does not exist." + + TOOLCHAIN_DIR="$(realpath "$TOOLCHAIN_DIR")" + + # Autodetect prefix if not supplied + if [[ -z "$TOOLCHAIN_PREFIX" ]]; then + local detected + detected="$(find "$TOOLCHAIN_DIR" -maxdepth 1 -name '*-gcc' | + head -1 | xargs basename 2>/dev/null)" + [[ -n "$detected" ]] || + die "Could not autodetect toolchain prefix in '$TOOLCHAIN_DIR'. Use -x to specify it." + TOOLCHAIN_PREFIX="${detected%-gcc}" + log_info "Autodetected toolchain prefix: $TOOLCHAIN_PREFIX" + fi + + local tc_cc="$TOOLCHAIN_DIR/${TOOLCHAIN_PREFIX}-gcc" + local tc_cxx="$TOOLCHAIN_DIR/${TOOLCHAIN_PREFIX}-g++" + local tc_ar="$TOOLCHAIN_DIR/${TOOLCHAIN_PREFIX}-ar" + + [[ -x "$tc_cc" ]] || die "Toolchain compiler not found: $tc_cc" + [[ -x "$tc_ar" ]] || die "Toolchain ar not found: $tc_ar" + + export CC="$tc_cc" + export CXX="$tc_cxx" + export AR="$tc_ar" + export CROSS_COMPILE="${TOOLCHAIN_PREFIX}-" + + # Prepend toolchain bin dir to PATH so make/cmake/meson find the + # prefixed binaries when they search by name rather than full path + export PATH="$TOOLCHAIN_DIR:$PATH" + + log_info "Toolchain: $TOOLCHAIN_PREFIX" + log_info " CC = $CC" + log_info " CXX = $CXX" + log_info " AR = $AR" +} +setup_toolchain + +# --------------------------------------------------------------------------- +# Clone source from git if -u was supplied +# --------------------------------------------------------------------------- +clone_source() { + local clone_dir + clone_dir="$(mktemp -d /tmp/gbuild_clone.XXXXXXXX)" + + if [[ -n "$REPO_REF" ]]; then + # Try shallow clone with --branch first (works for tags and branches) + if ! git clone --branch "$REPO_REF" --depth 1 "$REPO_URL" "$clone_dir" 2>/dev/null; then + # Fall back to full clone + checkout for commit hashes + # stderr: stdout is the clone dir, captured by the caller + log_warn "Shallow clone failed, falling back to full clone for commit checkout..." >&2 + rm -rf "$clone_dir" + clone_dir="$(mktemp -d /tmp/gbuild_clone.XXXXXXXX)" + git clone "$REPO_URL" "$clone_dir" >&2 \ + || die "Failed to clone $REPO_URL" + git -C "$clone_dir" checkout "$REPO_REF" >&2 \ + || die "Failed to check out ref $REPO_REF" + fi + else + git clone --depth 1 "$REPO_URL" "$clone_dir" \ + || die "Failed to clone $REPO_URL" + fi + + echo "$clone_dir" +} + +# --------------------------------------------------------------------------- +# Build system autodetection +# --------------------------------------------------------------------------- +detect_build_system() { + local src="$1" + + if [[ -f "$src/CMakeLists.txt" ]]; then + echo "cmake" + elif [[ -f "$src/meson.build" ]]; then + echo "meson" + elif [[ -f "$src/Cargo.toml" ]]; then + echo "cargo" + elif [[ -f "$src/go.mod" ]]; then + echo "go" + # configure BEFORE a bare Makefile: musl and plenty of hand-rolled + # projects ship both, and running make without configure builds + # with the wrong defaults (CLAUDE.md bug 8, regressed once already). + elif [[ -f "$src/configure" ]] || + [[ -f "$src/configure.ac" ]]; then + echo "autotools" + elif [[ -f "$src/Makefile" ]] || + [[ -f "$src/GNUmakefile" ]]; then + echo "make" + else + echo "unknown" + fi +} + +# --------------------------------------------------------------------------- +# Run a command, honouring VERBOSE +# --------------------------------------------------------------------------- +run_cmd() { + if [[ $VERBOSE -eq 1 ]]; then + "$@" + else + "$@" >/tmp/gbuild_cmd.log 2>&1 || + { + log_err "Command failed: $*" + cat /tmp/gbuild_cmd.log >&2 + exit 1 + } + fi +} + +# --------------------------------------------------------------------------- +# Build step +# --------------------------------------------------------------------------- +do_build() { + local src="$1" + local destdir="$2" + local bsys + + bsys="$(detect_build_system "$src")" + log_info "Detected build system: $(printf "${_COL_BOLD}")${bsys}$(printf "${_COL_RESET}")" + + # Export extra compiler flags so all build systems inherit them + if [[ -n "$EXTRA_CFLAGS" ]]; then + log_info "Extra compiler flags: $EXTRA_CFLAGS" + export CFLAGS="${CFLAGS:-} $EXTRA_CFLAGS" + export CXXFLAGS="${CXXFLAGS:-} $EXTRA_CFLAGS" + fi + + # --- override if user supplied either build or install command --- + if [[ -n "$BUILD_CMD" ]] || [[ -n "$INSTALL_CMD" ]]; then + local effective_build="${BUILD_CMD:-make}" + local effective_install="${INSTALL_CMD:-make install}" + + log_step "Building with custom command: $effective_build" + pushd "$src" >/dev/null + run_cmd bash -c "$effective_build" + popd >/dev/null + + log_step "Installing into staging area" + pushd "$src" >/dev/null + run_cmd bash -c "export DESTDIR='$destdir'; $effective_install" + popd >/dev/null + return + fi + + # --- autodetected paths --- + case "$bsys" in + + make) + log_step "Building with make" + pushd "$src" >/dev/null + run_cmd make -j"$JOBS" + popd >/dev/null + + log_step "Installing into staging area (make install)" + pushd "$src" >/dev/null + run_cmd make install DESTDIR="$destdir" + popd >/dev/null + ;; + + autotools) + log_step "Running ./configure" + pushd "$src" >/dev/null + [[ -f configure ]] || run_cmd autoreconf -fi + run_cmd ./configure --prefix=/usr + popd >/dev/null + + log_step "Building with make" + pushd "$src" >/dev/null + run_cmd make -j"$JOBS" + popd >/dev/null + + log_step "Installing into staging area" + pushd "$src" >/dev/null + run_cmd make install DESTDIR="$destdir" + popd >/dev/null + ;; + + cmake) + local build_dir="$src/_gbuild_cmake" + mkdir -p "$build_dir" + log_step "Configuring with CMake" + run_cmd cmake -S "$src" -B "$build_dir" \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_INSTALL_PREFIX=/usr \ + -DCMAKE_C_COMPILER="$CC" \ + -DCMAKE_CXX_COMPILER="${CXX:-c++}" \ + ${EXTRA_CFLAGS:+-DCMAKE_C_FLAGS="$EXTRA_CFLAGS"} \ + ${EXTRA_CFLAGS:+-DCMAKE_CXX_FLAGS="$EXTRA_CFLAGS"} + + log_step "Building with CMake" + run_cmd cmake --build "$build_dir" --parallel "$JOBS" + + log_step "Installing into staging area" + run_cmd cmake --install "$build_dir" --prefix "$destdir/usr" + ;; + + meson) + local build_dir="$src/_gbuild_meson" + log_step "Configuring with Meson" + run_cmd env CC="$CC" CXX="${CXX:-c++}" \ + meson setup "$build_dir" "$src" \ + --prefix=/usr \ + --buildtype=release \ + ${EXTRA_CFLAGS:+-Dc_args="$EXTRA_CFLAGS"} \ + ${EXTRA_CFLAGS:+-Dcpp_args="$EXTRA_CFLAGS"} + + log_step "Building with Ninja" + run_cmd ninja -C "$build_dir" -j"$JOBS" + + log_step "Installing into staging area" + run_cmd env DESTDIR="$destdir" ninja -C "$build_dir" install + ;; + + cargo) + log_step "Building with Cargo (release)" + pushd "$src" >/dev/null + run_cmd cargo build --release + popd >/dev/null + + log_step "Staging Cargo binary" + local bin_name="$PKG_NAME" + local cargo_bin="$src/target/release/$bin_name" + if [[ ! -f "$cargo_bin" ]]; then + # try to find any release binary + cargo_bin="$(find "$src/target/release" -maxdepth 1 \ + -type f -executable ! -name '*.d' | head -1)" + fi + [[ -f "$cargo_bin" ]] || die "Could not locate Cargo release binary." + mkdir -p "$destdir/usr/bin" + cp "$cargo_bin" "$destdir/usr/bin/$PKG_NAME" + ;; + + go) + log_step "Building with Go" + pushd "$src" >/dev/null + run_cmd go build -o "$PKG_NAME" ./... + popd >/dev/null + + log_step "Staging Go binary" + mkdir -p "$destdir/usr/bin" + cp "$src/$PKG_NAME" "$destdir/usr/bin/$PKG_NAME" + ;; + + unknown) + die "Could not detect a build system in '$src'. " \ + "Use -b BUILD_CMD and -i INSTALL_CMD to specify commands manually." + ;; + esac +} + +# --------------------------------------------------------------------------- +# Generate the .gpm.cfg manifest (libconfig syntax used by gl_gpm2gpkg) +# --------------------------------------------------------------------------- +write_manifest() { + local manifest_path="$1" + shift + + # split semver + optional tag + local ver_core="${PKG_VER%%-*}" + local ver_tag="" + [[ "$PKG_VER" == *-* ]] && ver_tag="${PKG_VER#*-}" + + local maj min pat + IFS='.' read -r maj min pat <<<"$ver_core" + + { + echo "// Glacier Package Manifest" + echo "// Generated by gbuild on $(date -u '+%Y-%m-%d %H:%M:%S UTC')" + echo "" + echo "PKG_NAME = \"${PKG_NAME}\";" + if [[ -n "$ver_tag" ]]; then + echo "PKG_VER = \"${maj}.${min}.${pat}-${ver_tag}\";" + else + echo "PKG_VER = \"${maj}.${min}.${pat}\";" + fi + echo "PKG_DESC = \"${PKG_DESC}\";" + echo "PKG_MAINT = \"${PKG_MAINT}\";" + echo "PKG_COPYRIGHT = \"${PKG_COPYRIGHT}\";" + echo "PKG_REPO = \"${PKG_REPO}\";" + echo "" + + # Dependencies + if [[ ${#DEPS[@]} -gt 0 ]]; then + echo "PKG_DEPS = (" + for raw in "${DEPS[@]}"; do + read -r dname dver <<<"$(parse_dep_or_conf "$raw" "dependency")" + local dmaj dmin dpat + IFS='.' read -r dmaj dmin dpat <<<"$dver" + echo " {" + echo " PKG_NAME = \"${dname}\";" + echo " PKG_VER = \"${dmaj}.${dmin}.${dpat}\";" + echo " }," + done + echo ");" + else + echo "PKG_DEPS = ();" + fi + echo "" + + # Conflicts + if [[ ${#CONFS[@]} -gt 0 ]]; then + echo "PKG_CONFS = (" + for raw in "${CONFS[@]}"; do + read -r cname cver <<<"$(parse_dep_or_conf "$raw" "conflict")" + local cmaj cmin cpat + IFS='.' read -r cmaj cmin cpat <<<"$cver" + echo " {" + echo " PKG_NAME = \"${cname}\";" + echo " PKG_VER = \"${cmaj}.${cmin}.${cpat}\";" + echo " }," + done + echo ");" + else + echo "PKG_CONFS = ();" + fi + + } >"$manifest_path" +} + +# --------------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------------- +log_step "gbuild — Glacier Package Builder" +[[ -n "$REPO_URL" ]] && log_info "URL: $REPO_URL" +[[ -n "$REPO_REF" ]] && log_info "Ref: $REPO_REF" +log_info "Package: $PKG_NAME $PKG_VER" +log_info "Maintainer: $PKG_MAINT" +[[ -n "$EXTRA_CFLAGS" ]] && log_info "Flags: $EXTRA_CFLAGS" +[[ -n "$TOOLCHAIN_PREFIX" ]] && log_info "Target: $TOOLCHAIN_PREFIX" + +# Clone source if -u was supplied +if [[ -n "$REPO_URL" ]]; then + log_step "Cloning source repository" + SOURCE_DIR="$(clone_source)" + log_success "Cloned to $SOURCE_DIR" + # Clean up clone dir on exit alongside WORK_DIR + trap 'rm -rf "$WORK_DIR" "$SOURCE_DIR"' EXIT +fi + +[[ -z "$PKG_NAME" ]] && PKG_NAME="$(basename "$SOURCE_DIR")" +PKG_NAME="${PKG_NAME//[^a-zA-Z0-9-]/}" +PKG_NAME="${PKG_NAME,,}" +[[ -z "$PKG_NAME" ]] && die "Could not derive a valid package name." + +log_info "Source: $SOURCE_DIR" + +# Create working directories +WORK_DIR="$(mktemp -d /tmp/gbuild.XXXXXXXX)" +PKG_DIR="$WORK_DIR/pkg" +mkdir -p "$PKG_DIR" + +# DESTDIR: use user-supplied staging dir if given, otherwise temp +if [[ -n "$STAGE_DIR" ]]; then + DESTDIR="$(realpath "$STAGE_DIR")" + mkdir -p "$DESTDIR" + log_info "Staging dir: $DESTDIR" + # Don't clean up STAGE_DIR on exit — user wants to inspect it + trap 'rm -rf "$WORK_DIR"' EXIT +else + DESTDIR="$WORK_DIR/destdir" + mkdir -p "$DESTDIR" + trap 'rm -rf "$WORK_DIR"' EXIT +fi + +# --- Build --- +if [[ $SKIP_BUILD -eq 0 ]]; then + do_build "$SOURCE_DIR" "$DESTDIR" + log_success "Build complete." +else + log_warn "Skipping build step (-s flag set)." +fi + +# --- Assemble package directory --- +# Layout inside the .gpkg dir: +# -/ +# manifest.gpm.cfg <- parsed by gl_gpm2gpkg +# files/ <- the DESTDIR tree (what gets installed) + +PKG_FULL_NAME="${PKG_NAME}-${PKG_VER}" +PKG_STAGE="$PKG_DIR/$PKG_FULL_NAME" +mkdir -p "$PKG_STAGE/files" + +log_step "Assembling package layout" + +# Copy staged files +if [[ $SKIP_BUILD -eq 0 ]]; then + if [[ -n "$(ls -A "$DESTDIR" 2>/dev/null)" ]]; then + cp -a "$DESTDIR/." "$PKG_STAGE/files/" + log_info "Staged file tree copied." + else + log_warn "DESTDIR is empty — the package will contain no files." + log_warn "Check your build/install commands." + fi +fi + +# Write manifest +MANIFEST_PATH="$PKG_STAGE/manifest.gpm.cfg" +write_manifest "$MANIFEST_PATH" +log_success "Manifest written: manifest.gpm.cfg" + +if [[ $VERBOSE -eq 1 ]]; then + log_info "--- manifest.gpm.cfg ---" + cat "$MANIFEST_PATH" + echo "" +fi + +# --- Archive and compress into OUTPUT_DIR --- +OUTPUT_DIR="$(realpath "$OUTPUT_DIR")" +mkdir -p "$OUTPUT_DIR" +FINAL_PKG="$OUTPUT_DIR/$PKG_FULL_NAME.gpkg" + +log_step "Compressing package" + +# Remove old output if present +rm -f "$FINAL_PKG" + +# Hardlinks become plain files: glacier refuses a package with a +# hardlink entry (binutils installs ld as a hardlink to ld.bfd). +find "$PKG_DIR/$PKG_FULL_NAME" -type f -links +1 | while IFS= read -r f; do + cp -p "$f" "$f.unlink" && mv -f "$f.unlink" "$f" || + die "Cannot copy hardlink $f." +done + +# tar the staged package directory, compress with gzip, write to .gpkg +# -C into the parent so the archive root is just -/ +tar -czf "$FINAL_PKG" -C "$PKG_DIR" "$PKG_FULL_NAME" || + die "Failed to create package archive." + +log_step "Hashing package" +SIDECAR_PATH="$FINAL_PKG.sha256" +"$GSHA256SUM" "$FINAL_PKG" > "$SIDECAR_PATH" || + die "Failed to hash package archive." +log_success "Sidecar: ${_COL_BOLD}${SIDECAR_PATH}${_COL_RESET}" +log_info "$(cat "$SIDECAR_PATH")" + +rm -f "$SIDECAR_PATH.sig" +if [[ -n "$SIGN_KEY" ]]; then + log_step "Signing sidecar" + _out="$("$GSIGN" -S -s "$SIGN_KEY" -m "$SIDECAR_PATH" 2>&1)" || + { printf '%s\n' "$_out" >&2; exit 1; } + log_success "Signature: ${_COL_BOLD}${SIDECAR_PATH}.sig${_COL_RESET}" +fi + +log_step "Package ready" +log_success "Output: ${_COL_BOLD}${FINAL_PKG}${_COL_RESET}" +log_info "Size: $(du -sh "$FINAL_PKG" | cut -f1)" +echo "" +log_info "Contents:" +tar -tzf "$FINAL_PKG" | sort | while read -r line; do + printf " %s\n" "$line" +done diff --git a/bin/glacier-bootstrap b/bin/glacier-bootstrap new file mode 100755 index 0000000..77f3e2d --- /dev/null +++ b/bin/glacier-bootstrap @@ -0,0 +1,642 @@ +#!/usr/bin/luajit +-- glacier-bootstrap: build a chrootable Everest system in TARGET from a +-- template index and a directory of packages (GLACIER_BOOTSTRAP.txt, +-- local mode). +-- +-- glacier-bootstrap [-hvntV] -d PKGDIR TEMPLATE TARGET +-- +-- 1. parse TEMPLATE (strict: anything unexpected is an error) +-- 2. copy each PKGDIR/NAME-VER.gpkg into a private directory, hashing it +-- on the way, against its sidecar and the template's pin if any +-- 3. read the copies' manifests: name and version must match the +-- template, every dependency must be listed (at least that version), +-- and nothing listed may conflict +-- 4. syspkg -R TARGET -n (skipped if TARGET is initialised +-- and empty) +-- 5. syspkg -R TARGET -l COPY... ONE transaction, strict +-- 6. syspkg -R TARGET -y fetch the indexes of every +-- repository TARGET's own +-- repos.conf gives a url (skipped, +-- with a warning, if none does) +-- 7. -t: chroot TARGET /bin/sh -c true +-- +-- It NEVER WRITES INTO TARGET ITSELF: every byte there comes from +-- syspkg, run through doas (directly when already root). The syspkg is +-- the one on PATH. The copies handed to syspkg carry the sidecar +-- verified here (its bytes as read, which match the copy's hash and the +-- pin), so a pin is enforced by syspkg's own sidecar check too, and a +-- file swapped in PKGDIR afterwards is never read. A NAME-VER.gpkg +-- .sha256.sig next to it is carried too: syspkg requires one for base +-- (REPO_DESIGN.txt section 7) and checks it against the HOST's keyring. +-- +-- Unprivileged: nothing here needs root, so unlike syspkg and gstore +-- there is no root-ownership check. Its own lib/ is still found from +-- its real location, not the current directory. +-- +-- Exit status: 1 usage or target, 2 template, 3 verification, +-- 4 resolution, 5 installation, 6 smoke test, 7 repositories (TARGET +-- is installed, but its indexes could not all be fetched). + +local ffi = require("ffi") + +ffi.cdef[[ +char *bootstrap_realpath(const char *path, char *resolved) asm("realpath"); +]] + +local self_dir +do + local buf = ffi.new("char[4096]") + if ffi.C.bootstrap_realpath(arg[0], buf) == nil then + io.stderr:write("glacier-bootstrap: cannot resolve own location\n") + os.exit(1) + end + self_dir = ffi.string(buf):match("^(.*)/[^/]*$") + if not self_dir or self_dir == "" then self_dir = "/" end +end + +package.path = self_dir .. "/?.lua" +package.cpath = "" + +require("lib/glacier_cdef") +local so_dir = self_dir .. "/lib/glacier" +local log = ffi.load(so_dir .. "/libglacier_log.so") +local istore = ffi.load(so_dir .. "/libglacier_istoreutils.so") +local txn = ffi.load(so_dir .. "/libglacier_transaction.so") +local verify = ffi.load(so_dir .. "/libglacier_verify.so") + +local EXIT_USAGE, EXIT_TEMPLATE, EXIT_VERIFY = 1, 2, 3 +local EXIT_RESOLVE, EXIT_INSTALL, EXIT_SMOKE = 4, 5, 6 +local EXIT_REPOS = 7 + +local function msg(level, fmt, ...) + log.lg_printf(level, "%s", string.format(fmt, ...)) +end + +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +local function run(cmd) + io.stdout:flush() + local ok = os.execute(cmd) + return ok == true or ok == 0 +end + +-- The private directory holding verified copies; removed on every exit. +local private_dir + +local function finish(code) + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +-- --------------------------------------------------------------------- +-- Arguments +-- --------------------------------------------------------------------- + +local usage_line = "usage: glacier-bootstrap [-hvntV] -d PKGDIR TEMPLATE TARGET" + +local function usage(code) + if code ~= 0 then + msg(2, "%s", usage_line) + os.exit(code) + end + local function opt(flag, text) + print(string.format("%-25s %s", flag, text)) + end + print("glacier-bootstrap: Install a template's packages into a new system") + print(usage_line) + print() + opt("{-h --help}", "Show this message") + opt("{-v --version}", "Show the current version") + opt("{-d --pkgdir} PKGDIR", "Take the template's packages from PKGDIR") + opt("{-n --dry-run}", "Verify and resolve only, never touch TARGET") + opt("{-t --test}", "Run a smoke test in TARGET afterwards") + opt("{-V --verbose}", "Log events more verbosely") + print() + print("This program is free software.") + print("See the GNU GPL version 3 for details.") + os.exit(0) +end + +-- Long options, as the short flag they stand for. +local long_opts = { + ["--help"] = "-h", ["--version"] = "-v", ["--pkgdir"] = "-d", + ["--dry-run"] = "-n", ["--test"] = "-t", ["--verbose"] = "-V", +} + +local pkgdir, dry_run, smoke, verbose +local operands = {} + +do + local i = 1 + while i <= #arg do + local a = arg[i] + if a:sub(1, 2) == "--" and #a > 2 then + local name, value = a:match("^(%-%-[^=]+)=(.*)$") + if name == "--pkgdir" then + a = "-d" + table.insert(arg, i + 1, value) + elseif long_opts[a] then + a = long_opts[a] + else + msg(2, "Unknown option: %s", a) + usage(EXIT_USAGE) + end + end + if a:sub(1, 1) == "-" and #a > 1 then + local flags = a:sub(2) + for k = 1, #flags do + local c = flags:sub(k, k) + if c == "h" then + usage(0) + elseif c == "v" then + print("v4.0.0") + os.exit(0) + elseif c == "n" then + dry_run = true + elseif c == "t" then + smoke = true + elseif c == "V" then + verbose = true + elseif c == "d" then + if k ~= #flags then + msg(2, "-d must come last in %s.", a) + os.exit(EXIT_USAGE) + end + if pkgdir then + msg(2, "-d given more than once.") + os.exit(EXIT_USAGE) + end + i = i + 1 + pkgdir = arg[i] + if not pkgdir or pkgdir == "" then + msg(2, "-d needs a directory.") + os.exit(EXIT_USAGE) + end + else + msg(2, "Unknown option: -%s", c) + usage(EXIT_USAGE) + end + end + else + table.insert(operands, a) + end + i = i + 1 + end +end + +if not pkgdir or #operands ~= 2 then + usage(EXIT_USAGE) +end + +local template_path, target = operands[1], operands[2] + +-- syspkg -R refuses relative roots; say so here, before any work. +if target:sub(1, 1) ~= "/" then + msg(2, "TARGET must be an absolute path: %s", target) + os.exit(EXIT_USAGE) +end +target = target:gsub("(.)/+$", "%1") +if target == "/" then + msg(2, "TARGET must not be /.") + os.exit(EXIT_USAGE) +end + +-- --------------------------------------------------------------------- +-- 1. Template +-- --------------------------------------------------------------------- +-- +-- # comment +-- NAME=minimal +-- PKG=musl 1.2.5 sha256:<64 hex> (the pin is optional) +-- +-- Exact versions only. Unknown keys (SYS_PROFILE included, until +-- manifests record one: ROADMAP 3.3), a repeated NAME or package, a +-- malformed line and an empty package list are all errors. + +local function valid_ident(s) + return s:match("^[A-Za-z0-9._-]+$") ~= nil and s ~= "." and s ~= ".." +end + +local function valid_version(s) + return s:match("^%d+%.%d+%.%d+$") ~= nil + or s:match("^%d+%.%d+%.%d+%-[A-Za-z0-9.]+$") ~= nil +end + +local function parse_template(path) + local f = io.open(path, "r") + if not f then + msg(2, "Cannot read template %s.", path) + finish(EXIT_TEMPLATE) + end + + local t = { pkgs = {} } + local seen = {} + local bad = false + local n = 0 + local function err(fmt, ...) + msg(2, "%s:%d: " .. fmt, path, n, ...) + bad = true + end + + for line in f:lines() do + n = n + 1 + line = line:gsub("^%s+", ""):gsub("%s+$", "") + if line ~= "" and line:sub(1, 1) ~= "#" then + local key, value = line:match("^([A-Za-z_]+)=(.*)$") + if not key then + err("Expected KEY=value.") + elseif key == "NAME" then + if t.name then + err("NAME given more than once.") + elseif not valid_ident(value) then + err("Invalid NAME: %s", value) + else + t.name = value + end + elseif key == "PKG" then + local fields = {} + for w in value:gmatch("%S+") do table.insert(fields, w) end + local name, ver, pin = fields[1], fields[2], fields[3] + if #fields < 2 or #fields > 3 then + err("Expected PKG=NAME VERSION [sha256:HEX].") + elseif not valid_ident(name) then + err("Invalid package name: %s", name) + elseif not valid_version(ver) then + err("Invalid version for %s: %s", name, ver) + elseif pin and not (pin:match("^sha256:%x+$") and #pin == 71) then + err("Malformed pin for %s: %s", name, pin) + elseif seen[name] then + err("%s is listed twice (first on line %d).", name, seen[name]) + else + seen[name] = n + table.insert(t.pkgs, { + name = name, ver = ver, + pin = pin and pin:sub(8):lower(), + }) + end + else + err("Unknown key: %s", key) + end + end + end + f:close() + + if not t.name then + msg(2, "%s: No NAME.", path) + bad = true + end + if #t.pkgs == 0 and not bad then + msg(2, "%s: No packages.", path) + bad = true + end + if bad then finish(EXIT_TEMPLATE) end + return t +end + +-- --------------------------------------------------------------------- +-- 2. Verification +-- --------------------------------------------------------------------- + +-- Copy `src` to `dst`, returning the sha256 of what was copied (hex), +-- or nil. +local function copy_hashed(src, dst) + local i = io.open(src, "rb") + if not i then return nil end + local o = io.open(dst, "wb") + if not o then i:close(); return nil end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = i:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + o:write(chunk) + end + i:close() + o:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +local function verify_all(t) + local mk = io.popen("mktemp -d 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + msg(2, "Cannot create a private working directory.") + finish(EXIT_VERIFY) + end + + local bad = false + for _, p in ipairs(t.pkgs) do + local file = string.format("%s-%s.gpkg", p.name, p.ver) + local src = pkgdir .. "/" .. file + local why + + local sf = io.open(src .. ".sha256", "r") + local sidecar_text = sf and (sf:read("*a") or "") + local expected = sidecar_text and sidecar_text:match("^sha256:(%x+)%s*$") + if sf then sf:close() end + + local probe = io.open(src, "rb") + if probe then probe:close() end + + if not probe then + why = "no such file" + elseif not sf then + why = "no sidecar " .. src .. ".sha256" + elseif not expected or #expected ~= 64 then + why = "malformed sidecar " .. src .. ".sha256" + else + expected = expected:lower() + if p.pin and p.pin ~= expected then + why = "the template pins " .. p.pin .. + ", the sidecar says " .. expected + end + end + + if not why then + p.copy = private_dir .. "/" .. file + local got = copy_hashed(src, p.copy) + if not got then + why = "cannot copy it to " .. p.copy + elseif got ~= expected then + why = "hash mismatch (sidecar says " .. expected .. + ", file is " .. got .. ")" + else + -- The same bytes, not a sidecar written + -- anew: a signature covers these. + local o = io.open(p.copy .. ".sha256", "w") + if not o or not o:write(sidecar_text) then + why = "cannot write " .. p.copy .. ".sha256" + end + if o then o:close() end + end + end + if not why then + local sig = io.open(src .. ".sha256.sig", "rb") + if sig then + local bytes = sig:read("*a") or "" + sig:close() + local o = io.open(p.copy .. ".sha256.sig", "wb") + if not o or not o:write(bytes) then + why = "cannot write " .. p.copy .. ".sha256.sig" + end + if o then o:close() end + end + end + + if why then + msg(2, "Refusing %s: %s.", src, why) + bad = true + end + end + if bad then finish(EXIT_VERIFY) end +end + +-- --------------------------------------------------------------------- +-- 3. Resolution +-- --------------------------------------------------------------------- + +local function semver_str(v) + local s = string.format("%d.%d.%d", v.maj, v.min, v.pat) + if v.tag ~= nil then s = s .. "-" .. ffi.string(v.tag) end + return s +end + +-- Same ordering as the library (deps.c semver_cmp): tags are ignored. +local function semver_ge(a, b) + if a.maj ~= b.maj then return a.maj > b.maj end + if a.min ~= b.min then return a.min > b.min end + return a.pat >= b.pat +end + +local function resolve(t) + local bad = false + local by_name = {} + + for _, p in ipairs(t.pkgs) do + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(p.copy, m) ~= 0 then + msg(2, "Cannot read the manifest of %s/%s-%s.gpkg.", pkgdir, p.name, p.ver) + bad = true + else + local name = ffi.string(m.pkg_name) + local ver = semver_str(m.pkg_ver) + p.repo = ffi.string(m.pkg_repo) + p.semver = { maj = m.pkg_ver.maj, min = m.pkg_ver.min, pat = m.pkg_ver.pat } + p.deps, p.confs = {}, {} + local d = m.pkg_dependencies + while d ~= nil and d.dep_name ~= nil do + table.insert(p.deps, { + name = ffi.string(d.dep_name), + ver = { maj = d.dep_ver.maj, min = d.dep_ver.min, pat = d.dep_ver.pat }, + str = semver_str(d.dep_ver), + }) + d = d + 1 + end + local c = m.pkg_conflicts + while c ~= nil and c.conf_name ~= nil do + table.insert(p.confs, ffi.string(c.conf_name)) + c = c + 1 + end + istore.gl_free_pkg(m) + + if name ~= p.name or ver ~= p.ver then + msg(2, "%s/%s-%s.gpkg is %s %s, not %s %s.", + pkgdir, p.name, p.ver, name, ver, p.name, p.ver) + bad = true + end + by_name[p.name] = p + end + end + if bad then finish(EXIT_RESOLVE) end + + for _, p in ipairs(t.pkgs) do + for _, d in ipairs(p.deps) do + local q = by_name[d.name] + if not q then + msg(2, "%s::%s requires %s >= %s, which the template does not list.", + p.repo, p.name, d.name, d.str) + bad = true + elseif not semver_ge(q.semver, d.ver) then + msg(2, "%s::%s requires %s >= %s, but the template lists %s.", + p.repo, p.name, d.name, d.str, q.ver) + bad = true + end + end + end + + -- Conflicts, by name, either direction; each pair once. + for i, p in ipairs(t.pkgs) do + for j = i + 1, #t.pkgs do + local q = t.pkgs[j] + local hit = false + for _, c in ipairs(p.confs) do hit = hit or c == q.name end + for _, c in ipairs(q.confs) do hit = hit or c == p.name end + if hit then + msg(2, "%s::%s conflicts with %s::%s.", p.repo, p.name, q.repo, q.name) + bad = true + end + end + end + if bad then finish(EXIT_RESOLVE) end +end + +-- --------------------------------------------------------------------- +-- The target +-- --------------------------------------------------------------------- + +-- Installed packages under TARGET as a set of "repo::name::ver", or nil +-- if TARGET has no system index. The index is world-readable. +local function target_index() + local f = io.open(target .. "/glacier/sys/index/current", "r") + if not f then return nil end + local set, n = {}, 0 + for line in f:lines() do + local repo, name, ver = line:match("^([^:]+)::([^:]+)::([^:]+)") + if repo then + set[repo .. "::" .. name .. "::" .. ver] = true + n = n + 1 + end + end + f:close() + return set, n +end + +local function exists(path) + return run("test -e " .. shell_quote(path) .. " -o -L " .. shell_quote(path)) +end + +-- --------------------------------------------------------------------- +-- Main +-- --------------------------------------------------------------------- + +local t = parse_template(template_path) + +-- The same refusal syspkg -R makes, read-only, before any work. +if txn.gl_check_sysroot(target) ~= 0 then + finish(EXIT_USAGE) +end + +-- A fresh TARGET, or one syspkg -n initialised with nothing installed +-- (a run that stopped at the prompt). Anything else isn't ours to add to. +local initialised = exists(target .. "/glacier/sys") +if initialised then + local _, n = target_index() + if n == nil then + msg(2, "%s/glacier/sys exists but has no system index.", target) + finish(EXIT_USAGE) + elseif n > 0 then + msg(2, "%s already has packages installed.", target) + finish(EXIT_USAGE) + end +end + +verify_all(t) +resolve(t) + +msg(0, "Template %s, %d package%s for %s:", t.name, #t.pkgs, + #t.pkgs == 1 and "" or "s", target) +for _, p in ipairs(t.pkgs) do + print(string.format(" * %s::%s %s%s", p.repo, p.name, p.ver, + p.pin and " (pinned)" or "")) +end + +if dry_run then + msg(3, "Dry run: every package verified and resolved.") + finish(0) +end + +local is_root = ffi.C.geteuid() == 0 +local as_root = is_root and "" or "doas " + +local syspkg +do + local p = io.popen("command -v syspkg 2>/dev/null") + syspkg = p and p:read("*l") + if p then p:close() end + if not syspkg or syspkg:sub(1, 1) ~= "/" then + msg(2, "syspkg is not on PATH.") + finish(EXIT_INSTALL) + end +end + +local sys = as_root .. shell_quote(syspkg) .. " -R " .. shell_quote(target) +local v = verbose and " -V" or "" + +if not initialised then + if not run(sys .. " -n" .. v) then + finish(EXIT_INSTALL) + end +end + +local cmd = sys .. v .. " -l" +for _, p in ipairs(t.pkgs) do + cmd = cmd .. " " .. shell_quote(p.copy) +end +if not run(cmd) then + finish(EXIT_INSTALL) +end + +-- syspkg exits 0 when its prompt is declined; check what it installed. +local installed, n = target_index() +local missing = {} +for _, p in ipairs(t.pkgs) do + if not (installed and installed[p.repo .. "::" .. p.name .. "::" .. p.ver]) then + table.insert(missing, p) + end +end +if #missing == #t.pkgs and (n or 0) == 0 then + msg(2, "Nothing was installed into %s.", target) + finish(EXIT_INSTALL) +elseif #missing > 0 then + for _, p in ipairs(missing) do + msg(2, "%s::%s %s was not installed into %s.", p.repo, p.name, p.ver, target) + end + finish(EXIT_INSTALL) +end + +-- TARGET's repositories, as its own repos.conf (from a package) gives +-- them: syspkg -R reads TARGET's keyring for -y, and fetches into +-- TARGET's /glacier/sys/repos. This also sets TARGET's rollback floor. +-- A repos.conf this can't parse is left to syspkg to report. +do + local conf = target:gsub("/+$", "") .. "/etc/glacier/repos.conf" + local buf = ffi.new("char[65536]") + local st = tonumber(istore.gl_conf_repos(conf, buf, 65536)) + local remote = st ~= 0 and exists(conf) + if st == 0 then + for _, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then remote = true end + end + end + if not remote then + msg(1, "No remote repositories are configured in %s.", target) + elseif not run(sys .. v .. " -y") then + finish(EXIT_REPOS) + end +end + +msg(3, "Bootstrapped %s into %s.", t.name, target) + +if smoke then + if not run(as_root .. "chroot " .. shell_quote(target) .. " /bin/sh -c true") then + msg(2, "chroot %s /bin/sh -c true failed.", target) + finish(EXIT_SMOKE) + end + msg(3, "chroot %s /bin/sh -c true succeeded.", target) +end + +finish(0) diff --git a/bin/gpkg b/bin/gpkg new file mode 100755 index 0000000..b509e16 --- /dev/null +++ b/bin/gpkg @@ -0,0 +1,307 @@ +#!/usr/bin/luajit + +local ffi = require("ffi") + +-- lib/ is found beside this script's REAL location (an installed +-- /usr/bin/gpkg is a symlink into the store), never the current +-- directory. Unprivileged, so no ownership checks (syspkg/gstore have +-- those). +ffi.cdef[[ +char *gpkg_realpath(const char *path, char *resolved) asm("realpath"); +]] +local self_dir +do + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_realpath(arg[0], buf) == nil then + io.stderr:write("gpkg: cannot resolve own location\n") + os.exit(1) + end + self_dir = ffi.string(buf):match("^(.*)/[^/]*$") + if not self_dir or self_dir == "" then self_dir = "/" end +end +package.path = self_dir .. "/?.lua" +package.cpath = "" + +local cargs = require("lib/cargs") +local color = require("lib/color") + +local glacier_cdef = require("lib/glacier_cdef") +local common = require("lib/gpkg_common") + +-- gpkg is a PER-USER tool only. It deliberately never constructs a +-- GL_SCOPE_SYS context anywhere in this file -- that capability lives +-- exclusively in syspkg. See SECURITY_DESIGN.txt section 5. +local so_dir = self_dir .. "/lib/glacier" +local log = ffi.load(so_dir .. "/libglacier_log.so") +local istore = ffi.load(so_dir .. "/libglacier_istoreutils.so") +local txn = ffi.load(so_dir .. "/libglacier_transaction.so") +local verify = ffi.load(so_dir .. "/libglacier_verify.so") + +local txn_name = glacier_cdef.txn_name + +local function get_loginuid() + local f = io.open("/proc/self/loginuid", "r") + if f then + local raw = f:read("*l") + f:close() + local n = tonumber(raw) + if n and n ~= 4294967295 then + return n + end + end + return tonumber(ffi.C.getuid()) +end +local argc, argv = cargs.get_argv() +local args = {} + +local longopts = { + help = "-h", + version = "-v", + merge = "-f", + ["local"] = "-l", + update = "-u", + remove = "-x", + refresh = "-y", + verbose = "-V", + quiet = "-q", + ["skip-installed"] = "-S", + overwrite = "-O", +} + +for i = 1, argc - 1 do + table.insert(args, ffi.string(argv[i])) +end + +if #args == 0 then + log.lg_printf(2, "usage: %s [-hv] [-y] [-flux PKG] [-OSVq]", argv[0]) + os.exit(1) +end + +local mode +local pkgs = {} + +local isVerbose = false +local skipInstalled = false + +-- Wire the shared module up now that log/istore/txn and argv exist. +common.init({ log = log, istore = istore, txn = txn, verify = verify, argv = argv, + so_dir = so_dir }) + +-- Why a user's /glacier/usr/ is unusable, before any transaction +-- starts (and before any prompt). Mirrors gl_usr_base_status_t. +local function require_user_dirs(uidn) + local base = "/glacier/usr/" .. tostring(uidn) + local st = tonumber(istore.gl_usr_base_status(uidn)) + if st == 1 then + log.lg_printf(2, "No Glacier directories for UID %s. Run doas gstore -n first.", tostring(uidn)) + elseif st == 2 then + log.lg_printf(2, "Refusing to run: /glacier/usr is not root-owned, or is group/world-writable.") + elseif st == 3 then + log.lg_printf(2, "Refusing to run: %s is not a directory owned by UID %s with mode 0700.", + base, tostring(uidn)) + end + if st ~= 0 then os.exit(1) end + + if not istore.gl_usr_istore_exists(ffi.C.INDEX, uidn) + or not istore.gl_usr_istore_exists(ffi.C.STORE, uidn) then + log.lg_printf(2, "%s is incomplete (no index or store). Ask an administrator to recreate it.", base) + os.exit(1) + end +end + +local function handle_flag(flag, i) + if flag == "-h" then + log.lg_gpkg_help(argc, argv) + elseif flag == "-v" then + print("v4.0.0") + elseif flag == "-V" then + isVerbose = true + common.set_verbose(true) + log.lg_printf(0, "This option enables verbose logging.") + elseif flag == "-q" then + common.set_quiet(true) + elseif flag == "-O" then + common.set_overwrite(true) + elseif flag == "-S" then + skipInstalled = true + common.set_skip_installed(true) + if isVerbose then + log.lg_printf(0, "Skipping already installed packages.") + end + elseif flag == "-f" or flag == "-u" then + local uidn = get_loginuid() + + if uidn < 1000 then + log.lg_printf(2, "Cannot run %s as a system account.", argv[0]) + os.exit(1) + end + + local names = {} + local j = i + 1 + + while j <= #args do + local arg = args[j] + if arg:sub(1, 1) == "-" then break end + table.insert(names, arg) + j = j + 1 + end + + if flag == "-f" and #names == 0 then + log.lg_printf(2, "usage: %s -f PKG...", argv[0]) + os.exit(1) + end + + require_user_dirs(uidn) + + local opts = { + scope = ffi.C.GL_SCOPE_USR, + uid = uidn, + scope_label = string.format("for UID %d", uidn), + } + if flag == "-f" then + common.fetch(names, opts) + else + common.upgrade(names, opts) + end + elseif flag == "-l" then + local uidn = get_loginuid() + + if uidn < 1000 then + log.lg_printf(2, "Cannot run %s as a system account.", argv[0]) + os.exit(1) + end + + local gpkg_paths = {} + local j = i + 1 + + while j <= #args do + local arg = args[j] + if arg:sub(1, 1) == "-" then break end + table.insert(gpkg_paths, arg) + j = j + 1 + end + + if #gpkg_paths == 0 then + log.lg_printf(2, "usage: %s -l PKG...", argv[0]) + os.exit(1) + end + + require_user_dirs(uidn) + + common.install(gpkg_paths, { + scope = ffi.C.GL_SCOPE_USR, + uid = uidn, + scope_label = string.format("for UID %d", uidn), + }) + elseif flag == "-y" then + local uidn = get_loginuid() + + if uidn < 1000 then + log.lg_printf(2, "Cannot run %s as a system account.", argv[0]) + os.exit(1) + end + if args[i + 1] and args[i + 1]:sub(1, 1) ~= "-" then + log.lg_printf(2, "-y takes no arguments.") + os.exit(1) + end + + require_user_dirs(uidn) + + os.exit(common.refresh({ + scope = ffi.C.GL_SCOPE_USR, + uid = uidn, + scope_label = string.format("for UID %d", uidn), + }) and 0 or 1) + elseif flag == "-x" then + local uidn = get_loginuid() + + if uidn < 1000 then + log.lg_printf(2, "Cannot run %s as a system account.", argv[0]) + os.exit(1) + end + + local pkg_names = {} + local j = i + 1 + + while j <= #args do + local arg = args[j] + if arg:sub(1, 1) == "-" then break end + table.insert(pkg_names, arg) + j = j + 1 + end + + if #pkg_names == 0 then + log.lg_printf(2, "usage: %s -x PKG...", argv[0]) + os.exit(1) + end + + require_user_dirs(uidn) + + common.remove(pkg_names, { + scope = ffi.C.GL_SCOPE_USR, + uid = uidn, + scope_label = string.format("for UID %d", uidn), + }) + else + log.lg_printf(2, "Unknown option: %s", flag) + log.lg_printf(2, "usage: %s [-hv] [-y] [-flux PKG] [-OSVq]", argv[0]) + os.exit(1) + end +end + +-- Modifier flags change how an action runs but aren't actions. They are +-- applied in a pre-pass so their position doesn't matter: -l acts (and +-- exits) as soon as it's parsed, so without this `-lO` never saw its O +-- and only `-Ol` worked. +local MODIFIERS = { ["-O"] = true, ["-S"] = true, ["-V"] = true, ["-q"] = true } + +for idx, raw in ipairs(args) do + local a = raw + if a:sub(1, 2) == "--" then + a = longopts[a:sub(3)] or a + end + if a:sub(1, 1) == "-" and a:sub(2, 2) ~= "-" then + for c in a:sub(2):gmatch(".") do + if MODIFIERS["-" .. c] then + handle_flag("-" .. c, idx) + end + end + end +end + +local i = 1 +while i <= #args do + local a = args[i] + + -- long option conversion + if a:sub(1, 2) == "--" then + local name = a:sub(3) + local short = longopts[name] + if not short then + log.lg_printf(2, "Unknown option: %s", a) + log.lg_printf(2, "usage: %s [-hv] [-y] [-flux PKG] [-OSVq]", argv[0]) + os.exit(1) + end + a = short + end + + -- grouped flags: -fV, -uxV, etc. + if a:sub(1, 1) == "-" and #a > 2 and a:sub(2, 2) ~= "-" then + for c in a:sub(2):gmatch(".") do + if not MODIFIERS["-" .. c] then + handle_flag("-" .. c, i) + end + end + + -- single flag: -f, -V, -u, etc. + elseif a:sub(1, 1) == "-" then + if not MODIFIERS[a] then + handle_flag(a, i) + end + else + log.lg_printf(2, "Unknown option: %s", a) + os.exit(1) + end + + i = i + 1 +end diff --git a/bin/gstore b/bin/gstore new file mode 100755 index 0000000..44f30bd --- /dev/null +++ b/bin/gstore @@ -0,0 +1,354 @@ +#!/usr/bin/luajit -E + +-- gstore: per-user glacier directory management (GL_SCOPE_USR only — +-- this tool never touches system scope; that is syspkg's alone). +-- +-- `gstore -n` is the one operation that needs root: it creates +-- /glacier/usr/, which lives in a root-owned parent so no user can +-- create (or squat) another uid's directory. Root runs it directly with +-- an explicit UID; a user runs it for themselves through a doas rule +-- that pins the arguments to exactly `-n`: +-- +-- permit nopass :wheel as root cmd /path/to/gstore args -n +-- +-- doas is the privilege boundary (SECURITY_DESIGN.txt section 6): that +-- rule is what stops a user passing someone else's UID. With no UID, +-- gstore acts for the invoking user, resolved the same way gpkg resolves +-- whose store it uses, so `doas gstore -n` always creates the directory +-- gpkg will look for. +-- +-- Because it can run as root, gstore follows syspkg's loading rules, not +-- the CWD-relative convention: -E in the shebang, package.path and every +-- ffi.load() pinned to this script's own real directory, and when root, +-- everything loaded must be root-owned and not group/world-writable all +-- the way up to /. KEEP THIS PREAMBLE IN SYNC WITH syspkg's. It can't be +-- shared through a lib/ file, since it has to run before anything from +-- lib/ is trusted. + +local ffi = require("ffi") +local bit = require("bit") + +-- asm() aliases so these don't collide with glacier_cdef's own +-- declarations of the same libc symbols (ffi.cdef refuses redefinition). +ffi.cdef[[ +unsigned int gstore_geteuid(void) asm("geteuid"); +char *gstore_realpath(const char *path, char *resolved) asm("realpath"); +struct gstore_passwd { + char *pw_name; + char *pw_passwd; + unsigned int pw_uid; + unsigned int pw_gid; + char *pw_gecos; + char *pw_dir; + char *pw_shell; +}; +struct gstore_passwd *gstore_getpwnam(const char *name) asm("getpwnam"); +]] + +-- Errors raised before the trust checks below have passed. Same as +-- syspkg: reproduces lg_printf(LG_ERR, ...) byte for byte, because +-- loading libglacier_log as root before verifying it is the hole the +-- checks close. +local function die(fmt, ...) + io.stdout:write("\27[31m\27[1m[x]\27[0m\27[m " .. string.format(fmt, ...) .. "\n") + os.exit(1) +end + +local is_root = ffi.C.gstore_geteuid() == 0 + +-- This script's own directory, symlinks resolved. +local self_dir +do + local buf = ffi.new("char[4096]") + if ffi.C.gstore_realpath(arg[0], buf) == nil then + die("Cannot resolve own location from '%s'.", tostring(arg[0])) + end + self_dir = ffi.string(buf):match("^(.*)/[^/]*$") + if not self_dir or self_dir == "" then self_dir = "/" end +end + +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +local function require_root_owned(path) + local p = io.popen("stat -L -c '%u %a' -- " .. shell_quote(path) .. " 2>/dev/null") + local line = p and p:read("*l") + if p then p:close() end + + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then + die("Cannot stat %s.", path) + end + if tonumber(uid) ~= 0 then + die("Refusing to run: %s is not owned by root.", path) + end + if bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + die("Refusing to run: %s is group- or world-writable.", path) + end +end + +local trusted = {} +do + local d = self_dir + while true do + table.insert(trusted, d) + if d == "/" then break end + d = d:match("^(.*)/[^/]*$") + if d == "" then d = "/" end + end +end + +local lib_dir = self_dir .. "/lib" +local so_dir = lib_dir .. "/glacier" +local so = { + log = so_dir .. "/libglacier_log.so", + istore = so_dir .. "/libglacier_istoreutils.so", +} + +-- libglacier_pkg.so and libglacier_transaction.so are never ffi.load()ed +-- directly, but istoreutils pulls them in through its $ORIGIN RUNPATH, +-- so they run as root too. +for _, p in ipairs({ + lib_dir, so_dir, + lib_dir .. "/cargs.lua", + lib_dir .. "/glacier_cdef.lua", + so.log, so.istore, + so_dir .. "/libglacier_pkg.so", + so_dir .. "/libglacier_transaction.so", +}) do + table.insert(trusted, p) +end + +if is_root then + -- Installed, lib/glacier and each .so are symlinks out of this + -- package's store dir (lib/glacier -> /usr/lib/glacier -> links + -- into libglacier-ng's), so the directories the loader really + -- walks are the REAL path's ancestors. Check those too. + local checked = {} + local buf = ffi.new("char[4096]") + for _, p in ipairs(trusted) do + require_root_owned(p) + if ffi.C.gstore_realpath(p, buf) == nil then + die("Cannot stat %s.", p) + end + local d = ffi.string(buf) + while not checked[d] do + checked[d] = true + require_root_owned(d) + if d == "/" then break end + d = d:match("^(.*)/[^/]*$") + if d == "" then d = "/" end + end + end +end + +package.path = self_dir .. "/?.lua" +package.cpath = "" + +local cargs = require("lib/cargs") +require("lib/glacier_cdef") + +local log = ffi.load(so.log) +local istore = ffi.load(so.istore) + +local USR_ROOT = "/glacier/usr" + +local argc, argv = cargs.get_argv() +local args = {} + +local usage_line = "usage: %s [-hv] [-n [UID]] [-sbx UID] [-V]" + +local longopts = { + help = "-h", + version = "-v", + sync = "-s", + new = "-n", + delete = "-x", + backup = "-b", + verbose = "-V", +} + +for i = 1, argc - 1 do + table.insert(args, ffi.string(argv[i])) +end + +if #args == 0 then + log.lg_printf(2, usage_line, argv[0]) + os.exit(1) +end + +local isVerbose = false + +-- Whose directory `gstore -n` with no UID is for. Same order as gpkg's +-- get_loginuid (so the two always agree), plus DOAS_USER for when doas +-- is the reason we're uid 0: the kernel's loginuid if one was set at +-- login, else the user doas says invoked it, else our real uid. +local function invoking_uid() + local f = io.open("/proc/self/loginuid", "r") + if f then + local n = tonumber(f:read("*l")) + f:close() + if n and n ~= 4294967295 then return n end + end + + local doas_user = os.getenv("DOAS_USER") + if is_root and doas_user then + local pw = ffi.C.gstore_getpwnam(doas_user) + if pw ~= nil then return tonumber(pw.pw_uid) end + end + + return tonumber(ffi.C.getuid()) +end + +-- `-n`'s UID is optional; everything else's isn't. +local function uid_arg(i, optional) + local uid = args[i + 1] + if uid == nil or uid:sub(1, 1) == "-" then + if optional then return nil end + log.lg_printf(2, "No UID was supplied.") + os.exit(1) + end + + -- A uid_t: anything else would wrap around in C to some other UID. + local uidn = tonumber(uid) + if not uidn or uidn ~= math.floor(uidn) or uidn < 0 or uidn > 4294967294 then + log.lg_printf(2, "Invalid UID: %s", uid) + os.exit(1) + end + return uidn +end + +local function handle_flag(flag, i) + if flag == "-h" then + log.lg_gstore_help(argc, argv) + os.exit(0) + elseif flag == "-v" then + print("v4.0.0") + os.exit(0) + elseif flag == "-V" then + isVerbose = true + elseif flag == "-s" then + log.lg_printf(2, "-s is not implemented yet.") + os.exit(1) + elseif flag == "-n" then + if isVerbose then + print("Glacier v4.0.0") + end + + if not is_root then + log.lg_printf(2, "Cannot create Glacier directories: Permission denied") + os.exit(1) + end + + local uidn = uid_arg(i, true) or invoking_uid() + if uidn == 0 then + log.lg_printf(2, "No UID was supplied.") + os.exit(1) + end + + if uidn < 1000 then + log.lg_printf(2, "Cannot create Glacier directories for system UIDs.") + os.exit(1) + end + + if istore.gl_init_user(uidn, isVerbose) ~= 0 then + os.exit(1) + end + + local base = string.format("%s/%d", USR_ROOT, uidn) + log.lg_printf(3, "Successfully created Glacier directories for UID %d", ffi.new("int", uidn)) + log.lg_printf(3, "The new directories are located at:") + print("\t* " .. base .. "/index") + print("\t* " .. base .. "/store") + print("\t* " .. base .. "/links") + os.exit(0) + elseif flag == "-b" then + local uidn = uid_arg(i, false) + local uids = tostring(uidn) + + local tar_path = args[i + 2] + if not tar_path then + log.lg_printf(2, "No OUTFILE was supplied.") + os.exit(1) + end + + local base = USR_ROOT .. "/" .. uids + + local uid_index_exists = istore.gl_usr_istore_exists(ffi.C.INDEX, uidn) + local uid_store_exists = istore.gl_usr_istore_exists(ffi.C.STORE, uidn) + + if not uid_index_exists and not uid_store_exists then + log.lg_printf(2, "Index and store for UID %s do not exist.", uids) + os.exit(1) + end + + if not uid_index_exists and uid_store_exists then + log.lg_printf(2, "UID %s is missing its index directory.", uids) + os.exit(1) + end + + if uid_index_exists and not uid_store_exists then + log.lg_printf(2, "UID %s is missing its store directory.", uids) + os.exit(1) + end + + local status = istore.gl_backup_istore(tar_path, USR_ROOT, uids) + + if status ~= 0 then + log.lg_printf(2, "Failed to create backup for UID %s.", uids) + os.exit(1) + end + + log.lg_printf(3, "Successfully created backup for UID %s.", uids) + log.lg_printf(3, "Archived the following directories:") + print("\t* " .. base .. "/index") + print("\t* " .. base .. "/store") + print("\t* " .. base .. "/links") + os.exit(0) + elseif flag == "-x" then + local uidn = uid_arg(i, false) + + if uidn < 1000 then + log.lg_printf(2, "Cannot delete Glacier directories for system UIDs.") + os.exit(1) + end + + if istore.gl_delete_user(uidn, isVerbose) == 0 then + os.exit(0) + end + os.exit(1) + else + log.lg_printf(2, "Unknown option: %s", flag) + log.lg_printf(2, usage_line, argv[0]) + os.exit(1) + end +end + +for i = 1, #args do + local a = args[i] + + if a:sub(1, 2) == "--" then + local name = a:sub(3) + local short = longopts[name] + if not short then + log.lg_printf(2, "Unknown option: %s", a) + log.lg_printf(2, usage_line, argv[0]) + os.exit(1) + end + a = short + end + + if a:sub(1, 1) == "-" and #a > 2 and a:sub(2, 2) ~= "-" then + for c in a:sub(2):gmatch(".") do + handle_flag("-" .. c, i) + end + elseif a:sub(1, 1) == "-" then + handle_flag(a, i) + elseif i > 1 and args[i - 1]:sub(1, 1) == "-" then + -- operand of the preceding flag (UID / OUTFILE); handled there + else + log.lg_printf(2, "Unexpected argument: %s", a) + os.exit(1) + end +end diff --git a/bin/syspkg b/bin/syspkg new file mode 100755 index 0000000..e424c35 --- /dev/null +++ b/bin/syspkg @@ -0,0 +1,385 @@ +#!/usr/bin/luajit -E + +-- syspkg: the SOLE system-scope glacier tool. Install, remove, and +-- system store creation under GL_SCOPE_SYS. See SECURITY_DESIGN.txt +-- sections 5 and 6. +-- +-- Always run as root via doas (or sudo). NEVER setuid. syspkg's own +-- job is only to refuse when euid != 0; the privilege boundary itself +-- belongs to doas. +-- +-- Unlike gpkg, this file does NOT follow the CWD-relative +-- require("lib/...") / ffi.load("./lib/...") convention. As root, that +-- convention means "load whatever lib/ is in the caller's current +-- directory" — under a doas rule restricted to `cmd syspkg`, that is a +-- full root escalation. So: +-- * -E in the shebang: LuaJIT ignores LUA_PATH/LUA_CPATH/LUA_INIT. +-- * package.path is pinned to this script's own real directory, and +-- every .so is ffi.load()ed by absolute path from the same place. +-- * every directory and file we load from must be root-owned and not +-- group/world-writable, all the way up to /, or we refuse to run. + +local ffi = require("ffi") +local bit = require("bit") + +-- asm() aliases so these don't collide with glacier_cdef's own +-- declarations of the same libc symbols (ffi.cdef refuses redefinition). +ffi.cdef[[ +unsigned int syspkg_geteuid(void) asm("geteuid"); +char *syspkg_realpath(const char *path, char *resolved) asm("realpath"); +]] + +-- Errors raised before the trust checks below have passed. These can't +-- go through libglacier_log's lg_printf: loading that .so as root before +-- verifying it is exactly what the checks exist to prevent. So this +-- reproduces lg_printf(LG_ERR, ...) byte for byte instead (color.h's +-- COL_RED / COL_RESET, stdout, trailing newline). +local function die(fmt, ...) + io.stdout:write("\27[31m\27[1m[x]\27[0m\27[m " .. string.format(fmt, ...) .. "\n") + os.exit(1) +end + +-- Non-root may still reach -h and -v; anything that touches the system +-- store is refused after argument parsing, below. +local is_root = ffi.C.syspkg_geteuid() == 0 + +-- This script's own directory, symlinks resolved. +local self_dir +do + local buf = ffi.new("char[4096]") + if ffi.C.syspkg_realpath(arg[0], buf) == nil then + die("Cannot resolve own location from '%s'.", tostring(arg[0])) + end + self_dir = ffi.string(buf):match("^(.*)/[^/]*$") + if not self_dir or self_dir == "" then self_dir = "/" end +end + +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +-- Refuse unless `path` is owned by root and not writable by group or +-- other. Anything less means a non-root user could swap in code that +-- syspkg would then run as root. +local function require_root_owned(path) + local p = io.popen("stat -L -c '%u %a' -- " .. shell_quote(path) .. " 2>/dev/null") + local line = p and p:read("*l") + if p then p:close() end + + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then + die("Cannot stat %s.", path) + end + if tonumber(uid) ~= 0 then + die("Refusing to run: %s is not owned by root.", path) + end + if bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + die("Refusing to run: %s is group- or world-writable.", path) + end +end + +local trusted = {} +do + local d = self_dir + while true do + table.insert(trusted, d) + if d == "/" then break end + d = d:match("^(.*)/[^/]*$") + if d == "" then d = "/" end + end +end + +local lib_dir = self_dir .. "/lib" +local so_dir = lib_dir .. "/glacier" +local so = { + log = so_dir .. "/libglacier_log.so", + istore = so_dir .. "/libglacier_istoreutils.so", + txn = so_dir .. "/libglacier_transaction.so", + verify = so_dir .. "/libglacier_verify.so", +} + +-- libglacier_pkg.so is never ffi.load()ed directly, but istoreutils +-- pulls it in through its $ORIGIN RUNPATH, so it runs as root too. +for _, p in ipairs({ + lib_dir, so_dir, + lib_dir .. "/cargs.lua", + lib_dir .. "/glacier_cdef.lua", + lib_dir .. "/gpkg_common.lua", + lib_dir .. "/gpkg_build.lua", + so.log, so.istore, so.txn, so.verify, + so_dir .. "/libglacier_pkg.so", +}) do + table.insert(trusted, p) +end + +-- Only meaningful as root: unprivileged, loading a user-owned lib/ gains +-- the caller nothing they couldn't already run themselves. +if is_root then + -- Installed, lib/glacier and each .so are symlinks out of this + -- package's store dir (lib/glacier -> /usr/lib/glacier -> links + -- into libglacier-ng's), so the directories the loader really + -- walks are the REAL path's ancestors. Check those too. + local checked = {} + local buf = ffi.new("char[4096]") + for _, p in ipairs(trusted) do + require_root_owned(p) + if ffi.C.syspkg_realpath(p, buf) == nil then + die("Cannot stat %s.", p) + end + local d = ffi.string(buf) + while not checked[d] do + checked[d] = true + require_root_owned(d) + if d == "/" then break end + d = d:match("^(.*)/[^/]*$") + if d == "" then d = "/" end + end + end +end + +package.path = self_dir .. "/?.lua" +package.cpath = "" + +local cargs = require("lib/cargs") +local glacier_cdef = require("lib/glacier_cdef") +local common = require("lib/gpkg_common") + +local log = ffi.load(so.log) +local istore = ffi.load(so.istore) +local txn = ffi.load(so.txn) +local verify = ffi.load(so.verify) + +local argc, argv = cargs.get_argv() + +local usage_line = "usage: %s [-hv] [-n] [-y] [-flux PKG] [-OSVq] [-R DIR] [--strict]" + +local longopts = { + help = "-h", + version = "-v", + verbose = "-V", + quiet = "-q", + ["skip-installed"] = "-S", + overwrite = "-O", + new = "-n", + ["local"] = "-l", + merge = "-f", + update = "-u", + remove = "-x", + refresh = "-y", + root = "-R", + strict = "--strict", +} + +local args = {} +for i = 1, argc - 1 do + table.insert(args, ffi.string(argv[i])) +end + +if #args == 0 then + log.lg_printf(2, usage_line, argv[0]) + os.exit(1) +end + +-- Parse everything first, then act once: unlike gpkg, the outcome +-- doesn't depend on whether -V came before or after -l. +local mode +local operands = {} +local isVerbose = false +local root -- -R DIR: operate on the system installed under DIR +local strict = false -- --strict (implied by -R) + +local function set_mode(m) + if mode and mode ~= m then + log.lg_printf(2, "-n, -l, -f, -u, -x and -y are mutually exclusive.") + os.exit(1) + end + mode = m +end + +local function handle_flag(flag) + if flag == "-h" then + log.lg_syspkg_help(argc, argv) + os.exit(0) + elseif flag == "-v" then + print("v4.0.0") + os.exit(0) + elseif flag == "-V" then + isVerbose = true + common.set_verbose(true) + elseif flag == "-q" then + common.set_quiet(true) + elseif flag == "-S" then + common.set_skip_installed(true) + elseif flag == "-O" then + common.set_overwrite(true) + elseif flag == "-n" then + set_mode("new") + elseif flag == "-l" then + set_mode("install") + elseif flag == "-f" then + set_mode("fetch") + elseif flag == "-u" then + set_mode("upgrade") + elseif flag == "-x" then + set_mode("remove") + elseif flag == "-y" then + set_mode("refresh") + elseif flag == "--strict" then + strict = true + else + log.lg_printf(2, "Unknown option: %s", flag) + log.lg_printf(2, usage_line, argv[0]) + os.exit(1) + end +end + +common.init({ log = log, istore = istore, txn = txn, verify = verify, argv = argv, + so_dir = so_dir }) + +-- -R takes the next argument (or --root=DIR); in a bundle like -lR it +-- must come last. +local function set_root(dir) + if not dir or dir == "" then + log.lg_printf(2, "-R needs a directory.") + os.exit(1) + end + if root then + log.lg_printf(2, "-R given more than once.") + os.exit(1) + end + root = dir +end + +local i = 1 +while i <= #args do + local a = args[i] + if a:sub(1, 2) == "--" then + local name, value = a:sub(3):match("^([^=]*)=(.*)$") + name = name or a:sub(3) + local short = longopts[name] + if not short or (value and short ~= "-R") then + log.lg_printf(2, "Unknown option: %s", a) + log.lg_printf(2, usage_line, argv[0]) + os.exit(1) + end + if short == "-R" then + if not value then i = i + 1; value = args[i] end + set_root(value) + else + handle_flag(short) + end + elseif a:sub(1, 1) == "-" and #a > 1 then + local flags = a:sub(2) + for k = 1, #flags do + local c = flags:sub(k, k) + if c == "R" then + if k ~= #flags then + log.lg_printf(2, "-R must come last in %s.", a) + os.exit(1) + end + i = i + 1 + set_root(args[i]) + else + handle_flag("-" .. c) + end + end + elseif mode == "install" or mode == "remove" or mode == "fetch" + or mode == "upgrade" then + table.insert(operands, a) + else + log.lg_printf(2, "Unexpected argument: %s", a) + os.exit(1) + end + i = i + 1 +end + +if mode and not is_root then + log.lg_printf(2, "Cannot open system index: Permission denied") + os.exit(1) +end + +-- The install root, refused here (by the library, which says why) before +-- anything reads or writes under it: it and every directory above it +-- must be root-owned directories that aren't group/world-writable. +-- `prefix` is what the messages below put in front of /glacier/... +local prefix = "" +if root then + if txn.gl_check_sysroot(root) ~= 0 then + os.exit(1) + end + prefix = root:gsub("/+$", "") +end + +local function exists(path, test) + local ok = os.execute("test " .. test .. " " .. shell_quote(path)) + return ok == true or ok == 0 +end + +local function require_sys_istore() + local run = ffi.string(argv[0]) .. (root and (" -R " .. root) or "") + if not exists(prefix .. "/glacier/sys/index/current", "-e") then + log.lg_printf(2, "No system index found. Run %s -n first.", run) + os.exit(1) + end + if not exists(prefix .. "/glacier/sys/store", "-d") then + log.lg_printf(2, "No system store found. Run %s -n first.", run) + os.exit(1) + end +end + +local opts = { + scope = ffi.C.GL_SCOPE_SYS, + uid = 0, + scope_label = "for the system scope", + sysroot = root, + -- An image's /usr starts empty: anything refused there is two + -- packages colliding or a broken package, never a distro file. + strict = strict or root ~= nil, +} + +if mode == "new" then + if #operands > 0 then + log.lg_printf(2, "-n takes no arguments.") + os.exit(1) + end + -- gl_init_sys logs its own reason (e.g. "already exists"), + -- same as gstore -n leaves it to gl_init_user. + if istore.gl_init_sys_at(root or "/", isVerbose) ~= 0 then + os.exit(1) + end + log.lg_printf(3, "Created system glacier directories:") + print("\t* " .. prefix .. "/glacier/sys/index") + print("\t* " .. prefix .. "/glacier/sys/store") + print("\t* " .. prefix .. "/glacier/sys/links") + os.exit(0) +elseif mode == "install" then + if #operands == 0 then + log.lg_printf(2, "usage: %s -l PKG...", argv[0]) + os.exit(1) + end + require_sys_istore() + common.install(operands, opts) +elseif mode == "fetch" then + if #operands == 0 then + log.lg_printf(2, "usage: %s -f PKG...", argv[0]) + os.exit(1) + end + require_sys_istore() + common.fetch(operands, opts) +elseif mode == "upgrade" then + require_sys_istore() + common.upgrade(operands, opts) +elseif mode == "remove" then + if #operands == 0 then + log.lg_printf(2, "usage: %s -x PKG...", argv[0]) + os.exit(1) + end + require_sys_istore() + common.remove(operands, opts) +elseif mode == "refresh" then + require_sys_istore() + os.exit(common.refresh(opts) and 0 or 1) +else + log.lg_printf(2, usage_line, argv[0]) + os.exit(1) +end diff --git a/docker/Dockerfile.alpine b/docker/Dockerfile.alpine new file mode 100644 index 0000000..bf7c384 --- /dev/null +++ b/docker/Dockerfile.alpine @@ -0,0 +1,80 @@ +# Alpine test image, default user `glacier` (uid 1000, in wheel). +# +# Build/run with: ./run_docker.sh (Dockerfile.alpine is the default) +# +# Layout rules this image has to respect (see PACKAGE_SCOPES.txt §1): +# * /app is root-owned and not group/world-writable. gstore -n and +# syspkg run as root and refuse to load code from anything a user +# could edit — so the source tree can't be handed to `glacier`. +# * /glacier is NOT pre-created or chown'd. `doas /app/gstore -n` +# creates /glacier/usr/1000 (owned by glacier); `doas /app/syspkg -n` +# creates /glacier/sys. A user-owned /glacier/usr is refused. +# * The .so's checked into lib/glacier/ are host (glibc) builds and +# won't load on musl, so libglacier-ng is built from source here, +# from the named build context `libglacier` (run_docker.sh passes it). + +FROM alpine:latest AS libglacier-build + +RUN apk add --no-cache build-base luajit-dev libarchive-dev libconfig-dev linux-headers + +COPY --from=libglacier . /build +WORKDIR /build +RUN make clean && make + +FROM alpine:latest + +RUN apk update && apk add build-base git lua-dev luajit-dev doas libarchive-static libarchive-dev libconfig-dev linux-headers valgrind gdb +RUN apk add --no-cache shadow +RUN adduser -D -u 1000 glacier && \ + echo "glacier:password" | chpasswd && \ + addgroup glacier wheel + +WORKDIR /app +COPY . . +COPY --from=libglacier-build /build/build/lib/shared/libglacier_*.so /app/lib/glacier/ +COPY --from=libglacier-build /build/build/bin/gsandbox /app/lib/glacier/ +RUN chown -R root:root /app && chmod -R go-w /app +RUN install -Dm644 /app/etc/glacier/glacier.conf /etc/glacier/glacier.conf + +# A TEST signing key, so base packages can be installed here: syspkg +# requires their sidecar signed by a key listed for base in +# /etc/glacier/repos.conf (REPO_DESIGN.txt section 7). Its secret half is +# in the image, so never trust it anywhere else. Sign with +# `tests/mkpkg -k /root/glacier-test.sec ... base` (or gbuild -k; gbuild +# finds gsha256sum and gsign on PATH). grepo is there too. +COPY --from=libglacier-build /build/build/bin/gsign /build/build/bin/gsha256sum /build/build/bin/grepo /usr/local/bin/ +RUN mkdir -p /etc/glacier/keys && \ + gsign -G -p /etc/glacier/keys/glacier-test.pub -s /root/glacier-test.sec -c glacier-test >/dev/null && \ + printf 'repos = (\n\t{ name = "base"; keys = [ "glacier-test" ]; }\n);\n' > /etc/glacier/repos.conf && \ + chmod 644 /etc/glacier/repos.conf + +RUN chmod 4755 /bin/su +RUN chmod 4755 /usr/bin/doas +RUN passwd -d root + +# doas uses the LAST rule that matches. +# 1. glacier may run anything as root (this image's dev convenience, +# same as before) — needed for `doas /app/syspkg ...`. +# 2. The rule Everest itself would ship: any wheel user may run +# exactly `gstore -n` as root (no other arguments), so they can +# create their OWN /glacier/usr/ but can't name another UID. +# With rule 1 present it adds nothing for glacier; delete rule 1 to +# test glacier under the real, restricted setup. +RUN printf '%s\n' \ + 'permit nopass glacier' \ + 'permit nopass :wheel as root cmd /app/gstore args -n' \ + > /etc/doas.conf && chmod 0400 /etc/doas.conf + +RUN printf '%s\n' \ + '# Per-user links first, then system-scope (non-base) links. Not' \ + '# conditional on the dirs existing: /glacier is only created later,' \ + '# by syspkg -n / gstore -n, and a missing PATH entry is harmless.' \ + 'GLACIER_LINKS="/glacier/usr/$(id -u)/links"' \ + 'GLACIER_SYS_LINKS="/glacier/sys/links"' \ + 'export PATH="$GLACIER_LINKS/bin:$GLACIER_SYS_LINKS/bin:$PATH"' \ + 'export LD_LIBRARY_PATH="$GLACIER_LINKS/lib:$GLACIER_SYS_LINKS/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"' \ + > /etc/profile.d/glacier.sh + +USER glacier + +CMD ["/bin/sh", "-l"] diff --git a/docker/Dockerfile.alpine_root b/docker/Dockerfile.alpine_root new file mode 100644 index 0000000..90bd441 --- /dev/null +++ b/docker/Dockerfile.alpine_root @@ -0,0 +1,79 @@ +# Root variant of Dockerfile.alpine, for exercising syspkg. +# +# syspkg refuses to run as root unless every directory up to / and every +# .lua/.so it loads is root-owned and not group/world-writable, so /app is +# root-owned, go-w, and the default user is root. +# +# The .so's checked into lib/glacier/ are host (glibc) builds and won't +# load on musl, so libglacier-ng is built from source in a first stage. +# Its source comes from a named build context: +# +# ./run_docker.sh Dockerfile.alpine_root +# +# (which passes --build-context libglacier=../libglacier-ng; override the +# path with LIBGLACIER_SRC). + +FROM alpine:latest AS libglacier-build + +# linux-headers: , which Dockerfile.alpine is missing. +RUN apk add --no-cache build-base luajit-dev libarchive-dev libconfig-dev linux-headers + +COPY --from=libglacier . /build +WORKDIR /build +RUN make clean && make + +FROM alpine:latest + +# curl: https repositories and build sources. +RUN apk update && apk add build-base curl git tar lua-dev luajit-dev libarchive-static libarchive-dev libconfig-dev linux-headers valgrind gdb doas + +WORKDIR /app +COPY . . +COPY --from=libglacier-build /build/build/lib/shared/libglacier_*.so /app/lib/glacier/ +COPY --from=libglacier-build /build/build/bin/gsandbox /app/lib/glacier/ + +RUN chown -R root:root /app && chmod -R go-w /app +RUN install -Dm644 /app/etc/glacier/glacier.conf /etc/glacier/glacier.conf + +# A TEST signing key, so base packages can be installed here: syspkg +# requires their sidecar signed by a key listed for base in +# /etc/glacier/repos.conf (REPO_DESIGN.txt section 7). Its secret half is +# in the image, so never trust it anywhere else. Sign with +# `tests/mkpkg -k /root/glacier-test.sec ... base` (or gbuild -k; gbuild +# finds gsha256sum and gsign on PATH). grepo is there too. +COPY --from=libglacier-build /build/build/bin/gsign /build/build/bin/gsha256sum /build/build/bin/grepo /usr/local/bin/ +RUN mkdir -p /etc/glacier/keys && \ + gsign -G -p /etc/glacier/keys/glacier-test.pub -s /root/glacier-test.sec -c glacier-test >/dev/null && \ + printf 'repos = (\n\t{ name = "base"; keys = [ "glacier-test" ]; }\n);\n' > /etc/glacier/repos.conf && \ + chmod 644 /etc/glacier/repos.conf + +# /glacier is deliberately not pre-created: `syspkg -n` builds the whole +# system tree, and `gstore -n` a user's /glacier/usr/, parents +# included. + +# An unprivileged user to exercise per-user scope (`su glacier`). The +# wheel rule pins gstore's arguments to exactly `-n`, so a user can create +# their OWN /glacier/usr/ but can't name anyone else's UID. glacier +# itself may run anything as root, for interactive use (`doas syspkg`); +# user_layout_alpine.sh drops that rule to test the pinned one. +RUN adduser -D -u 1000 glacier && addgroup glacier wheel && \ + printf '%s\n' 'permit nopass glacier as root' \ + 'permit nopass :wheel as root cmd /app/gstore args -n' > /etc/doas.conf && \ + chmod 0400 /etc/doas.conf +# /app (gpkg, syspkg, gstore, ...) on PATH: here for `docker exec` and +# `su`, and in profile.d because Alpine's /etc/profile resets PATH. +ENV PATH="$PATH:/app" +RUN printf '%s\n' \ + '# Per-user links first, then system-scope (non-base) links. Not' \ + '# conditional on the dirs existing: /glacier is only created later,' \ + '# by syspkg -n / gstore -n, and a missing PATH entry is harmless.' \ + '# /app (the glacier-ng tree) last.' \ + 'GLACIER_LINKS="/glacier/usr/$(id -u)/links"' \ + 'GLACIER_SYS_LINKS="/glacier/sys/links"' \ + 'export PATH="$GLACIER_LINKS/bin:$GLACIER_SYS_LINKS/bin:$PATH:/app"' \ + 'export LD_LIBRARY_PATH="$GLACIER_LINKS/lib:$GLACIER_SYS_LINKS/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"' \ + > /etc/profile.d/glacier.sh + +USER root + +CMD ["/bin/sh", "-l"] diff --git a/docker/Dockerfile.arch b/docker/Dockerfile.arch new file mode 100644 index 0000000..70440db --- /dev/null +++ b/docker/Dockerfile.arch @@ -0,0 +1,67 @@ +# Arch (glibc) test image, default user `glacier` (uid 1000, in wheel). +# Same layout rules as Dockerfile.alpine — read its header: +# * /app root-owned, not group/world-writable (gstore -n and syspkg run +# as root and refuse code a user could edit); +# * /glacier NOT pre-created (`doas /app/gstore -n`, `doas /app/syspkg -n`); +# * libglacier-ng built from source here, from the named build context +# `libglacier` that run_docker.sh passes. +# +# ./run_docker.sh Dockerfile.arch + +FROM archlinux:latest AS base +RUN pacman-key --init && pacman-key --populate archlinux && \ + pacman -Syu --noconfirm --needed archlinux-keyring && \ + pacman -S --noconfirm --needed base-devel libarchive libconfig && \ + pacman -Scc --noconfirm + +FROM base AS libglacier-build +COPY --from=libglacier . /build +WORKDIR /build +RUN make clean && make + +FROM base +RUN pacman -S --noconfirm --needed luajit opendoas git && pacman -Scc --noconfirm + +RUN useradd -m -u 1000 -G wheel glacier && \ + echo "glacier:password" | chpasswd + +WORKDIR /app +COPY . . +COPY --from=libglacier-build /build/build/lib/shared/libglacier_*.so /app/lib/glacier/ +COPY --from=libglacier-build /build/build/bin/gsandbox /app/lib/glacier/ +RUN chown -R root:root /app && chmod -R go-w /app +RUN install -Dm644 /app/etc/glacier/glacier.conf /etc/glacier/glacier.conf + +# A TEST signing key, so base packages can be installed here: syspkg +# requires their sidecar signed by a key listed for base in +# /etc/glacier/repos.conf (REPO_DESIGN.txt section 7). Its secret half is +# in the image, so never trust it anywhere else. Sign with +# `tests/mkpkg -k /root/glacier-test.sec ... base` (or gbuild -k; gbuild +# finds gsha256sum and gsign on PATH). grepo is there too. +COPY --from=libglacier-build /build/build/bin/gsign /build/build/bin/gsha256sum /build/build/bin/grepo /usr/local/bin/ +RUN mkdir -p /etc/glacier/keys && \ + gsign -G -p /etc/glacier/keys/glacier-test.pub -s /root/glacier-test.sec -c glacier-test >/dev/null && \ + printf 'repos = (\n\t{ name = "base"; keys = [ "glacier-test" ]; }\n);\n' > /etc/glacier/repos.conf && \ + chmod 644 /etc/glacier/repos.conf + +# doas uses the LAST matching rule. 1: this image's dev convenience +# (glacier may do anything as root). 2: the rule Everest itself ships — +# any wheel user may run exactly `gstore -n`, i.e. create their OWN +# /glacier/usr/. Delete rule 1 to test under the real setup. +RUN printf '%s\n' \ + 'permit nopass glacier' \ + 'permit nopass :wheel as root cmd /app/gstore args -n' \ + > /etc/doas.conf && chmod 0400 /etc/doas.conf + +RUN printf '%s\n' \ + '# Per-user links first, then system-scope (non-base) links. Not' \ + '# conditional on the dirs existing: /glacier is only created later,' \ + '# by syspkg -n / gstore -n, and a missing PATH entry is harmless.' \ + 'GLACIER_LINKS="/glacier/usr/$(id -u)/links"' \ + 'GLACIER_SYS_LINKS="/glacier/sys/links"' \ + 'export PATH="$GLACIER_LINKS/bin:$GLACIER_SYS_LINKS/bin:$PATH"' \ + 'export LD_LIBRARY_PATH="$GLACIER_LINKS/lib:$GLACIER_SYS_LINKS/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"' \ + > /etc/profile.d/glacier.sh + +USER glacier +CMD ["/bin/sh", "-l"] diff --git a/docker/Dockerfile.debian b/docker/Dockerfile.debian new file mode 100644 index 0000000..5bc42fb --- /dev/null +++ b/docker/Dockerfile.debian @@ -0,0 +1,69 @@ +# Debian (glibc) test image, default user `glacier` (uid 1000, in wheel). +# Same layout rules as Dockerfile.alpine — read its header: +# * /app root-owned, not group/world-writable (gstore -n and syspkg run +# as root and refuse code a user could edit); +# * /glacier NOT pre-created (`doas /app/gstore -n`, `doas /app/syspkg -n`); +# * libglacier-ng built from source here, from the named build context +# `libglacier` that run_docker.sh passes. +# +# ./run_docker.sh Dockerfile.debian + +FROM debian:stable AS base +RUN apt-get update && apt-get install -y --no-install-recommends \ + build-essential libarchive-dev libconfig-dev \ + && rm -rf /var/lib/apt/lists/* + +FROM base AS libglacier-build +COPY --from=libglacier . /build +WORKDIR /build +RUN make clean && make + +FROM base +RUN apt-get update && apt-get install -y --no-install-recommends \ + luajit doas git ca-certificates \ + && rm -rf /var/lib/apt/lists/* + +# Debian has no wheel group; the doas rule below is written against it. +RUN groupadd -f wheel && useradd -m -u 1000 -G wheel glacier && \ + echo "glacier:password" | chpasswd + +WORKDIR /app +COPY . . +COPY --from=libglacier-build /build/build/lib/shared/libglacier_*.so /app/lib/glacier/ +COPY --from=libglacier-build /build/build/bin/gsandbox /app/lib/glacier/ +RUN chown -R root:root /app && chmod -R go-w /app +RUN install -Dm644 /app/etc/glacier/glacier.conf /etc/glacier/glacier.conf + +# A TEST signing key, so base packages can be installed here: syspkg +# requires their sidecar signed by a key listed for base in +# /etc/glacier/repos.conf (REPO_DESIGN.txt section 7). Its secret half is +# in the image, so never trust it anywhere else. Sign with +# `tests/mkpkg -k /root/glacier-test.sec ... base` (or gbuild -k; gbuild +# finds gsha256sum and gsign on PATH). grepo is there too. +COPY --from=libglacier-build /build/build/bin/gsign /build/build/bin/gsha256sum /build/build/bin/grepo /usr/local/bin/ +RUN mkdir -p /etc/glacier/keys && \ + gsign -G -p /etc/glacier/keys/glacier-test.pub -s /root/glacier-test.sec -c glacier-test >/dev/null && \ + printf 'repos = (\n\t{ name = "base"; keys = [ "glacier-test" ]; }\n);\n' > /etc/glacier/repos.conf && \ + chmod 644 /etc/glacier/repos.conf + +# doas uses the LAST matching rule. 1: this image's dev convenience +# (glacier may do anything as root). 2: the rule Everest itself ships — +# any wheel user may run exactly `gstore -n`, i.e. create their OWN +# /glacier/usr/. Delete rule 1 to test under the real setup. +RUN printf '%s\n' \ + 'permit nopass glacier' \ + 'permit nopass :wheel as root cmd /app/gstore args -n' \ + > /etc/doas.conf && chmod 0400 /etc/doas.conf + +RUN printf '%s\n' \ + '# Per-user links first, then system-scope (non-base) links. Not' \ + '# conditional on the dirs existing: /glacier is only created later,' \ + '# by syspkg -n / gstore -n, and a missing PATH entry is harmless.' \ + 'GLACIER_LINKS="/glacier/usr/$(id -u)/links"' \ + 'GLACIER_SYS_LINKS="/glacier/sys/links"' \ + 'export PATH="$GLACIER_LINKS/bin:$GLACIER_SYS_LINKS/bin:$PATH"' \ + 'export LD_LIBRARY_PATH="$GLACIER_LINKS/lib:$GLACIER_SYS_LINKS/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"' \ + > /etc/profile.d/glacier.sh + +USER glacier +CMD ["/bin/sh", "-l"] diff --git a/etc/glacier/glacier.conf b/etc/glacier/glacier.conf new file mode 100644 index 0000000..1597afc --- /dev/null +++ b/etc/glacier/glacier.conf @@ -0,0 +1,32 @@ +// /etc/glacier/glacier.conf - glacier configuration (libconfig syntax). +// Read by gpkg and syspkg. Settings have no built-in defaults: if a +// setting an operation needs is missing, that operation refuses to run. + +// How many backups of replaced package versions to keep, per package. +// When `-lO` replaces an installed version, the old one is compressed +// into /backup///-.gpkg (+ .sha256) +// and the oldest backups beyond this count are deleted. 0 = no backups. +KEEP_OLD = 1; + +// Building from source (BUILD_DESIGN.txt). Used only when a package is +// built from a NAME-src repository; a build without what it needs +// refuses. Uncomment and adapt: +// +// The packages every build root has (from the binary repositories). +// BUILD_ROOT = [ "musl", "busybox", "binutils", "gcc", "make", "patch" ]; +// +// The unprivileged user syspkg builds as (not root; owns +// /glacier/sys/build). gpkg builds as the user running it. +// BUILD_USER = "_gbuild"; +// +// Traits for every build, "name" on or "-name" off. A user's own +// /glacier/usr//config/glacier.conf overrides these, and a +// per-package file (/etc/glacier/config/NAME.conf, or the user's +// config/NAME.conf: TRAITS, CFLAGS, CXXFLAGS, LDFLAGS, CONFIGURE) +// overrides both. +// TRAITS = [ "-x11" ]; +// +// CFLAGS = "-O2 -pipe"; +// CXXFLAGS = "-O2 -pipe"; +// LDFLAGS = ""; +// JOBS = 4; diff --git a/etc/glacier/glacier.conf.old b/etc/glacier/glacier.conf.old new file mode 100644 index 0000000..b26b432 --- /dev/null +++ b/etc/glacier/glacier.conf.old @@ -0,0 +1,9 @@ +// /etc/glacier/glacier.conf - glacier configuration (libconfig syntax). +// Read by gpkg and syspkg. Settings have no built-in defaults: if a +// setting an operation needs is missing, that operation refuses to run. + +// How many backups of replaced package versions to keep, per package. +// When `-lO` replaces an installed version, the old one is compressed +// into /backup///-.gpkg (+ .sha256) +// and the oldest backups beyond this count are deleted. 0 = no backups. +KEEP_OLD = 1; diff --git a/include/common.h b/include/common.h new file mode 100644 index 0000000..963dc3d --- /dev/null +++ b/include/common.h @@ -0,0 +1,23 @@ +#ifndef COMMON_H_ +#define COMMON_H_ + +#ifndef _POSIX_C_SOURCE +#define _POSIX_C_SOURCE 200809L +#endif +#ifndef _DEFAULT_SOURCE +#define _DEFAULT_SOURCE +#endif +#ifndef _XOPEN_SOURCE +#define _XOPEN_SOURCE 700 +#endif + +#include + +typedef struct +{ + const char *path; + mode_t mode; +} +dir_t; + +#endif diff --git a/include/istoreutils.h b/include/istoreutils.h new file mode 100644 index 0000000..d615efc --- /dev/null +++ b/include/istoreutils.h @@ -0,0 +1,70 @@ +#ifndef ISTOREUTILS_H_ +#define ISTOREUTILS_H_ + +#include +#include +#include + +typedef enum { + INDEX, + STORE +} +index_store_t; + +typedef enum { + GL_BACKUP_OK = 0, + GL_BACKUP_ERR_ALLOC = 1, + GL_BACKUP_ERR_OPEN = 2, + GL_BACKUP_ERR_ADD_INDEX = 3, + GL_BACKUP_ERR_ADD_STORE = 4, + GL_BACKUP_ERR_CLOSE = 5 +} +gl_backup_status_t; + +/* + * GL_INSTALL_OK: installation successful + * GL_INSTALL_ERR_OPEN: unable to open .gpkg file + * GL_INSTALL_ERR_MANIFEST: manifest is missing or unparseable + * GL_INSTALL_ERR_EXTRACT: unable to extract files + * GL_INSTALL_ERR_INDEX: unable to update index + * GL_INSTALL_ERR_ALREADY_INSTALLED: package already installed + */ + +typedef enum { + GL_INSTALL_OK = 0, + GL_INSTALL_ERR_OPEN = 1, + GL_INSTALL_ERR_MANIFEST = 2, + GL_INSTALL_ERR_EXTRACT = 3, + GL_INSTALL_ERR_INDEX = 4, + GL_INSTALL_ERR_ALREADY_INSTALLED = 5, +} +gl_install_status_t; + +struct gpkg_entry { + char *repo; + char *pkg; +}; + +struct gindex { + int uid; + int listed; + struct gpkg_entry *entries; + size_t count; +}; + +bool gl_usr_istore_exists(index_store_t index_or_store, int uid); +bool gl_sys_istore_exists(index_store_t index_or_store); + +int gl_init_user(uid_t uid, bool isVerbose); + +int gl_parse_index(struct gindex *idx, FILE *f); +void gl_free_index(struct gindex *idx); + +int gl_rebuild_index(uid_t uid, const char *out_dir); + +gl_backup_status_t gl_backup_istore(const char *tar_path, const char *glacier_root, + const char *uid); + +gl_install_status_t gl_install_pkg(const char *gpkg_path, uid_t uid); + +#endif diff --git a/include/pkg.h b/include/pkg.h new file mode 100644 index 0000000..7d263ad --- /dev/null +++ b/include/pkg.h @@ -0,0 +1,84 @@ +#ifndef PKG_H_ +#define PKG_H_ + +#define _POSIX_C_SOURCE 200809L +#define _XOPEN_SOURCE 700 + +#include +#include +#include +#include + +#include "common.h" + +typedef struct { + int maj; + int min; + int pat; + char *tag; +} +semver_t; + +typedef struct { + char *dep_name; + semver_t dep_ver; +} +dep_t; + +typedef struct { + char *conf_name; + semver_t conf_ver; +} +conf_t; + +typedef struct { + char *pkg_name; + semver_t pkg_ver; + char *pkg_desc; + char *pkg_maint; + char *pkg_copyright; + dep_t *pkg_dependencies; + conf_t *pkg_conflicts; +} +gl_pkg_t; + +extern const dir_t gl_root; + +extern const dir_t gl_usr; +extern const dir_t gl_usr_index; +extern const dir_t gl_usr_store; + +extern const dir_t gl_sys; +extern const dir_t gl_sys_index; +extern const dir_t gl_sys_store; + +extern dep_t null_dep; +extern conf_t null_conf; +extern gl_pkg_t empty; + +semver_t gl_pkgver(int major, int minor, int patch); +semver_t gl_parse_semver(const char *str); +void gl_free_semver(semver_t *v); + +gl_pkg_t *gl_spawn_pkg( + char *name, semver_t *ver, char *desc, + char *maint, char *copy, dep_t *dep, + conf_t conf +); + +void gl_show_pkg_props(const gl_pkg_t *pkg); +void gl_free_pkg(gl_pkg_t *pkg); + +int gl_mkdir(dir_t *dir); +char *gl_cat_dir(const dir_t *a, const dir_t *b); +char *gl_cat_dir_and_ver(const dir_t *base, const gl_pkg_t *pkg); +dir_t gl_return_dir(const dir_t *a, const dir_t *b, mode_t mode); +dir_t gl_return_dir_and_ver(const dir_t *base, gl_pkg_t *pkg, mode_t mode); +void gl_free_path(char *path); +void gl_free_dir(dir_t *dir); + +int gl_gpm2gpkg(const char *filename, gl_pkg_t *pkg); +int gl_prepare_pkgdir(gl_pkg_t *pkg, bool is_syspkg); +char *join_with_cwd(const char *path); + +#endif diff --git a/lib/build-driver.sh b/lib/build-driver.sh new file mode 100644 index 0000000..9789adf --- /dev/null +++ b/lib/build-driver.sh @@ -0,0 +1,160 @@ +# build-driver.sh: runs INSIDE gsandbox as /.glacier/in/driver +# (BUILD_DESIGN.txt section 6). POSIX sh: the build root may only have +# busybox. Everything it reads is under /.glacier/in, written by +# gpkg/syspkg: +# +# env NAME, VER, BUILD, PREFIX, SOURCES, PATCHES, +# CONFIGURE_ARGS, TRAITS, JOBS, CFLAGS, CXXFLAGS, +# LDFLAGS (shell assignments, every value quoted) +# bundle.grcp the recipe bundle (already checked by the library) +# sources/FILE each source, hash already checked +# manifest.gpm.cfg the package's manifest +# +# It writes /.glacier/out/NAME-VER.gpkg and nothing else counts. The +# package is checked again outside, so nothing here is trusted. +# +# PREFIX is where the package's usr/ will be linked (/usr for base, +# else /glacier/sys/links or the user's links), so the build compiles +# in the paths its files really have. It installs into DESTDIR$PREFIX, +# which becomes the package's usr/. During the build PREFIX is a link +# to /usr, where the layers are, so paths taken from them (.pc files, +# libtool archives) resolve. + +set -eu +. /.glacier/in/env + +say() { printf '==> %s\n' "$*"; } +die() { printf '==> ERROR: %s\n' "$*"; exit 1; } + +# trait NAME: whether trait NAME is on (for build hooks). +trait() { + for t in $TRAITS; do + [ "$t" = "$1" ] && return 0 + done + return 1 +} + +B=/build +R=$B/recipe/$NAME-$VER +DESTDIR=$B/dest +mkdir -p $B/recipe $B/src $DESTDIR $B/pkg +export DESTDIR PREFIX CFLAGS CXXFLAGS LDFLAGS +export MAKEFLAGS="-j$JOBS" + +case $PREFIX in +/usr) ;; +/?*) mkdir -p "${PREFIX%/*}" && ln -s /usr "$PREFIX" ;; +*) die "Bad PREFIX $PREFIX" ;; +esac + +say "Unpacking $NAME $VER" +tar -xzf /.glacier/in/bundle.grcp -C $B/recipe +cd $B/src +for f in $SOURCES; do + case $f in + *.tar|*.tar.gz|*.tgz|*.tar.xz|*.txz|*.tar.bz2|*.tbz2|*.tar.zst|*.tzst) + tar -xf "/.glacier/in/sources/$f" ;; + *) + cp "/.glacier/in/sources/$f" . ;; + esac +done + +# The source tree: the one directory the sources unpacked into, else +# the unpack directory itself. +S=$B/src +n=0 +for d in $B/src/* $B/src/.[!.]*; do + [ -d "$d" ] && { n=$((n + 1)); one=$d; } +done +[ "$n" = 1 ] && S=$one +cd "$S" + +for p in $PATCHES; do + say "Applying $p" + patch -p1 < "$R/patches/$p" +done + +# configure_args CMD...: run CMD with CONFIGURE_ARGS appended. Those +# are quoted words: the recipe's CONFIGURE, the trait arguments, then +# the per-package CONFIGURE. +configure_args() { eval "set -- \"\$@\" $CONFIGURE_ARGS"; "$@"; } + +if [ -z "$BUILD" ]; then + if [ -f CMakeLists.txt ]; then BUILD=cmake + elif [ -f meson.build ]; then BUILD=meson + # configure BEFORE a bare Makefile (CLAUDE.md bug 8) + elif [ -f configure ] || [ -f configure.ac ]; then BUILD=autotools + elif [ -f Makefile ] || [ -f GNUmakefile ] || [ -f makefile ]; then BUILD=make + else die "Cannot tell how to build $NAME: set BUILD in the recipe" + fi + say "Build system: $BUILD" +fi + +case $BUILD in +autotools) + prepare() { [ -x configure ] || autoreconf -fi; } + configure() { configure_args ./configure --prefix="$PREFIX" --sysconfdir=/etc --localstatedir=/var; } + compile() { make; } + package() { make install DESTDIR="$DESTDIR"; } + ;; +cmake) + prepare() { :; } + configure() { configure_args cmake -B _build -DCMAKE_INSTALL_PREFIX="$PREFIX" -DCMAKE_BUILD_TYPE=Release; } + compile() { cmake --build _build -j "$JOBS"; } + package() { DESTDIR="$DESTDIR" cmake --install _build; } + ;; +meson) + prepare() { :; } + configure() { configure_args meson setup _build --prefix="$PREFIX" --buildtype=release; } + compile() { meson compile -C _build -j "$JOBS"; } + package() { DESTDIR="$DESTDIR" meson install -C _build; } + ;; +make) + prepare() { :; } + configure() { :; } + compile() { configure_args make PREFIX="$PREFIX"; } + package() { make install PREFIX="$PREFIX" DESTDIR="$DESTDIR"; } + ;; +hooks) + prepare() { :; } + configure() { :; } + compile() { :; } + package() { :; } + ;; +*) + die "Unknown build system $BUILD" + ;; +esac + +# The recipe's own hooks replace any of the four. +[ -f "$R/build" ] && . "$R/build" + +say "Preparing"; prepare +say "Configuring"; configure +say "Compiling"; compile +say "Installing into DESTDIR"; package + +[ -n "$(ls -A "$DESTDIR")" ] || die "$NAME installed nothing" + +# DESTDIR$PREFIX is the package's usr/; the rest (etc/, var/) stays. +if [ "$PREFIX" != /usr ] && [ -d "$DESTDIR$PREFIX" ]; then + [ -e "$DESTDIR/usr" ] && die "$NAME installed into both $PREFIX and /usr" + mv "$DESTDIR$PREFIX" "$B/usr" + d=$DESTDIR$PREFIX + while d=${d%/*}; [ "$d" != "$DESTDIR" ]; do + rmdir "$d" 2>/dev/null || die "$NAME installed files beside $PREFIX: ${d#$DESTDIR}" + done + mv "$B/usr" "$DESTDIR/usr" +fi + +say "Packing $NAME-$VER.gpkg" +mkdir -p "$B/pkg/$NAME-$VER" +mv "$DESTDIR" "$B/pkg/$NAME-$VER/files" +cp /.glacier/in/manifest.gpm.cfg "$B/pkg/$NAME-$VER/manifest.gpm.cfg" +# Hardlinks become plain files: glacier refuses a package with a +# hardlink entry. +find "$B/pkg/$NAME-$VER" -type f -links +1 | while IFS= read -r f; do + cp -p "$f" "$f.unlink" && mv -f "$f.unlink" "$f" || die "Cannot copy hardlink $f" +done +tar -czf "/.glacier/out/$NAME-$VER.gpkg" -C "$B/pkg" "$NAME-$VER" +say "Done" diff --git a/lib/build-driver.sh.old b/lib/build-driver.sh.old new file mode 100644 index 0000000..ccd3bed --- /dev/null +++ b/lib/build-driver.sh.old @@ -0,0 +1,131 @@ +# build-driver.sh: runs INSIDE gsandbox as /.glacier/in/driver +# (BUILD_DESIGN.txt section 6). POSIX sh: the build root may only have +# busybox. Everything it reads is under /.glacier/in, written by +# gpkg/syspkg: +# +# env NAME, VER, BUILD, SOURCES, PATCHES, CONFIGURE_ARGS, +# TRAITS, JOBS, CFLAGS, CXXFLAGS, LDFLAGS (shell +# assignments, every value quoted) +# bundle.grcp the recipe bundle (already checked by the library) +# sources/FILE each source, hash already checked +# manifest.gpm.cfg the package's manifest +# +# It writes /.glacier/out/NAME-VER.gpkg and nothing else counts. The +# package is checked again outside, so nothing here is trusted. + +set -eu +. /.glacier/in/env + +say() { printf '==> %s\n' "$*"; } +die() { printf '==> ERROR: %s\n' "$*"; exit 1; } + +# trait NAME: whether trait NAME is on (for build hooks). +trait() { + for t in $TRAITS; do + [ "$t" = "$1" ] && return 0 + done + return 1 +} + +B=/build +R=$B/recipe/$NAME-$VER +DESTDIR=$B/dest +mkdir -p $B/recipe $B/src $DESTDIR $B/pkg +export DESTDIR CFLAGS CXXFLAGS LDFLAGS +export MAKEFLAGS="-j$JOBS" + +say "Unpacking $NAME $VER" +tar -xzf /.glacier/in/bundle.grcp -C $B/recipe +cd $B/src +for f in $SOURCES; do + case $f in + *.tar|*.tar.gz|*.tgz|*.tar.xz|*.txz|*.tar.bz2|*.tbz2|*.tar.zst|*.tzst) + tar -xf "/.glacier/in/sources/$f" ;; + *) + cp "/.glacier/in/sources/$f" . ;; + esac +done + +# The source tree: the one directory the sources unpacked into, else +# the unpack directory itself. +S=$B/src +n=0 +for d in $B/src/* $B/src/.[!.]*; do + [ -d "$d" ] && { n=$((n + 1)); one=$d; } +done +[ "$n" = 1 ] && S=$one +cd "$S" + +for p in $PATCHES; do + say "Applying $p" + patch -p1 < "$R/patches/$p" +done + +# configure_args CMD...: run CMD with CONFIGURE_ARGS appended. Those +# are quoted words: the recipe's CONFIGURE, the trait arguments, then +# the per-package CONFIGURE. +configure_args() { eval "set -- \"\$@\" $CONFIGURE_ARGS"; "$@"; } + +if [ -z "$BUILD" ]; then + if [ -f CMakeLists.txt ]; then BUILD=cmake + elif [ -f meson.build ]; then BUILD=meson + # configure BEFORE a bare Makefile (CLAUDE.md bug 8) + elif [ -f configure ] || [ -f configure.ac ]; then BUILD=autotools + elif [ -f Makefile ] || [ -f GNUmakefile ] || [ -f makefile ]; then BUILD=make + else die "Cannot tell how to build $NAME: set BUILD in the recipe" + fi + say "Build system: $BUILD" +fi + +case $BUILD in +autotools) + prepare() { [ -x configure ] || autoreconf -fi; } + configure() { configure_args ./configure --prefix=/usr --sysconfdir=/etc --localstatedir=/var; } + compile() { make; } + package() { make install DESTDIR="$DESTDIR"; } + ;; +cmake) + prepare() { :; } + configure() { configure_args cmake -B _build -DCMAKE_INSTALL_PREFIX=/usr -DCMAKE_BUILD_TYPE=Release; } + compile() { cmake --build _build -j "$JOBS"; } + package() { DESTDIR="$DESTDIR" cmake --install _build; } + ;; +meson) + prepare() { :; } + configure() { configure_args meson setup _build --prefix=/usr --buildtype=release; } + compile() { meson compile -C _build -j "$JOBS"; } + package() { DESTDIR="$DESTDIR" meson install -C _build; } + ;; +make) + prepare() { :; } + configure() { :; } + compile() { configure_args make PREFIX=/usr; } + package() { make install PREFIX=/usr DESTDIR="$DESTDIR"; } + ;; +hooks) + prepare() { :; } + configure() { :; } + compile() { :; } + package() { :; } + ;; +*) + die "Unknown build system $BUILD" + ;; +esac + +# The recipe's own hooks replace any of the four. +[ -f "$R/build" ] && . "$R/build" + +say "Preparing"; prepare +say "Configuring"; configure +say "Compiling"; compile +say "Installing into DESTDIR"; package + +[ -n "$(ls -A "$DESTDIR")" ] || die "$NAME installed nothing" + +say "Packing $NAME-$VER.gpkg" +mkdir -p "$B/pkg/$NAME-$VER" +mv "$DESTDIR" "$B/pkg/$NAME-$VER/files" +cp /.glacier/in/manifest.gpm.cfg "$B/pkg/$NAME-$VER/manifest.gpm.cfg" +tar -czf "/.glacier/out/$NAME-$VER.gpkg" -C "$B/pkg" "$NAME-$VER" +say "Done" diff --git a/lib/build-driver.sh.old2 b/lib/build-driver.sh.old2 new file mode 100644 index 0000000..ccc0f67 --- /dev/null +++ b/lib/build-driver.sh.old2 @@ -0,0 +1,155 @@ +# build-driver.sh: runs INSIDE gsandbox as /.glacier/in/driver +# (BUILD_DESIGN.txt section 6). POSIX sh: the build root may only have +# busybox. Everything it reads is under /.glacier/in, written by +# gpkg/syspkg: +# +# env NAME, VER, BUILD, PREFIX, SOURCES, PATCHES, +# CONFIGURE_ARGS, TRAITS, JOBS, CFLAGS, CXXFLAGS, +# LDFLAGS (shell assignments, every value quoted) +# bundle.grcp the recipe bundle (already checked by the library) +# sources/FILE each source, hash already checked +# manifest.gpm.cfg the package's manifest +# +# It writes /.glacier/out/NAME-VER.gpkg and nothing else counts. The +# package is checked again outside, so nothing here is trusted. +# +# PREFIX is where the package's usr/ will be linked (/usr for base, +# else /glacier/sys/links or the user's links), so the build compiles +# in the paths its files really have. It installs into DESTDIR$PREFIX, +# which becomes the package's usr/. During the build PREFIX is a link +# to /usr, where the layers are, so paths taken from them (.pc files, +# libtool archives) resolve. + +set -eu +. /.glacier/in/env + +say() { printf '==> %s\n' "$*"; } +die() { printf '==> ERROR: %s\n' "$*"; exit 1; } + +# trait NAME: whether trait NAME is on (for build hooks). +trait() { + for t in $TRAITS; do + [ "$t" = "$1" ] && return 0 + done + return 1 +} + +B=/build +R=$B/recipe/$NAME-$VER +DESTDIR=$B/dest +mkdir -p $B/recipe $B/src $DESTDIR $B/pkg +export DESTDIR PREFIX CFLAGS CXXFLAGS LDFLAGS +export MAKEFLAGS="-j$JOBS" + +case $PREFIX in +/usr) ;; +/?*) mkdir -p "${PREFIX%/*}" && ln -s /usr "$PREFIX" ;; +*) die "Bad PREFIX $PREFIX" ;; +esac + +say "Unpacking $NAME $VER" +tar -xzf /.glacier/in/bundle.grcp -C $B/recipe +cd $B/src +for f in $SOURCES; do + case $f in + *.tar|*.tar.gz|*.tgz|*.tar.xz|*.txz|*.tar.bz2|*.tbz2|*.tar.zst|*.tzst) + tar -xf "/.glacier/in/sources/$f" ;; + *) + cp "/.glacier/in/sources/$f" . ;; + esac +done + +# The source tree: the one directory the sources unpacked into, else +# the unpack directory itself. +S=$B/src +n=0 +for d in $B/src/* $B/src/.[!.]*; do + [ -d "$d" ] && { n=$((n + 1)); one=$d; } +done +[ "$n" = 1 ] && S=$one +cd "$S" + +for p in $PATCHES; do + say "Applying $p" + patch -p1 < "$R/patches/$p" +done + +# configure_args CMD...: run CMD with CONFIGURE_ARGS appended. Those +# are quoted words: the recipe's CONFIGURE, the trait arguments, then +# the per-package CONFIGURE. +configure_args() { eval "set -- \"\$@\" $CONFIGURE_ARGS"; "$@"; } + +if [ -z "$BUILD" ]; then + if [ -f CMakeLists.txt ]; then BUILD=cmake + elif [ -f meson.build ]; then BUILD=meson + # configure BEFORE a bare Makefile (CLAUDE.md bug 8) + elif [ -f configure ] || [ -f configure.ac ]; then BUILD=autotools + elif [ -f Makefile ] || [ -f GNUmakefile ] || [ -f makefile ]; then BUILD=make + else die "Cannot tell how to build $NAME: set BUILD in the recipe" + fi + say "Build system: $BUILD" +fi + +case $BUILD in +autotools) + prepare() { [ -x configure ] || autoreconf -fi; } + configure() { configure_args ./configure --prefix="$PREFIX" --sysconfdir=/etc --localstatedir=/var; } + compile() { make; } + package() { make install DESTDIR="$DESTDIR"; } + ;; +cmake) + prepare() { :; } + configure() { configure_args cmake -B _build -DCMAKE_INSTALL_PREFIX="$PREFIX" -DCMAKE_BUILD_TYPE=Release; } + compile() { cmake --build _build -j "$JOBS"; } + package() { DESTDIR="$DESTDIR" cmake --install _build; } + ;; +meson) + prepare() { :; } + configure() { configure_args meson setup _build --prefix="$PREFIX" --buildtype=release; } + compile() { meson compile -C _build -j "$JOBS"; } + package() { DESTDIR="$DESTDIR" meson install -C _build; } + ;; +make) + prepare() { :; } + configure() { :; } + compile() { configure_args make PREFIX="$PREFIX"; } + package() { make install PREFIX="$PREFIX" DESTDIR="$DESTDIR"; } + ;; +hooks) + prepare() { :; } + configure() { :; } + compile() { :; } + package() { :; } + ;; +*) + die "Unknown build system $BUILD" + ;; +esac + +# The recipe's own hooks replace any of the four. +[ -f "$R/build" ] && . "$R/build" + +say "Preparing"; prepare +say "Configuring"; configure +say "Compiling"; compile +say "Installing into DESTDIR"; package + +[ -n "$(ls -A "$DESTDIR")" ] || die "$NAME installed nothing" + +# DESTDIR$PREFIX is the package's usr/; the rest (etc/, var/) stays. +if [ "$PREFIX" != /usr ] && [ -d "$DESTDIR$PREFIX" ]; then + [ -e "$DESTDIR/usr" ] && die "$NAME installed into both $PREFIX and /usr" + mv "$DESTDIR$PREFIX" "$B/usr" + d=$DESTDIR$PREFIX + while d=${d%/*}; [ "$d" != "$DESTDIR" ]; do + rmdir "$d" 2>/dev/null || die "$NAME installed files beside $PREFIX: ${d#$DESTDIR}" + done + mv "$B/usr" "$DESTDIR/usr" +fi + +say "Packing $NAME-$VER.gpkg" +mkdir -p "$B/pkg/$NAME-$VER" +mv "$DESTDIR" "$B/pkg/$NAME-$VER/files" +cp /.glacier/in/manifest.gpm.cfg "$B/pkg/$NAME-$VER/manifest.gpm.cfg" +tar -czf "/.glacier/out/$NAME-$VER.gpkg" -C "$B/pkg" "$NAME-$VER" +say "Done" diff --git a/lib/cargs.lua b/lib/cargs.lua new file mode 100644 index 0000000..65ff406 --- /dev/null +++ b/lib/cargs.lua @@ -0,0 +1,17 @@ +local ffi = require("ffi") + +local M = {} + +function M.get_argv() + local argc = #arg + local argv = ffi.new("const char *[?]", argc + 1) + + argv[0] = arg[0] or "" + for i = 1, argc do + argv[i] = arg[i] + end + + return argc + 1, argv +end + +return M diff --git a/lib/color.lua b/lib/color.lua new file mode 100644 index 0000000..a18feec --- /dev/null +++ b/lib/color.lua @@ -0,0 +1,24 @@ +-- color.lua +local M = {} + +-- Standard colors (bold) +M.RED = "\x1b[31m\x1b[1m" +M.GREEN = "\x1b[32m\x1b[1m" +M.YELLOW = "\x1b[33m\x1b[1m" +M.BLUE = "\x1b[34m\x1b[1m" +M.MAGENTA = "\x1b[35m\x1b[1m" +M.CYAN = "\x1b[36m\x1b[1m" + +-- Standard colors (not bold) +M.RED_NB = "\x1b[31m" +M.GREEN_NB = "\x1b[32m" +M.YELLOW_NB = "\x1b[33m" +M.BLUE_NB = "\x1b[34m" +M.MAGENTA_NB = "\x1b[35m" +M.CYAN_NB = "\x1b[36m" + +-- Reset +M.RESET = "\x1b[0m\x1b[m" + +return M + diff --git a/lib/glacier_cdef.lua b/lib/glacier_cdef.lua new file mode 100644 index 0000000..60506d3 --- /dev/null +++ b/lib/glacier_cdef.lua @@ -0,0 +1,424 @@ +-- lib/glacier_cdef.lua +-- +-- Single source of truth for every ffi.cdef() declaration used across +-- gpkg, gstore, and the Lua test suite. These used to be hand-copied +-- into each entry point separately, which is exactly what let a stale +-- gl_install_pkg/gl_remove_pkg signature drift silently into gpkg +-- during the transaction-context refactor: nothing caught it, because +-- Lua FFI has no compiler to reject a mismatched declaration the way C +-- would. +-- +-- require() caches modules, so the ffi.cdef() call below runs exactly +-- once per process no matter how many files require() this — calling +-- ffi.cdef() twice with conflicting content would error, but that's +-- not a concern here since there's only one copy now. +-- +-- This module declares the C ABI only. It does not call ffi.load() for +-- you automatically — different entry points may want the library from +-- different explicit paths — but M.load() below gives every caller a +-- consistent, CWD-independent way to find it if they don't need +-- anything more specific. + +local ffi = require("ffi") + +ffi.cdef[[ +typedef unsigned int uid_t; +typedef int pid_t; + +unsigned int getuid(void); +unsigned int getpid(void); +uid_t geteuid(void); +void free(void *ptr); +char *getcwd(char *buf, size_t size); +char *strerror(int errnum); + +void lg_printf(int loglevel, const char *fmt, ...); +void lg_gpkg_help(int argc, const char *argv[]); +void lg_gstore_help(int argc, const char *argv[]); +void lg_syspkg_help(int argc, const char *argv[]); + +typedef enum { + INDEX, + STORE +} index_store_t; +_Bool gl_usr_istore_exists(index_store_t index_or_store, int uid); +int gl_usr_base_status(uid_t uid); +int gl_prune_backups(const char *dir, int keep); + +/* --- pkg.h: glacier.conf --- */ +typedef enum { + GL_CONF_OK = 0, + GL_CONF_ERR_READ = 1, + GL_CONF_ERR_MISSING = 2, + GL_CONF_ERR_TYPE = 3, + GL_CONF_ERR_INVALID = 4, + GL_CONF_ERR_SPACE = 5 +} gl_conf_status_t; +gl_conf_status_t gl_conf_get_int(const char *path, const char *key, int *out); +gl_conf_status_t gl_conf_repo_keys(const char *path, const char *repo, + char *out, size_t outlen); +gl_conf_status_t gl_conf_repos(const char *path, char *out, size_t outlen); +typedef struct { + char *traits; + char *cflags; + char *cxxflags; + char *ldflags; + char *configure; + int jobs; + char *build_user; + char *build_root; +} gl_build_conf_t; +typedef enum { + GL_CONF_SYSTEM = 0, + GL_CONF_USER = 1, + GL_CONF_PACKAGE = 2 +} gl_conf_kind_t; +gl_conf_status_t gl_conf_build(const char *path, gl_conf_kind_t kind, + gl_build_conf_t *out); +void gl_build_conf_free(gl_build_conf_t *c); + +/* --- pkg.h: repository indexes --- */ +typedef struct { + char *name; + char *ver; + char *file; + char *sha256; + int64_t size; + char *deps; + char *confs; + char *build_deps; + char *traits; +} gl_index_pkg_t; +typedef struct { + char *repo; + int64_t serial; + int64_t valid_until; + size_t npkgs; + gl_index_pkg_t *pkgs; +} gl_index_t; +typedef enum { + GL_INDEX_OK = 0, + GL_INDEX_ERR_FORMAT = 1, + GL_INDEX_ERR_REPO = 2, + GL_INDEX_ERR_NOMEM = 3 +} gl_index_status_t; +gl_index_status_t gl_index_parse(const char *text, size_t len, + const char *repo, gl_index_t *out); +void gl_index_free(gl_index_t *idx); + +typedef struct { + char *name; + char *ver; + char *repo; + char *desc; + char *maint; + char *copyright; + char *sources; + char *patches; + char *build; + char *configure; + char *traits; + char *trait_args; + char *deps; + char *build_deps; + char *confs; +} gl_recipe_t; +typedef enum { + GL_RECIPE_OK = 0, + GL_RECIPE_ERR_READ = 1, + GL_RECIPE_ERR_BUNDLE = 2, + GL_RECIPE_ERR_FORMAT = 3, + GL_RECIPE_ERR_NOMEM = 4 +} gl_recipe_status_t; +gl_recipe_status_t gl_recipe_parse(const char *text, size_t len, gl_recipe_t *out); +gl_recipe_status_t gl_recipe_read(const char *bundle, gl_recipe_t *out); +const char *gl_recipe_error(void); +void gl_recipe_free(gl_recipe_t *r); +bool gl_valid_trait(const char *s); + +/* --- transaction.h --- */ + +typedef enum { + GL_CTX_LIVE, + GL_CTX_STAGE +} gl_ctx_mode_t; + +typedef enum { + GL_SCOPE_USR, + GL_SCOPE_SYS +} gl_ctx_scope_t; + +typedef struct { + uid_t uid; + + char root_path[4096]; + char index_path[4096]; + char store_path[4096]; + char links_path[4096]; + + gl_ctx_mode_t mode; + gl_ctx_scope_t scope; + + int lock_fd; + + int overwrite; + + char sysroot[4096]; + + int link_refusals; + + int strict; +} gl_context_t; + +typedef enum { + GL_TXN_OK = 0, + GL_TXN_ERR_LOCK = 1, + GL_TXN_ERR_MKDIR = 2, + GL_TXN_ERR_PERM = 3, + GL_TXN_ERR_RENAME = 4, + GL_TXN_ERR_SYNC = 5, + GL_TXN_ERR_CLEANUP = 6, + GL_TXN_ERR_NO_TXN = 7, + GL_TXN_ERR_XDEV = 8, + GL_TXN_ERR_DEPS = 9 +} gl_txn_status_t; + +int gl_check_sysroot(const char *sysroot); +int gl_init_live_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid); +int gl_init_live_context_at(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid, + const char *sysroot); +gl_txn_status_t gl_init_stage_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid); +gl_txn_status_t gl_init_stage_context_at(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid, + const char *sysroot); +gl_txn_status_t gl_begin_transaction(gl_context_t *ctx); +int gl_scope_state_dir(const gl_context_t *ctx, const char *name, char *out); +int gl_scope_cache_dir(const gl_context_t *ctx, const char *repo, char *out); +int gl_scope_build_dir(const gl_context_t *ctx, const char *name, int owner, char *out); +gl_txn_status_t gl_commit_transaction(gl_context_t *ctx); +gl_txn_status_t gl_abort_transaction(gl_context_t *ctx); + +/* --- istoreutils.h --- */ + +typedef enum { + GL_INSTALL_OK = 0, + GL_INSTALL_ERR_OPEN = 1, + GL_INSTALL_ERR_MANIFEST = 2, + GL_INSTALL_ERR_EXTRACT = 3, + GL_INSTALL_ERR_INDEX = 4, + GL_INSTALL_ERR_ALREADY_INSTALLED = 5, + GL_INSTALL_SKIPPED = 6, + GL_INSTALL_ERR_SCOPE = 7, + GL_INSTALL_ERR_DEPS = 8 +} gl_install_status_t; + +typedef enum { + GL_REMOVE_OK = 0, + GL_REMOVE_ERR_NOT_FOUND = 1, + GL_REMOVE_ERR_UNLINK = 2, + GL_REMOVE_ERR_INDEX = 3, + GL_REMOVE_ERR_DEPS = 4 +} gl_remove_status_t; + +typedef struct { + char **repos; + size_t count; +} gl_repo_list_t; + +int gl_init_user(uid_t uid, bool isVerbose); +int gl_init_sys(bool isVerbose); +int gl_init_sys_at(const char *sysroot, bool isVerbose); +int gl_create_fs_tree(const char *root, bool isVerbose); +int gl_delete_user(uid_t uid, bool isVerbose); + +gl_repo_list_t gl_find_pkg_repos(gl_context_t *ctx, const char *pkg_name); +void gl_free_repo_list(gl_repo_list_t *list); + +gl_install_status_t gl_install_pkg(gl_context_t *ctx, const char *gpkg_path); +gl_install_status_t gl_extract_files(const char *gpkg_path, const char *dest); +gl_remove_status_t gl_remove_pkg(gl_context_t *ctx, const char *pkg_name, const char *pkg_repo); +int gl_backup_pkg(gl_context_t *ctx, const char *repo, const char *name, const char *out_path); +int gl_relink_store(gl_context_t *ctx); +int gl_set_pkg_auto(gl_context_t *ctx, const char *repo, const char *name, bool automatic); +int gl_set_pkg_src(gl_context_t *ctx, const char *repo, const char *name, const char *src_repo); +int gl_pkg_src(gl_context_t *ctx, const char *repo, const char *name, char *out, size_t len); + +/* --- deps.h (built into libglacier_istoreutils.so) --- */ +int gl_check_plan(const gl_context_t *live, + const char *const *add_paths, size_t n_add, + const char *const *remove_ids, size_t n_remove); +int gl_check_txn(const gl_context_t *stage); + +int gl_backup_istore(const char *tar_path, const char *glacier_root, const char *uid); + +/* --- pkg.h: parsed manifests (arrays end at a NULL name) --- */ +typedef struct { + int maj; + int min; + int pat; + char *tag; +} semver_t; +typedef struct { + char *dep_name; + semver_t dep_ver; +} dep_t; +typedef struct { + char *conf_name; + semver_t conf_ver; +} conf_t; +typedef struct { + char *pkg_name; + semver_t pkg_ver; + char *pkg_desc; + char *pkg_maint; + char *pkg_copyright; + char *pkg_repo; + dep_t *pkg_dependencies; + conf_t *pkg_conflicts; + char *pkg_traits; +} gl_pkg_t; +/* libglacier_istoreutils.so; *pkg must be zeroed, free with gl_free_pkg */ +int gl_read_pkg_manifest(const char *gpkg_path, gl_pkg_t *pkg); +int gl_gpm2gpkg(const char *filename, gl_pkg_t *pkg); +void gl_free_pkg(gl_pkg_t *pkg); + +/* --- libc: process control, used by the crash/contention tests --- */ +pid_t fork(void); +pid_t waitpid(pid_t pid, int *status, int options); +int kill(pid_t pid, int sig); +void _exit(int status); +unsigned int sleep(unsigned int seconds); + +/* --- libc: mount, used by the EXDEV test --- */ +int mount(const char *source, const char *target, const char *filesystemtype, + unsigned long mountflags, const void *data); +int umount2(const char *target, int flags); + +/* --- sha256.h (libglacier_verify.so, private) --- */ +typedef struct { + uint32_t state[8]; + uint64_t bitlen; + uint8_t data[64]; + size_t datalen; +} gl_sha256_ctx_t; + +void gl_sha256_init(gl_sha256_ctx_t *ctx); +void gl_sha256_update(gl_sha256_ctx_t *ctx, const uint8_t *data, size_t len); +void gl_sha256_final(gl_sha256_ctx_t *ctx, uint8_t digest[32]); +void gl_sha256_to_hex(const uint8_t digest[32], char *out); + +/* --- sign.h (libglacier_verify.so, private) --- */ +typedef enum { + GL_SIGN_OK = 0, + GL_SIGN_ERR_IO = 1, + GL_SIGN_ERR_FORMAT = 2, + GL_SIGN_ERR_ENCRYPTED = 3, + GL_SIGN_ERR_KEYNUM = 4, + GL_SIGN_ERR_BAD = 5, + GL_SIGN_ERR_TOOBIG = 6, + GL_SIGN_ERR_RANDOM = 7, + GL_SIGN_ERR_EXISTS = 8, + GL_SIGN_ERR_WRITE = 9, +} gl_sign_status_t; + +typedef struct { + uint8_t keynum[8]; + uint8_t key[32]; +} gl_sign_pubkey_t; + +typedef struct { + uint8_t keynum[8]; + uint8_t sig[64]; +} gl_sign_sig_t; + +int gl_sign_read_pubkey(const char *path, gl_sign_pubkey_t *out); +int gl_sign_check_seckey(const char *path); +int gl_sign_read_sig(const char *path, gl_sign_sig_t *out); +int gl_sign_verify(const gl_sign_pubkey_t *pub, const gl_sign_sig_t *sig, + const uint8_t *msg, size_t len); +int gl_sign_verify_file(const char *pubkey_path, const char *msg_path, + const char *sig_path); +int gl_sign_file(const char *seckey_path, const char *msg_path, + const char *sig_path); +int gl_sign_generate(const char *pubkey_path, const char *seckey_path, + const char *comment); +]] + +local M = { ffi = ffi } + +M.SCOPE_USR = 0 +M.SCOPE_SYS = 1 + +local TXN_NAMES = { + [0] = "GL_TXN_OK", [1] = "GL_TXN_ERR_LOCK", [2] = "GL_TXN_ERR_MKDIR", + [3] = "GL_TXN_ERR_PERM", [4] = "GL_TXN_ERR_RENAME", [5] = "GL_TXN_ERR_SYNC", + [6] = "GL_TXN_ERR_CLEANUP", [7] = "GL_TXN_ERR_NO_TXN", [8] = "GL_TXN_ERR_XDEV", + [9] = "GL_TXN_ERR_DEPS", +} +local INSTALL_NAMES = { + [0] = "GL_INSTALL_OK", [1] = "GL_INSTALL_ERR_OPEN", [2] = "GL_INSTALL_ERR_MANIFEST", + [3] = "GL_INSTALL_ERR_EXTRACT", [4] = "GL_INSTALL_ERR_INDEX", + [5] = "GL_INSTALL_ERR_ALREADY_INSTALLED", [6] = "GL_INSTALL_SKIPPED", + [7] = "GL_INSTALL_ERR_SCOPE", [8] = "GL_INSTALL_ERR_DEPS", +} +local REMOVE_NAMES = { + [0] = "GL_REMOVE_OK", [1] = "GL_REMOVE_ERR_NOT_FOUND", + [2] = "GL_REMOVE_ERR_UNLINK", [3] = "GL_REMOVE_ERR_INDEX", + [4] = "GL_REMOVE_ERR_DEPS", +} +local SIGN_NAMES = { + [0] = "GL_SIGN_OK", [1] = "GL_SIGN_ERR_IO", [2] = "GL_SIGN_ERR_FORMAT", + [3] = "GL_SIGN_ERR_ENCRYPTED", [4] = "GL_SIGN_ERR_KEYNUM", [5] = "GL_SIGN_ERR_BAD", + [6] = "GL_SIGN_ERR_TOOBIG", [7] = "GL_SIGN_ERR_RANDOM", [8] = "GL_SIGN_ERR_EXISTS", + [9] = "GL_SIGN_ERR_WRITE", +} + +function M.txn_name(v) return TXN_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.install_name(v) return INSTALL_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.sign_name(v) return SIGN_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.remove_name(v) return REMOVE_NAMES[tonumber(v)] or ("?" .. tostring(v)) end + +function M.new_context() + return ffi.new("gl_context_t") +end + +-- Human-readable current errno, for reporting why a libc call (mount, +-- etc.) failed rather than just that it did. Must be called immediately +-- after the failing call, before any other libc-touching code runs. +function M.strerror() + local err = ffi.errno() + return err .. " (" .. ffi.string(ffi.C.strerror(err)) .. ")" +end + +-- This module's own directory on disk, independent of CWD and +-- independent of how deeply nested the require()ing script is. Lua's +-- debug.getinfo(1, "S").source gives the path this exact file was +-- loaded from, prefixed with "@" for a real file — not the path of +-- whoever called into it. +local function this_dir() + local src = debug.getinfo(1, "S").source + if src:sub(1, 1) == "@" then src = src:sub(2) end + return src:match("(.*/)") or "./" +end + +-- Loads the combined library. Resolution order: +-- 1. an explicit path argument +-- 2. LIBGLACIER_SO env var +-- 3. glacier/libglacier-ng.so relative to *this file's own location* +-- (i.e. /lib/glacier/libglacier-ng.so), not CWD — +-- this is what makes M.load() work correctly no matter where the +-- calling script was invoked from. +function M.load(path) + local target = path or os.getenv("LIBGLACIER_SO") + or (this_dir() .. "glacier/libglacier-ng.so") + local ok, lib = pcall(ffi.load, target) + if not ok then + io.stderr:write(string.format( + "glacier_cdef: could not load %s (%s)\n" .. + "Set LIBGLACIER_SO to the full path of the built .so if it isn't at the default location.\n", + target, tostring(lib))) + os.exit(1) + end + return lib +end + +return M diff --git a/lib/glacier_cdef.lua.old b/lib/glacier_cdef.lua.old new file mode 100644 index 0000000..35b33fd --- /dev/null +++ b/lib/glacier_cdef.lua.old @@ -0,0 +1,367 @@ +-- lib/glacier_cdef.lua +-- +-- Single source of truth for every ffi.cdef() declaration used across +-- gpkg, gstore, and the Lua test suite. These used to be hand-copied +-- into each entry point separately, which is exactly what let a stale +-- gl_install_pkg/gl_remove_pkg signature drift silently into gpkg +-- during the transaction-context refactor: nothing caught it, because +-- Lua FFI has no compiler to reject a mismatched declaration the way C +-- would. +-- +-- require() caches modules, so the ffi.cdef() call below runs exactly +-- once per process no matter how many files require() this — calling +-- ffi.cdef() twice with conflicting content would error, but that's +-- not a concern here since there's only one copy now. +-- +-- This module declares the C ABI only. It does not call ffi.load() for +-- you automatically — different entry points may want the library from +-- different explicit paths — but M.load() below gives every caller a +-- consistent, CWD-independent way to find it if they don't need +-- anything more specific. + +local ffi = require("ffi") + +ffi.cdef[[ +typedef unsigned int uid_t; +typedef int pid_t; + +unsigned int getuid(void); +unsigned int getpid(void); +uid_t geteuid(void); +void free(void *ptr); +char *getcwd(char *buf, size_t size); +char *strerror(int errnum); + +void lg_printf(int loglevel, const char *fmt, ...); +void lg_gpkg_help(int argc, const char *argv[]); +void lg_gstore_help(int argc, const char *argv[]); +void lg_syspkg_help(int argc, const char *argv[]); + +typedef enum { + INDEX, + STORE +} index_store_t; +_Bool gl_usr_istore_exists(index_store_t index_or_store, int uid); +int gl_usr_base_status(uid_t uid); +int gl_prune_backups(const char *dir, int keep); + +/* --- pkg.h: glacier.conf --- */ +typedef enum { + GL_CONF_OK = 0, + GL_CONF_ERR_READ = 1, + GL_CONF_ERR_MISSING = 2, + GL_CONF_ERR_TYPE = 3, + GL_CONF_ERR_INVALID = 4, + GL_CONF_ERR_SPACE = 5 +} gl_conf_status_t; +gl_conf_status_t gl_conf_get_int(const char *path, const char *key, int *out); +gl_conf_status_t gl_conf_repo_keys(const char *path, const char *repo, + char *out, size_t outlen); +gl_conf_status_t gl_conf_repos(const char *path, char *out, size_t outlen); + +/* --- pkg.h: repository indexes --- */ +typedef struct { + char *name; + char *ver; + char *file; + char *sha256; + int64_t size; + char *deps; + char *confs; +} gl_index_pkg_t; +typedef struct { + char *repo; + int64_t serial; + int64_t valid_until; + size_t npkgs; + gl_index_pkg_t *pkgs; +} gl_index_t; +typedef enum { + GL_INDEX_OK = 0, + GL_INDEX_ERR_FORMAT = 1, + GL_INDEX_ERR_REPO = 2, + GL_INDEX_ERR_NOMEM = 3 +} gl_index_status_t; +gl_index_status_t gl_index_parse(const char *text, size_t len, + const char *repo, gl_index_t *out); +void gl_index_free(gl_index_t *idx); + +/* --- transaction.h --- */ + +typedef enum { + GL_CTX_LIVE, + GL_CTX_STAGE +} gl_ctx_mode_t; + +typedef enum { + GL_SCOPE_USR, + GL_SCOPE_SYS +} gl_ctx_scope_t; + +typedef struct { + uid_t uid; + + char root_path[4096]; + char index_path[4096]; + char store_path[4096]; + char links_path[4096]; + + gl_ctx_mode_t mode; + gl_ctx_scope_t scope; + + int lock_fd; + + int overwrite; + + char sysroot[4096]; + + int link_refusals; + + int strict; +} gl_context_t; + +typedef enum { + GL_TXN_OK = 0, + GL_TXN_ERR_LOCK = 1, + GL_TXN_ERR_MKDIR = 2, + GL_TXN_ERR_PERM = 3, + GL_TXN_ERR_RENAME = 4, + GL_TXN_ERR_SYNC = 5, + GL_TXN_ERR_CLEANUP = 6, + GL_TXN_ERR_NO_TXN = 7, + GL_TXN_ERR_XDEV = 8, + GL_TXN_ERR_DEPS = 9 +} gl_txn_status_t; + +int gl_check_sysroot(const char *sysroot); +int gl_init_live_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid); +int gl_init_live_context_at(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid, + const char *sysroot); +gl_txn_status_t gl_init_stage_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid); +gl_txn_status_t gl_init_stage_context_at(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid, + const char *sysroot); +gl_txn_status_t gl_begin_transaction(gl_context_t *ctx); +int gl_scope_state_dir(const gl_context_t *ctx, const char *name, char *out); +gl_txn_status_t gl_commit_transaction(gl_context_t *ctx); +gl_txn_status_t gl_abort_transaction(gl_context_t *ctx); + +/* --- istoreutils.h --- */ + +typedef enum { + GL_INSTALL_OK = 0, + GL_INSTALL_ERR_OPEN = 1, + GL_INSTALL_ERR_MANIFEST = 2, + GL_INSTALL_ERR_EXTRACT = 3, + GL_INSTALL_ERR_INDEX = 4, + GL_INSTALL_ERR_ALREADY_INSTALLED = 5, + GL_INSTALL_SKIPPED = 6, + GL_INSTALL_ERR_SCOPE = 7, + GL_INSTALL_ERR_DEPS = 8 +} gl_install_status_t; + +typedef enum { + GL_REMOVE_OK = 0, + GL_REMOVE_ERR_NOT_FOUND = 1, + GL_REMOVE_ERR_UNLINK = 2, + GL_REMOVE_ERR_INDEX = 3, + GL_REMOVE_ERR_DEPS = 4 +} gl_remove_status_t; + +typedef struct { + char **repos; + size_t count; +} gl_repo_list_t; + +int gl_init_user(uid_t uid, bool isVerbose); +int gl_init_sys(bool isVerbose); +int gl_init_sys_at(const char *sysroot, bool isVerbose); +int gl_create_fs_tree(const char *root, bool isVerbose); +int gl_delete_user(uid_t uid, bool isVerbose); + +gl_repo_list_t gl_find_pkg_repos(gl_context_t *ctx, const char *pkg_name); +void gl_free_repo_list(gl_repo_list_t *list); + +gl_install_status_t gl_install_pkg(gl_context_t *ctx, const char *gpkg_path); +gl_remove_status_t gl_remove_pkg(gl_context_t *ctx, const char *pkg_name, const char *pkg_repo); +int gl_backup_pkg(gl_context_t *ctx, const char *repo, const char *name, const char *out_path); +int gl_relink_store(gl_context_t *ctx); +int gl_set_pkg_auto(gl_context_t *ctx, const char *repo, const char *name, bool automatic); + +/* --- deps.h (built into libglacier_istoreutils.so) --- */ +int gl_check_plan(const gl_context_t *live, + const char *const *add_paths, size_t n_add, + const char *const *remove_ids, size_t n_remove); +int gl_check_txn(const gl_context_t *stage); + +int gl_backup_istore(const char *tar_path, const char *glacier_root, const char *uid); + +/* --- pkg.h: parsed manifests (arrays end at a NULL name) --- */ +typedef struct { + int maj; + int min; + int pat; + char *tag; +} semver_t; +typedef struct { + char *dep_name; + semver_t dep_ver; +} dep_t; +typedef struct { + char *conf_name; + semver_t conf_ver; +} conf_t; +typedef struct { + char *pkg_name; + semver_t pkg_ver; + char *pkg_desc; + char *pkg_maint; + char *pkg_copyright; + char *pkg_repo; + dep_t *pkg_dependencies; + conf_t *pkg_conflicts; +} gl_pkg_t; +/* libglacier_istoreutils.so; *pkg must be zeroed, free with gl_free_pkg */ +int gl_read_pkg_manifest(const char *gpkg_path, gl_pkg_t *pkg); +void gl_free_pkg(gl_pkg_t *pkg); + +/* --- libc: process control, used by the crash/contention tests --- */ +pid_t fork(void); +pid_t waitpid(pid_t pid, int *status, int options); +int kill(pid_t pid, int sig); +void _exit(int status); +unsigned int sleep(unsigned int seconds); + +/* --- libc: mount, used by the EXDEV test --- */ +int mount(const char *source, const char *target, const char *filesystemtype, + unsigned long mountflags, const void *data); +int umount2(const char *target, int flags); + +/* --- sha256.h (libglacier_verify.so, private) --- */ +typedef struct { + uint32_t state[8]; + uint64_t bitlen; + uint8_t data[64]; + size_t datalen; +} gl_sha256_ctx_t; + +void gl_sha256_init(gl_sha256_ctx_t *ctx); +void gl_sha256_update(gl_sha256_ctx_t *ctx, const uint8_t *data, size_t len); +void gl_sha256_final(gl_sha256_ctx_t *ctx, uint8_t digest[32]); +void gl_sha256_to_hex(const uint8_t digest[32], char *out); + +/* --- sign.h (libglacier_verify.so, private) --- */ +typedef enum { + GL_SIGN_OK = 0, + GL_SIGN_ERR_IO = 1, + GL_SIGN_ERR_FORMAT = 2, + GL_SIGN_ERR_ENCRYPTED = 3, + GL_SIGN_ERR_KEYNUM = 4, + GL_SIGN_ERR_BAD = 5, + GL_SIGN_ERR_TOOBIG = 6, + GL_SIGN_ERR_RANDOM = 7, + GL_SIGN_ERR_EXISTS = 8, + GL_SIGN_ERR_WRITE = 9, +} gl_sign_status_t; + +typedef struct { + uint8_t keynum[8]; + uint8_t key[32]; +} gl_sign_pubkey_t; + +typedef struct { + uint8_t keynum[8]; + uint8_t sig[64]; +} gl_sign_sig_t; + +int gl_sign_read_pubkey(const char *path, gl_sign_pubkey_t *out); +int gl_sign_check_seckey(const char *path); +int gl_sign_read_sig(const char *path, gl_sign_sig_t *out); +int gl_sign_verify(const gl_sign_pubkey_t *pub, const gl_sign_sig_t *sig, + const uint8_t *msg, size_t len); +int gl_sign_verify_file(const char *pubkey_path, const char *msg_path, + const char *sig_path); +int gl_sign_file(const char *seckey_path, const char *msg_path, + const char *sig_path); +int gl_sign_generate(const char *pubkey_path, const char *seckey_path, + const char *comment); +]] + +local M = { ffi = ffi } + +M.SCOPE_USR = 0 +M.SCOPE_SYS = 1 + +local TXN_NAMES = { + [0] = "GL_TXN_OK", [1] = "GL_TXN_ERR_LOCK", [2] = "GL_TXN_ERR_MKDIR", + [3] = "GL_TXN_ERR_PERM", [4] = "GL_TXN_ERR_RENAME", [5] = "GL_TXN_ERR_SYNC", + [6] = "GL_TXN_ERR_CLEANUP", [7] = "GL_TXN_ERR_NO_TXN", [8] = "GL_TXN_ERR_XDEV", + [9] = "GL_TXN_ERR_DEPS", +} +local INSTALL_NAMES = { + [0] = "GL_INSTALL_OK", [1] = "GL_INSTALL_ERR_OPEN", [2] = "GL_INSTALL_ERR_MANIFEST", + [3] = "GL_INSTALL_ERR_EXTRACT", [4] = "GL_INSTALL_ERR_INDEX", + [5] = "GL_INSTALL_ERR_ALREADY_INSTALLED", [6] = "GL_INSTALL_SKIPPED", + [7] = "GL_INSTALL_ERR_SCOPE", [8] = "GL_INSTALL_ERR_DEPS", +} +local REMOVE_NAMES = { + [0] = "GL_REMOVE_OK", [1] = "GL_REMOVE_ERR_NOT_FOUND", + [2] = "GL_REMOVE_ERR_UNLINK", [3] = "GL_REMOVE_ERR_INDEX", + [4] = "GL_REMOVE_ERR_DEPS", +} +local SIGN_NAMES = { + [0] = "GL_SIGN_OK", [1] = "GL_SIGN_ERR_IO", [2] = "GL_SIGN_ERR_FORMAT", + [3] = "GL_SIGN_ERR_ENCRYPTED", [4] = "GL_SIGN_ERR_KEYNUM", [5] = "GL_SIGN_ERR_BAD", + [6] = "GL_SIGN_ERR_TOOBIG", [7] = "GL_SIGN_ERR_RANDOM", [8] = "GL_SIGN_ERR_EXISTS", + [9] = "GL_SIGN_ERR_WRITE", +} + +function M.txn_name(v) return TXN_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.install_name(v) return INSTALL_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.sign_name(v) return SIGN_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.remove_name(v) return REMOVE_NAMES[tonumber(v)] or ("?" .. tostring(v)) end + +function M.new_context() + return ffi.new("gl_context_t") +end + +-- Human-readable current errno, for reporting why a libc call (mount, +-- etc.) failed rather than just that it did. Must be called immediately +-- after the failing call, before any other libc-touching code runs. +function M.strerror() + local err = ffi.errno() + return err .. " (" .. ffi.string(ffi.C.strerror(err)) .. ")" +end + +-- This module's own directory on disk, independent of CWD and +-- independent of how deeply nested the require()ing script is. Lua's +-- debug.getinfo(1, "S").source gives the path this exact file was +-- loaded from, prefixed with "@" for a real file — not the path of +-- whoever called into it. +local function this_dir() + local src = debug.getinfo(1, "S").source + if src:sub(1, 1) == "@" then src = src:sub(2) end + return src:match("(.*/)") or "./" +end + +-- Loads the combined library. Resolution order: +-- 1. an explicit path argument +-- 2. LIBGLACIER_SO env var +-- 3. glacier/libglacier-ng.so relative to *this file's own location* +-- (i.e. /lib/glacier/libglacier-ng.so), not CWD — +-- this is what makes M.load() work correctly no matter where the +-- calling script was invoked from. +function M.load(path) + local target = path or os.getenv("LIBGLACIER_SO") + or (this_dir() .. "glacier/libglacier-ng.so") + local ok, lib = pcall(ffi.load, target) + if not ok then + io.stderr:write(string.format( + "glacier_cdef: could not load %s (%s)\n" .. + "Set LIBGLACIER_SO to the full path of the built .so if it isn't at the default location.\n", + target, tostring(lib))) + os.exit(1) + end + return lib +end + +return M diff --git a/lib/glacier_cdef.lua.old2 b/lib/glacier_cdef.lua.old2 new file mode 100644 index 0000000..d62e539 --- /dev/null +++ b/lib/glacier_cdef.lua.old2 @@ -0,0 +1,368 @@ +-- lib/glacier_cdef.lua +-- +-- Single source of truth for every ffi.cdef() declaration used across +-- gpkg, gstore, and the Lua test suite. These used to be hand-copied +-- into each entry point separately, which is exactly what let a stale +-- gl_install_pkg/gl_remove_pkg signature drift silently into gpkg +-- during the transaction-context refactor: nothing caught it, because +-- Lua FFI has no compiler to reject a mismatched declaration the way C +-- would. +-- +-- require() caches modules, so the ffi.cdef() call below runs exactly +-- once per process no matter how many files require() this — calling +-- ffi.cdef() twice with conflicting content would error, but that's +-- not a concern here since there's only one copy now. +-- +-- This module declares the C ABI only. It does not call ffi.load() for +-- you automatically — different entry points may want the library from +-- different explicit paths — but M.load() below gives every caller a +-- consistent, CWD-independent way to find it if they don't need +-- anything more specific. + +local ffi = require("ffi") + +ffi.cdef[[ +typedef unsigned int uid_t; +typedef int pid_t; + +unsigned int getuid(void); +unsigned int getpid(void); +uid_t geteuid(void); +void free(void *ptr); +char *getcwd(char *buf, size_t size); +char *strerror(int errnum); + +void lg_printf(int loglevel, const char *fmt, ...); +void lg_gpkg_help(int argc, const char *argv[]); +void lg_gstore_help(int argc, const char *argv[]); +void lg_syspkg_help(int argc, const char *argv[]); + +typedef enum { + INDEX, + STORE +} index_store_t; +_Bool gl_usr_istore_exists(index_store_t index_or_store, int uid); +int gl_usr_base_status(uid_t uid); +int gl_prune_backups(const char *dir, int keep); + +/* --- pkg.h: glacier.conf --- */ +typedef enum { + GL_CONF_OK = 0, + GL_CONF_ERR_READ = 1, + GL_CONF_ERR_MISSING = 2, + GL_CONF_ERR_TYPE = 3, + GL_CONF_ERR_INVALID = 4, + GL_CONF_ERR_SPACE = 5 +} gl_conf_status_t; +gl_conf_status_t gl_conf_get_int(const char *path, const char *key, int *out); +gl_conf_status_t gl_conf_repo_keys(const char *path, const char *repo, + char *out, size_t outlen); +gl_conf_status_t gl_conf_repos(const char *path, char *out, size_t outlen); + +/* --- pkg.h: repository indexes --- */ +typedef struct { + char *name; + char *ver; + char *file; + char *sha256; + int64_t size; + char *deps; + char *confs; +} gl_index_pkg_t; +typedef struct { + char *repo; + int64_t serial; + int64_t valid_until; + size_t npkgs; + gl_index_pkg_t *pkgs; +} gl_index_t; +typedef enum { + GL_INDEX_OK = 0, + GL_INDEX_ERR_FORMAT = 1, + GL_INDEX_ERR_REPO = 2, + GL_INDEX_ERR_NOMEM = 3 +} gl_index_status_t; +gl_index_status_t gl_index_parse(const char *text, size_t len, + const char *repo, gl_index_t *out); +void gl_index_free(gl_index_t *idx); + +/* --- transaction.h --- */ + +typedef enum { + GL_CTX_LIVE, + GL_CTX_STAGE +} gl_ctx_mode_t; + +typedef enum { + GL_SCOPE_USR, + GL_SCOPE_SYS +} gl_ctx_scope_t; + +typedef struct { + uid_t uid; + + char root_path[4096]; + char index_path[4096]; + char store_path[4096]; + char links_path[4096]; + + gl_ctx_mode_t mode; + gl_ctx_scope_t scope; + + int lock_fd; + + int overwrite; + + char sysroot[4096]; + + int link_refusals; + + int strict; +} gl_context_t; + +typedef enum { + GL_TXN_OK = 0, + GL_TXN_ERR_LOCK = 1, + GL_TXN_ERR_MKDIR = 2, + GL_TXN_ERR_PERM = 3, + GL_TXN_ERR_RENAME = 4, + GL_TXN_ERR_SYNC = 5, + GL_TXN_ERR_CLEANUP = 6, + GL_TXN_ERR_NO_TXN = 7, + GL_TXN_ERR_XDEV = 8, + GL_TXN_ERR_DEPS = 9 +} gl_txn_status_t; + +int gl_check_sysroot(const char *sysroot); +int gl_init_live_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid); +int gl_init_live_context_at(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid, + const char *sysroot); +gl_txn_status_t gl_init_stage_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid); +gl_txn_status_t gl_init_stage_context_at(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid, + const char *sysroot); +gl_txn_status_t gl_begin_transaction(gl_context_t *ctx); +int gl_scope_state_dir(const gl_context_t *ctx, const char *name, char *out); +int gl_scope_cache_dir(const gl_context_t *ctx, const char *repo, char *out); +gl_txn_status_t gl_commit_transaction(gl_context_t *ctx); +gl_txn_status_t gl_abort_transaction(gl_context_t *ctx); + +/* --- istoreutils.h --- */ + +typedef enum { + GL_INSTALL_OK = 0, + GL_INSTALL_ERR_OPEN = 1, + GL_INSTALL_ERR_MANIFEST = 2, + GL_INSTALL_ERR_EXTRACT = 3, + GL_INSTALL_ERR_INDEX = 4, + GL_INSTALL_ERR_ALREADY_INSTALLED = 5, + GL_INSTALL_SKIPPED = 6, + GL_INSTALL_ERR_SCOPE = 7, + GL_INSTALL_ERR_DEPS = 8 +} gl_install_status_t; + +typedef enum { + GL_REMOVE_OK = 0, + GL_REMOVE_ERR_NOT_FOUND = 1, + GL_REMOVE_ERR_UNLINK = 2, + GL_REMOVE_ERR_INDEX = 3, + GL_REMOVE_ERR_DEPS = 4 +} gl_remove_status_t; + +typedef struct { + char **repos; + size_t count; +} gl_repo_list_t; + +int gl_init_user(uid_t uid, bool isVerbose); +int gl_init_sys(bool isVerbose); +int gl_init_sys_at(const char *sysroot, bool isVerbose); +int gl_create_fs_tree(const char *root, bool isVerbose); +int gl_delete_user(uid_t uid, bool isVerbose); + +gl_repo_list_t gl_find_pkg_repos(gl_context_t *ctx, const char *pkg_name); +void gl_free_repo_list(gl_repo_list_t *list); + +gl_install_status_t gl_install_pkg(gl_context_t *ctx, const char *gpkg_path); +gl_remove_status_t gl_remove_pkg(gl_context_t *ctx, const char *pkg_name, const char *pkg_repo); +int gl_backup_pkg(gl_context_t *ctx, const char *repo, const char *name, const char *out_path); +int gl_relink_store(gl_context_t *ctx); +int gl_set_pkg_auto(gl_context_t *ctx, const char *repo, const char *name, bool automatic); + +/* --- deps.h (built into libglacier_istoreutils.so) --- */ +int gl_check_plan(const gl_context_t *live, + const char *const *add_paths, size_t n_add, + const char *const *remove_ids, size_t n_remove); +int gl_check_txn(const gl_context_t *stage); + +int gl_backup_istore(const char *tar_path, const char *glacier_root, const char *uid); + +/* --- pkg.h: parsed manifests (arrays end at a NULL name) --- */ +typedef struct { + int maj; + int min; + int pat; + char *tag; +} semver_t; +typedef struct { + char *dep_name; + semver_t dep_ver; +} dep_t; +typedef struct { + char *conf_name; + semver_t conf_ver; +} conf_t; +typedef struct { + char *pkg_name; + semver_t pkg_ver; + char *pkg_desc; + char *pkg_maint; + char *pkg_copyright; + char *pkg_repo; + dep_t *pkg_dependencies; + conf_t *pkg_conflicts; +} gl_pkg_t; +/* libglacier_istoreutils.so; *pkg must be zeroed, free with gl_free_pkg */ +int gl_read_pkg_manifest(const char *gpkg_path, gl_pkg_t *pkg); +void gl_free_pkg(gl_pkg_t *pkg); + +/* --- libc: process control, used by the crash/contention tests --- */ +pid_t fork(void); +pid_t waitpid(pid_t pid, int *status, int options); +int kill(pid_t pid, int sig); +void _exit(int status); +unsigned int sleep(unsigned int seconds); + +/* --- libc: mount, used by the EXDEV test --- */ +int mount(const char *source, const char *target, const char *filesystemtype, + unsigned long mountflags, const void *data); +int umount2(const char *target, int flags); + +/* --- sha256.h (libglacier_verify.so, private) --- */ +typedef struct { + uint32_t state[8]; + uint64_t bitlen; + uint8_t data[64]; + size_t datalen; +} gl_sha256_ctx_t; + +void gl_sha256_init(gl_sha256_ctx_t *ctx); +void gl_sha256_update(gl_sha256_ctx_t *ctx, const uint8_t *data, size_t len); +void gl_sha256_final(gl_sha256_ctx_t *ctx, uint8_t digest[32]); +void gl_sha256_to_hex(const uint8_t digest[32], char *out); + +/* --- sign.h (libglacier_verify.so, private) --- */ +typedef enum { + GL_SIGN_OK = 0, + GL_SIGN_ERR_IO = 1, + GL_SIGN_ERR_FORMAT = 2, + GL_SIGN_ERR_ENCRYPTED = 3, + GL_SIGN_ERR_KEYNUM = 4, + GL_SIGN_ERR_BAD = 5, + GL_SIGN_ERR_TOOBIG = 6, + GL_SIGN_ERR_RANDOM = 7, + GL_SIGN_ERR_EXISTS = 8, + GL_SIGN_ERR_WRITE = 9, +} gl_sign_status_t; + +typedef struct { + uint8_t keynum[8]; + uint8_t key[32]; +} gl_sign_pubkey_t; + +typedef struct { + uint8_t keynum[8]; + uint8_t sig[64]; +} gl_sign_sig_t; + +int gl_sign_read_pubkey(const char *path, gl_sign_pubkey_t *out); +int gl_sign_check_seckey(const char *path); +int gl_sign_read_sig(const char *path, gl_sign_sig_t *out); +int gl_sign_verify(const gl_sign_pubkey_t *pub, const gl_sign_sig_t *sig, + const uint8_t *msg, size_t len); +int gl_sign_verify_file(const char *pubkey_path, const char *msg_path, + const char *sig_path); +int gl_sign_file(const char *seckey_path, const char *msg_path, + const char *sig_path); +int gl_sign_generate(const char *pubkey_path, const char *seckey_path, + const char *comment); +]] + +local M = { ffi = ffi } + +M.SCOPE_USR = 0 +M.SCOPE_SYS = 1 + +local TXN_NAMES = { + [0] = "GL_TXN_OK", [1] = "GL_TXN_ERR_LOCK", [2] = "GL_TXN_ERR_MKDIR", + [3] = "GL_TXN_ERR_PERM", [4] = "GL_TXN_ERR_RENAME", [5] = "GL_TXN_ERR_SYNC", + [6] = "GL_TXN_ERR_CLEANUP", [7] = "GL_TXN_ERR_NO_TXN", [8] = "GL_TXN_ERR_XDEV", + [9] = "GL_TXN_ERR_DEPS", +} +local INSTALL_NAMES = { + [0] = "GL_INSTALL_OK", [1] = "GL_INSTALL_ERR_OPEN", [2] = "GL_INSTALL_ERR_MANIFEST", + [3] = "GL_INSTALL_ERR_EXTRACT", [4] = "GL_INSTALL_ERR_INDEX", + [5] = "GL_INSTALL_ERR_ALREADY_INSTALLED", [6] = "GL_INSTALL_SKIPPED", + [7] = "GL_INSTALL_ERR_SCOPE", [8] = "GL_INSTALL_ERR_DEPS", +} +local REMOVE_NAMES = { + [0] = "GL_REMOVE_OK", [1] = "GL_REMOVE_ERR_NOT_FOUND", + [2] = "GL_REMOVE_ERR_UNLINK", [3] = "GL_REMOVE_ERR_INDEX", + [4] = "GL_REMOVE_ERR_DEPS", +} +local SIGN_NAMES = { + [0] = "GL_SIGN_OK", [1] = "GL_SIGN_ERR_IO", [2] = "GL_SIGN_ERR_FORMAT", + [3] = "GL_SIGN_ERR_ENCRYPTED", [4] = "GL_SIGN_ERR_KEYNUM", [5] = "GL_SIGN_ERR_BAD", + [6] = "GL_SIGN_ERR_TOOBIG", [7] = "GL_SIGN_ERR_RANDOM", [8] = "GL_SIGN_ERR_EXISTS", + [9] = "GL_SIGN_ERR_WRITE", +} + +function M.txn_name(v) return TXN_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.install_name(v) return INSTALL_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.sign_name(v) return SIGN_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.remove_name(v) return REMOVE_NAMES[tonumber(v)] or ("?" .. tostring(v)) end + +function M.new_context() + return ffi.new("gl_context_t") +end + +-- Human-readable current errno, for reporting why a libc call (mount, +-- etc.) failed rather than just that it did. Must be called immediately +-- after the failing call, before any other libc-touching code runs. +function M.strerror() + local err = ffi.errno() + return err .. " (" .. ffi.string(ffi.C.strerror(err)) .. ")" +end + +-- This module's own directory on disk, independent of CWD and +-- independent of how deeply nested the require()ing script is. Lua's +-- debug.getinfo(1, "S").source gives the path this exact file was +-- loaded from, prefixed with "@" for a real file — not the path of +-- whoever called into it. +local function this_dir() + local src = debug.getinfo(1, "S").source + if src:sub(1, 1) == "@" then src = src:sub(2) end + return src:match("(.*/)") or "./" +end + +-- Loads the combined library. Resolution order: +-- 1. an explicit path argument +-- 2. LIBGLACIER_SO env var +-- 3. glacier/libglacier-ng.so relative to *this file's own location* +-- (i.e. /lib/glacier/libglacier-ng.so), not CWD — +-- this is what makes M.load() work correctly no matter where the +-- calling script was invoked from. +function M.load(path) + local target = path or os.getenv("LIBGLACIER_SO") + or (this_dir() .. "glacier/libglacier-ng.so") + local ok, lib = pcall(ffi.load, target) + if not ok then + io.stderr:write(string.format( + "glacier_cdef: could not load %s (%s)\n" .. + "Set LIBGLACIER_SO to the full path of the built .so if it isn't at the default location.\n", + target, tostring(lib))) + os.exit(1) + end + return lib +end + +return M diff --git a/lib/glacier_cdef.lua.old3 b/lib/glacier_cdef.lua.old3 new file mode 100644 index 0000000..2f7839a --- /dev/null +++ b/lib/glacier_cdef.lua.old3 @@ -0,0 +1,423 @@ +-- lib/glacier_cdef.lua +-- +-- Single source of truth for every ffi.cdef() declaration used across +-- gpkg, gstore, and the Lua test suite. These used to be hand-copied +-- into each entry point separately, which is exactly what let a stale +-- gl_install_pkg/gl_remove_pkg signature drift silently into gpkg +-- during the transaction-context refactor: nothing caught it, because +-- Lua FFI has no compiler to reject a mismatched declaration the way C +-- would. +-- +-- require() caches modules, so the ffi.cdef() call below runs exactly +-- once per process no matter how many files require() this — calling +-- ffi.cdef() twice with conflicting content would error, but that's +-- not a concern here since there's only one copy now. +-- +-- This module declares the C ABI only. It does not call ffi.load() for +-- you automatically — different entry points may want the library from +-- different explicit paths — but M.load() below gives every caller a +-- consistent, CWD-independent way to find it if they don't need +-- anything more specific. + +local ffi = require("ffi") + +ffi.cdef[[ +typedef unsigned int uid_t; +typedef int pid_t; + +unsigned int getuid(void); +unsigned int getpid(void); +uid_t geteuid(void); +void free(void *ptr); +char *getcwd(char *buf, size_t size); +char *strerror(int errnum); + +void lg_printf(int loglevel, const char *fmt, ...); +void lg_gpkg_help(int argc, const char *argv[]); +void lg_gstore_help(int argc, const char *argv[]); +void lg_syspkg_help(int argc, const char *argv[]); + +typedef enum { + INDEX, + STORE +} index_store_t; +_Bool gl_usr_istore_exists(index_store_t index_or_store, int uid); +int gl_usr_base_status(uid_t uid); +int gl_prune_backups(const char *dir, int keep); + +/* --- pkg.h: glacier.conf --- */ +typedef enum { + GL_CONF_OK = 0, + GL_CONF_ERR_READ = 1, + GL_CONF_ERR_MISSING = 2, + GL_CONF_ERR_TYPE = 3, + GL_CONF_ERR_INVALID = 4, + GL_CONF_ERR_SPACE = 5 +} gl_conf_status_t; +gl_conf_status_t gl_conf_get_int(const char *path, const char *key, int *out); +gl_conf_status_t gl_conf_repo_keys(const char *path, const char *repo, + char *out, size_t outlen); +gl_conf_status_t gl_conf_repos(const char *path, char *out, size_t outlen); +typedef struct { + char *traits; + char *cflags; + char *cxxflags; + char *ldflags; + char *configure; + int jobs; + char *build_user; + char *build_root; +} gl_build_conf_t; +typedef enum { + GL_CONF_SYSTEM = 0, + GL_CONF_USER = 1, + GL_CONF_PACKAGE = 2 +} gl_conf_kind_t; +gl_conf_status_t gl_conf_build(const char *path, gl_conf_kind_t kind, + gl_build_conf_t *out); +void gl_build_conf_free(gl_build_conf_t *c); + +/* --- pkg.h: repository indexes --- */ +typedef struct { + char *name; + char *ver; + char *file; + char *sha256; + int64_t size; + char *deps; + char *confs; + char *build_deps; + char *traits; +} gl_index_pkg_t; +typedef struct { + char *repo; + int64_t serial; + int64_t valid_until; + size_t npkgs; + gl_index_pkg_t *pkgs; +} gl_index_t; +typedef enum { + GL_INDEX_OK = 0, + GL_INDEX_ERR_FORMAT = 1, + GL_INDEX_ERR_REPO = 2, + GL_INDEX_ERR_NOMEM = 3 +} gl_index_status_t; +gl_index_status_t gl_index_parse(const char *text, size_t len, + const char *repo, gl_index_t *out); +void gl_index_free(gl_index_t *idx); + +typedef struct { + char *name; + char *ver; + char *repo; + char *desc; + char *maint; + char *copyright; + char *sources; + char *patches; + char *build; + char *configure; + char *traits; + char *trait_args; + char *deps; + char *build_deps; + char *confs; +} gl_recipe_t; +typedef enum { + GL_RECIPE_OK = 0, + GL_RECIPE_ERR_READ = 1, + GL_RECIPE_ERR_BUNDLE = 2, + GL_RECIPE_ERR_FORMAT = 3, + GL_RECIPE_ERR_NOMEM = 4 +} gl_recipe_status_t; +gl_recipe_status_t gl_recipe_parse(const char *text, size_t len, gl_recipe_t *out); +gl_recipe_status_t gl_recipe_read(const char *bundle, gl_recipe_t *out); +void gl_recipe_free(gl_recipe_t *r); +bool gl_valid_trait(const char *s); + +/* --- transaction.h --- */ + +typedef enum { + GL_CTX_LIVE, + GL_CTX_STAGE +} gl_ctx_mode_t; + +typedef enum { + GL_SCOPE_USR, + GL_SCOPE_SYS +} gl_ctx_scope_t; + +typedef struct { + uid_t uid; + + char root_path[4096]; + char index_path[4096]; + char store_path[4096]; + char links_path[4096]; + + gl_ctx_mode_t mode; + gl_ctx_scope_t scope; + + int lock_fd; + + int overwrite; + + char sysroot[4096]; + + int link_refusals; + + int strict; +} gl_context_t; + +typedef enum { + GL_TXN_OK = 0, + GL_TXN_ERR_LOCK = 1, + GL_TXN_ERR_MKDIR = 2, + GL_TXN_ERR_PERM = 3, + GL_TXN_ERR_RENAME = 4, + GL_TXN_ERR_SYNC = 5, + GL_TXN_ERR_CLEANUP = 6, + GL_TXN_ERR_NO_TXN = 7, + GL_TXN_ERR_XDEV = 8, + GL_TXN_ERR_DEPS = 9 +} gl_txn_status_t; + +int gl_check_sysroot(const char *sysroot); +int gl_init_live_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid); +int gl_init_live_context_at(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid, + const char *sysroot); +gl_txn_status_t gl_init_stage_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid); +gl_txn_status_t gl_init_stage_context_at(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid, + const char *sysroot); +gl_txn_status_t gl_begin_transaction(gl_context_t *ctx); +int gl_scope_state_dir(const gl_context_t *ctx, const char *name, char *out); +int gl_scope_cache_dir(const gl_context_t *ctx, const char *repo, char *out); +int gl_scope_build_dir(const gl_context_t *ctx, const char *name, int owner, char *out); +gl_txn_status_t gl_commit_transaction(gl_context_t *ctx); +gl_txn_status_t gl_abort_transaction(gl_context_t *ctx); + +/* --- istoreutils.h --- */ + +typedef enum { + GL_INSTALL_OK = 0, + GL_INSTALL_ERR_OPEN = 1, + GL_INSTALL_ERR_MANIFEST = 2, + GL_INSTALL_ERR_EXTRACT = 3, + GL_INSTALL_ERR_INDEX = 4, + GL_INSTALL_ERR_ALREADY_INSTALLED = 5, + GL_INSTALL_SKIPPED = 6, + GL_INSTALL_ERR_SCOPE = 7, + GL_INSTALL_ERR_DEPS = 8 +} gl_install_status_t; + +typedef enum { + GL_REMOVE_OK = 0, + GL_REMOVE_ERR_NOT_FOUND = 1, + GL_REMOVE_ERR_UNLINK = 2, + GL_REMOVE_ERR_INDEX = 3, + GL_REMOVE_ERR_DEPS = 4 +} gl_remove_status_t; + +typedef struct { + char **repos; + size_t count; +} gl_repo_list_t; + +int gl_init_user(uid_t uid, bool isVerbose); +int gl_init_sys(bool isVerbose); +int gl_init_sys_at(const char *sysroot, bool isVerbose); +int gl_create_fs_tree(const char *root, bool isVerbose); +int gl_delete_user(uid_t uid, bool isVerbose); + +gl_repo_list_t gl_find_pkg_repos(gl_context_t *ctx, const char *pkg_name); +void gl_free_repo_list(gl_repo_list_t *list); + +gl_install_status_t gl_install_pkg(gl_context_t *ctx, const char *gpkg_path); +gl_install_status_t gl_extract_files(const char *gpkg_path, const char *dest); +gl_remove_status_t gl_remove_pkg(gl_context_t *ctx, const char *pkg_name, const char *pkg_repo); +int gl_backup_pkg(gl_context_t *ctx, const char *repo, const char *name, const char *out_path); +int gl_relink_store(gl_context_t *ctx); +int gl_set_pkg_auto(gl_context_t *ctx, const char *repo, const char *name, bool automatic); +int gl_set_pkg_src(gl_context_t *ctx, const char *repo, const char *name, const char *src_repo); +int gl_pkg_src(gl_context_t *ctx, const char *repo, const char *name, char *out, size_t len); + +/* --- deps.h (built into libglacier_istoreutils.so) --- */ +int gl_check_plan(const gl_context_t *live, + const char *const *add_paths, size_t n_add, + const char *const *remove_ids, size_t n_remove); +int gl_check_txn(const gl_context_t *stage); + +int gl_backup_istore(const char *tar_path, const char *glacier_root, const char *uid); + +/* --- pkg.h: parsed manifests (arrays end at a NULL name) --- */ +typedef struct { + int maj; + int min; + int pat; + char *tag; +} semver_t; +typedef struct { + char *dep_name; + semver_t dep_ver; +} dep_t; +typedef struct { + char *conf_name; + semver_t conf_ver; +} conf_t; +typedef struct { + char *pkg_name; + semver_t pkg_ver; + char *pkg_desc; + char *pkg_maint; + char *pkg_copyright; + char *pkg_repo; + dep_t *pkg_dependencies; + conf_t *pkg_conflicts; + char *pkg_traits; +} gl_pkg_t; +/* libglacier_istoreutils.so; *pkg must be zeroed, free with gl_free_pkg */ +int gl_read_pkg_manifest(const char *gpkg_path, gl_pkg_t *pkg); +int gl_gpm2gpkg(const char *filename, gl_pkg_t *pkg); +void gl_free_pkg(gl_pkg_t *pkg); + +/* --- libc: process control, used by the crash/contention tests --- */ +pid_t fork(void); +pid_t waitpid(pid_t pid, int *status, int options); +int kill(pid_t pid, int sig); +void _exit(int status); +unsigned int sleep(unsigned int seconds); + +/* --- libc: mount, used by the EXDEV test --- */ +int mount(const char *source, const char *target, const char *filesystemtype, + unsigned long mountflags, const void *data); +int umount2(const char *target, int flags); + +/* --- sha256.h (libglacier_verify.so, private) --- */ +typedef struct { + uint32_t state[8]; + uint64_t bitlen; + uint8_t data[64]; + size_t datalen; +} gl_sha256_ctx_t; + +void gl_sha256_init(gl_sha256_ctx_t *ctx); +void gl_sha256_update(gl_sha256_ctx_t *ctx, const uint8_t *data, size_t len); +void gl_sha256_final(gl_sha256_ctx_t *ctx, uint8_t digest[32]); +void gl_sha256_to_hex(const uint8_t digest[32], char *out); + +/* --- sign.h (libglacier_verify.so, private) --- */ +typedef enum { + GL_SIGN_OK = 0, + GL_SIGN_ERR_IO = 1, + GL_SIGN_ERR_FORMAT = 2, + GL_SIGN_ERR_ENCRYPTED = 3, + GL_SIGN_ERR_KEYNUM = 4, + GL_SIGN_ERR_BAD = 5, + GL_SIGN_ERR_TOOBIG = 6, + GL_SIGN_ERR_RANDOM = 7, + GL_SIGN_ERR_EXISTS = 8, + GL_SIGN_ERR_WRITE = 9, +} gl_sign_status_t; + +typedef struct { + uint8_t keynum[8]; + uint8_t key[32]; +} gl_sign_pubkey_t; + +typedef struct { + uint8_t keynum[8]; + uint8_t sig[64]; +} gl_sign_sig_t; + +int gl_sign_read_pubkey(const char *path, gl_sign_pubkey_t *out); +int gl_sign_check_seckey(const char *path); +int gl_sign_read_sig(const char *path, gl_sign_sig_t *out); +int gl_sign_verify(const gl_sign_pubkey_t *pub, const gl_sign_sig_t *sig, + const uint8_t *msg, size_t len); +int gl_sign_verify_file(const char *pubkey_path, const char *msg_path, + const char *sig_path); +int gl_sign_file(const char *seckey_path, const char *msg_path, + const char *sig_path); +int gl_sign_generate(const char *pubkey_path, const char *seckey_path, + const char *comment); +]] + +local M = { ffi = ffi } + +M.SCOPE_USR = 0 +M.SCOPE_SYS = 1 + +local TXN_NAMES = { + [0] = "GL_TXN_OK", [1] = "GL_TXN_ERR_LOCK", [2] = "GL_TXN_ERR_MKDIR", + [3] = "GL_TXN_ERR_PERM", [4] = "GL_TXN_ERR_RENAME", [5] = "GL_TXN_ERR_SYNC", + [6] = "GL_TXN_ERR_CLEANUP", [7] = "GL_TXN_ERR_NO_TXN", [8] = "GL_TXN_ERR_XDEV", + [9] = "GL_TXN_ERR_DEPS", +} +local INSTALL_NAMES = { + [0] = "GL_INSTALL_OK", [1] = "GL_INSTALL_ERR_OPEN", [2] = "GL_INSTALL_ERR_MANIFEST", + [3] = "GL_INSTALL_ERR_EXTRACT", [4] = "GL_INSTALL_ERR_INDEX", + [5] = "GL_INSTALL_ERR_ALREADY_INSTALLED", [6] = "GL_INSTALL_SKIPPED", + [7] = "GL_INSTALL_ERR_SCOPE", [8] = "GL_INSTALL_ERR_DEPS", +} +local REMOVE_NAMES = { + [0] = "GL_REMOVE_OK", [1] = "GL_REMOVE_ERR_NOT_FOUND", + [2] = "GL_REMOVE_ERR_UNLINK", [3] = "GL_REMOVE_ERR_INDEX", + [4] = "GL_REMOVE_ERR_DEPS", +} +local SIGN_NAMES = { + [0] = "GL_SIGN_OK", [1] = "GL_SIGN_ERR_IO", [2] = "GL_SIGN_ERR_FORMAT", + [3] = "GL_SIGN_ERR_ENCRYPTED", [4] = "GL_SIGN_ERR_KEYNUM", [5] = "GL_SIGN_ERR_BAD", + [6] = "GL_SIGN_ERR_TOOBIG", [7] = "GL_SIGN_ERR_RANDOM", [8] = "GL_SIGN_ERR_EXISTS", + [9] = "GL_SIGN_ERR_WRITE", +} + +function M.txn_name(v) return TXN_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.install_name(v) return INSTALL_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.sign_name(v) return SIGN_NAMES[tonumber(v)] or ("?" .. tostring(v)) end +function M.remove_name(v) return REMOVE_NAMES[tonumber(v)] or ("?" .. tostring(v)) end + +function M.new_context() + return ffi.new("gl_context_t") +end + +-- Human-readable current errno, for reporting why a libc call (mount, +-- etc.) failed rather than just that it did. Must be called immediately +-- after the failing call, before any other libc-touching code runs. +function M.strerror() + local err = ffi.errno() + return err .. " (" .. ffi.string(ffi.C.strerror(err)) .. ")" +end + +-- This module's own directory on disk, independent of CWD and +-- independent of how deeply nested the require()ing script is. Lua's +-- debug.getinfo(1, "S").source gives the path this exact file was +-- loaded from, prefixed with "@" for a real file — not the path of +-- whoever called into it. +local function this_dir() + local src = debug.getinfo(1, "S").source + if src:sub(1, 1) == "@" then src = src:sub(2) end + return src:match("(.*/)") or "./" +end + +-- Loads the combined library. Resolution order: +-- 1. an explicit path argument +-- 2. LIBGLACIER_SO env var +-- 3. glacier/libglacier-ng.so relative to *this file's own location* +-- (i.e. /lib/glacier/libglacier-ng.so), not CWD — +-- this is what makes M.load() work correctly no matter where the +-- calling script was invoked from. +function M.load(path) + local target = path or os.getenv("LIBGLACIER_SO") + or (this_dir() .. "glacier/libglacier-ng.so") + local ok, lib = pcall(ffi.load, target) + if not ok then + io.stderr:write(string.format( + "glacier_cdef: could not load %s (%s)\n" .. + "Set LIBGLACIER_SO to the full path of the built .so if it isn't at the default location.\n", + target, tostring(lib))) + os.exit(1) + end + return lib +end + +return M diff --git a/lib/gpkg_build.lua b/lib/gpkg_build.lua new file mode 100644 index 0000000..467e32b --- /dev/null +++ b/lib/gpkg_build.lua @@ -0,0 +1,695 @@ +-- lib/gpkg_build.lua +-- +-- The package builder (BUILD_DESIGN.txt): turns a recipe from a NAME-src +-- repository into a .gpkg, built in gsandbox, which gpkg_common then +-- installs like any fetched package. Used only through gpkg_common. +-- +-- Nothing a build produces is trusted: the output is copied privately +-- while hashed and its manifest (read by the library) must be exactly +-- the one handed in. What IS trusted is what decides the build: the +-- bundle (hash from the signed index, then checked by gl_recipe_read), +-- each source (the recipe's SHA256), the layers (packages verified +-- against their signed indexes) and this file and build-driver.sh. + +local ffi = require("ffi") +local bit = require("bit") + +local M = {} + +-- Set by M.init(): FFI handles and gpkg_common's helpers. +local log, istore, txn, h + +function M.init(env) + log, istore, txn = env.log, env.istore, env.txn + h = env +end + +local SYSTEM_CONF = "/etc/glacier/glacier.conf" +local SYSTEM_CONFIG_DIR = "/etc/glacier/config" + +-- --------------------------------------------------------------------- +-- Small helpers +-- --------------------------------------------------------------------- + +local function lines(s) + local out = {} + for l in (s or ""):gmatch("([^\n]*)\n") do table.insert(out, l) end + return out +end + +local function exists(path) + local f = io.open(path, "rb") + if f then f:close() return true end + local ok = os.execute("test -e " .. h.shell_quote(path)) + return ok == true or ok == 0 +end + +-- The exit status of a shell command line. +local function status_of(cmd) + local p = io.popen(cmd .. "; echo \"rc=$?\"") + local out = p:read("*a") + p:close() + return tonumber(out:match("rc=(%d+)%s*$")) or 255 +end + +local function sh_ok(cmd) + return status_of(cmd .. " >/dev/null 2>&1") == 0 +end + +-- A libconfig string literal. +local function cfg_string(s) + return '"' .. s:gsub("\\", "\\\\"):gsub('"', '\\"') .. '"' +end + +-- --------------------------------------------------------------------- +-- Settings (BUILD_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +-- One configuration file's build settings, or nil if it doesn't exist. +-- Exits if it is malformed (or, read by syspkg, untrusted). +local conf_cache = {} +local function read_conf(path, kind, opts) + if conf_cache[path] ~= nil then return conf_cache[path] or nil end + if not exists(path) then + conf_cache[path] = false + return nil + end + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(path) + end + local c = ffi.new("gl_build_conf_t") + if tonumber(istore.gl_conf_build(path, kind, c)) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + h.finish(1) + end + local function str(v) return v ~= nil and ffi.string(v) or nil end + local r = { + traits = lines(str(c.traits)), cflags = str(c.cflags), + cxxflags = str(c.cxxflags), ldflags = str(c.ldflags), + configure = lines(str(c.configure)), + jobs = c.jobs > 0 and tonumber(c.jobs) or nil, + build_user = str(c.build_user), build_root = lines(str(c.build_root)), + path = path, + } + istore.gl_build_conf_free(c) + conf_cache[path] = r + return r +end + +-- The user's base directory (, beside index and store). +local function user_base(opts) + return string.format("/glacier/usr/%d", opts.uid) +end + +-- The configuration layers for package `name`, lowest first: +-- { global = {...}, package = {...} } lists of read_conf results. +local function conf_layers(name, opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if opts.scope == ffi.C.GL_SCOPE_SYS then + return { sys }, read_conf(SYSTEM_CONFIG_DIR .. "/" .. name .. ".conf", + ffi.C.GL_CONF_PACKAGE, opts) + end + local base = user_base(opts) .. "/config" + return { sys, read_conf(base .. "/glacier.conf", ffi.C.GL_CONF_USER, opts) }, + read_conf(base .. "/" .. name .. ".conf", ffi.C.GL_CONF_PACKAGE, opts) +end + +-- The system's settings a build can't do without: BUILD_ROOT, and for +-- syspkg BUILD_USER (its uid too). Exits saying which is missing. +local function system_settings(opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if not sys then + log.lg_printf(2, "Cannot read %s.", SYSTEM_CONF) + h.finish(1) + end + if #sys.build_root == 0 then + log.lg_printf(2, "BUILD_ROOT is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local s = { build_root = sys.build_root } + if opts.scope == ffi.C.GL_SCOPE_SYS then + if not sys.build_user then + log.lg_printf(2, "BUILD_USER is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local p = io.popen("id -u -- " .. h.shell_quote(sys.build_user) .. " 2>/dev/null") + local uid = tonumber(p and p:read("*l") or "") + if p then p:close() end + if not uid then + log.lg_printf(2, "BUILD_USER %s in %s is not a user.", sys.build_user, + SYSTEM_CONF) + h.finish(1) + elseif uid == 0 then + log.lg_printf(2, "BUILD_USER in %s must not be root.", SYSTEM_CONF) + h.finish(1) + end + s.build_user, s.build_uid = sys.build_user, uid + end + return s +end + +--- The effective traits of building `name`, whose recipe (or -src index +--- entry) declares `declared` ("NAME D\n" lines). Returns a table +--- { on = { trait = bool }, list = sorted { "ssl", "-ldap" }, show = +--- "[+ssl -ldap]" (or "" with no traits) }. Exits if a per-package file +--- names a trait the recipe doesn't declare. +function M.traits(name, declared, opts) + local on, names = {}, {} + for _, l in ipairs(lines(declared)) do + local t, d = l:match("^(%S+) ([01])$") + on[t] = d == "1" + table.insert(names, t) + end + local function apply(conf, strict) + if not conf then return end + for _, s in ipairs(conf.traits) do + local neg = s:sub(1, 1) == "-" + local t = neg and s:sub(2) or s + if on[t] ~= nil then + on[t] = not neg + elseif strict then + log.lg_printf(2, "%s: %s has no trait %s.", conf.path, name, t) + h.finish(1) + end + end + end + local globals, pkg = conf_layers(name, opts) + for _, g in ipairs(globals) do apply(g, false) end + apply(pkg, true) + + table.sort(names) + local list, show = {}, {} + for _, t in ipairs(names) do + table.insert(list, on[t] and t or ("-" .. t)) + table.insert(show, (on[t] and "+" or "-") .. t) + end + return { on = on, list = list, + show = #show > 0 and ("[" .. table.concat(show, " ") .. "]") or "" } +end + +--- Relation lines ("NAME VER[ IF]\n") with their IF resolved against +--- traits `tr`: "NAME VER\n" for each that applies. +function M.effective(rel, tr) + local out = {} + for _, l in ipairs(lines(rel)) do + local n, v, c = l:match("^(%S+) (%S+) ?(%S*)$") + local applies = c == "" or + (c:sub(1, 1) == "-" and not tr.on[c:sub(2)]) or + (c:sub(1, 1) ~= "-" and tr.on[c]) + if applies then table.insert(out, n .. " " .. v .. "\n") end + end + return table.concat(out) +end + +--- Check, before the prompt, everything a build of `name` needs from +--- the configuration (exits on a problem): BUILD_ROOT, BUILD_USER. +function M.check(opts) + if opts.sysroot then + log.lg_printf(2, "Building from source under -R is not supported.") + h.finish(1) + end + system_settings(opts) + -- gsandbox and the driver decide what a build produces, which + -- root then installs: checked like syspkg's own files, here + -- rather than at startup, since only builds need them. + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(h.gsandbox_path) + h.require_trusted(h.lib_dir .. "/build-driver.sh") + end +end + +-- --------------------------------------------------------------------- +-- The build +-- --------------------------------------------------------------------- + +-- /build/NAME, made and checked by the library; owned by the +-- builder (`owner` = BUILD_USER's uid, syspkg) or the scope. +local function build_dir(ctx, name, owner) + local out = ffi.new("char[4096]") + if txn.gl_scope_build_dir(ctx, name, owner or -1, out) ~= 0 then + h.finish(1) -- the library said why + end + return ffi.string(out) +end + +-- Remove a build's directory tree (the builder's files may be +-- read-only to it: overlayfs's work dir is mode 000). +local function remove_tree(path) + os.execute("chmod -R u+rwX " .. h.shell_quote(path) .. " 2>/dev/null; rm -rf " + .. h.shell_quote(path)) +end + +-- Copy a file (cp, then the given mode). +local function copy_file(src, dst, mode) + return sh_ok("cp -- " .. h.shell_quote(src) .. " " .. h.shell_quote(dst)) + and sh_ok("chmod " .. mode .. " " .. h.shell_quote(dst)) +end + +-- Fetch a source URL (https through curl, file:// a copy) into dest +-- hashed: true if it arrived and has hash `hex`. Redirects are +-- followed, https only (release tarballs are mostly served that way); +-- the hash decides. +local MAX_SOURCE = 4 * 1024 * 1024 * 1024 +local function fetch_source(url, dest, hex) + local tmp = dest .. ".part" + os.remove(tmp) + local cmd + local path = url:match("^file://(/.*)$") + if path then + cmd = "cp -- " .. h.shell_quote(path) .. " " .. h.shell_quote(tmp) + else + cmd = "curl -sfL --max-redirs 5 --proto =https --proto-redir =https --connect-timeout 30" .. + " --max-filesize " .. MAX_SOURCE .. " -o " .. h.shell_quote(tmp) .. + " -- " .. h.shell_quote(url) + end + if not sh_ok(cmd) then + os.remove(tmp) + return false, false + end + if h.sha256_file(tmp) ~= hex then + os.remove(tmp) + return false, true + end + return os.rename(tmp, dest) ~= nil +end + +-- The libconfig manifest a build must produce. +local function manifest_text(r, deps, confs, tr) + local function rel(text) + local out = {} + for n, v in text:gmatch("(%S+) (%S+)\n") do + table.insert(out, string.format('{ PKG_NAME = "%s"; PKG_VER = "%s"; }', n, v)) + end + return "(" .. table.concat(out, ", ") .. ")" + end + local t = {} + for _, s in ipairs(tr.list) do table.insert(t, '"' .. s .. '"') end + return table.concat({ + "PKG_NAME = " .. cfg_string(r.name) .. ";", + "PKG_VER = " .. cfg_string(r.ver) .. ";", + "PKG_DESC = " .. cfg_string(r.desc) .. ";", + "PKG_MAINT = " .. cfg_string(r.maint) .. ";", + "PKG_COPYRIGHT = " .. cfg_string(r.copyright) .. ";", + "PKG_REPO = " .. cfg_string(r.repo) .. ";", + "PKG_DEPS = " .. rel(deps) .. ";", + "PKG_CONFS = " .. rel(confs) .. ";", + "PKG_TRAITS = [ " .. table.concat(t, ", ") .. " ];", + }, "\n") .. "\n" +end + +-- The driver's env file: shell assignments, every value quoted. +local function env_text(r, settings, tr, sources, prefix) + local q = h.shell_quote + local args = {} + for _, a in ipairs(lines(r.configure)) do table.insert(args, q(a)) end + for _, l in ipairs(lines(r.trait_args)) do + local t, side, a = l:match("^([^\t]+)\t([+-])\t(.*)$") + if (side == "+") == (tr.on[t] == true) then table.insert(args, q(a)) end + end + for _, a in ipairs(settings.configure) do table.insert(args, q(a)) end + local on = {} + for _, s in ipairs(tr.list) do + if s:sub(1, 1) ~= "-" then table.insert(on, s) end + end + local function kv(k, v) return k .. "=" .. q(v or "") .. "\n" end + return kv("NAME", r.name) .. kv("VER", r.ver) .. kv("BUILD", r.build) .. + kv("PREFIX", prefix) .. + kv("SOURCES", table.concat(sources, " ")) .. + kv("PATCHES", table.concat(lines(r.patches), " ")) .. + kv("CONFIGURE_ARGS", table.concat(args, " ")) .. + kv("TRAITS", table.concat(on, " ")) .. + kv("JOBS", tostring(settings.jobs)) .. + kv("CFLAGS", settings.cflags) .. kv("CXXFLAGS", settings.cxxflags) .. + kv("LDFLAGS", settings.ldflags) +end + +-- CFLAGS/CXXFLAGS/LDFLAGS/CONFIGURE/JOBS for package `name`: the +-- per-package value replaces the global one; the user's global replaces +-- the system's. +local function flags_for(name, opts) + local globals, pkg = conf_layers(name, opts) + local s = { configure = pkg and pkg.configure or {}, jobs = 1 } + for _, k in ipairs({ "cflags", "cxxflags", "ldflags" }) do + for _, g in ipairs(globals) do + if g and g[k] then s[k] = g[k] end + end + if pkg and pkg[k] then s[k] = pkg[k] end + end + for _, g in ipairs(globals) do + if g and g.jobs then s.jobs = g.jobs end + end + return s +end + +-- Whether the private copy `path`'s manifest (read by the library) is +-- exactly what the build was handed. +local function output_matches(path, r, deps, confs, tr) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then return false end + local want_traits = #tr.list > 0 and (table.concat(tr.list, "\n") .. "\n") or "" + local ok = ffi.string(m.pkg_name) == r.name + and ffi.string(m.pkg_repo) == r.repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == r.ver + and h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == deps + and h.relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == confs + and m.pkg_traits ~= nil and ffi.string(m.pkg_traits) == want_traits + istore.gl_free_pkg(m) + return ok +end + +-- The recipe of a verified bundle copy, as a table, or nil and why. +local function read_recipe(path) + local r = ffi.new("gl_recipe_t") + if tonumber(istore.gl_recipe_read(path, r)) ~= 0 then + return nil, ffi.string(istore.gl_recipe_error()) + end + local t = {} + for _, k in ipairs({ "name", "ver", "repo", "desc", "maint", "copyright", + "sources", "patches", "build", "configure", "traits", "trait_args", + "deps", "build_deps", "confs" }) do + t[k] = ffi.string(r[k]) + end + istore.gl_recipe_free(r) + return t +end + +-- The packages a build stacks as layers: BUILD_ROOT, the effective +-- BUILD_DEPS and DEPS, and everything they depend on, each from +-- `built` (this run's own builds), `kept` (installed source builds, +-- M.kept) or the binary repositories, in that order, at a high enough +-- version. A list of { name, path, sha (hex) }, top first. Exits if +-- one can't be had. +local function layer_plan(id, root_names, build_deps, deps, indexes, built, kept) + local plan, seen = {}, {} + local queue = {} + for _, rel in ipairs({ deps, build_deps }) do + for n, v in rel:gmatch("(%S+) (%S+)\n") do table.insert(queue, { n, v }) end + end + for _, n in ipairs(root_names) do table.insert(queue, { n, "0.0.0" }) end + local k = 1 + while k <= #queue do + local n, v = queue[k][1], queue[k][2] + k = k + 1 + if not seen[n] then + seen[n] = true + local b = built[n] + if not (b and h.vercmp(b.ver, v) >= 0) then b = kept[n] end + if b and b.path and not b.sha then b.sha = h.sha256_file(b.path) or false end + if b and b.sha ~= false and h.vercmp(b.ver, v) >= 0 then + table.insert(plan, { name = n, ver = b.ver, path = b.path, sha = b.sha }) + for dn, dv in b.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + else + -- indexes.layers: base too, even for gpkg + local r, e = h.pick_binary(indexes.layers or indexes, n) + if not e or h.vercmp(e.ver, v) < 0 then + log.lg_printf(2, "%s needs %s %s or later to build, and no binary repository has it.", + id, n, v) + h.finish(1) + end + table.insert(plan, { name = n, ver = e.ver, repo = r, entry = e, + sha = e.sha256:match("^sha256:(%x+)$") }) + for dn, dv in e.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + end + end + end + return plan +end + +--- Check, before the prompt, that every layer a build of plan item `it` +--- needs can be had (exits otherwise). `planned` maps the names this +--- run builds to { ver, deps }. +function M.check_layers(it, indexes, planned, opts) + local settings = system_settings(opts) + local id = string.format("%s::%s %s", it.repo.name, it.entry.name, it.entry.ver) + layer_plan(id, settings.build_root, M.effective(it.entry.build_deps, it.traits), + it.deps, indexes, planned, M.kept(opts)) +end + +--- Build plan item `it` (a -src repository's entry, with it.traits from +--- M.traits) into a verified private copy of its .gpkg. `built` maps +--- names this run has already built to { ver, path, sha }, for layers. +--- Returns the copy and its sidecar text; exits on any failure. +function M.build(it, indexes, built, opts) + local e, r_src = it.entry, it.repo + local id = string.format("%s::%s %s", r_src.name, e.name, e.ver) + local settings = system_settings(opts) + local owner = settings.build_uid + local ctx = h.live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600" + + -- The bundle: downloaded and hashed against the signed index, + -- copied privately, then read and checked by the library. + local cached, wrong = h.download(ctx, r_src, e, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + local copy = cached and h.verify_and_copy(cached, e.sha256 .. "\n") + local r, bad = nil, nil + if copy then r, bad = read_recipe(copy) end + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + h.finish(1) + end + if bad then + log.lg_printf(2, "%s has a malformed recipe bundle: %s.", id, bad) + if cached then os.remove(cached) end + h.finish(1) + end + if not r or r.name ~= e.name or r.ver ~= e.ver or r.repo .. "-src" ~= r_src.name + or r.deps ~= e.deps or r.confs ~= e.confs or r.build_deps ~= e.build_deps + or r.traits ~= e.traits then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + h.finish(1) + end + if cached then os.remove(cached) end + + local tr = it.traits + local deps, confs = M.effective(r.deps, tr), M.effective(r.confs, tr) + local build_deps = M.effective(r.build_deps, tr) + local flags = flags_for(r.name, opts) + + -- The prefix the package is built for: where its usr/ will be + -- linked, so it finds its own files at run time. /usr for base, + -- else the scope's links (no -R here: these are runtime paths). + local prefix = r.repo == "base" and "/usr" or + (ffi.string(ctx.links_path):gsub("/+$", "")) + + -- Sources, by hash, in /build/sources. + local sources_dir = build_dir(ctx, "sources") + local sources = {} + for url, hex in r.sources:gmatch("(%S+) sha256:(%x+)\n") do + local file = url:match("([^/]+)$") + local dest = sources_dir .. "/" .. hex + if h.sha256_file(dest) ~= hex then + local ok, mismatch = fetch_source(url, dest, hex) + if not ok then + log.lg_printf(2, mismatch and "A source of %s does not match its hash." + or "Cannot fetch the sources of %s.", id) + h.finish(1) + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(dest)) + end + table.insert(sources, { file = file, path = dest }) + end + + -- This build's input (the scope's) and work/output (the builder's). + local tag = string.format("%s-%s-%d", r.name, r.ver, ffi.C.gpkg_build_getpid()) + local in_dir = build_dir(ctx, "in-" .. tag) + local work = build_dir(ctx, "work-" .. tag, owner) + local out = build_dir(ctx, "out-" .. tag, owner) + local function cleanup() + remove_tree(in_dir) + remove_tree(work) + remove_tree(out) + end + local function fail(fmt, ...) + log.lg_printf(2, fmt, ...) + cleanup() + h.finish(1) + end + + -- Layers, extracted once each into /build/layers by the + -- builder: NAME-VER-. + local layers_dir = build_dir(ctx, "layers", owner) + local layer_names = {} + local user_flag = settings.build_user and (" -u " .. h.shell_quote(settings.build_user)) or "" + for _, l in ipairs(layer_plan(id, settings.build_root, build_deps, deps, indexes, built, + M.kept(opts))) do + local lname = string.format("%s-%s-%s", l.name, l.ver, l.sha:sub(1, 8)) + if not exists(layers_dir .. "/" .. lname) then + local path = l.path + if l.entry then + path = h.download(ctx, l.repo, l.entry, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + if not path then fail("Cannot fetch %s::%s %s.", l.repo.name, l.name, l.ver) end + else + -- A package this run built: its private copy, + -- copied where the builder can read it. + local p = in_dir .. "/" .. lname .. ".gpkg" + if not copy_file(l.path, p, "644") then + fail("Cannot write %s.", p) + end + path = p + end + local tmp = string.format(".%s.%d", lname, ffi.C.gpkg_build_getpid()) + if not sh_ok(h.gsandbox .. " -X" .. user_flag .. " -p " .. h.shell_quote(path) .. + " -d " .. h.shell_quote(layers_dir .. "/" .. tmp)) then + fail("Cannot extract %s %s for %s.", l.name, l.ver, id) + end + if not os.rename(layers_dir .. "/" .. tmp, layers_dir .. "/" .. lname) then + remove_tree(layers_dir .. "/" .. tmp) + end + end + table.insert(layer_names, lname) + end + + -- The input: bundle, sources, manifest, env, driver. + local function put(name, text) + local f = io.open(in_dir .. "/" .. name, "wb") + if not f or not f:write(text) then fail("Cannot write %s/%s.", in_dir, name) end + f:close() + if not sh_ok("chmod 644 " .. h.shell_quote(in_dir .. "/" .. name)) then + fail("Cannot write %s/%s.", in_dir, name) + end + end + if not copy_file(copy, in_dir .. "/bundle.grcp", "644") or + not sh_ok("mkdir -m 755 " .. h.shell_quote(in_dir .. "/sources")) then + fail("Cannot write %s.", in_dir) + end + local files = {} + for _, s in ipairs(sources) do + if not copy_file(s.path, in_dir .. "/sources/" .. s.file, "644") then + fail("Cannot write %s.", in_dir) + end + table.insert(files, s.file) + end + put("manifest.gpm.cfg", manifest_text(r, deps, confs, tr)) + put("env", env_text(r, flags, tr, files, prefix)) + local df = io.open(h.lib_dir .. "/build-driver.sh", "rb") + local driver = df and df:read("*a") + if df then df:close() end + if not driver then fail("Cannot read %s/build-driver.sh.", h.lib_dir) end + put("driver", driver) + + -- The build. Its output goes to /build/logs/NAME-VER.log, + -- and to the terminal unless -q. + local log_path = build_dir(ctx, "logs") .. "/" .. r.name .. "-" .. r.ver .. ".log" + local cmd = h.gsandbox .. " -R" .. user_flag .. " -L " .. h.shell_quote(layers_dir) + for _, l in ipairs(layer_names) do cmd = cmd .. " -l " .. h.shell_quote(l) end + cmd = cmd .. " -w " .. h.shell_quote(work) .. " -i " .. h.shell_quote(in_dir) .. + " -o " .. h.shell_quote(out) + log.lg_printf(0, "Building %s%s...", id, tr.show ~= "" and (" " .. tr.show) or "") + local st + if not h.quiet() then + local stf = in_dir .. "/.status" + os.execute("{ " .. cmd .. " 2>&1; echo $? > " .. h.shell_quote(stf) .. "; } | tee " + .. h.shell_quote(log_path)) + local f = io.open(stf, "r") + st = f and tonumber(f:read("*l")) or 255 + if f then f:close() end + else + st = status_of(cmd .. " > " .. h.shell_quote(log_path) .. " 2>&1") + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(log_path)) + if st ~= 0 then + fail("Building %s failed. Log: %s", id, log_path) + end + + -- The output, untrusted: copied privately while hashed, then its + -- manifest must be exactly the one handed in. + local result = out .. "/" .. r.name .. "-" .. r.ver .. ".gpkg" + local hex = h.sha256_file(result) + local pkg = hex and h.verify_and_copy(result, "sha256:" .. hex .. "\n") + if not pkg or not output_matches(pkg, r, deps, confs, tr) then + fail("%s: the build produced another package.", id) + end + cleanup() + log.lg_printf(3, "Built %s.", id) + return pkg, "sha256:" .. hex .. "\n", hex +end + +-- --------------------------------------------------------------------- +-- Kept packages: the verified .gpkg of each installed source build, +-- the bytes that were installed, so a later build can use it as a +-- layer (no binary repository has it). /build/packages/ +-- REPO@NAME-VER.gpkg ('@' is in no name), kept while that version is +-- installed and built from source. +-- --------------------------------------------------------------------- + +local function kept_name(repo, name, ver) + return repo .. "@" .. name .. "-" .. ver .. ".gpkg" +end + +-- /build/packages, or nil if there is none (not made here). +local function kept_dir(ctx) + local d = ffi.string(ctx.store_path):gsub("/store$", "") .. "/build/packages" + return exists(d) and d or nil +end + +-- The kept packages of the installed source builds: the file names a +-- prune leaves, and (for layer_plan) name -> { ver, path, deps }. +local function kept_scan(opts) + local ctx = h.live_context(opts) + local dir = kept_dir(ctx) + if not dir then return nil, {}, {} end + local want, by_name = {}, {} + for _, i in ipairs(h.installed_entries(opts)) do + if h.built_from(ctx, i.repo, i.name) then + local f = kept_name(i.repo, i.name, i.ver) + local path = dir .. "/" .. f + want[f] = true + local m = ffi.new("gl_pkg_t") + if exists(path) and istore.gl_read_pkg_manifest(path, m) == 0 then + by_name[i.name] = { ver = i.ver, path = path, + deps = h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") } + istore.gl_free_pkg(m) + end + end + end + return dir, want, by_name +end + +--- The installed source builds a build can use as layers: name -> +--- { ver, path, deps }. +function M.kept(opts) + local _, _, by_name = kept_scan(opts) + return by_name +end + +--- After a commit: keep the private copy `path` of a package this run +--- built and installed (repo::name ver). A failure only warns: the +--- package is installed, and only later builds would miss it. +function M.keep(opts, path, repo, name, ver) + local ctx = h.live_context(opts) + local out = ffi.new("char[4096]") + local ok = txn.gl_scope_build_dir(ctx, "packages", -1, out) == 0 + local dest = ok and (ffi.string(out) .. "/" .. kept_name(repo, name, ver)) + if not ok or not copy_file(path, dest .. ".part", + opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600") + or not os.rename(dest .. ".part", dest) then + if dest then os.remove(dest .. ".part") end + log.lg_printf(1, "Could not keep %s::%s %s for later builds.", repo, name, ver) + end +end + +--- After a commit: delete the kept packages that are no longer an +--- installed source build (removed, replaced, or reinstalled from a +--- binary repository). +function M.prune_kept(opts) + local dir, want = kept_scan(opts) + if not dir then return end + local p = io.popen("ls -A -- " .. h.shell_quote(dir)) + for f in p:lines() do + if not want[f] then os.remove(dir .. "/" .. f) end + end + p:close() +end + +ffi.cdef[[ +int gpkg_build_getpid(void) asm("getpid"); +]] + +return M diff --git a/lib/gpkg_build.lua.old b/lib/gpkg_build.lua.old new file mode 100644 index 0000000..5166b1b --- /dev/null +++ b/lib/gpkg_build.lua.old @@ -0,0 +1,593 @@ +-- lib/gpkg_build.lua +-- +-- The package builder (BUILD_DESIGN.txt): turns a recipe from a NAME-src +-- repository into a .gpkg, built in gsandbox, which gpkg_common then +-- installs like any fetched package. Used only through gpkg_common. +-- +-- Nothing a build produces is trusted: the output is copied privately +-- while hashed and its manifest (read by the library) must be exactly +-- the one handed in. What IS trusted is what decides the build: the +-- bundle (hash from the signed index, then checked by gl_recipe_read), +-- each source (the recipe's SHA256), the layers (packages verified +-- against their signed indexes) and this file and build-driver.sh. + +local ffi = require("ffi") +local bit = require("bit") + +local M = {} + +-- Set by M.init(): FFI handles and gpkg_common's helpers. +local log, istore, txn, h + +function M.init(env) + log, istore, txn = env.log, env.istore, env.txn + h = env +end + +local SYSTEM_CONF = "/etc/glacier/glacier.conf" +local SYSTEM_CONFIG_DIR = "/etc/glacier/config" + +-- --------------------------------------------------------------------- +-- Small helpers +-- --------------------------------------------------------------------- + +local function lines(s) + local out = {} + for l in (s or ""):gmatch("([^\n]*)\n") do table.insert(out, l) end + return out +end + +local function exists(path) + local f = io.open(path, "rb") + if f then f:close() return true end + local ok = os.execute("test -e " .. h.shell_quote(path)) + return ok == true or ok == 0 +end + +-- The exit status of a shell command line. +local function status_of(cmd) + local p = io.popen(cmd .. "; echo \"rc=$?\"") + local out = p:read("*a") + p:close() + return tonumber(out:match("rc=(%d+)%s*$")) or 255 +end + +local function sh_ok(cmd) + return status_of(cmd .. " >/dev/null 2>&1") == 0 +end + +-- A libconfig string literal. +local function cfg_string(s) + return '"' .. s:gsub("\\", "\\\\"):gsub('"', '\\"') .. '"' +end + +-- --------------------------------------------------------------------- +-- Settings (BUILD_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +-- One configuration file's build settings, or nil if it doesn't exist. +-- Exits if it is malformed (or, read by syspkg, untrusted). +local conf_cache = {} +local function read_conf(path, kind, opts) + if conf_cache[path] ~= nil then return conf_cache[path] or nil end + if not exists(path) then + conf_cache[path] = false + return nil + end + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(path) + end + local c = ffi.new("gl_build_conf_t") + if tonumber(istore.gl_conf_build(path, kind, c)) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + h.finish(1) + end + local function str(v) return v ~= nil and ffi.string(v) or nil end + local r = { + traits = lines(str(c.traits)), cflags = str(c.cflags), + cxxflags = str(c.cxxflags), ldflags = str(c.ldflags), + configure = lines(str(c.configure)), + jobs = c.jobs > 0 and tonumber(c.jobs) or nil, + build_user = str(c.build_user), build_root = lines(str(c.build_root)), + path = path, + } + istore.gl_build_conf_free(c) + conf_cache[path] = r + return r +end + +-- The user's base directory (, beside index and store). +local function user_base(opts) + return string.format("/glacier/usr/%d", opts.uid) +end + +-- The configuration layers for package `name`, lowest first: +-- { global = {...}, package = {...} } lists of read_conf results. +local function conf_layers(name, opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if opts.scope == ffi.C.GL_SCOPE_SYS then + return { sys }, read_conf(SYSTEM_CONFIG_DIR .. "/" .. name .. ".conf", + ffi.C.GL_CONF_PACKAGE, opts) + end + local base = user_base(opts) .. "/config" + return { sys, read_conf(base .. "/glacier.conf", ffi.C.GL_CONF_USER, opts) }, + read_conf(base .. "/" .. name .. ".conf", ffi.C.GL_CONF_PACKAGE, opts) +end + +-- The system's settings a build can't do without: BUILD_ROOT, and for +-- syspkg BUILD_USER (its uid too). Exits saying which is missing. +local function system_settings(opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if not sys then + log.lg_printf(2, "Cannot read %s.", SYSTEM_CONF) + h.finish(1) + end + if #sys.build_root == 0 then + log.lg_printf(2, "BUILD_ROOT is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local s = { build_root = sys.build_root } + if opts.scope == ffi.C.GL_SCOPE_SYS then + if not sys.build_user then + log.lg_printf(2, "BUILD_USER is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local p = io.popen("id -u -- " .. h.shell_quote(sys.build_user) .. " 2>/dev/null") + local uid = tonumber(p and p:read("*l") or "") + if p then p:close() end + if not uid then + log.lg_printf(2, "BUILD_USER %s in %s is not a user.", sys.build_user, + SYSTEM_CONF) + h.finish(1) + elseif uid == 0 then + log.lg_printf(2, "BUILD_USER in %s must not be root.", SYSTEM_CONF) + h.finish(1) + end + s.build_user, s.build_uid = sys.build_user, uid + end + return s +end + +--- The effective traits of building `name`, whose recipe (or -src index +--- entry) declares `declared` ("NAME D\n" lines). Returns a table +--- { on = { trait = bool }, list = sorted { "ssl", "-ldap" }, show = +--- "[+ssl -ldap]" (or "" with no traits) }. Exits if a per-package file +--- names a trait the recipe doesn't declare. +function M.traits(name, declared, opts) + local on, names = {}, {} + for _, l in ipairs(lines(declared)) do + local t, d = l:match("^(%S+) ([01])$") + on[t] = d == "1" + table.insert(names, t) + end + local function apply(conf, strict) + if not conf then return end + for _, s in ipairs(conf.traits) do + local neg = s:sub(1, 1) == "-" + local t = neg and s:sub(2) or s + if on[t] ~= nil then + on[t] = not neg + elseif strict then + log.lg_printf(2, "%s: %s has no trait %s.", conf.path, name, t) + h.finish(1) + end + end + end + local globals, pkg = conf_layers(name, opts) + for _, g in ipairs(globals) do apply(g, false) end + apply(pkg, true) + + table.sort(names) + local list, show = {}, {} + for _, t in ipairs(names) do + table.insert(list, on[t] and t or ("-" .. t)) + table.insert(show, (on[t] and "+" or "-") .. t) + end + return { on = on, list = list, + show = #show > 0 and ("[" .. table.concat(show, " ") .. "]") or "" } +end + +--- Relation lines ("NAME VER[ IF]\n") with their IF resolved against +--- traits `tr`: "NAME VER\n" for each that applies. +function M.effective(rel, tr) + local out = {} + for _, l in ipairs(lines(rel)) do + local n, v, c = l:match("^(%S+) (%S+) ?(%S*)$") + local applies = c == "" or + (c:sub(1, 1) == "-" and not tr.on[c:sub(2)]) or + (c:sub(1, 1) ~= "-" and tr.on[c]) + if applies then table.insert(out, n .. " " .. v .. "\n") end + end + return table.concat(out) +end + +--- Check, before the prompt, everything a build of `name` needs from +--- the configuration (exits on a problem): BUILD_ROOT, BUILD_USER. +function M.check(opts) + if opts.sysroot then + log.lg_printf(2, "Building from source under -R is not supported.") + h.finish(1) + end + system_settings(opts) + -- gsandbox and the driver decide what a build produces, which + -- root then installs: checked like syspkg's own files, here + -- rather than at startup, since only builds need them. + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(h.gsandbox_path) + h.require_trusted(h.lib_dir .. "/build-driver.sh") + end +end + +-- --------------------------------------------------------------------- +-- The build +-- --------------------------------------------------------------------- + +-- /build/NAME, made and checked by the library; owned by the +-- builder (`owner` = BUILD_USER's uid, syspkg) or the scope. +local function build_dir(ctx, name, owner) + local out = ffi.new("char[4096]") + if txn.gl_scope_build_dir(ctx, name, owner or -1, out) ~= 0 then + h.finish(1) -- the library said why + end + return ffi.string(out) +end + +-- Remove a build's directory tree (the builder's files may be +-- read-only to it: overlayfs's work dir is mode 000). +local function remove_tree(path) + os.execute("chmod -R u+rwX " .. h.shell_quote(path) .. " 2>/dev/null; rm -rf " + .. h.shell_quote(path)) +end + +-- Copy a file (cp, then the given mode). +local function copy_file(src, dst, mode) + return sh_ok("cp -- " .. h.shell_quote(src) .. " " .. h.shell_quote(dst)) + and sh_ok("chmod " .. mode .. " " .. h.shell_quote(dst)) +end + +-- Fetch a source URL (https through curl, file:// a copy) into dest +-- hashed: true if it arrived and has hash `hex`. +local MAX_SOURCE = 4 * 1024 * 1024 * 1024 +local function fetch_source(url, dest, hex) + local tmp = dest .. ".part" + os.remove(tmp) + local cmd + local path = url:match("^file://(/.*)$") + if path then + cmd = "cp -- " .. h.shell_quote(path) .. " " .. h.shell_quote(tmp) + else + cmd = "curl -sf --proto =https --proto-redir =https --connect-timeout 30" .. + " --max-filesize " .. MAX_SOURCE .. " -o " .. h.shell_quote(tmp) .. + " -- " .. h.shell_quote(url) + end + if not sh_ok(cmd) then + os.remove(tmp) + return false, false + end + if h.sha256_file(tmp) ~= hex then + os.remove(tmp) + return false, true + end + return os.rename(tmp, dest) ~= nil +end + +-- The libconfig manifest a build must produce. +local function manifest_text(r, deps, confs, tr) + local function rel(text) + local out = {} + for n, v in text:gmatch("(%S+) (%S+)\n") do + table.insert(out, string.format('{ PKG_NAME = "%s"; PKG_VER = "%s"; }', n, v)) + end + return "(" .. table.concat(out, ", ") .. ")" + end + local t = {} + for _, s in ipairs(tr.list) do table.insert(t, '"' .. s .. '"') end + return table.concat({ + "PKG_NAME = " .. cfg_string(r.name) .. ";", + "PKG_VER = " .. cfg_string(r.ver) .. ";", + "PKG_DESC = " .. cfg_string(r.desc) .. ";", + "PKG_MAINT = " .. cfg_string(r.maint) .. ";", + "PKG_COPYRIGHT = " .. cfg_string(r.copyright) .. ";", + "PKG_REPO = " .. cfg_string(r.repo) .. ";", + "PKG_DEPS = " .. rel(deps) .. ";", + "PKG_CONFS = " .. rel(confs) .. ";", + "PKG_TRAITS = [ " .. table.concat(t, ", ") .. " ];", + }, "\n") .. "\n" +end + +-- The driver's env file: shell assignments, every value quoted. +local function env_text(r, settings, tr, sources) + local q = h.shell_quote + local args = {} + for _, a in ipairs(lines(r.configure)) do table.insert(args, q(a)) end + for _, l in ipairs(lines(r.trait_args)) do + local t, side, a = l:match("^([^\t]+)\t([+-])\t(.*)$") + if (side == "+") == (tr.on[t] == true) then table.insert(args, q(a)) end + end + for _, a in ipairs(settings.configure) do table.insert(args, q(a)) end + local on = {} + for _, s in ipairs(tr.list) do + if s:sub(1, 1) ~= "-" then table.insert(on, s) end + end + local function kv(k, v) return k .. "=" .. q(v or "") .. "\n" end + return kv("NAME", r.name) .. kv("VER", r.ver) .. kv("BUILD", r.build) .. + kv("SOURCES", table.concat(sources, " ")) .. + kv("PATCHES", table.concat(lines(r.patches), " ")) .. + kv("CONFIGURE_ARGS", table.concat(args, " ")) .. + kv("TRAITS", table.concat(on, " ")) .. + kv("JOBS", tostring(settings.jobs)) .. + kv("CFLAGS", settings.cflags) .. kv("CXXFLAGS", settings.cxxflags) .. + kv("LDFLAGS", settings.ldflags) +end + +-- CFLAGS/CXXFLAGS/LDFLAGS/CONFIGURE/JOBS for package `name`: the +-- per-package value replaces the global one; the user's global replaces +-- the system's. +local function flags_for(name, opts) + local globals, pkg = conf_layers(name, opts) + local s = { configure = pkg and pkg.configure or {}, jobs = 1 } + for _, k in ipairs({ "cflags", "cxxflags", "ldflags" }) do + for _, g in ipairs(globals) do + if g and g[k] then s[k] = g[k] end + end + if pkg and pkg[k] then s[k] = pkg[k] end + end + for _, g in ipairs(globals) do + if g and g.jobs then s.jobs = g.jobs end + end + return s +end + +-- Whether the private copy `path`'s manifest (read by the library) is +-- exactly what the build was handed. +local function output_matches(path, r, deps, confs, tr) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then return false end + local want_traits = #tr.list > 0 and (table.concat(tr.list, "\n") .. "\n") or "" + local ok = ffi.string(m.pkg_name) == r.name + and ffi.string(m.pkg_repo) == r.repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == r.ver + and h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == deps + and h.relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == confs + and m.pkg_traits ~= nil and ffi.string(m.pkg_traits) == want_traits + istore.gl_free_pkg(m) + return ok +end + +-- The recipe of a verified bundle copy, as a table, or nil. +local function read_recipe(path) + local r = ffi.new("gl_recipe_t") + if tonumber(istore.gl_recipe_read(path, r)) ~= 0 then return nil end + local t = {} + for _, k in ipairs({ "name", "ver", "repo", "desc", "maint", "copyright", + "sources", "patches", "build", "configure", "traits", "trait_args", + "deps", "build_deps", "confs" }) do + t[k] = ffi.string(r[k]) + end + istore.gl_recipe_free(r) + return t +end + +-- The packages a build stacks as layers: BUILD_ROOT, the effective +-- BUILD_DEPS and DEPS, and everything they depend on, each from the +-- binary repositories (or `built`: this run's own builds). A list of +-- { name, path, sha (hex) }, top first. Exits if one can't be had. +local function layer_plan(id, root_names, build_deps, deps, indexes, built) + local plan, seen = {}, {} + local queue = {} + for _, rel in ipairs({ deps, build_deps }) do + for n, v in rel:gmatch("(%S+) (%S+)\n") do table.insert(queue, { n, v }) end + end + for _, n in ipairs(root_names) do table.insert(queue, { n, "0.0.0" }) end + local k = 1 + while k <= #queue do + local n, v = queue[k][1], queue[k][2] + k = k + 1 + if not seen[n] then + seen[n] = true + local b = built[n] + if b and h.vercmp(b.ver, v) >= 0 then + table.insert(plan, { name = n, ver = b.ver, path = b.path, sha = b.sha }) + else + local r, e = h.pick_binary(indexes, n) + if not e or h.vercmp(e.ver, v) < 0 then + log.lg_printf(2, "%s needs %s %s or later to build, and no binary repository has it.", + id, n, v) + h.finish(1) + end + table.insert(plan, { name = n, ver = e.ver, repo = r, entry = e, + sha = e.sha256:match("^sha256:(%x+)$") }) + for dn, dv in e.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + end + end + end + return plan +end + +--- Check, before the prompt, that every layer a build of plan item `it` +--- needs can be had (exits otherwise). `planned` maps the names this +--- run builds to their versions. +function M.check_layers(it, indexes, planned, opts) + local settings = system_settings(opts) + local built = {} + for n, v in pairs(planned) do built[n] = { ver = v } end + local id = string.format("%s::%s %s", it.repo.name, it.entry.name, it.entry.ver) + layer_plan(id, settings.build_root, M.effective(it.entry.build_deps, it.traits), + it.deps, indexes, built) +end + +--- Build plan item `it` (a -src repository's entry, with it.traits from +--- M.traits) into a verified private copy of its .gpkg. `built` maps +--- names this run has already built to { ver, path, sha }, for layers. +--- Returns the copy and its sidecar text; exits on any failure. +function M.build(it, indexes, built, opts) + local e, r_src = it.entry, it.repo + local id = string.format("%s::%s %s", r_src.name, e.name, e.ver) + local settings = system_settings(opts) + local owner = settings.build_uid + local ctx = h.live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600" + + -- The bundle: downloaded and hashed against the signed index, + -- copied privately, then read and checked by the library. + local cached, wrong = h.download(ctx, r_src, e, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + local copy = cached and h.verify_and_copy(cached, e.sha256 .. "\n") + local r = copy and read_recipe(copy) + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + h.finish(1) + end + if not r or r.name ~= e.name or r.ver ~= e.ver or r.repo .. "-src" ~= r_src.name + or r.deps ~= e.deps or r.confs ~= e.confs or r.build_deps ~= e.build_deps + or r.traits ~= e.traits then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + h.finish(1) + end + if cached then os.remove(cached) end + + local tr = it.traits + local deps, confs = M.effective(r.deps, tr), M.effective(r.confs, tr) + local build_deps = M.effective(r.build_deps, tr) + local flags = flags_for(r.name, opts) + + -- Sources, by hash, in /build/sources. + local sources_dir = build_dir(ctx, "sources") + local sources = {} + for url, hex in r.sources:gmatch("(%S+) sha256:(%x+)\n") do + local file = url:match("([^/]+)$") + local dest = sources_dir .. "/" .. hex + if h.sha256_file(dest) ~= hex then + local ok, mismatch = fetch_source(url, dest, hex) + if not ok then + log.lg_printf(2, mismatch and "A source of %s does not match its hash." + or "Cannot fetch the sources of %s.", id) + h.finish(1) + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(dest)) + end + table.insert(sources, { file = file, path = dest }) + end + + -- This build's input (the scope's) and work/output (the builder's). + local tag = string.format("%s-%s-%d", r.name, r.ver, ffi.C.gpkg_build_getpid()) + local in_dir = build_dir(ctx, "in-" .. tag) + local work = build_dir(ctx, "work-" .. tag, owner) + local out = build_dir(ctx, "out-" .. tag, owner) + local function cleanup() + remove_tree(in_dir) + remove_tree(work) + remove_tree(out) + end + local function fail(fmt, ...) + log.lg_printf(2, fmt, ...) + cleanup() + h.finish(1) + end + + -- Layers, extracted once each into /build/layers by the + -- builder: NAME-VER-. + local layers_dir = build_dir(ctx, "layers", owner) + local layer_names = {} + local user_flag = settings.build_user and (" -u " .. h.shell_quote(settings.build_user)) or "" + for _, l in ipairs(layer_plan(id, settings.build_root, build_deps, deps, indexes, built)) do + local lname = string.format("%s-%s-%s", l.name, l.ver, l.sha:sub(1, 8)) + if not exists(layers_dir .. "/" .. lname) then + local path = l.path + if l.entry then + path = h.download(ctx, l.repo, l.entry, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + if not path then fail("Cannot fetch %s::%s %s.", l.repo.name, l.name, l.ver) end + else + -- A package this run built: its private copy, + -- copied where the builder can read it. + local p = in_dir .. "/" .. lname .. ".gpkg" + if not copy_file(l.path, p, "644") then + fail("Cannot write %s.", p) + end + path = p + end + local tmp = string.format(".%s.%d", lname, ffi.C.gpkg_build_getpid()) + if not sh_ok(h.gsandbox .. " -X" .. user_flag .. " -p " .. h.shell_quote(path) .. + " -d " .. h.shell_quote(layers_dir .. "/" .. tmp)) then + fail("Cannot extract %s %s for %s.", l.name, l.ver, id) + end + if not os.rename(layers_dir .. "/" .. tmp, layers_dir .. "/" .. lname) then + remove_tree(layers_dir .. "/" .. tmp) + end + end + table.insert(layer_names, lname) + end + + -- The input: bundle, sources, manifest, env, driver. + local function put(name, text) + local f = io.open(in_dir .. "/" .. name, "wb") + if not f or not f:write(text) then fail("Cannot write %s/%s.", in_dir, name) end + f:close() + if not sh_ok("chmod 644 " .. h.shell_quote(in_dir .. "/" .. name)) then + fail("Cannot write %s/%s.", in_dir, name) + end + end + if not copy_file(copy, in_dir .. "/bundle.grcp", "644") or + not sh_ok("mkdir -m 755 " .. h.shell_quote(in_dir .. "/sources")) then + fail("Cannot write %s.", in_dir) + end + local files = {} + for _, s in ipairs(sources) do + if not copy_file(s.path, in_dir .. "/sources/" .. s.file, "644") then + fail("Cannot write %s.", in_dir) + end + table.insert(files, s.file) + end + put("manifest.gpm.cfg", manifest_text(r, deps, confs, tr)) + put("env", env_text(r, flags, tr, files)) + local df = io.open(h.lib_dir .. "/build-driver.sh", "rb") + local driver = df and df:read("*a") + if df then df:close() end + if not driver then fail("Cannot read %s/build-driver.sh.", h.lib_dir) end + put("driver", driver) + + -- The build. Its output goes to /build/logs/NAME-VER.log. + local log_path = build_dir(ctx, "logs") .. "/" .. r.name .. "-" .. r.ver .. ".log" + local cmd = h.gsandbox .. " -R" .. user_flag .. " -L " .. h.shell_quote(layers_dir) + for _, l in ipairs(layer_names) do cmd = cmd .. " -l " .. h.shell_quote(l) end + cmd = cmd .. " -w " .. h.shell_quote(work) .. " -i " .. h.shell_quote(in_dir) .. + " -o " .. h.shell_quote(out) + log.lg_printf(0, "Building %s%s...", id, tr.show ~= "" and (" " .. tr.show) or "") + local st + if h.verbose() then + local stf = in_dir .. "/.status" + os.execute("{ " .. cmd .. " 2>&1; echo $? > " .. h.shell_quote(stf) .. "; } | tee " + .. h.shell_quote(log_path)) + local f = io.open(stf, "r") + st = f and tonumber(f:read("*l")) or 255 + if f then f:close() end + else + st = status_of(cmd .. " > " .. h.shell_quote(log_path) .. " 2>&1") + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(log_path)) + if st ~= 0 then + fail("Building %s failed. Log: %s", id, log_path) + end + + -- The output, untrusted: copied privately while hashed, then its + -- manifest must be exactly the one handed in. + local result = out .. "/" .. r.name .. "-" .. r.ver .. ".gpkg" + local hex = h.sha256_file(result) + local pkg = hex and h.verify_and_copy(result, "sha256:" .. hex .. "\n") + if not pkg or not output_matches(pkg, r, deps, confs, tr) then + fail("%s: the build produced another package.", id) + end + cleanup() + log.lg_printf(3, "Built %s.", id) + return pkg, "sha256:" .. hex .. "\n", hex +end + +ffi.cdef[[ +int gpkg_build_getpid(void) asm("getpid"); +]] + +return M diff --git a/lib/gpkg_build.lua.old2 b/lib/gpkg_build.lua.old2 new file mode 100644 index 0000000..8f705c2 --- /dev/null +++ b/lib/gpkg_build.lua.old2 @@ -0,0 +1,602 @@ +-- lib/gpkg_build.lua +-- +-- The package builder (BUILD_DESIGN.txt): turns a recipe from a NAME-src +-- repository into a .gpkg, built in gsandbox, which gpkg_common then +-- installs like any fetched package. Used only through gpkg_common. +-- +-- Nothing a build produces is trusted: the output is copied privately +-- while hashed and its manifest (read by the library) must be exactly +-- the one handed in. What IS trusted is what decides the build: the +-- bundle (hash from the signed index, then checked by gl_recipe_read), +-- each source (the recipe's SHA256), the layers (packages verified +-- against their signed indexes) and this file and build-driver.sh. + +local ffi = require("ffi") +local bit = require("bit") + +local M = {} + +-- Set by M.init(): FFI handles and gpkg_common's helpers. +local log, istore, txn, h + +function M.init(env) + log, istore, txn = env.log, env.istore, env.txn + h = env +end + +local SYSTEM_CONF = "/etc/glacier/glacier.conf" +local SYSTEM_CONFIG_DIR = "/etc/glacier/config" + +-- --------------------------------------------------------------------- +-- Small helpers +-- --------------------------------------------------------------------- + +local function lines(s) + local out = {} + for l in (s or ""):gmatch("([^\n]*)\n") do table.insert(out, l) end + return out +end + +local function exists(path) + local f = io.open(path, "rb") + if f then f:close() return true end + local ok = os.execute("test -e " .. h.shell_quote(path)) + return ok == true or ok == 0 +end + +-- The exit status of a shell command line. +local function status_of(cmd) + local p = io.popen(cmd .. "; echo \"rc=$?\"") + local out = p:read("*a") + p:close() + return tonumber(out:match("rc=(%d+)%s*$")) or 255 +end + +local function sh_ok(cmd) + return status_of(cmd .. " >/dev/null 2>&1") == 0 +end + +-- A libconfig string literal. +local function cfg_string(s) + return '"' .. s:gsub("\\", "\\\\"):gsub('"', '\\"') .. '"' +end + +-- --------------------------------------------------------------------- +-- Settings (BUILD_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +-- One configuration file's build settings, or nil if it doesn't exist. +-- Exits if it is malformed (or, read by syspkg, untrusted). +local conf_cache = {} +local function read_conf(path, kind, opts) + if conf_cache[path] ~= nil then return conf_cache[path] or nil end + if not exists(path) then + conf_cache[path] = false + return nil + end + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(path) + end + local c = ffi.new("gl_build_conf_t") + if tonumber(istore.gl_conf_build(path, kind, c)) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + h.finish(1) + end + local function str(v) return v ~= nil and ffi.string(v) or nil end + local r = { + traits = lines(str(c.traits)), cflags = str(c.cflags), + cxxflags = str(c.cxxflags), ldflags = str(c.ldflags), + configure = lines(str(c.configure)), + jobs = c.jobs > 0 and tonumber(c.jobs) or nil, + build_user = str(c.build_user), build_root = lines(str(c.build_root)), + path = path, + } + istore.gl_build_conf_free(c) + conf_cache[path] = r + return r +end + +-- The user's base directory (, beside index and store). +local function user_base(opts) + return string.format("/glacier/usr/%d", opts.uid) +end + +-- The configuration layers for package `name`, lowest first: +-- { global = {...}, package = {...} } lists of read_conf results. +local function conf_layers(name, opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if opts.scope == ffi.C.GL_SCOPE_SYS then + return { sys }, read_conf(SYSTEM_CONFIG_DIR .. "/" .. name .. ".conf", + ffi.C.GL_CONF_PACKAGE, opts) + end + local base = user_base(opts) .. "/config" + return { sys, read_conf(base .. "/glacier.conf", ffi.C.GL_CONF_USER, opts) }, + read_conf(base .. "/" .. name .. ".conf", ffi.C.GL_CONF_PACKAGE, opts) +end + +-- The system's settings a build can't do without: BUILD_ROOT, and for +-- syspkg BUILD_USER (its uid too). Exits saying which is missing. +local function system_settings(opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if not sys then + log.lg_printf(2, "Cannot read %s.", SYSTEM_CONF) + h.finish(1) + end + if #sys.build_root == 0 then + log.lg_printf(2, "BUILD_ROOT is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local s = { build_root = sys.build_root } + if opts.scope == ffi.C.GL_SCOPE_SYS then + if not sys.build_user then + log.lg_printf(2, "BUILD_USER is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local p = io.popen("id -u -- " .. h.shell_quote(sys.build_user) .. " 2>/dev/null") + local uid = tonumber(p and p:read("*l") or "") + if p then p:close() end + if not uid then + log.lg_printf(2, "BUILD_USER %s in %s is not a user.", sys.build_user, + SYSTEM_CONF) + h.finish(1) + elseif uid == 0 then + log.lg_printf(2, "BUILD_USER in %s must not be root.", SYSTEM_CONF) + h.finish(1) + end + s.build_user, s.build_uid = sys.build_user, uid + end + return s +end + +--- The effective traits of building `name`, whose recipe (or -src index +--- entry) declares `declared` ("NAME D\n" lines). Returns a table +--- { on = { trait = bool }, list = sorted { "ssl", "-ldap" }, show = +--- "[+ssl -ldap]" (or "" with no traits) }. Exits if a per-package file +--- names a trait the recipe doesn't declare. +function M.traits(name, declared, opts) + local on, names = {}, {} + for _, l in ipairs(lines(declared)) do + local t, d = l:match("^(%S+) ([01])$") + on[t] = d == "1" + table.insert(names, t) + end + local function apply(conf, strict) + if not conf then return end + for _, s in ipairs(conf.traits) do + local neg = s:sub(1, 1) == "-" + local t = neg and s:sub(2) or s + if on[t] ~= nil then + on[t] = not neg + elseif strict then + log.lg_printf(2, "%s: %s has no trait %s.", conf.path, name, t) + h.finish(1) + end + end + end + local globals, pkg = conf_layers(name, opts) + for _, g in ipairs(globals) do apply(g, false) end + apply(pkg, true) + + table.sort(names) + local list, show = {}, {} + for _, t in ipairs(names) do + table.insert(list, on[t] and t or ("-" .. t)) + table.insert(show, (on[t] and "+" or "-") .. t) + end + return { on = on, list = list, + show = #show > 0 and ("[" .. table.concat(show, " ") .. "]") or "" } +end + +--- Relation lines ("NAME VER[ IF]\n") with their IF resolved against +--- traits `tr`: "NAME VER\n" for each that applies. +function M.effective(rel, tr) + local out = {} + for _, l in ipairs(lines(rel)) do + local n, v, c = l:match("^(%S+) (%S+) ?(%S*)$") + local applies = c == "" or + (c:sub(1, 1) == "-" and not tr.on[c:sub(2)]) or + (c:sub(1, 1) ~= "-" and tr.on[c]) + if applies then table.insert(out, n .. " " .. v .. "\n") end + end + return table.concat(out) +end + +--- Check, before the prompt, everything a build of `name` needs from +--- the configuration (exits on a problem): BUILD_ROOT, BUILD_USER. +function M.check(opts) + if opts.sysroot then + log.lg_printf(2, "Building from source under -R is not supported.") + h.finish(1) + end + system_settings(opts) + -- gsandbox and the driver decide what a build produces, which + -- root then installs: checked like syspkg's own files, here + -- rather than at startup, since only builds need them. + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(h.gsandbox_path) + h.require_trusted(h.lib_dir .. "/build-driver.sh") + end +end + +-- --------------------------------------------------------------------- +-- The build +-- --------------------------------------------------------------------- + +-- /build/NAME, made and checked by the library; owned by the +-- builder (`owner` = BUILD_USER's uid, syspkg) or the scope. +local function build_dir(ctx, name, owner) + local out = ffi.new("char[4096]") + if txn.gl_scope_build_dir(ctx, name, owner or -1, out) ~= 0 then + h.finish(1) -- the library said why + end + return ffi.string(out) +end + +-- Remove a build's directory tree (the builder's files may be +-- read-only to it: overlayfs's work dir is mode 000). +local function remove_tree(path) + os.execute("chmod -R u+rwX " .. h.shell_quote(path) .. " 2>/dev/null; rm -rf " + .. h.shell_quote(path)) +end + +-- Copy a file (cp, then the given mode). +local function copy_file(src, dst, mode) + return sh_ok("cp -- " .. h.shell_quote(src) .. " " .. h.shell_quote(dst)) + and sh_ok("chmod " .. mode .. " " .. h.shell_quote(dst)) +end + +-- Fetch a source URL (https through curl, file:// a copy) into dest +-- hashed: true if it arrived and has hash `hex`. Redirects are +-- followed, https only (release tarballs are mostly served that way); +-- the hash decides. +local MAX_SOURCE = 4 * 1024 * 1024 * 1024 +local function fetch_source(url, dest, hex) + local tmp = dest .. ".part" + os.remove(tmp) + local cmd + local path = url:match("^file://(/.*)$") + if path then + cmd = "cp -- " .. h.shell_quote(path) .. " " .. h.shell_quote(tmp) + else + cmd = "curl -sfL --max-redirs 5 --proto =https --proto-redir =https --connect-timeout 30" .. + " --max-filesize " .. MAX_SOURCE .. " -o " .. h.shell_quote(tmp) .. + " -- " .. h.shell_quote(url) + end + if not sh_ok(cmd) then + os.remove(tmp) + return false, false + end + if h.sha256_file(tmp) ~= hex then + os.remove(tmp) + return false, true + end + return os.rename(tmp, dest) ~= nil +end + +-- The libconfig manifest a build must produce. +local function manifest_text(r, deps, confs, tr) + local function rel(text) + local out = {} + for n, v in text:gmatch("(%S+) (%S+)\n") do + table.insert(out, string.format('{ PKG_NAME = "%s"; PKG_VER = "%s"; }', n, v)) + end + return "(" .. table.concat(out, ", ") .. ")" + end + local t = {} + for _, s in ipairs(tr.list) do table.insert(t, '"' .. s .. '"') end + return table.concat({ + "PKG_NAME = " .. cfg_string(r.name) .. ";", + "PKG_VER = " .. cfg_string(r.ver) .. ";", + "PKG_DESC = " .. cfg_string(r.desc) .. ";", + "PKG_MAINT = " .. cfg_string(r.maint) .. ";", + "PKG_COPYRIGHT = " .. cfg_string(r.copyright) .. ";", + "PKG_REPO = " .. cfg_string(r.repo) .. ";", + "PKG_DEPS = " .. rel(deps) .. ";", + "PKG_CONFS = " .. rel(confs) .. ";", + "PKG_TRAITS = [ " .. table.concat(t, ", ") .. " ];", + }, "\n") .. "\n" +end + +-- The driver's env file: shell assignments, every value quoted. +local function env_text(r, settings, tr, sources, prefix) + local q = h.shell_quote + local args = {} + for _, a in ipairs(lines(r.configure)) do table.insert(args, q(a)) end + for _, l in ipairs(lines(r.trait_args)) do + local t, side, a = l:match("^([^\t]+)\t([+-])\t(.*)$") + if (side == "+") == (tr.on[t] == true) then table.insert(args, q(a)) end + end + for _, a in ipairs(settings.configure) do table.insert(args, q(a)) end + local on = {} + for _, s in ipairs(tr.list) do + if s:sub(1, 1) ~= "-" then table.insert(on, s) end + end + local function kv(k, v) return k .. "=" .. q(v or "") .. "\n" end + return kv("NAME", r.name) .. kv("VER", r.ver) .. kv("BUILD", r.build) .. + kv("PREFIX", prefix) .. + kv("SOURCES", table.concat(sources, " ")) .. + kv("PATCHES", table.concat(lines(r.patches), " ")) .. + kv("CONFIGURE_ARGS", table.concat(args, " ")) .. + kv("TRAITS", table.concat(on, " ")) .. + kv("JOBS", tostring(settings.jobs)) .. + kv("CFLAGS", settings.cflags) .. kv("CXXFLAGS", settings.cxxflags) .. + kv("LDFLAGS", settings.ldflags) +end + +-- CFLAGS/CXXFLAGS/LDFLAGS/CONFIGURE/JOBS for package `name`: the +-- per-package value replaces the global one; the user's global replaces +-- the system's. +local function flags_for(name, opts) + local globals, pkg = conf_layers(name, opts) + local s = { configure = pkg and pkg.configure or {}, jobs = 1 } + for _, k in ipairs({ "cflags", "cxxflags", "ldflags" }) do + for _, g in ipairs(globals) do + if g and g[k] then s[k] = g[k] end + end + if pkg and pkg[k] then s[k] = pkg[k] end + end + for _, g in ipairs(globals) do + if g and g.jobs then s.jobs = g.jobs end + end + return s +end + +-- Whether the private copy `path`'s manifest (read by the library) is +-- exactly what the build was handed. +local function output_matches(path, r, deps, confs, tr) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then return false end + local want_traits = #tr.list > 0 and (table.concat(tr.list, "\n") .. "\n") or "" + local ok = ffi.string(m.pkg_name) == r.name + and ffi.string(m.pkg_repo) == r.repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == r.ver + and h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == deps + and h.relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == confs + and m.pkg_traits ~= nil and ffi.string(m.pkg_traits) == want_traits + istore.gl_free_pkg(m) + return ok +end + +-- The recipe of a verified bundle copy, as a table, or nil. +local function read_recipe(path) + local r = ffi.new("gl_recipe_t") + if tonumber(istore.gl_recipe_read(path, r)) ~= 0 then return nil end + local t = {} + for _, k in ipairs({ "name", "ver", "repo", "desc", "maint", "copyright", + "sources", "patches", "build", "configure", "traits", "trait_args", + "deps", "build_deps", "confs" }) do + t[k] = ffi.string(r[k]) + end + istore.gl_recipe_free(r) + return t +end + +-- The packages a build stacks as layers: BUILD_ROOT, the effective +-- BUILD_DEPS and DEPS, and everything they depend on, each from the +-- binary repositories (or `built`: this run's own builds). A list of +-- { name, path, sha (hex) }, top first. Exits if one can't be had. +local function layer_plan(id, root_names, build_deps, deps, indexes, built) + local plan, seen = {}, {} + local queue = {} + for _, rel in ipairs({ deps, build_deps }) do + for n, v in rel:gmatch("(%S+) (%S+)\n") do table.insert(queue, { n, v }) end + end + for _, n in ipairs(root_names) do table.insert(queue, { n, "0.0.0" }) end + local k = 1 + while k <= #queue do + local n, v = queue[k][1], queue[k][2] + k = k + 1 + if not seen[n] then + seen[n] = true + local b = built[n] + if b and h.vercmp(b.ver, v) >= 0 then + table.insert(plan, { name = n, ver = b.ver, path = b.path, sha = b.sha }) + else + local r, e = h.pick_binary(indexes, n) + if not e or h.vercmp(e.ver, v) < 0 then + log.lg_printf(2, "%s needs %s %s or later to build, and no binary repository has it.", + id, n, v) + h.finish(1) + end + table.insert(plan, { name = n, ver = e.ver, repo = r, entry = e, + sha = e.sha256:match("^sha256:(%x+)$") }) + for dn, dv in e.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + end + end + end + return plan +end + +--- Check, before the prompt, that every layer a build of plan item `it` +--- needs can be had (exits otherwise). `planned` maps the names this +--- run builds to their versions. +function M.check_layers(it, indexes, planned, opts) + local settings = system_settings(opts) + local built = {} + for n, v in pairs(planned) do built[n] = { ver = v } end + local id = string.format("%s::%s %s", it.repo.name, it.entry.name, it.entry.ver) + layer_plan(id, settings.build_root, M.effective(it.entry.build_deps, it.traits), + it.deps, indexes, built) +end + +--- Build plan item `it` (a -src repository's entry, with it.traits from +--- M.traits) into a verified private copy of its .gpkg. `built` maps +--- names this run has already built to { ver, path, sha }, for layers. +--- Returns the copy and its sidecar text; exits on any failure. +function M.build(it, indexes, built, opts) + local e, r_src = it.entry, it.repo + local id = string.format("%s::%s %s", r_src.name, e.name, e.ver) + local settings = system_settings(opts) + local owner = settings.build_uid + local ctx = h.live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600" + + -- The bundle: downloaded and hashed against the signed index, + -- copied privately, then read and checked by the library. + local cached, wrong = h.download(ctx, r_src, e, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + local copy = cached and h.verify_and_copy(cached, e.sha256 .. "\n") + local r = copy and read_recipe(copy) + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + h.finish(1) + end + if not r or r.name ~= e.name or r.ver ~= e.ver or r.repo .. "-src" ~= r_src.name + or r.deps ~= e.deps or r.confs ~= e.confs or r.build_deps ~= e.build_deps + or r.traits ~= e.traits then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + h.finish(1) + end + if cached then os.remove(cached) end + + local tr = it.traits + local deps, confs = M.effective(r.deps, tr), M.effective(r.confs, tr) + local build_deps = M.effective(r.build_deps, tr) + local flags = flags_for(r.name, opts) + + -- The prefix the package is built for: where its usr/ will be + -- linked, so it finds its own files at run time. /usr for base, + -- else the scope's links (no -R here: these are runtime paths). + local prefix = r.repo == "base" and "/usr" or + (ffi.string(ctx.links_path):gsub("/+$", "")) + + -- Sources, by hash, in /build/sources. + local sources_dir = build_dir(ctx, "sources") + local sources = {} + for url, hex in r.sources:gmatch("(%S+) sha256:(%x+)\n") do + local file = url:match("([^/]+)$") + local dest = sources_dir .. "/" .. hex + if h.sha256_file(dest) ~= hex then + local ok, mismatch = fetch_source(url, dest, hex) + if not ok then + log.lg_printf(2, mismatch and "A source of %s does not match its hash." + or "Cannot fetch the sources of %s.", id) + h.finish(1) + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(dest)) + end + table.insert(sources, { file = file, path = dest }) + end + + -- This build's input (the scope's) and work/output (the builder's). + local tag = string.format("%s-%s-%d", r.name, r.ver, ffi.C.gpkg_build_getpid()) + local in_dir = build_dir(ctx, "in-" .. tag) + local work = build_dir(ctx, "work-" .. tag, owner) + local out = build_dir(ctx, "out-" .. tag, owner) + local function cleanup() + remove_tree(in_dir) + remove_tree(work) + remove_tree(out) + end + local function fail(fmt, ...) + log.lg_printf(2, fmt, ...) + cleanup() + h.finish(1) + end + + -- Layers, extracted once each into /build/layers by the + -- builder: NAME-VER-. + local layers_dir = build_dir(ctx, "layers", owner) + local layer_names = {} + local user_flag = settings.build_user and (" -u " .. h.shell_quote(settings.build_user)) or "" + for _, l in ipairs(layer_plan(id, settings.build_root, build_deps, deps, indexes, built)) do + local lname = string.format("%s-%s-%s", l.name, l.ver, l.sha:sub(1, 8)) + if not exists(layers_dir .. "/" .. lname) then + local path = l.path + if l.entry then + path = h.download(ctx, l.repo, l.entry, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + if not path then fail("Cannot fetch %s::%s %s.", l.repo.name, l.name, l.ver) end + else + -- A package this run built: its private copy, + -- copied where the builder can read it. + local p = in_dir .. "/" .. lname .. ".gpkg" + if not copy_file(l.path, p, "644") then + fail("Cannot write %s.", p) + end + path = p + end + local tmp = string.format(".%s.%d", lname, ffi.C.gpkg_build_getpid()) + if not sh_ok(h.gsandbox .. " -X" .. user_flag .. " -p " .. h.shell_quote(path) .. + " -d " .. h.shell_quote(layers_dir .. "/" .. tmp)) then + fail("Cannot extract %s %s for %s.", l.name, l.ver, id) + end + if not os.rename(layers_dir .. "/" .. tmp, layers_dir .. "/" .. lname) then + remove_tree(layers_dir .. "/" .. tmp) + end + end + table.insert(layer_names, lname) + end + + -- The input: bundle, sources, manifest, env, driver. + local function put(name, text) + local f = io.open(in_dir .. "/" .. name, "wb") + if not f or not f:write(text) then fail("Cannot write %s/%s.", in_dir, name) end + f:close() + if not sh_ok("chmod 644 " .. h.shell_quote(in_dir .. "/" .. name)) then + fail("Cannot write %s/%s.", in_dir, name) + end + end + if not copy_file(copy, in_dir .. "/bundle.grcp", "644") or + not sh_ok("mkdir -m 755 " .. h.shell_quote(in_dir .. "/sources")) then + fail("Cannot write %s.", in_dir) + end + local files = {} + for _, s in ipairs(sources) do + if not copy_file(s.path, in_dir .. "/sources/" .. s.file, "644") then + fail("Cannot write %s.", in_dir) + end + table.insert(files, s.file) + end + put("manifest.gpm.cfg", manifest_text(r, deps, confs, tr)) + put("env", env_text(r, flags, tr, files, prefix)) + local df = io.open(h.lib_dir .. "/build-driver.sh", "rb") + local driver = df and df:read("*a") + if df then df:close() end + if not driver then fail("Cannot read %s/build-driver.sh.", h.lib_dir) end + put("driver", driver) + + -- The build. Its output goes to /build/logs/NAME-VER.log. + local log_path = build_dir(ctx, "logs") .. "/" .. r.name .. "-" .. r.ver .. ".log" + local cmd = h.gsandbox .. " -R" .. user_flag .. " -L " .. h.shell_quote(layers_dir) + for _, l in ipairs(layer_names) do cmd = cmd .. " -l " .. h.shell_quote(l) end + cmd = cmd .. " -w " .. h.shell_quote(work) .. " -i " .. h.shell_quote(in_dir) .. + " -o " .. h.shell_quote(out) + log.lg_printf(0, "Building %s%s...", id, tr.show ~= "" and (" " .. tr.show) or "") + local st + if h.verbose() then + local stf = in_dir .. "/.status" + os.execute("{ " .. cmd .. " 2>&1; echo $? > " .. h.shell_quote(stf) .. "; } | tee " + .. h.shell_quote(log_path)) + local f = io.open(stf, "r") + st = f and tonumber(f:read("*l")) or 255 + if f then f:close() end + else + st = status_of(cmd .. " > " .. h.shell_quote(log_path) .. " 2>&1") + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(log_path)) + if st ~= 0 then + fail("Building %s failed. Log: %s", id, log_path) + end + + -- The output, untrusted: copied privately while hashed, then its + -- manifest must be exactly the one handed in. + local result = out .. "/" .. r.name .. "-" .. r.ver .. ".gpkg" + local hex = h.sha256_file(result) + local pkg = hex and h.verify_and_copy(result, "sha256:" .. hex .. "\n") + if not pkg or not output_matches(pkg, r, deps, confs, tr) then + fail("%s: the build produced another package.", id) + end + cleanup() + log.lg_printf(3, "Built %s.", id) + return pkg, "sha256:" .. hex .. "\n", hex +end + +ffi.cdef[[ +int gpkg_build_getpid(void) asm("getpid"); +]] + +return M diff --git a/lib/gpkg_build.lua.old3 b/lib/gpkg_build.lua.old3 new file mode 100644 index 0000000..849ae1c --- /dev/null +++ b/lib/gpkg_build.lua.old3 @@ -0,0 +1,685 @@ +-- lib/gpkg_build.lua +-- +-- The package builder (BUILD_DESIGN.txt): turns a recipe from a NAME-src +-- repository into a .gpkg, built in gsandbox, which gpkg_common then +-- installs like any fetched package. Used only through gpkg_common. +-- +-- Nothing a build produces is trusted: the output is copied privately +-- while hashed and its manifest (read by the library) must be exactly +-- the one handed in. What IS trusted is what decides the build: the +-- bundle (hash from the signed index, then checked by gl_recipe_read), +-- each source (the recipe's SHA256), the layers (packages verified +-- against their signed indexes) and this file and build-driver.sh. + +local ffi = require("ffi") +local bit = require("bit") + +local M = {} + +-- Set by M.init(): FFI handles and gpkg_common's helpers. +local log, istore, txn, h + +function M.init(env) + log, istore, txn = env.log, env.istore, env.txn + h = env +end + +local SYSTEM_CONF = "/etc/glacier/glacier.conf" +local SYSTEM_CONFIG_DIR = "/etc/glacier/config" + +-- --------------------------------------------------------------------- +-- Small helpers +-- --------------------------------------------------------------------- + +local function lines(s) + local out = {} + for l in (s or ""):gmatch("([^\n]*)\n") do table.insert(out, l) end + return out +end + +local function exists(path) + local f = io.open(path, "rb") + if f then f:close() return true end + local ok = os.execute("test -e " .. h.shell_quote(path)) + return ok == true or ok == 0 +end + +-- The exit status of a shell command line. +local function status_of(cmd) + local p = io.popen(cmd .. "; echo \"rc=$?\"") + local out = p:read("*a") + p:close() + return tonumber(out:match("rc=(%d+)%s*$")) or 255 +end + +local function sh_ok(cmd) + return status_of(cmd .. " >/dev/null 2>&1") == 0 +end + +-- A libconfig string literal. +local function cfg_string(s) + return '"' .. s:gsub("\\", "\\\\"):gsub('"', '\\"') .. '"' +end + +-- --------------------------------------------------------------------- +-- Settings (BUILD_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +-- One configuration file's build settings, or nil if it doesn't exist. +-- Exits if it is malformed (or, read by syspkg, untrusted). +local conf_cache = {} +local function read_conf(path, kind, opts) + if conf_cache[path] ~= nil then return conf_cache[path] or nil end + if not exists(path) then + conf_cache[path] = false + return nil + end + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(path) + end + local c = ffi.new("gl_build_conf_t") + if tonumber(istore.gl_conf_build(path, kind, c)) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + h.finish(1) + end + local function str(v) return v ~= nil and ffi.string(v) or nil end + local r = { + traits = lines(str(c.traits)), cflags = str(c.cflags), + cxxflags = str(c.cxxflags), ldflags = str(c.ldflags), + configure = lines(str(c.configure)), + jobs = c.jobs > 0 and tonumber(c.jobs) or nil, + build_user = str(c.build_user), build_root = lines(str(c.build_root)), + path = path, + } + istore.gl_build_conf_free(c) + conf_cache[path] = r + return r +end + +-- The user's base directory (, beside index and store). +local function user_base(opts) + return string.format("/glacier/usr/%d", opts.uid) +end + +-- The configuration layers for package `name`, lowest first: +-- { global = {...}, package = {...} } lists of read_conf results. +local function conf_layers(name, opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if opts.scope == ffi.C.GL_SCOPE_SYS then + return { sys }, read_conf(SYSTEM_CONFIG_DIR .. "/" .. name .. ".conf", + ffi.C.GL_CONF_PACKAGE, opts) + end + local base = user_base(opts) .. "/config" + return { sys, read_conf(base .. "/glacier.conf", ffi.C.GL_CONF_USER, opts) }, + read_conf(base .. "/" .. name .. ".conf", ffi.C.GL_CONF_PACKAGE, opts) +end + +-- The system's settings a build can't do without: BUILD_ROOT, and for +-- syspkg BUILD_USER (its uid too). Exits saying which is missing. +local function system_settings(opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if not sys then + log.lg_printf(2, "Cannot read %s.", SYSTEM_CONF) + h.finish(1) + end + if #sys.build_root == 0 then + log.lg_printf(2, "BUILD_ROOT is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local s = { build_root = sys.build_root } + if opts.scope == ffi.C.GL_SCOPE_SYS then + if not sys.build_user then + log.lg_printf(2, "BUILD_USER is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local p = io.popen("id -u -- " .. h.shell_quote(sys.build_user) .. " 2>/dev/null") + local uid = tonumber(p and p:read("*l") or "") + if p then p:close() end + if not uid then + log.lg_printf(2, "BUILD_USER %s in %s is not a user.", sys.build_user, + SYSTEM_CONF) + h.finish(1) + elseif uid == 0 then + log.lg_printf(2, "BUILD_USER in %s must not be root.", SYSTEM_CONF) + h.finish(1) + end + s.build_user, s.build_uid = sys.build_user, uid + end + return s +end + +--- The effective traits of building `name`, whose recipe (or -src index +--- entry) declares `declared` ("NAME D\n" lines). Returns a table +--- { on = { trait = bool }, list = sorted { "ssl", "-ldap" }, show = +--- "[+ssl -ldap]" (or "" with no traits) }. Exits if a per-package file +--- names a trait the recipe doesn't declare. +function M.traits(name, declared, opts) + local on, names = {}, {} + for _, l in ipairs(lines(declared)) do + local t, d = l:match("^(%S+) ([01])$") + on[t] = d == "1" + table.insert(names, t) + end + local function apply(conf, strict) + if not conf then return end + for _, s in ipairs(conf.traits) do + local neg = s:sub(1, 1) == "-" + local t = neg and s:sub(2) or s + if on[t] ~= nil then + on[t] = not neg + elseif strict then + log.lg_printf(2, "%s: %s has no trait %s.", conf.path, name, t) + h.finish(1) + end + end + end + local globals, pkg = conf_layers(name, opts) + for _, g in ipairs(globals) do apply(g, false) end + apply(pkg, true) + + table.sort(names) + local list, show = {}, {} + for _, t in ipairs(names) do + table.insert(list, on[t] and t or ("-" .. t)) + table.insert(show, (on[t] and "+" or "-") .. t) + end + return { on = on, list = list, + show = #show > 0 and ("[" .. table.concat(show, " ") .. "]") or "" } +end + +--- Relation lines ("NAME VER[ IF]\n") with their IF resolved against +--- traits `tr`: "NAME VER\n" for each that applies. +function M.effective(rel, tr) + local out = {} + for _, l in ipairs(lines(rel)) do + local n, v, c = l:match("^(%S+) (%S+) ?(%S*)$") + local applies = c == "" or + (c:sub(1, 1) == "-" and not tr.on[c:sub(2)]) or + (c:sub(1, 1) ~= "-" and tr.on[c]) + if applies then table.insert(out, n .. " " .. v .. "\n") end + end + return table.concat(out) +end + +--- Check, before the prompt, everything a build of `name` needs from +--- the configuration (exits on a problem): BUILD_ROOT, BUILD_USER. +function M.check(opts) + if opts.sysroot then + log.lg_printf(2, "Building from source under -R is not supported.") + h.finish(1) + end + system_settings(opts) + -- gsandbox and the driver decide what a build produces, which + -- root then installs: checked like syspkg's own files, here + -- rather than at startup, since only builds need them. + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(h.gsandbox_path) + h.require_trusted(h.lib_dir .. "/build-driver.sh") + end +end + +-- --------------------------------------------------------------------- +-- The build +-- --------------------------------------------------------------------- + +-- /build/NAME, made and checked by the library; owned by the +-- builder (`owner` = BUILD_USER's uid, syspkg) or the scope. +local function build_dir(ctx, name, owner) + local out = ffi.new("char[4096]") + if txn.gl_scope_build_dir(ctx, name, owner or -1, out) ~= 0 then + h.finish(1) -- the library said why + end + return ffi.string(out) +end + +-- Remove a build's directory tree (the builder's files may be +-- read-only to it: overlayfs's work dir is mode 000). +local function remove_tree(path) + os.execute("chmod -R u+rwX " .. h.shell_quote(path) .. " 2>/dev/null; rm -rf " + .. h.shell_quote(path)) +end + +-- Copy a file (cp, then the given mode). +local function copy_file(src, dst, mode) + return sh_ok("cp -- " .. h.shell_quote(src) .. " " .. h.shell_quote(dst)) + and sh_ok("chmod " .. mode .. " " .. h.shell_quote(dst)) +end + +-- Fetch a source URL (https through curl, file:// a copy) into dest +-- hashed: true if it arrived and has hash `hex`. Redirects are +-- followed, https only (release tarballs are mostly served that way); +-- the hash decides. +local MAX_SOURCE = 4 * 1024 * 1024 * 1024 +local function fetch_source(url, dest, hex) + local tmp = dest .. ".part" + os.remove(tmp) + local cmd + local path = url:match("^file://(/.*)$") + if path then + cmd = "cp -- " .. h.shell_quote(path) .. " " .. h.shell_quote(tmp) + else + cmd = "curl -sfL --max-redirs 5 --proto =https --proto-redir =https --connect-timeout 30" .. + " --max-filesize " .. MAX_SOURCE .. " -o " .. h.shell_quote(tmp) .. + " -- " .. h.shell_quote(url) + end + if not sh_ok(cmd) then + os.remove(tmp) + return false, false + end + if h.sha256_file(tmp) ~= hex then + os.remove(tmp) + return false, true + end + return os.rename(tmp, dest) ~= nil +end + +-- The libconfig manifest a build must produce. +local function manifest_text(r, deps, confs, tr) + local function rel(text) + local out = {} + for n, v in text:gmatch("(%S+) (%S+)\n") do + table.insert(out, string.format('{ PKG_NAME = "%s"; PKG_VER = "%s"; }', n, v)) + end + return "(" .. table.concat(out, ", ") .. ")" + end + local t = {} + for _, s in ipairs(tr.list) do table.insert(t, '"' .. s .. '"') end + return table.concat({ + "PKG_NAME = " .. cfg_string(r.name) .. ";", + "PKG_VER = " .. cfg_string(r.ver) .. ";", + "PKG_DESC = " .. cfg_string(r.desc) .. ";", + "PKG_MAINT = " .. cfg_string(r.maint) .. ";", + "PKG_COPYRIGHT = " .. cfg_string(r.copyright) .. ";", + "PKG_REPO = " .. cfg_string(r.repo) .. ";", + "PKG_DEPS = " .. rel(deps) .. ";", + "PKG_CONFS = " .. rel(confs) .. ";", + "PKG_TRAITS = [ " .. table.concat(t, ", ") .. " ];", + }, "\n") .. "\n" +end + +-- The driver's env file: shell assignments, every value quoted. +local function env_text(r, settings, tr, sources, prefix) + local q = h.shell_quote + local args = {} + for _, a in ipairs(lines(r.configure)) do table.insert(args, q(a)) end + for _, l in ipairs(lines(r.trait_args)) do + local t, side, a = l:match("^([^\t]+)\t([+-])\t(.*)$") + if (side == "+") == (tr.on[t] == true) then table.insert(args, q(a)) end + end + for _, a in ipairs(settings.configure) do table.insert(args, q(a)) end + local on = {} + for _, s in ipairs(tr.list) do + if s:sub(1, 1) ~= "-" then table.insert(on, s) end + end + local function kv(k, v) return k .. "=" .. q(v or "") .. "\n" end + return kv("NAME", r.name) .. kv("VER", r.ver) .. kv("BUILD", r.build) .. + kv("PREFIX", prefix) .. + kv("SOURCES", table.concat(sources, " ")) .. + kv("PATCHES", table.concat(lines(r.patches), " ")) .. + kv("CONFIGURE_ARGS", table.concat(args, " ")) .. + kv("TRAITS", table.concat(on, " ")) .. + kv("JOBS", tostring(settings.jobs)) .. + kv("CFLAGS", settings.cflags) .. kv("CXXFLAGS", settings.cxxflags) .. + kv("LDFLAGS", settings.ldflags) +end + +-- CFLAGS/CXXFLAGS/LDFLAGS/CONFIGURE/JOBS for package `name`: the +-- per-package value replaces the global one; the user's global replaces +-- the system's. +local function flags_for(name, opts) + local globals, pkg = conf_layers(name, opts) + local s = { configure = pkg and pkg.configure or {}, jobs = 1 } + for _, k in ipairs({ "cflags", "cxxflags", "ldflags" }) do + for _, g in ipairs(globals) do + if g and g[k] then s[k] = g[k] end + end + if pkg and pkg[k] then s[k] = pkg[k] end + end + for _, g in ipairs(globals) do + if g and g.jobs then s.jobs = g.jobs end + end + return s +end + +-- Whether the private copy `path`'s manifest (read by the library) is +-- exactly what the build was handed. +local function output_matches(path, r, deps, confs, tr) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then return false end + local want_traits = #tr.list > 0 and (table.concat(tr.list, "\n") .. "\n") or "" + local ok = ffi.string(m.pkg_name) == r.name + and ffi.string(m.pkg_repo) == r.repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == r.ver + and h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == deps + and h.relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == confs + and m.pkg_traits ~= nil and ffi.string(m.pkg_traits) == want_traits + istore.gl_free_pkg(m) + return ok +end + +-- The recipe of a verified bundle copy, as a table, or nil. +local function read_recipe(path) + local r = ffi.new("gl_recipe_t") + if tonumber(istore.gl_recipe_read(path, r)) ~= 0 then return nil end + local t = {} + for _, k in ipairs({ "name", "ver", "repo", "desc", "maint", "copyright", + "sources", "patches", "build", "configure", "traits", "trait_args", + "deps", "build_deps", "confs" }) do + t[k] = ffi.string(r[k]) + end + istore.gl_recipe_free(r) + return t +end + +-- The packages a build stacks as layers: BUILD_ROOT, the effective +-- BUILD_DEPS and DEPS, and everything they depend on, each from +-- `built` (this run's own builds), `kept` (installed source builds, +-- M.kept) or the binary repositories, in that order, at a high enough +-- version. A list of { name, path, sha (hex) }, top first. Exits if +-- one can't be had. +local function layer_plan(id, root_names, build_deps, deps, indexes, built, kept) + local plan, seen = {}, {} + local queue = {} + for _, rel in ipairs({ deps, build_deps }) do + for n, v in rel:gmatch("(%S+) (%S+)\n") do table.insert(queue, { n, v }) end + end + for _, n in ipairs(root_names) do table.insert(queue, { n, "0.0.0" }) end + local k = 1 + while k <= #queue do + local n, v = queue[k][1], queue[k][2] + k = k + 1 + if not seen[n] then + seen[n] = true + local b = built[n] + if not (b and h.vercmp(b.ver, v) >= 0) then b = kept[n] end + if b and b.path and not b.sha then b.sha = h.sha256_file(b.path) or false end + if b and b.sha ~= false and h.vercmp(b.ver, v) >= 0 then + table.insert(plan, { name = n, ver = b.ver, path = b.path, sha = b.sha }) + for dn, dv in b.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + else + local r, e = h.pick_binary(indexes, n) + if not e or h.vercmp(e.ver, v) < 0 then + log.lg_printf(2, "%s needs %s %s or later to build, and no binary repository has it.", + id, n, v) + h.finish(1) + end + table.insert(plan, { name = n, ver = e.ver, repo = r, entry = e, + sha = e.sha256:match("^sha256:(%x+)$") }) + for dn, dv in e.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + end + end + end + return plan +end + +--- Check, before the prompt, that every layer a build of plan item `it` +--- needs can be had (exits otherwise). `planned` maps the names this +--- run builds to { ver, deps }. +function M.check_layers(it, indexes, planned, opts) + local settings = system_settings(opts) + local id = string.format("%s::%s %s", it.repo.name, it.entry.name, it.entry.ver) + layer_plan(id, settings.build_root, M.effective(it.entry.build_deps, it.traits), + it.deps, indexes, planned, M.kept(opts)) +end + +--- Build plan item `it` (a -src repository's entry, with it.traits from +--- M.traits) into a verified private copy of its .gpkg. `built` maps +--- names this run has already built to { ver, path, sha }, for layers. +--- Returns the copy and its sidecar text; exits on any failure. +function M.build(it, indexes, built, opts) + local e, r_src = it.entry, it.repo + local id = string.format("%s::%s %s", r_src.name, e.name, e.ver) + local settings = system_settings(opts) + local owner = settings.build_uid + local ctx = h.live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600" + + -- The bundle: downloaded and hashed against the signed index, + -- copied privately, then read and checked by the library. + local cached, wrong = h.download(ctx, r_src, e, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + local copy = cached and h.verify_and_copy(cached, e.sha256 .. "\n") + local r = copy and read_recipe(copy) + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + h.finish(1) + end + if not r or r.name ~= e.name or r.ver ~= e.ver or r.repo .. "-src" ~= r_src.name + or r.deps ~= e.deps or r.confs ~= e.confs or r.build_deps ~= e.build_deps + or r.traits ~= e.traits then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + h.finish(1) + end + if cached then os.remove(cached) end + + local tr = it.traits + local deps, confs = M.effective(r.deps, tr), M.effective(r.confs, tr) + local build_deps = M.effective(r.build_deps, tr) + local flags = flags_for(r.name, opts) + + -- The prefix the package is built for: where its usr/ will be + -- linked, so it finds its own files at run time. /usr for base, + -- else the scope's links (no -R here: these are runtime paths). + local prefix = r.repo == "base" and "/usr" or + (ffi.string(ctx.links_path):gsub("/+$", "")) + + -- Sources, by hash, in /build/sources. + local sources_dir = build_dir(ctx, "sources") + local sources = {} + for url, hex in r.sources:gmatch("(%S+) sha256:(%x+)\n") do + local file = url:match("([^/]+)$") + local dest = sources_dir .. "/" .. hex + if h.sha256_file(dest) ~= hex then + local ok, mismatch = fetch_source(url, dest, hex) + if not ok then + log.lg_printf(2, mismatch and "A source of %s does not match its hash." + or "Cannot fetch the sources of %s.", id) + h.finish(1) + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(dest)) + end + table.insert(sources, { file = file, path = dest }) + end + + -- This build's input (the scope's) and work/output (the builder's). + local tag = string.format("%s-%s-%d", r.name, r.ver, ffi.C.gpkg_build_getpid()) + local in_dir = build_dir(ctx, "in-" .. tag) + local work = build_dir(ctx, "work-" .. tag, owner) + local out = build_dir(ctx, "out-" .. tag, owner) + local function cleanup() + remove_tree(in_dir) + remove_tree(work) + remove_tree(out) + end + local function fail(fmt, ...) + log.lg_printf(2, fmt, ...) + cleanup() + h.finish(1) + end + + -- Layers, extracted once each into /build/layers by the + -- builder: NAME-VER-. + local layers_dir = build_dir(ctx, "layers", owner) + local layer_names = {} + local user_flag = settings.build_user and (" -u " .. h.shell_quote(settings.build_user)) or "" + for _, l in ipairs(layer_plan(id, settings.build_root, build_deps, deps, indexes, built, + M.kept(opts))) do + local lname = string.format("%s-%s-%s", l.name, l.ver, l.sha:sub(1, 8)) + if not exists(layers_dir .. "/" .. lname) then + local path = l.path + if l.entry then + path = h.download(ctx, l.repo, l.entry, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + if not path then fail("Cannot fetch %s::%s %s.", l.repo.name, l.name, l.ver) end + else + -- A package this run built: its private copy, + -- copied where the builder can read it. + local p = in_dir .. "/" .. lname .. ".gpkg" + if not copy_file(l.path, p, "644") then + fail("Cannot write %s.", p) + end + path = p + end + local tmp = string.format(".%s.%d", lname, ffi.C.gpkg_build_getpid()) + if not sh_ok(h.gsandbox .. " -X" .. user_flag .. " -p " .. h.shell_quote(path) .. + " -d " .. h.shell_quote(layers_dir .. "/" .. tmp)) then + fail("Cannot extract %s %s for %s.", l.name, l.ver, id) + end + if not os.rename(layers_dir .. "/" .. tmp, layers_dir .. "/" .. lname) then + remove_tree(layers_dir .. "/" .. tmp) + end + end + table.insert(layer_names, lname) + end + + -- The input: bundle, sources, manifest, env, driver. + local function put(name, text) + local f = io.open(in_dir .. "/" .. name, "wb") + if not f or not f:write(text) then fail("Cannot write %s/%s.", in_dir, name) end + f:close() + if not sh_ok("chmod 644 " .. h.shell_quote(in_dir .. "/" .. name)) then + fail("Cannot write %s/%s.", in_dir, name) + end + end + if not copy_file(copy, in_dir .. "/bundle.grcp", "644") or + not sh_ok("mkdir -m 755 " .. h.shell_quote(in_dir .. "/sources")) then + fail("Cannot write %s.", in_dir) + end + local files = {} + for _, s in ipairs(sources) do + if not copy_file(s.path, in_dir .. "/sources/" .. s.file, "644") then + fail("Cannot write %s.", in_dir) + end + table.insert(files, s.file) + end + put("manifest.gpm.cfg", manifest_text(r, deps, confs, tr)) + put("env", env_text(r, flags, tr, files, prefix)) + local df = io.open(h.lib_dir .. "/build-driver.sh", "rb") + local driver = df and df:read("*a") + if df then df:close() end + if not driver then fail("Cannot read %s/build-driver.sh.", h.lib_dir) end + put("driver", driver) + + -- The build. Its output goes to /build/logs/NAME-VER.log. + local log_path = build_dir(ctx, "logs") .. "/" .. r.name .. "-" .. r.ver .. ".log" + local cmd = h.gsandbox .. " -R" .. user_flag .. " -L " .. h.shell_quote(layers_dir) + for _, l in ipairs(layer_names) do cmd = cmd .. " -l " .. h.shell_quote(l) end + cmd = cmd .. " -w " .. h.shell_quote(work) .. " -i " .. h.shell_quote(in_dir) .. + " -o " .. h.shell_quote(out) + log.lg_printf(0, "Building %s%s...", id, tr.show ~= "" and (" " .. tr.show) or "") + local st + if h.verbose() then + local stf = in_dir .. "/.status" + os.execute("{ " .. cmd .. " 2>&1; echo $? > " .. h.shell_quote(stf) .. "; } | tee " + .. h.shell_quote(log_path)) + local f = io.open(stf, "r") + st = f and tonumber(f:read("*l")) or 255 + if f then f:close() end + else + st = status_of(cmd .. " > " .. h.shell_quote(log_path) .. " 2>&1") + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(log_path)) + if st ~= 0 then + fail("Building %s failed. Log: %s", id, log_path) + end + + -- The output, untrusted: copied privately while hashed, then its + -- manifest must be exactly the one handed in. + local result = out .. "/" .. r.name .. "-" .. r.ver .. ".gpkg" + local hex = h.sha256_file(result) + local pkg = hex and h.verify_and_copy(result, "sha256:" .. hex .. "\n") + if not pkg or not output_matches(pkg, r, deps, confs, tr) then + fail("%s: the build produced another package.", id) + end + cleanup() + log.lg_printf(3, "Built %s.", id) + return pkg, "sha256:" .. hex .. "\n", hex +end + +-- --------------------------------------------------------------------- +-- Kept packages: the verified .gpkg of each installed source build, +-- the bytes that were installed, so a later build can use it as a +-- layer (no binary repository has it). /build/packages/ +-- REPO@NAME-VER.gpkg ('@' is in no name), kept while that version is +-- installed and built from source. +-- --------------------------------------------------------------------- + +local function kept_name(repo, name, ver) + return repo .. "@" .. name .. "-" .. ver .. ".gpkg" +end + +-- /build/packages, or nil if there is none (not made here). +local function kept_dir(ctx) + local d = ffi.string(ctx.store_path):gsub("/store$", "") .. "/build/packages" + return exists(d) and d or nil +end + +-- The kept packages of the installed source builds: the file names a +-- prune leaves, and (for layer_plan) name -> { ver, path, deps }. +local function kept_scan(opts) + local ctx = h.live_context(opts) + local dir = kept_dir(ctx) + if not dir then return nil, {}, {} end + local want, by_name = {}, {} + for _, i in ipairs(h.installed_entries(opts)) do + if h.built_from(ctx, i.repo, i.name) then + local f = kept_name(i.repo, i.name, i.ver) + local path = dir .. "/" .. f + want[f] = true + local m = ffi.new("gl_pkg_t") + if exists(path) and istore.gl_read_pkg_manifest(path, m) == 0 then + by_name[i.name] = { ver = i.ver, path = path, + deps = h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") } + istore.gl_free_pkg(m) + end + end + end + return dir, want, by_name +end + +--- The installed source builds a build can use as layers: name -> +--- { ver, path, deps }. +function M.kept(opts) + local _, _, by_name = kept_scan(opts) + return by_name +end + +--- After a commit: keep the private copy `path` of a package this run +--- built and installed (repo::name ver). A failure only warns: the +--- package is installed, and only later builds would miss it. +function M.keep(opts, path, repo, name, ver) + local ctx = h.live_context(opts) + local out = ffi.new("char[4096]") + local ok = txn.gl_scope_build_dir(ctx, "packages", -1, out) == 0 + local dest = ok and (ffi.string(out) .. "/" .. kept_name(repo, name, ver)) + if not ok or not copy_file(path, dest .. ".part", + opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600") + or not os.rename(dest .. ".part", dest) then + if dest then os.remove(dest .. ".part") end + log.lg_printf(1, "Could not keep %s::%s %s for later builds.", repo, name, ver) + end +end + +--- After a commit: delete the kept packages that are no longer an +--- installed source build (removed, replaced, or reinstalled from a +--- binary repository). +function M.prune_kept(opts) + local dir, want = kept_scan(opts) + if not dir then return end + local p = io.popen("ls -A -- " .. h.shell_quote(dir)) + for f in p:lines() do + if not want[f] then os.remove(dir .. "/" .. f) end + end + p:close() +end + +ffi.cdef[[ +int gpkg_build_getpid(void) asm("getpid"); +]] + +return M diff --git a/lib/gpkg_build.lua.old4 b/lib/gpkg_build.lua.old4 new file mode 100644 index 0000000..9919268 --- /dev/null +++ b/lib/gpkg_build.lua.old4 @@ -0,0 +1,686 @@ +-- lib/gpkg_build.lua +-- +-- The package builder (BUILD_DESIGN.txt): turns a recipe from a NAME-src +-- repository into a .gpkg, built in gsandbox, which gpkg_common then +-- installs like any fetched package. Used only through gpkg_common. +-- +-- Nothing a build produces is trusted: the output is copied privately +-- while hashed and its manifest (read by the library) must be exactly +-- the one handed in. What IS trusted is what decides the build: the +-- bundle (hash from the signed index, then checked by gl_recipe_read), +-- each source (the recipe's SHA256), the layers (packages verified +-- against their signed indexes) and this file and build-driver.sh. + +local ffi = require("ffi") +local bit = require("bit") + +local M = {} + +-- Set by M.init(): FFI handles and gpkg_common's helpers. +local log, istore, txn, h + +function M.init(env) + log, istore, txn = env.log, env.istore, env.txn + h = env +end + +local SYSTEM_CONF = "/etc/glacier/glacier.conf" +local SYSTEM_CONFIG_DIR = "/etc/glacier/config" + +-- --------------------------------------------------------------------- +-- Small helpers +-- --------------------------------------------------------------------- + +local function lines(s) + local out = {} + for l in (s or ""):gmatch("([^\n]*)\n") do table.insert(out, l) end + return out +end + +local function exists(path) + local f = io.open(path, "rb") + if f then f:close() return true end + local ok = os.execute("test -e " .. h.shell_quote(path)) + return ok == true or ok == 0 +end + +-- The exit status of a shell command line. +local function status_of(cmd) + local p = io.popen(cmd .. "; echo \"rc=$?\"") + local out = p:read("*a") + p:close() + return tonumber(out:match("rc=(%d+)%s*$")) or 255 +end + +local function sh_ok(cmd) + return status_of(cmd .. " >/dev/null 2>&1") == 0 +end + +-- A libconfig string literal. +local function cfg_string(s) + return '"' .. s:gsub("\\", "\\\\"):gsub('"', '\\"') .. '"' +end + +-- --------------------------------------------------------------------- +-- Settings (BUILD_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +-- One configuration file's build settings, or nil if it doesn't exist. +-- Exits if it is malformed (or, read by syspkg, untrusted). +local conf_cache = {} +local function read_conf(path, kind, opts) + if conf_cache[path] ~= nil then return conf_cache[path] or nil end + if not exists(path) then + conf_cache[path] = false + return nil + end + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(path) + end + local c = ffi.new("gl_build_conf_t") + if tonumber(istore.gl_conf_build(path, kind, c)) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + h.finish(1) + end + local function str(v) return v ~= nil and ffi.string(v) or nil end + local r = { + traits = lines(str(c.traits)), cflags = str(c.cflags), + cxxflags = str(c.cxxflags), ldflags = str(c.ldflags), + configure = lines(str(c.configure)), + jobs = c.jobs > 0 and tonumber(c.jobs) or nil, + build_user = str(c.build_user), build_root = lines(str(c.build_root)), + path = path, + } + istore.gl_build_conf_free(c) + conf_cache[path] = r + return r +end + +-- The user's base directory (, beside index and store). +local function user_base(opts) + return string.format("/glacier/usr/%d", opts.uid) +end + +-- The configuration layers for package `name`, lowest first: +-- { global = {...}, package = {...} } lists of read_conf results. +local function conf_layers(name, opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if opts.scope == ffi.C.GL_SCOPE_SYS then + return { sys }, read_conf(SYSTEM_CONFIG_DIR .. "/" .. name .. ".conf", + ffi.C.GL_CONF_PACKAGE, opts) + end + local base = user_base(opts) .. "/config" + return { sys, read_conf(base .. "/glacier.conf", ffi.C.GL_CONF_USER, opts) }, + read_conf(base .. "/" .. name .. ".conf", ffi.C.GL_CONF_PACKAGE, opts) +end + +-- The system's settings a build can't do without: BUILD_ROOT, and for +-- syspkg BUILD_USER (its uid too). Exits saying which is missing. +local function system_settings(opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if not sys then + log.lg_printf(2, "Cannot read %s.", SYSTEM_CONF) + h.finish(1) + end + if #sys.build_root == 0 then + log.lg_printf(2, "BUILD_ROOT is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local s = { build_root = sys.build_root } + if opts.scope == ffi.C.GL_SCOPE_SYS then + if not sys.build_user then + log.lg_printf(2, "BUILD_USER is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local p = io.popen("id -u -- " .. h.shell_quote(sys.build_user) .. " 2>/dev/null") + local uid = tonumber(p and p:read("*l") or "") + if p then p:close() end + if not uid then + log.lg_printf(2, "BUILD_USER %s in %s is not a user.", sys.build_user, + SYSTEM_CONF) + h.finish(1) + elseif uid == 0 then + log.lg_printf(2, "BUILD_USER in %s must not be root.", SYSTEM_CONF) + h.finish(1) + end + s.build_user, s.build_uid = sys.build_user, uid + end + return s +end + +--- The effective traits of building `name`, whose recipe (or -src index +--- entry) declares `declared` ("NAME D\n" lines). Returns a table +--- { on = { trait = bool }, list = sorted { "ssl", "-ldap" }, show = +--- "[+ssl -ldap]" (or "" with no traits) }. Exits if a per-package file +--- names a trait the recipe doesn't declare. +function M.traits(name, declared, opts) + local on, names = {}, {} + for _, l in ipairs(lines(declared)) do + local t, d = l:match("^(%S+) ([01])$") + on[t] = d == "1" + table.insert(names, t) + end + local function apply(conf, strict) + if not conf then return end + for _, s in ipairs(conf.traits) do + local neg = s:sub(1, 1) == "-" + local t = neg and s:sub(2) or s + if on[t] ~= nil then + on[t] = not neg + elseif strict then + log.lg_printf(2, "%s: %s has no trait %s.", conf.path, name, t) + h.finish(1) + end + end + end + local globals, pkg = conf_layers(name, opts) + for _, g in ipairs(globals) do apply(g, false) end + apply(pkg, true) + + table.sort(names) + local list, show = {}, {} + for _, t in ipairs(names) do + table.insert(list, on[t] and t or ("-" .. t)) + table.insert(show, (on[t] and "+" or "-") .. t) + end + return { on = on, list = list, + show = #show > 0 and ("[" .. table.concat(show, " ") .. "]") or "" } +end + +--- Relation lines ("NAME VER[ IF]\n") with their IF resolved against +--- traits `tr`: "NAME VER\n" for each that applies. +function M.effective(rel, tr) + local out = {} + for _, l in ipairs(lines(rel)) do + local n, v, c = l:match("^(%S+) (%S+) ?(%S*)$") + local applies = c == "" or + (c:sub(1, 1) == "-" and not tr.on[c:sub(2)]) or + (c:sub(1, 1) ~= "-" and tr.on[c]) + if applies then table.insert(out, n .. " " .. v .. "\n") end + end + return table.concat(out) +end + +--- Check, before the prompt, everything a build of `name` needs from +--- the configuration (exits on a problem): BUILD_ROOT, BUILD_USER. +function M.check(opts) + if opts.sysroot then + log.lg_printf(2, "Building from source under -R is not supported.") + h.finish(1) + end + system_settings(opts) + -- gsandbox and the driver decide what a build produces, which + -- root then installs: checked like syspkg's own files, here + -- rather than at startup, since only builds need them. + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(h.gsandbox_path) + h.require_trusted(h.lib_dir .. "/build-driver.sh") + end +end + +-- --------------------------------------------------------------------- +-- The build +-- --------------------------------------------------------------------- + +-- /build/NAME, made and checked by the library; owned by the +-- builder (`owner` = BUILD_USER's uid, syspkg) or the scope. +local function build_dir(ctx, name, owner) + local out = ffi.new("char[4096]") + if txn.gl_scope_build_dir(ctx, name, owner or -1, out) ~= 0 then + h.finish(1) -- the library said why + end + return ffi.string(out) +end + +-- Remove a build's directory tree (the builder's files may be +-- read-only to it: overlayfs's work dir is mode 000). +local function remove_tree(path) + os.execute("chmod -R u+rwX " .. h.shell_quote(path) .. " 2>/dev/null; rm -rf " + .. h.shell_quote(path)) +end + +-- Copy a file (cp, then the given mode). +local function copy_file(src, dst, mode) + return sh_ok("cp -- " .. h.shell_quote(src) .. " " .. h.shell_quote(dst)) + and sh_ok("chmod " .. mode .. " " .. h.shell_quote(dst)) +end + +-- Fetch a source URL (https through curl, file:// a copy) into dest +-- hashed: true if it arrived and has hash `hex`. Redirects are +-- followed, https only (release tarballs are mostly served that way); +-- the hash decides. +local MAX_SOURCE = 4 * 1024 * 1024 * 1024 +local function fetch_source(url, dest, hex) + local tmp = dest .. ".part" + os.remove(tmp) + local cmd + local path = url:match("^file://(/.*)$") + if path then + cmd = "cp -- " .. h.shell_quote(path) .. " " .. h.shell_quote(tmp) + else + cmd = "curl -sfL --max-redirs 5 --proto =https --proto-redir =https --connect-timeout 30" .. + " --max-filesize " .. MAX_SOURCE .. " -o " .. h.shell_quote(tmp) .. + " -- " .. h.shell_quote(url) + end + if not sh_ok(cmd) then + os.remove(tmp) + return false, false + end + if h.sha256_file(tmp) ~= hex then + os.remove(tmp) + return false, true + end + return os.rename(tmp, dest) ~= nil +end + +-- The libconfig manifest a build must produce. +local function manifest_text(r, deps, confs, tr) + local function rel(text) + local out = {} + for n, v in text:gmatch("(%S+) (%S+)\n") do + table.insert(out, string.format('{ PKG_NAME = "%s"; PKG_VER = "%s"; }', n, v)) + end + return "(" .. table.concat(out, ", ") .. ")" + end + local t = {} + for _, s in ipairs(tr.list) do table.insert(t, '"' .. s .. '"') end + return table.concat({ + "PKG_NAME = " .. cfg_string(r.name) .. ";", + "PKG_VER = " .. cfg_string(r.ver) .. ";", + "PKG_DESC = " .. cfg_string(r.desc) .. ";", + "PKG_MAINT = " .. cfg_string(r.maint) .. ";", + "PKG_COPYRIGHT = " .. cfg_string(r.copyright) .. ";", + "PKG_REPO = " .. cfg_string(r.repo) .. ";", + "PKG_DEPS = " .. rel(deps) .. ";", + "PKG_CONFS = " .. rel(confs) .. ";", + "PKG_TRAITS = [ " .. table.concat(t, ", ") .. " ];", + }, "\n") .. "\n" +end + +-- The driver's env file: shell assignments, every value quoted. +local function env_text(r, settings, tr, sources, prefix) + local q = h.shell_quote + local args = {} + for _, a in ipairs(lines(r.configure)) do table.insert(args, q(a)) end + for _, l in ipairs(lines(r.trait_args)) do + local t, side, a = l:match("^([^\t]+)\t([+-])\t(.*)$") + if (side == "+") == (tr.on[t] == true) then table.insert(args, q(a)) end + end + for _, a in ipairs(settings.configure) do table.insert(args, q(a)) end + local on = {} + for _, s in ipairs(tr.list) do + if s:sub(1, 1) ~= "-" then table.insert(on, s) end + end + local function kv(k, v) return k .. "=" .. q(v or "") .. "\n" end + return kv("NAME", r.name) .. kv("VER", r.ver) .. kv("BUILD", r.build) .. + kv("PREFIX", prefix) .. + kv("SOURCES", table.concat(sources, " ")) .. + kv("PATCHES", table.concat(lines(r.patches), " ")) .. + kv("CONFIGURE_ARGS", table.concat(args, " ")) .. + kv("TRAITS", table.concat(on, " ")) .. + kv("JOBS", tostring(settings.jobs)) .. + kv("CFLAGS", settings.cflags) .. kv("CXXFLAGS", settings.cxxflags) .. + kv("LDFLAGS", settings.ldflags) +end + +-- CFLAGS/CXXFLAGS/LDFLAGS/CONFIGURE/JOBS for package `name`: the +-- per-package value replaces the global one; the user's global replaces +-- the system's. +local function flags_for(name, opts) + local globals, pkg = conf_layers(name, opts) + local s = { configure = pkg and pkg.configure or {}, jobs = 1 } + for _, k in ipairs({ "cflags", "cxxflags", "ldflags" }) do + for _, g in ipairs(globals) do + if g and g[k] then s[k] = g[k] end + end + if pkg and pkg[k] then s[k] = pkg[k] end + end + for _, g in ipairs(globals) do + if g and g.jobs then s.jobs = g.jobs end + end + return s +end + +-- Whether the private copy `path`'s manifest (read by the library) is +-- exactly what the build was handed. +local function output_matches(path, r, deps, confs, tr) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then return false end + local want_traits = #tr.list > 0 and (table.concat(tr.list, "\n") .. "\n") or "" + local ok = ffi.string(m.pkg_name) == r.name + and ffi.string(m.pkg_repo) == r.repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == r.ver + and h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == deps + and h.relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == confs + and m.pkg_traits ~= nil and ffi.string(m.pkg_traits) == want_traits + istore.gl_free_pkg(m) + return ok +end + +-- The recipe of a verified bundle copy, as a table, or nil. +local function read_recipe(path) + local r = ffi.new("gl_recipe_t") + if tonumber(istore.gl_recipe_read(path, r)) ~= 0 then return nil end + local t = {} + for _, k in ipairs({ "name", "ver", "repo", "desc", "maint", "copyright", + "sources", "patches", "build", "configure", "traits", "trait_args", + "deps", "build_deps", "confs" }) do + t[k] = ffi.string(r[k]) + end + istore.gl_recipe_free(r) + return t +end + +-- The packages a build stacks as layers: BUILD_ROOT, the effective +-- BUILD_DEPS and DEPS, and everything they depend on, each from +-- `built` (this run's own builds), `kept` (installed source builds, +-- M.kept) or the binary repositories, in that order, at a high enough +-- version. A list of { name, path, sha (hex) }, top first. Exits if +-- one can't be had. +local function layer_plan(id, root_names, build_deps, deps, indexes, built, kept) + local plan, seen = {}, {} + local queue = {} + for _, rel in ipairs({ deps, build_deps }) do + for n, v in rel:gmatch("(%S+) (%S+)\n") do table.insert(queue, { n, v }) end + end + for _, n in ipairs(root_names) do table.insert(queue, { n, "0.0.0" }) end + local k = 1 + while k <= #queue do + local n, v = queue[k][1], queue[k][2] + k = k + 1 + if not seen[n] then + seen[n] = true + local b = built[n] + if not (b and h.vercmp(b.ver, v) >= 0) then b = kept[n] end + if b and b.path and not b.sha then b.sha = h.sha256_file(b.path) or false end + if b and b.sha ~= false and h.vercmp(b.ver, v) >= 0 then + table.insert(plan, { name = n, ver = b.ver, path = b.path, sha = b.sha }) + for dn, dv in b.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + else + local r, e = h.pick_binary(indexes, n) + if not e or h.vercmp(e.ver, v) < 0 then + log.lg_printf(2, "%s needs %s %s or later to build, and no binary repository has it.", + id, n, v) + h.finish(1) + end + table.insert(plan, { name = n, ver = e.ver, repo = r, entry = e, + sha = e.sha256:match("^sha256:(%x+)$") }) + for dn, dv in e.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + end + end + end + return plan +end + +--- Check, before the prompt, that every layer a build of plan item `it` +--- needs can be had (exits otherwise). `planned` maps the names this +--- run builds to { ver, deps }. +function M.check_layers(it, indexes, planned, opts) + local settings = system_settings(opts) + local id = string.format("%s::%s %s", it.repo.name, it.entry.name, it.entry.ver) + layer_plan(id, settings.build_root, M.effective(it.entry.build_deps, it.traits), + it.deps, indexes, planned, M.kept(opts)) +end + +--- Build plan item `it` (a -src repository's entry, with it.traits from +--- M.traits) into a verified private copy of its .gpkg. `built` maps +--- names this run has already built to { ver, path, sha }, for layers. +--- Returns the copy and its sidecar text; exits on any failure. +function M.build(it, indexes, built, opts) + local e, r_src = it.entry, it.repo + local id = string.format("%s::%s %s", r_src.name, e.name, e.ver) + local settings = system_settings(opts) + local owner = settings.build_uid + local ctx = h.live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600" + + -- The bundle: downloaded and hashed against the signed index, + -- copied privately, then read and checked by the library. + local cached, wrong = h.download(ctx, r_src, e, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + local copy = cached and h.verify_and_copy(cached, e.sha256 .. "\n") + local r = copy and read_recipe(copy) + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + h.finish(1) + end + if not r or r.name ~= e.name or r.ver ~= e.ver or r.repo .. "-src" ~= r_src.name + or r.deps ~= e.deps or r.confs ~= e.confs or r.build_deps ~= e.build_deps + or r.traits ~= e.traits then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + h.finish(1) + end + if cached then os.remove(cached) end + + local tr = it.traits + local deps, confs = M.effective(r.deps, tr), M.effective(r.confs, tr) + local build_deps = M.effective(r.build_deps, tr) + local flags = flags_for(r.name, opts) + + -- The prefix the package is built for: where its usr/ will be + -- linked, so it finds its own files at run time. /usr for base, + -- else the scope's links (no -R here: these are runtime paths). + local prefix = r.repo == "base" and "/usr" or + (ffi.string(ctx.links_path):gsub("/+$", "")) + + -- Sources, by hash, in /build/sources. + local sources_dir = build_dir(ctx, "sources") + local sources = {} + for url, hex in r.sources:gmatch("(%S+) sha256:(%x+)\n") do + local file = url:match("([^/]+)$") + local dest = sources_dir .. "/" .. hex + if h.sha256_file(dest) ~= hex then + local ok, mismatch = fetch_source(url, dest, hex) + if not ok then + log.lg_printf(2, mismatch and "A source of %s does not match its hash." + or "Cannot fetch the sources of %s.", id) + h.finish(1) + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(dest)) + end + table.insert(sources, { file = file, path = dest }) + end + + -- This build's input (the scope's) and work/output (the builder's). + local tag = string.format("%s-%s-%d", r.name, r.ver, ffi.C.gpkg_build_getpid()) + local in_dir = build_dir(ctx, "in-" .. tag) + local work = build_dir(ctx, "work-" .. tag, owner) + local out = build_dir(ctx, "out-" .. tag, owner) + local function cleanup() + remove_tree(in_dir) + remove_tree(work) + remove_tree(out) + end + local function fail(fmt, ...) + log.lg_printf(2, fmt, ...) + cleanup() + h.finish(1) + end + + -- Layers, extracted once each into /build/layers by the + -- builder: NAME-VER-. + local layers_dir = build_dir(ctx, "layers", owner) + local layer_names = {} + local user_flag = settings.build_user and (" -u " .. h.shell_quote(settings.build_user)) or "" + for _, l in ipairs(layer_plan(id, settings.build_root, build_deps, deps, indexes, built, + M.kept(opts))) do + local lname = string.format("%s-%s-%s", l.name, l.ver, l.sha:sub(1, 8)) + if not exists(layers_dir .. "/" .. lname) then + local path = l.path + if l.entry then + path = h.download(ctx, l.repo, l.entry, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + if not path then fail("Cannot fetch %s::%s %s.", l.repo.name, l.name, l.ver) end + else + -- A package this run built: its private copy, + -- copied where the builder can read it. + local p = in_dir .. "/" .. lname .. ".gpkg" + if not copy_file(l.path, p, "644") then + fail("Cannot write %s.", p) + end + path = p + end + local tmp = string.format(".%s.%d", lname, ffi.C.gpkg_build_getpid()) + if not sh_ok(h.gsandbox .. " -X" .. user_flag .. " -p " .. h.shell_quote(path) .. + " -d " .. h.shell_quote(layers_dir .. "/" .. tmp)) then + fail("Cannot extract %s %s for %s.", l.name, l.ver, id) + end + if not os.rename(layers_dir .. "/" .. tmp, layers_dir .. "/" .. lname) then + remove_tree(layers_dir .. "/" .. tmp) + end + end + table.insert(layer_names, lname) + end + + -- The input: bundle, sources, manifest, env, driver. + local function put(name, text) + local f = io.open(in_dir .. "/" .. name, "wb") + if not f or not f:write(text) then fail("Cannot write %s/%s.", in_dir, name) end + f:close() + if not sh_ok("chmod 644 " .. h.shell_quote(in_dir .. "/" .. name)) then + fail("Cannot write %s/%s.", in_dir, name) + end + end + if not copy_file(copy, in_dir .. "/bundle.grcp", "644") or + not sh_ok("mkdir -m 755 " .. h.shell_quote(in_dir .. "/sources")) then + fail("Cannot write %s.", in_dir) + end + local files = {} + for _, s in ipairs(sources) do + if not copy_file(s.path, in_dir .. "/sources/" .. s.file, "644") then + fail("Cannot write %s.", in_dir) + end + table.insert(files, s.file) + end + put("manifest.gpm.cfg", manifest_text(r, deps, confs, tr)) + put("env", env_text(r, flags, tr, files, prefix)) + local df = io.open(h.lib_dir .. "/build-driver.sh", "rb") + local driver = df and df:read("*a") + if df then df:close() end + if not driver then fail("Cannot read %s/build-driver.sh.", h.lib_dir) end + put("driver", driver) + + -- The build. Its output goes to /build/logs/NAME-VER.log, + -- and to the terminal unless -q. + local log_path = build_dir(ctx, "logs") .. "/" .. r.name .. "-" .. r.ver .. ".log" + local cmd = h.gsandbox .. " -R" .. user_flag .. " -L " .. h.shell_quote(layers_dir) + for _, l in ipairs(layer_names) do cmd = cmd .. " -l " .. h.shell_quote(l) end + cmd = cmd .. " -w " .. h.shell_quote(work) .. " -i " .. h.shell_quote(in_dir) .. + " -o " .. h.shell_quote(out) + log.lg_printf(0, "Building %s%s...", id, tr.show ~= "" and (" " .. tr.show) or "") + local st + if not h.quiet() then + local stf = in_dir .. "/.status" + os.execute("{ " .. cmd .. " 2>&1; echo $? > " .. h.shell_quote(stf) .. "; } | tee " + .. h.shell_quote(log_path)) + local f = io.open(stf, "r") + st = f and tonumber(f:read("*l")) or 255 + if f then f:close() end + else + st = status_of(cmd .. " > " .. h.shell_quote(log_path) .. " 2>&1") + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(log_path)) + if st ~= 0 then + fail("Building %s failed. Log: %s", id, log_path) + end + + -- The output, untrusted: copied privately while hashed, then its + -- manifest must be exactly the one handed in. + local result = out .. "/" .. r.name .. "-" .. r.ver .. ".gpkg" + local hex = h.sha256_file(result) + local pkg = hex and h.verify_and_copy(result, "sha256:" .. hex .. "\n") + if not pkg or not output_matches(pkg, r, deps, confs, tr) then + fail("%s: the build produced another package.", id) + end + cleanup() + log.lg_printf(3, "Built %s.", id) + return pkg, "sha256:" .. hex .. "\n", hex +end + +-- --------------------------------------------------------------------- +-- Kept packages: the verified .gpkg of each installed source build, +-- the bytes that were installed, so a later build can use it as a +-- layer (no binary repository has it). /build/packages/ +-- REPO@NAME-VER.gpkg ('@' is in no name), kept while that version is +-- installed and built from source. +-- --------------------------------------------------------------------- + +local function kept_name(repo, name, ver) + return repo .. "@" .. name .. "-" .. ver .. ".gpkg" +end + +-- /build/packages, or nil if there is none (not made here). +local function kept_dir(ctx) + local d = ffi.string(ctx.store_path):gsub("/store$", "") .. "/build/packages" + return exists(d) and d or nil +end + +-- The kept packages of the installed source builds: the file names a +-- prune leaves, and (for layer_plan) name -> { ver, path, deps }. +local function kept_scan(opts) + local ctx = h.live_context(opts) + local dir = kept_dir(ctx) + if not dir then return nil, {}, {} end + local want, by_name = {}, {} + for _, i in ipairs(h.installed_entries(opts)) do + if h.built_from(ctx, i.repo, i.name) then + local f = kept_name(i.repo, i.name, i.ver) + local path = dir .. "/" .. f + want[f] = true + local m = ffi.new("gl_pkg_t") + if exists(path) and istore.gl_read_pkg_manifest(path, m) == 0 then + by_name[i.name] = { ver = i.ver, path = path, + deps = h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") } + istore.gl_free_pkg(m) + end + end + end + return dir, want, by_name +end + +--- The installed source builds a build can use as layers: name -> +--- { ver, path, deps }. +function M.kept(opts) + local _, _, by_name = kept_scan(opts) + return by_name +end + +--- After a commit: keep the private copy `path` of a package this run +--- built and installed (repo::name ver). A failure only warns: the +--- package is installed, and only later builds would miss it. +function M.keep(opts, path, repo, name, ver) + local ctx = h.live_context(opts) + local out = ffi.new("char[4096]") + local ok = txn.gl_scope_build_dir(ctx, "packages", -1, out) == 0 + local dest = ok and (ffi.string(out) .. "/" .. kept_name(repo, name, ver)) + if not ok or not copy_file(path, dest .. ".part", + opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600") + or not os.rename(dest .. ".part", dest) then + if dest then os.remove(dest .. ".part") end + log.lg_printf(1, "Could not keep %s::%s %s for later builds.", repo, name, ver) + end +end + +--- After a commit: delete the kept packages that are no longer an +--- installed source build (removed, replaced, or reinstalled from a +--- binary repository). +function M.prune_kept(opts) + local dir, want = kept_scan(opts) + if not dir then return end + local p = io.popen("ls -A -- " .. h.shell_quote(dir)) + for f in p:lines() do + if not want[f] then os.remove(dir .. "/" .. f) end + end + p:close() +end + +ffi.cdef[[ +int gpkg_build_getpid(void) asm("getpid"); +]] + +return M diff --git a/lib/gpkg_build.lua.old5 b/lib/gpkg_build.lua.old5 new file mode 100644 index 0000000..4fee010 --- /dev/null +++ b/lib/gpkg_build.lua.old5 @@ -0,0 +1,694 @@ +-- lib/gpkg_build.lua +-- +-- The package builder (BUILD_DESIGN.txt): turns a recipe from a NAME-src +-- repository into a .gpkg, built in gsandbox, which gpkg_common then +-- installs like any fetched package. Used only through gpkg_common. +-- +-- Nothing a build produces is trusted: the output is copied privately +-- while hashed and its manifest (read by the library) must be exactly +-- the one handed in. What IS trusted is what decides the build: the +-- bundle (hash from the signed index, then checked by gl_recipe_read), +-- each source (the recipe's SHA256), the layers (packages verified +-- against their signed indexes) and this file and build-driver.sh. + +local ffi = require("ffi") +local bit = require("bit") + +local M = {} + +-- Set by M.init(): FFI handles and gpkg_common's helpers. +local log, istore, txn, h + +function M.init(env) + log, istore, txn = env.log, env.istore, env.txn + h = env +end + +local SYSTEM_CONF = "/etc/glacier/glacier.conf" +local SYSTEM_CONFIG_DIR = "/etc/glacier/config" + +-- --------------------------------------------------------------------- +-- Small helpers +-- --------------------------------------------------------------------- + +local function lines(s) + local out = {} + for l in (s or ""):gmatch("([^\n]*)\n") do table.insert(out, l) end + return out +end + +local function exists(path) + local f = io.open(path, "rb") + if f then f:close() return true end + local ok = os.execute("test -e " .. h.shell_quote(path)) + return ok == true or ok == 0 +end + +-- The exit status of a shell command line. +local function status_of(cmd) + local p = io.popen(cmd .. "; echo \"rc=$?\"") + local out = p:read("*a") + p:close() + return tonumber(out:match("rc=(%d+)%s*$")) or 255 +end + +local function sh_ok(cmd) + return status_of(cmd .. " >/dev/null 2>&1") == 0 +end + +-- A libconfig string literal. +local function cfg_string(s) + return '"' .. s:gsub("\\", "\\\\"):gsub('"', '\\"') .. '"' +end + +-- --------------------------------------------------------------------- +-- Settings (BUILD_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +-- One configuration file's build settings, or nil if it doesn't exist. +-- Exits if it is malformed (or, read by syspkg, untrusted). +local conf_cache = {} +local function read_conf(path, kind, opts) + if conf_cache[path] ~= nil then return conf_cache[path] or nil end + if not exists(path) then + conf_cache[path] = false + return nil + end + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(path) + end + local c = ffi.new("gl_build_conf_t") + if tonumber(istore.gl_conf_build(path, kind, c)) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + h.finish(1) + end + local function str(v) return v ~= nil and ffi.string(v) or nil end + local r = { + traits = lines(str(c.traits)), cflags = str(c.cflags), + cxxflags = str(c.cxxflags), ldflags = str(c.ldflags), + configure = lines(str(c.configure)), + jobs = c.jobs > 0 and tonumber(c.jobs) or nil, + build_user = str(c.build_user), build_root = lines(str(c.build_root)), + path = path, + } + istore.gl_build_conf_free(c) + conf_cache[path] = r + return r +end + +-- The user's base directory (, beside index and store). +local function user_base(opts) + return string.format("/glacier/usr/%d", opts.uid) +end + +-- The configuration layers for package `name`, lowest first: +-- { global = {...}, package = {...} } lists of read_conf results. +local function conf_layers(name, opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if opts.scope == ffi.C.GL_SCOPE_SYS then + return { sys }, read_conf(SYSTEM_CONFIG_DIR .. "/" .. name .. ".conf", + ffi.C.GL_CONF_PACKAGE, opts) + end + local base = user_base(opts) .. "/config" + return { sys, read_conf(base .. "/glacier.conf", ffi.C.GL_CONF_USER, opts) }, + read_conf(base .. "/" .. name .. ".conf", ffi.C.GL_CONF_PACKAGE, opts) +end + +-- The system's settings a build can't do without: BUILD_ROOT, and for +-- syspkg BUILD_USER (its uid too). Exits saying which is missing. +local function system_settings(opts) + local sys = read_conf(SYSTEM_CONF, ffi.C.GL_CONF_SYSTEM, opts) + if not sys then + log.lg_printf(2, "Cannot read %s.", SYSTEM_CONF) + h.finish(1) + end + if #sys.build_root == 0 then + log.lg_printf(2, "BUILD_ROOT is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local s = { build_root = sys.build_root } + if opts.scope == ffi.C.GL_SCOPE_SYS then + if not sys.build_user then + log.lg_printf(2, "BUILD_USER is not set in %s.", SYSTEM_CONF) + h.finish(1) + end + local p = io.popen("id -u -- " .. h.shell_quote(sys.build_user) .. " 2>/dev/null") + local uid = tonumber(p and p:read("*l") or "") + if p then p:close() end + if not uid then + log.lg_printf(2, "BUILD_USER %s in %s is not a user.", sys.build_user, + SYSTEM_CONF) + h.finish(1) + elseif uid == 0 then + log.lg_printf(2, "BUILD_USER in %s must not be root.", SYSTEM_CONF) + h.finish(1) + end + s.build_user, s.build_uid = sys.build_user, uid + end + return s +end + +--- The effective traits of building `name`, whose recipe (or -src index +--- entry) declares `declared` ("NAME D\n" lines). Returns a table +--- { on = { trait = bool }, list = sorted { "ssl", "-ldap" }, show = +--- "[+ssl -ldap]" (or "" with no traits) }. Exits if a per-package file +--- names a trait the recipe doesn't declare. +function M.traits(name, declared, opts) + local on, names = {}, {} + for _, l in ipairs(lines(declared)) do + local t, d = l:match("^(%S+) ([01])$") + on[t] = d == "1" + table.insert(names, t) + end + local function apply(conf, strict) + if not conf then return end + for _, s in ipairs(conf.traits) do + local neg = s:sub(1, 1) == "-" + local t = neg and s:sub(2) or s + if on[t] ~= nil then + on[t] = not neg + elseif strict then + log.lg_printf(2, "%s: %s has no trait %s.", conf.path, name, t) + h.finish(1) + end + end + end + local globals, pkg = conf_layers(name, opts) + for _, g in ipairs(globals) do apply(g, false) end + apply(pkg, true) + + table.sort(names) + local list, show = {}, {} + for _, t in ipairs(names) do + table.insert(list, on[t] and t or ("-" .. t)) + table.insert(show, (on[t] and "+" or "-") .. t) + end + return { on = on, list = list, + show = #show > 0 and ("[" .. table.concat(show, " ") .. "]") or "" } +end + +--- Relation lines ("NAME VER[ IF]\n") with their IF resolved against +--- traits `tr`: "NAME VER\n" for each that applies. +function M.effective(rel, tr) + local out = {} + for _, l in ipairs(lines(rel)) do + local n, v, c = l:match("^(%S+) (%S+) ?(%S*)$") + local applies = c == "" or + (c:sub(1, 1) == "-" and not tr.on[c:sub(2)]) or + (c:sub(1, 1) ~= "-" and tr.on[c]) + if applies then table.insert(out, n .. " " .. v .. "\n") end + end + return table.concat(out) +end + +--- Check, before the prompt, everything a build of `name` needs from +--- the configuration (exits on a problem): BUILD_ROOT, BUILD_USER. +function M.check(opts) + if opts.sysroot then + log.lg_printf(2, "Building from source under -R is not supported.") + h.finish(1) + end + system_settings(opts) + -- gsandbox and the driver decide what a build produces, which + -- root then installs: checked like syspkg's own files, here + -- rather than at startup, since only builds need them. + if opts.scope == ffi.C.GL_SCOPE_SYS then + h.require_trusted(h.gsandbox_path) + h.require_trusted(h.lib_dir .. "/build-driver.sh") + end +end + +-- --------------------------------------------------------------------- +-- The build +-- --------------------------------------------------------------------- + +-- /build/NAME, made and checked by the library; owned by the +-- builder (`owner` = BUILD_USER's uid, syspkg) or the scope. +local function build_dir(ctx, name, owner) + local out = ffi.new("char[4096]") + if txn.gl_scope_build_dir(ctx, name, owner or -1, out) ~= 0 then + h.finish(1) -- the library said why + end + return ffi.string(out) +end + +-- Remove a build's directory tree (the builder's files may be +-- read-only to it: overlayfs's work dir is mode 000). +local function remove_tree(path) + os.execute("chmod -R u+rwX " .. h.shell_quote(path) .. " 2>/dev/null; rm -rf " + .. h.shell_quote(path)) +end + +-- Copy a file (cp, then the given mode). +local function copy_file(src, dst, mode) + return sh_ok("cp -- " .. h.shell_quote(src) .. " " .. h.shell_quote(dst)) + and sh_ok("chmod " .. mode .. " " .. h.shell_quote(dst)) +end + +-- Fetch a source URL (https through curl, file:// a copy) into dest +-- hashed: true if it arrived and has hash `hex`. Redirects are +-- followed, https only (release tarballs are mostly served that way); +-- the hash decides. +local MAX_SOURCE = 4 * 1024 * 1024 * 1024 +local function fetch_source(url, dest, hex) + local tmp = dest .. ".part" + os.remove(tmp) + local cmd + local path = url:match("^file://(/.*)$") + if path then + cmd = "cp -- " .. h.shell_quote(path) .. " " .. h.shell_quote(tmp) + else + cmd = "curl -sfL --max-redirs 5 --proto =https --proto-redir =https --connect-timeout 30" .. + " --max-filesize " .. MAX_SOURCE .. " -o " .. h.shell_quote(tmp) .. + " -- " .. h.shell_quote(url) + end + if not sh_ok(cmd) then + os.remove(tmp) + return false, false + end + if h.sha256_file(tmp) ~= hex then + os.remove(tmp) + return false, true + end + return os.rename(tmp, dest) ~= nil +end + +-- The libconfig manifest a build must produce. +local function manifest_text(r, deps, confs, tr) + local function rel(text) + local out = {} + for n, v in text:gmatch("(%S+) (%S+)\n") do + table.insert(out, string.format('{ PKG_NAME = "%s"; PKG_VER = "%s"; }', n, v)) + end + return "(" .. table.concat(out, ", ") .. ")" + end + local t = {} + for _, s in ipairs(tr.list) do table.insert(t, '"' .. s .. '"') end + return table.concat({ + "PKG_NAME = " .. cfg_string(r.name) .. ";", + "PKG_VER = " .. cfg_string(r.ver) .. ";", + "PKG_DESC = " .. cfg_string(r.desc) .. ";", + "PKG_MAINT = " .. cfg_string(r.maint) .. ";", + "PKG_COPYRIGHT = " .. cfg_string(r.copyright) .. ";", + "PKG_REPO = " .. cfg_string(r.repo) .. ";", + "PKG_DEPS = " .. rel(deps) .. ";", + "PKG_CONFS = " .. rel(confs) .. ";", + "PKG_TRAITS = [ " .. table.concat(t, ", ") .. " ];", + }, "\n") .. "\n" +end + +-- The driver's env file: shell assignments, every value quoted. +local function env_text(r, settings, tr, sources, prefix) + local q = h.shell_quote + local args = {} + for _, a in ipairs(lines(r.configure)) do table.insert(args, q(a)) end + for _, l in ipairs(lines(r.trait_args)) do + local t, side, a = l:match("^([^\t]+)\t([+-])\t(.*)$") + if (side == "+") == (tr.on[t] == true) then table.insert(args, q(a)) end + end + for _, a in ipairs(settings.configure) do table.insert(args, q(a)) end + local on = {} + for _, s in ipairs(tr.list) do + if s:sub(1, 1) ~= "-" then table.insert(on, s) end + end + local function kv(k, v) return k .. "=" .. q(v or "") .. "\n" end + return kv("NAME", r.name) .. kv("VER", r.ver) .. kv("BUILD", r.build) .. + kv("PREFIX", prefix) .. + kv("SOURCES", table.concat(sources, " ")) .. + kv("PATCHES", table.concat(lines(r.patches), " ")) .. + kv("CONFIGURE_ARGS", table.concat(args, " ")) .. + kv("TRAITS", table.concat(on, " ")) .. + kv("JOBS", tostring(settings.jobs)) .. + kv("CFLAGS", settings.cflags) .. kv("CXXFLAGS", settings.cxxflags) .. + kv("LDFLAGS", settings.ldflags) +end + +-- CFLAGS/CXXFLAGS/LDFLAGS/CONFIGURE/JOBS for package `name`: the +-- per-package value replaces the global one; the user's global replaces +-- the system's. +local function flags_for(name, opts) + local globals, pkg = conf_layers(name, opts) + local s = { configure = pkg and pkg.configure or {}, jobs = 1 } + for _, k in ipairs({ "cflags", "cxxflags", "ldflags" }) do + for _, g in ipairs(globals) do + if g and g[k] then s[k] = g[k] end + end + if pkg and pkg[k] then s[k] = pkg[k] end + end + for _, g in ipairs(globals) do + if g and g.jobs then s.jobs = g.jobs end + end + return s +end + +-- Whether the private copy `path`'s manifest (read by the library) is +-- exactly what the build was handed. +local function output_matches(path, r, deps, confs, tr) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then return false end + local want_traits = #tr.list > 0 and (table.concat(tr.list, "\n") .. "\n") or "" + local ok = ffi.string(m.pkg_name) == r.name + and ffi.string(m.pkg_repo) == r.repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == r.ver + and h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == deps + and h.relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == confs + and m.pkg_traits ~= nil and ffi.string(m.pkg_traits) == want_traits + istore.gl_free_pkg(m) + return ok +end + +-- The recipe of a verified bundle copy, as a table, or nil and why. +local function read_recipe(path) + local r = ffi.new("gl_recipe_t") + if tonumber(istore.gl_recipe_read(path, r)) ~= 0 then + return nil, ffi.string(istore.gl_recipe_error()) + end + local t = {} + for _, k in ipairs({ "name", "ver", "repo", "desc", "maint", "copyright", + "sources", "patches", "build", "configure", "traits", "trait_args", + "deps", "build_deps", "confs" }) do + t[k] = ffi.string(r[k]) + end + istore.gl_recipe_free(r) + return t +end + +-- The packages a build stacks as layers: BUILD_ROOT, the effective +-- BUILD_DEPS and DEPS, and everything they depend on, each from +-- `built` (this run's own builds), `kept` (installed source builds, +-- M.kept) or the binary repositories, in that order, at a high enough +-- version. A list of { name, path, sha (hex) }, top first. Exits if +-- one can't be had. +local function layer_plan(id, root_names, build_deps, deps, indexes, built, kept) + local plan, seen = {}, {} + local queue = {} + for _, rel in ipairs({ deps, build_deps }) do + for n, v in rel:gmatch("(%S+) (%S+)\n") do table.insert(queue, { n, v }) end + end + for _, n in ipairs(root_names) do table.insert(queue, { n, "0.0.0" }) end + local k = 1 + while k <= #queue do + local n, v = queue[k][1], queue[k][2] + k = k + 1 + if not seen[n] then + seen[n] = true + local b = built[n] + if not (b and h.vercmp(b.ver, v) >= 0) then b = kept[n] end + if b and b.path and not b.sha then b.sha = h.sha256_file(b.path) or false end + if b and b.sha ~= false and h.vercmp(b.ver, v) >= 0 then + table.insert(plan, { name = n, ver = b.ver, path = b.path, sha = b.sha }) + for dn, dv in b.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + else + local r, e = h.pick_binary(indexes, n) + if not e or h.vercmp(e.ver, v) < 0 then + log.lg_printf(2, "%s needs %s %s or later to build, and no binary repository has it.", + id, n, v) + h.finish(1) + end + table.insert(plan, { name = n, ver = e.ver, repo = r, entry = e, + sha = e.sha256:match("^sha256:(%x+)$") }) + for dn, dv in e.deps:gmatch("(%S+) (%S+)\n") do + table.insert(queue, { dn, dv }) + end + end + end + end + return plan +end + +--- Check, before the prompt, that every layer a build of plan item `it` +--- needs can be had (exits otherwise). `planned` maps the names this +--- run builds to { ver, deps }. +function M.check_layers(it, indexes, planned, opts) + local settings = system_settings(opts) + local id = string.format("%s::%s %s", it.repo.name, it.entry.name, it.entry.ver) + layer_plan(id, settings.build_root, M.effective(it.entry.build_deps, it.traits), + it.deps, indexes, planned, M.kept(opts)) +end + +--- Build plan item `it` (a -src repository's entry, with it.traits from +--- M.traits) into a verified private copy of its .gpkg. `built` maps +--- names this run has already built to { ver, path, sha }, for layers. +--- Returns the copy and its sidecar text; exits on any failure. +function M.build(it, indexes, built, opts) + local e, r_src = it.entry, it.repo + local id = string.format("%s::%s %s", r_src.name, e.name, e.ver) + local settings = system_settings(opts) + local owner = settings.build_uid + local ctx = h.live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600" + + -- The bundle: downloaded and hashed against the signed index, + -- copied privately, then read and checked by the library. + local cached, wrong = h.download(ctx, r_src, e, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + local copy = cached and h.verify_and_copy(cached, e.sha256 .. "\n") + local r, bad = nil, nil + if copy then r, bad = read_recipe(copy) end + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + h.finish(1) + end + if bad then + log.lg_printf(2, "%s has a malformed recipe bundle: %s.", id, bad) + if cached then os.remove(cached) end + h.finish(1) + end + if not r or r.name ~= e.name or r.ver ~= e.ver or r.repo .. "-src" ~= r_src.name + or r.deps ~= e.deps or r.confs ~= e.confs or r.build_deps ~= e.build_deps + or r.traits ~= e.traits then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + h.finish(1) + end + if cached then os.remove(cached) end + + local tr = it.traits + local deps, confs = M.effective(r.deps, tr), M.effective(r.confs, tr) + local build_deps = M.effective(r.build_deps, tr) + local flags = flags_for(r.name, opts) + + -- The prefix the package is built for: where its usr/ will be + -- linked, so it finds its own files at run time. /usr for base, + -- else the scope's links (no -R here: these are runtime paths). + local prefix = r.repo == "base" and "/usr" or + (ffi.string(ctx.links_path):gsub("/+$", "")) + + -- Sources, by hash, in /build/sources. + local sources_dir = build_dir(ctx, "sources") + local sources = {} + for url, hex in r.sources:gmatch("(%S+) sha256:(%x+)\n") do + local file = url:match("([^/]+)$") + local dest = sources_dir .. "/" .. hex + if h.sha256_file(dest) ~= hex then + local ok, mismatch = fetch_source(url, dest, hex) + if not ok then + log.lg_printf(2, mismatch and "A source of %s does not match its hash." + or "Cannot fetch the sources of %s.", id) + h.finish(1) + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(dest)) + end + table.insert(sources, { file = file, path = dest }) + end + + -- This build's input (the scope's) and work/output (the builder's). + local tag = string.format("%s-%s-%d", r.name, r.ver, ffi.C.gpkg_build_getpid()) + local in_dir = build_dir(ctx, "in-" .. tag) + local work = build_dir(ctx, "work-" .. tag, owner) + local out = build_dir(ctx, "out-" .. tag, owner) + local function cleanup() + remove_tree(in_dir) + remove_tree(work) + remove_tree(out) + end + local function fail(fmt, ...) + log.lg_printf(2, fmt, ...) + cleanup() + h.finish(1) + end + + -- Layers, extracted once each into /build/layers by the + -- builder: NAME-VER-. + local layers_dir = build_dir(ctx, "layers", owner) + local layer_names = {} + local user_flag = settings.build_user and (" -u " .. h.shell_quote(settings.build_user)) or "" + for _, l in ipairs(layer_plan(id, settings.build_root, build_deps, deps, indexes, built, + M.kept(opts))) do + local lname = string.format("%s-%s-%s", l.name, l.ver, l.sha:sub(1, 8)) + if not exists(layers_dir .. "/" .. lname) then + local path = l.path + if l.entry then + path = h.download(ctx, l.repo, l.entry, + tonumber(opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600", 8)) + if not path then fail("Cannot fetch %s::%s %s.", l.repo.name, l.name, l.ver) end + else + -- A package this run built: its private copy, + -- copied where the builder can read it. + local p = in_dir .. "/" .. lname .. ".gpkg" + if not copy_file(l.path, p, "644") then + fail("Cannot write %s.", p) + end + path = p + end + local tmp = string.format(".%s.%d", lname, ffi.C.gpkg_build_getpid()) + if not sh_ok(h.gsandbox .. " -X" .. user_flag .. " -p " .. h.shell_quote(path) .. + " -d " .. h.shell_quote(layers_dir .. "/" .. tmp)) then + fail("Cannot extract %s %s for %s.", l.name, l.ver, id) + end + if not os.rename(layers_dir .. "/" .. tmp, layers_dir .. "/" .. lname) then + remove_tree(layers_dir .. "/" .. tmp) + end + end + table.insert(layer_names, lname) + end + + -- The input: bundle, sources, manifest, env, driver. + local function put(name, text) + local f = io.open(in_dir .. "/" .. name, "wb") + if not f or not f:write(text) then fail("Cannot write %s/%s.", in_dir, name) end + f:close() + if not sh_ok("chmod 644 " .. h.shell_quote(in_dir .. "/" .. name)) then + fail("Cannot write %s/%s.", in_dir, name) + end + end + if not copy_file(copy, in_dir .. "/bundle.grcp", "644") or + not sh_ok("mkdir -m 755 " .. h.shell_quote(in_dir .. "/sources")) then + fail("Cannot write %s.", in_dir) + end + local files = {} + for _, s in ipairs(sources) do + if not copy_file(s.path, in_dir .. "/sources/" .. s.file, "644") then + fail("Cannot write %s.", in_dir) + end + table.insert(files, s.file) + end + put("manifest.gpm.cfg", manifest_text(r, deps, confs, tr)) + put("env", env_text(r, flags, tr, files, prefix)) + local df = io.open(h.lib_dir .. "/build-driver.sh", "rb") + local driver = df and df:read("*a") + if df then df:close() end + if not driver then fail("Cannot read %s/build-driver.sh.", h.lib_dir) end + put("driver", driver) + + -- The build. Its output goes to /build/logs/NAME-VER.log, + -- and to the terminal unless -q. + local log_path = build_dir(ctx, "logs") .. "/" .. r.name .. "-" .. r.ver .. ".log" + local cmd = h.gsandbox .. " -R" .. user_flag .. " -L " .. h.shell_quote(layers_dir) + for _, l in ipairs(layer_names) do cmd = cmd .. " -l " .. h.shell_quote(l) end + cmd = cmd .. " -w " .. h.shell_quote(work) .. " -i " .. h.shell_quote(in_dir) .. + " -o " .. h.shell_quote(out) + log.lg_printf(0, "Building %s%s...", id, tr.show ~= "" and (" " .. tr.show) or "") + local st + if not h.quiet() then + local stf = in_dir .. "/.status" + os.execute("{ " .. cmd .. " 2>&1; echo $? > " .. h.shell_quote(stf) .. "; } | tee " + .. h.shell_quote(log_path)) + local f = io.open(stf, "r") + st = f and tonumber(f:read("*l")) or 255 + if f then f:close() end + else + st = status_of(cmd .. " > " .. h.shell_quote(log_path) .. " 2>&1") + end + sh_ok("chmod " .. file_mode .. " " .. h.shell_quote(log_path)) + if st ~= 0 then + fail("Building %s failed. Log: %s", id, log_path) + end + + -- The output, untrusted: copied privately while hashed, then its + -- manifest must be exactly the one handed in. + local result = out .. "/" .. r.name .. "-" .. r.ver .. ".gpkg" + local hex = h.sha256_file(result) + local pkg = hex and h.verify_and_copy(result, "sha256:" .. hex .. "\n") + if not pkg or not output_matches(pkg, r, deps, confs, tr) then + fail("%s: the build produced another package.", id) + end + cleanup() + log.lg_printf(3, "Built %s.", id) + return pkg, "sha256:" .. hex .. "\n", hex +end + +-- --------------------------------------------------------------------- +-- Kept packages: the verified .gpkg of each installed source build, +-- the bytes that were installed, so a later build can use it as a +-- layer (no binary repository has it). /build/packages/ +-- REPO@NAME-VER.gpkg ('@' is in no name), kept while that version is +-- installed and built from source. +-- --------------------------------------------------------------------- + +local function kept_name(repo, name, ver) + return repo .. "@" .. name .. "-" .. ver .. ".gpkg" +end + +-- /build/packages, or nil if there is none (not made here). +local function kept_dir(ctx) + local d = ffi.string(ctx.store_path):gsub("/store$", "") .. "/build/packages" + return exists(d) and d or nil +end + +-- The kept packages of the installed source builds: the file names a +-- prune leaves, and (for layer_plan) name -> { ver, path, deps }. +local function kept_scan(opts) + local ctx = h.live_context(opts) + local dir = kept_dir(ctx) + if not dir then return nil, {}, {} end + local want, by_name = {}, {} + for _, i in ipairs(h.installed_entries(opts)) do + if h.built_from(ctx, i.repo, i.name) then + local f = kept_name(i.repo, i.name, i.ver) + local path = dir .. "/" .. f + want[f] = true + local m = ffi.new("gl_pkg_t") + if exists(path) and istore.gl_read_pkg_manifest(path, m) == 0 then + by_name[i.name] = { ver = i.ver, path = path, + deps = h.relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") } + istore.gl_free_pkg(m) + end + end + end + return dir, want, by_name +end + +--- The installed source builds a build can use as layers: name -> +--- { ver, path, deps }. +function M.kept(opts) + local _, _, by_name = kept_scan(opts) + return by_name +end + +--- After a commit: keep the private copy `path` of a package this run +--- built and installed (repo::name ver). A failure only warns: the +--- package is installed, and only later builds would miss it. +function M.keep(opts, path, repo, name, ver) + local ctx = h.live_context(opts) + local out = ffi.new("char[4096]") + local ok = txn.gl_scope_build_dir(ctx, "packages", -1, out) == 0 + local dest = ok and (ffi.string(out) .. "/" .. kept_name(repo, name, ver)) + if not ok or not copy_file(path, dest .. ".part", + opts.scope == ffi.C.GL_SCOPE_SYS and "644" or "600") + or not os.rename(dest .. ".part", dest) then + if dest then os.remove(dest .. ".part") end + log.lg_printf(1, "Could not keep %s::%s %s for later builds.", repo, name, ver) + end +end + +--- After a commit: delete the kept packages that are no longer an +--- installed source build (removed, replaced, or reinstalled from a +--- binary repository). +function M.prune_kept(opts) + local dir, want = kept_scan(opts) + if not dir then return end + local p = io.popen("ls -A -- " .. h.shell_quote(dir)) + for f in p:lines() do + if not want[f] then os.remove(dir .. "/" .. f) end + end + p:close() +end + +ffi.cdef[[ +int gpkg_build_getpid(void) asm("getpid"); +]] + +return M diff --git a/lib/gpkg_common.lua b/lib/gpkg_common.lua new file mode 100644 index 0000000..c3f45f6 --- /dev/null +++ b/lib/gpkg_common.lua @@ -0,0 +1,1745 @@ +-- lib/gpkg_common.lua +-- +-- Shared machinery between gpkg (per-user scope only) and syspkg +-- (system scope only). See SECURITY_DESIGN.txt section 7. +-- +-- The interface here is deliberately COARSE-GRAINED: M.install() and +-- M.remove() own the entire staged-transaction lifecycle +-- (gl_init_stage_context -> loop -> commit/abort), rather than +-- exporting fine-grained pieces that each caller then has to sequence +-- itself. That's what keeps the sequencing — and, once Checkpoint 2's +-- verification lands, the hash refusal matrix — in exactly ONE place +-- instead of duplicated across two binaries and drifting apart. +-- +-- What callers keep for themselves: +-- * argument parsing +-- * deciding WHICH scope they're allowed to request (gpkg never +-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag +-- for it", the capability isn't in its code path at all) +-- * their own privilege model (only syspkg runs elevated) +-- +-- Callers pass a `env` table on construction with the FFI handles and +-- shared state, so this module doesn't ffi.load() anything itself and +-- doesn't care where the .so's came from. + +local ffi = require("ffi") +local bit = require("bit") +local glacier_cdef = require("lib/glacier_cdef") +local build = require("lib/gpkg_build") + +local M = {} + +-- Module-level handles, set by M.init(). Kept here rather than passed +-- through every function because every function needs them. +local log, istore, txn, verify +local argv +local so_dir -- lib/glacier: the .so's and gsandbox +local init_build -- set at the end of this file +local isVerbose = false +local isQuiet = false -- -q: build output only to the log +local skipInstalled = false +local overwrite = false + +local txn_name = glacier_cdef.txn_name + +--- Initialise the module. Must be called before anything else. +-- env.log / env.istore / env.txn : ffi.load() handles +-- env.verify : libglacier_verify.so handle (installs) +-- env.argv : argv table (for usage messages) +-- env.so_dir : lib/glacier, where gsandbox is +function M.init(env) + log = env.log + istore = env.istore + txn = env.txn + verify = env.verify + argv = env.argv + so_dir = env.so_dir + init_build() +end + +--- Toggle flags the CLIs parse but this module acts on. +function M.set_verbose(v) isVerbose = v end +function M.set_quiet(v) isQuiet = v end +function M.set_skip_installed(v) skipInstalled = v end +function M.set_overwrite(v) overwrite = v end + +-- --------------------------------------------------------------------- +-- Manifest reading +-- --------------------------------------------------------------------- + +-- Quote a string for /bin/sh: wrap in single quotes, and turn each +-- embedded ' into '\''. Package paths come from the command line and +-- manifest entry names come from the archive, and syspkg runs all of +-- this as root — an unescaped ' in either is command execution. +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +--- name, repo and version ("MAJ.MIN.PAT", as the store names versions) +--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same +--- reader gl_install_pkg uses, so what is shown, compared and installed +--- can never disagree. nil if the manifest can't be read. +local function manifest_of(path) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return nil + end + local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo) + local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) + istore.gl_free_pkg(m) + return name, repo, ver +end + +-- --------------------------------------------------------------------- +-- Integrity verification (SECURITY_DESIGN.txt sections 3-4) +-- --------------------------------------------------------------------- + +-- Private working dir for verified copies, removed by finish(). +local private_dir = nil + +-- Backups written during this transaction but not yet committed +-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that +-- were never promoted, so an aborted upgrade leaves no stray backup. +local pending_backups = {} + +--- Exit, removing the private copies (and uncommitted backups) first. +--- Every exit on the install path goes through here. +local function finish(code) + for _, b in ipairs(pending_backups) do + os.remove(b.part) + end + pending_backups = {} + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +--- sha256 of a file as "", or nil. +local function sha256_file(path) + local f = io.open(path, "rb") + if not f then return nil end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = f:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + end + f:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +--- Copy `path` into the private dir, hashing it in the same pass, and +--- check the hash against `path`.sha256. Returns the private copy's path, +--- or nil plus a reason. +--- +--- Everything after this (summary, manifest read, gl_install_pkg) reads +--- ONLY the copy. Verifying the original and then installing it would +--- leave a gap where it could be swapped — and under syspkg that's root +--- reading a file whose directory another user may control. The copy +--- lives in a mktemp -d dir only the invoking user (root, for syspkg) +--- can write. +--- +--- Refusal matrix (section 4). A missing sidecar is treated exactly like +--- a mismatch: +--- repo == base -> always refuse, no exceptions +--- scope == SYS -> always refuse, any repo +--- scope == USR, repo != base -> refuse by default; the ONLY place +--- a future bypass flag may apply +--- No bypass exists, so today every row refuses and the repo (which we +--- couldn't trust before verifying anyway) never needs consulting. A +--- bypass, if ever added, must check scope and the VERIFIED manifest's +--- repo here, before anything else reads the file. +--- +--- A package fetched from a repository passes `vouched`, the "sha256:" +--- its signed index gives, in place of a sidecar. +local function verify_and_copy(path, vouched) + local sidecar = path .. ".sha256" + local sidecar_text = vouched + if not sidecar_text then + local sf = io.open(sidecar, "r") + if not sf then + return nil, "no sidecar " .. sidecar + end + sidecar_text = sf:read("*a") or "" + sf:close() + end + local expected = sidecar_text:match("^sha256:(%x+)%s*$") + if not expected or #expected ~= 64 then + return nil, "malformed sidecar " .. sidecar + end + expected = expected:lower() + + if not private_dir then + local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + return nil, "cannot create a private working directory" + end + end + + local src = io.open(path, "rb") + if not src then + return nil, "cannot open " .. path + end + + -- Unique per argument, so two packages with the same basename + -- (from different directories) can't collide. + local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0, + path:match("([^/]+)$")) + M._ncopies = (M._ncopies or 0) + 1 + local dst = io.open(copy_path, "wb") + if not dst then + src:close() + return nil, "cannot write " .. copy_path + end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = src:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + + if ffi.string(hex) ~= expected then + return nil, "hash mismatch (sidecar says " .. expected .. + ", file is " .. ffi.string(hex) .. ")" + end + + return copy_path, nil, sidecar_text +end + +-- --------------------------------------------------------------------- +-- Signatures (REPO_DESIGN.txt section 7) +-- --------------------------------------------------------------------- + +-- A keyring: repos.conf and the keys it lists, under `sysroot` (nil or +-- "/" = the running system). Read only by syspkg (gpkg reads the +-- system's until user repos). The signature on a local base package +-- (-l) is checked with the HOST's, even under -R (the build host's +-- trust, as KEEP_OLD). Repository operations (-y/-f/-u) use the +-- keyring of the system they act on: under -R, TARGET's own, since the +-- indexes they accept are TARGET's and TARGET checks them from then on. +local function keyring(sysroot) + local root = (sysroot or "/"):gsub("/+$", "") + return { root = root, conf = root .. "/etc/glacier/repos.conf", + keys = root .. "/etc/glacier/keys" } +end +local HOST_KEYRING = keyring(nil) + +ffi.cdef[[ +char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath"); +]] + +local function realpath(path) + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_common_realpath(path, buf) == nil then return nil end + return ffi.string(buf) +end + +-- nil if `path`, every ancestor of it, and every ancestor of its real +-- path are root-owned and not group/world-writable (as syspkg's own +-- lib/: a key a non-root user could swap is no key). Else the path at +-- fault, plus true if it is missing (or can't be resolved). +local function untrusted(path) + local function chain(p) + while true do + local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null") + local line = f and f:read("*l") + if f then f:close() end + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then return p, true end + if tonumber(uid) ~= 0 + or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + return p + end + if p == "/" then return nil end + p = p:match("^(.*)/[^/]*$") + if p == "" then p = "/" end + end + end + local bad, missing = chain(path) + if bad then return bad, missing end + local real = realpath(path) + if not real then return path, true end + return chain(real) +end + +-- Stop the run unless `path`, part of keyring `kr`, is trusted (as +-- untrusted() says) and, in another root, resolves inside it: TARGET's +-- etc/glacier/repos.conf -> /etc/glacier/repos.conf would read the +-- host's file as TARGET's. +local function require_trusted(path, kr) + local bad, missing = untrusted(path) + if bad and missing then + log.lg_printf(2, "Cannot read %s.", bad) + finish(1) + elseif bad then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + path, bad) + finish(1) + end + if kr.root ~= "" then + local real, root = realpath(path), realpath(kr.root) + if not (real and root and real:sub(1, #root + 1) == root .. "/") then + log.lg_printf(2, "Refusing %s: it resolves outside %s.", path, kr.root) + finish(1) + end + end +end + +-- Whether keyring `kr`'s repos.conf exists, having checked it is +-- trusted (else the run stops: the admin's configuration is at fault, +-- not a package). +local function repos_conf_present(kr) + local f, _, code = io.open(kr.conf, "r") + if f then f:close() end + if not f and code == 2 then return false end + require_trusted(kr.conf, kr) + return true +end + +-- The public keys keyring `kr` trusts for `repo`, read once per run: +-- { { name, pub }... }. A missing repos.conf trusts nothing. A +-- repos.conf or listed key that is untrusted or can't be read stops the +-- run: that is the admin's configuration, not the package, at fault. +local trusted_keys_cache = {} +local function trusted_keys(repo, kr) + local cache_key = kr.conf .. "\n" .. repo + if trusted_keys_cache[cache_key] then return trusted_keys_cache[cache_key] end + local keys = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[4096]") + local st = tonumber(istore.gl_conf_repo_keys(kr.conf, repo, buf, 4096)) + if st == 1 or st == 3 or st == 4 or st == 5 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name in ffi.string(buf):gmatch("([^\n]+)\n") do + local path = kr.keys .. "/" .. name .. ".pub" + local pub = ffi.new("gl_sign_pubkey_t") + require_trusted(path, kr) + if verify.gl_sign_read_pubkey(path, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + table.insert(keys, { name = name, pub = pub }) + end + end + trusted_keys_cache[cache_key] = keys + return keys +end + +-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very +-- bytes the copy was checked against) by a key trusted for `repo`. The +-- key is picked by the signature's keynum, never by trying each one. +local function signed_for(path, sidecar_text, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then + return false + end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, HOST_KEYRING)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0 + end + end + return false +end + +--- Verify every package up front, before the summary is even shown. +--- Returns the private copies, plus a copy -> original map for messages. +--- +--- In system scope, a package whose manifest says base must also have a +--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the +--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg +--- does). +local function verify_all(gpkg_paths, opts) + local copies, original = {}, {} + local refused = false + + for _, p in ipairs(gpkg_paths) do + local copy, why, sidecar_text = verify_and_copy(p) + if copy and not manifest_of(copy) then + log.lg_printf(2, "Cannot read the manifest of %s.", p) + refused = true + copy = nil + end + if copy and opts.scope == ffi.C.GL_SCOPE_SYS then + local name, repo = manifest_of(copy) + if repo == "base" and not signed_for(p, sidecar_text, repo) then + log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.", + repo, name, repo) + refused = true + copy = nil + end + end + if copy then + table.insert(copies, copy) + original[copy] = p + elseif why then + log.lg_printf(2, "Refusing %s: %s.", p, why) + refused = true + end + end + + if refused then + finish(1) + end + return copies, original +end + +-- --------------------------------------------------------------------- +-- Confirmation summary +-- --------------------------------------------------------------------- + +--- Print the summary for `entries` ({repo, name, ver} each) and ask. +local function confirm(entries) + log.lg_printf(0, "SUMMARY:") + print("==============================") + print("") + for _, e in ipairs(entries) do + print(string.format(" * %s::%s\t\t%-16s", + e.repo or "unknown", e.name, e.ver or "unknown")) + end + print("") + io.write("Proceed? (y/N): ") + io.stdout:flush() + + local response = io.read("*l") + if not response then + return false + end + response = response:lower() + return response == "y" or response == "yes" +end + +--- Installed packages, from the live index for this scope: a list of +--- {repo, name, ver, auto}. The index's `current` file holds one +--- `repo::name::version::auto|explicit` line per package (index files +--- written before 2026-10-05 stop at the version). +--- A live context for opts' scope (and install root: syspkg -R only). +local function live_context(opts) + local ctx = ffi.new("gl_context_t") + if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then + finish(1) -- the library said why + end + return ctx +end + +-- The entries of an index `current` file ({} if there is none). +local function read_index_file(path) + local f = io.open(path, "r") + local out = {} + if not f then return out end + for line in f:lines() do + local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$") + if repo then + local ver, kind = rest:match("^(.-)::(%a+)$") + table.insert(out, { repo = repo, name = name, ver = ver or rest, + auto = kind == "auto" }) + end + end + f:close() + return out +end + +local function installed_entries(opts) + local ctx = live_context(opts) + return read_index_file(ffi.string(ctx.index_path) .. "/current") +end + +-- --------------------------------------------------------------------- +-- Repo resolution +-- --------------------------------------------------------------------- + +function M.resolve_repo(ctx, pkg_name) + local list = istore.gl_find_pkg_repos(ctx, pkg_name) + + if list.count == 0 then + log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name) + istore.gl_free_repo_list(list) + return nil + end + + if list.count == 1 then + local repo = ffi.string(list.repos[0]) + istore.gl_free_repo_list(list) + return repo + end + + log.lg_printf(1, "Multiple instances of %s found:", pkg_name) + for i = 0, tonumber(list.count) - 1 do + print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name)) + end + print("") + io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ") + io.stdout:flush() + local input = io.read("*l") + local choice = tonumber(input) + + if not choice or choice < 1 or choice > tonumber(list.count) then + log.lg_printf(2, "Invalid selection.") + istore.gl_free_repo_list(list) + return nil + end + + local repo = ffi.string(list.repos[choice - 1]) + istore.gl_free_repo_list(list) + return repo +end + +-- --------------------------------------------------------------------- +-- Single-package install (with reinstall-if-present handling) +-- --------------------------------------------------------------------- + +local function install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + if not pkg_name then + log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path) + finish(1) + end + + if isVerbose then + log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s", + pkg_name, version_str, manifest_repo, gpkg_path) + end + + local status = istore.gl_install_pkg(ctx, gpkg_path) + + if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then + if skipInstalled then + log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str) + return tonumber(ffi.C.GL_INSTALL_SKIPPED) + end + + log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str) + + local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo) + + if rm_status ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).", + manifest_repo, pkg_name, tostring(tonumber(rm_status))) + return tonumber(rm_status) + end + + status = istore.gl_install_pkg(ctx, gpkg_path) + if status == ffi.C.GL_INSTALL_OK then + -- M.install logs the one "staged from" line. + return 0 + else + log.lg_printf(2, "Reinstall of %s-%s failed (error %s).", + pkg_name, version_str, tostring(tonumber(status))) + return tonumber(status) + end + + elseif status == ffi.C.GL_INSTALL_OK then + return 0 + end + + return tonumber(status) +end + +-- --------------------------------------------------------------------- +-- Transaction lifecycle +-- --------------------------------------------------------------------- + +--- Open a staged transaction for the given scope. Exits on failure with +--- a scope-appropriate message. `scope_label` is used only in the +--- lock-contention message ("for UID 1000" vs "for the system scope"). +local function begin_staged(opts) + local scope_label = opts.scope_label + local ctx = ffi.new("gl_context_t") + local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") + + if txn_st ~= ffi.C.GL_TXN_OK then + if txn_st == ffi.C.GL_TXN_ERR_LOCK then + log.lg_printf(2, + "Another glacier transaction is already in progress %s.", + scope_label) + else + log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st)) + end + finish(1) + end + + ctx.strict = opts.strict and 1 or 0 + return ctx +end + +--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt. +--- The library prints each problem; this exits if there were any. The +--- commit checks again (gl_check_txn), which is what covers a removal +--- whose repo is only chosen after the prompt. +local function check_plan(opts, adds, removes, exit) + local live = live_context(opts) + live.strict = opts.strict and 1 or 0 + live.overwrite = overwrite and 1 or 0 + local a = ffi.new("const char *[?]", #adds + 1) + for i, p in ipairs(adds) do a[i - 1] = p end + local r = ffi.new("const char *[?]", #removes + 1) + for i, id in ipairs(removes) do r[i - 1] = id end + local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes)) + if problems < 0 then + log.lg_printf(2, "Cannot read the package store to check dependencies.") + end + if problems ~= 0 then exit(1) end +end + +--- Commit, or abort-and-exit on failure. +local function commit_or_die(ctx) + local commit_st = txn.gl_commit_transaction(ctx) + if commit_st == ffi.C.GL_TXN_ERR_DEPS then + -- The library already said what's wrong, one line each. + txn.gl_abort_transaction(ctx) + finish(1) + elseif commit_st ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st)) + txn.gl_abort_transaction(ctx) + finish(1) + end +end + +--- The last line of a committed transaction. If the link pass refused +--- any path (each refusal is already printed above), the transaction is +--- committed but did not fully succeed: an error, and exit status 1. +local function report_done(ctx, exit) + local n = tonumber(ctx.link_refusals) + if n > 0 then + log.lg_printf(2, "%s %s not linked.", tostring(n), + n == 1 and "path was" or "paths were") + exit(1) + end + log.lg_printf(3, "Completed with no errors.") + exit(0) +end + +--- Abort the transaction and exit non-zero. Every failure path inside a +--- staged loop goes through here so live state is never left partially +--- mutated. +local function abort_and_die(ctx) + txn.gl_abort_transaction(ctx) + finish(1) +end + +-- --------------------------------------------------------------------- +-- Repository indexes (REPO_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +ffi.cdef[[ +int gpkg_common_getpid(void) asm("getpid"); +int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod"); +int gpkg_common_close(int fd) asm("close"); +]] + +-- Largest index accepted: what gl_sign_verify will check. +local MAX_INDEX = 64 * 1024 * 1024 + +-- A whole file, or nil if it is missing, unreadable or over `max`. +local function read_capped(path, max) + local f = io.open(path, "rb") + if not f then return nil end + local data = f:read(max + 1) or "" + f:close() + if #data > max then return nil end + return data +end + +-- Fetch URL/NAME into `dest`. https goes through curl, refusing any +-- other protocol, redirects included; file:// is a plain copy of an +-- absolute path. True on success. +local function fetch(url, name, dest) + local path = url:match("^file://(/.*)$") + if path then + local data = read_capped(path .. "/" .. name, MAX_INDEX) + local f = data and io.open(dest, "wb") + if not f then return false end + local ok = f:write(data) + f:close() + return ok ~= nil + end + if not url:match("^https://") then return false end + local ok = os.execute("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 --max-filesize " .. MAX_INDEX .. + " -o " .. shell_quote(dest) .. " -- " .. + shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1") + return ok == true or ok == 0 +end + +-- Whether `text` is signed by `sig_path`, with a key keyring `kr` +-- trusts for `repo` (picked by keynum, as signed_for). +local function index_signed(text, sig_path, repo, kr) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, kr)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", text), #text) == 0 + end + end + return false +end + +-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the +-- gl_index_parse status. +local function parse_index(text, repo) + local idx = ffi.new("gl_index_t") + local st = tonumber(istore.gl_index_parse(text, #text, repo, idx)) + if st ~= 0 then return nil, st end + local r = { serial = idx.serial, valid_until = idx.valid_until, + npkgs = tonumber(idx.npkgs) } + istore.gl_index_free(idx) + return r +end + +-- Refresh one repository's index into `dir` (/repos): fetch, +-- verify, parse, refuse a rollback or an expired index, then rename +-- over the accepted copy, checking signatures with keyring `kr`. Any +-- failure keeps the accepted copy, prints one line and returns false. +local function refresh_one(repo, url, dir, file_mode, kr) + local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid()) + local tmp_sig = tmp .. ".sig" + local function fail(fmt, ...) + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(2, fmt, ...) + return false + end + + local text + if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then + text = read_capped(tmp, MAX_INDEX) + end + if not text then + return fail("Cannot fetch the index for %s.", repo) + end + -- The signature is checked over the very bytes parsed below. + if not index_signed(text, tmp_sig, repo, kr) then + return fail("Index for %s is not signed by a key trusted for %s.", repo, repo) + end + local new, st = parse_index(text, repo) + if st == 2 then + return fail("Index fetched for %s is the index of another repository.", repo) + elseif not new then + return fail("Malformed index for %s.", repo) + end + + local stored = dir .. "/" .. repo .. ".idx" + local old_text = read_capped(stored, MAX_INDEX) + local unchanged = false + if old_text then + local old = parse_index(old_text, repo) + if not old then + return fail("Malformed %s.", stored) + end + if new.serial < old.serial then + return fail("Index for %s is older than the one already accepted.", repo) + elseif new.serial == old.serial then + if text ~= old_text then + return fail("Index for %s has the serial of the one already accepted, but other contents.", repo) + end + unchanged = true + end + elseif io.open(stored, "rb") then + return fail("Cannot read %s.", stored) + end + if new.valid_until <= os.time() then + return fail("Index for %s has expired.", repo) + end + + local serial = string.format("%d", tonumber(new.serial)) + if unchanged then + os.remove(tmp) + os.remove(tmp_sig) + if isVerbose then + log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial) + end + return true + end + -- Never written in place (bug 25): renamed over the old copy. + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 + or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0 + or not os.rename(tmp_sig, stored .. ".sig") + or not os.rename(tmp, stored) then + return fail("Cannot write %s.", stored) + end + if isVerbose then + log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial, + tostring(new.npkgs), new.npkgs == 1 and "package" or "packages") + end + return true +end + +--- Refresh the index of every repository repos.conf gives a url +--- (REPO_DESIGN.txt section 5), into the scope's /repos, holding +--- the scope's lock. Every repository is tried; true if all succeeded. +--- Exits if there is nothing to refresh or the setup is at fault. +-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install +-- Every entry with a url in keyring `kr`'s repos.conf, in priority +-- order: { name, url }. Exits if there is none, or repos.conf is +-- malformed. +local function configured_remotes(kr) + local remotes = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[65536]") + if tonumber(istore.gl_conf_repos(kr.conf, buf, 65536)) ~= 0 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then + table.insert(remotes, { name = name, url = url }) + end + end + end + if #remotes == 0 then + log.lg_printf(2, "No remote repositories are configured.") + finish(1) + end + return remotes +end + +function M.refresh(opts) + local kr = keyring(opts.sysroot) + local remotes = configured_remotes(kr) + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) -- the library said why + end + if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Another glacier transaction is already in progress %s.", + opts.scope_label) + finish(1) + end + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + log.lg_printf(0, "Syncing all repositories...") + local all = true + for _, r in ipairs(remotes) do + all = refresh_one(r.name, r.url, ffi.string(dir), file_mode, kr) and all + end + ffi.C.gpkg_common_close(ctx.lock_fd) + if all then + log.lg_printf(3, "All repositories synced successfully.") + end + return all +end + +-- --------------------------------------------------------------------- +-- Public: whole-batch install / remove +-- --------------------------------------------------------------------- + +--- Install every package in gpkg_paths as ONE atomic staged transaction. +--- Any failure aborts the whole batch, leaving live state untouched. +--- Does not return on failure — exits. +-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS +-- opts.uid : uid for USR scope (ignored for SYS) +-- opts.scope_label : human string for the lock-contention message +-- opts.sysroot : install root (syspkg -R; nil = the running system) +-- opts.strict : refuse, before committing, anything the link pass +-- would refuse (syspkg --strict, implied by -R) +--- KEEP_OLD from glacier.conf: how many backups of replaced versions to +--- keep per package. There is no default — it ships as 1 in +--- glacier.conf, and an operation that would replace a version refuses +--- to run if it's missing or not a whole number. +local function keep_old() + local n = ffi.new("int[1]") + local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n)) + if st == 1 then + log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.") + elseif st == 2 then + log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.") + elseif st == 3 or (st == 0 and n[0] < 0) then + log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.") + end + if st ~= 0 or n[0] < 0 then finish(1) end + return tonumber(n[0]) +end + +-- Install verified private copies as one transaction. original[copy] +-- names each for messages. meta[copy], for packages fetched from a +-- repository (else nil): +-- auto : record it as installed as a dependency +-- may_replace : replace an installed other version without -O +-- (-u, and dependency upgrades) +-- dep : marked as a dependency in the summary +-- cache : the downloaded file, deleted once committed +-- src : built from this recipe repository (.glacier-src) +-- `confirmed`: the plan was already shown and accepted (builds ask +-- before building, so not again here). +local function install_copies(gpkg_paths, original, opts, meta, confirmed) + -- A different version of a package that's already installed is a + -- REPLACEMENT (upgrade or downgrade). Only -O permits it; without + -- -O it's refused here, before the prompt. + local installed = installed_entries(opts) + local entries, replacing, refused = {}, {}, false + for _, p in ipairs(gpkg_paths) do + local name, repo, ver = manifest_of(p) + local m = meta[p] or {} + local e = { repo = repo, name = name, ver = ver } + for _, i in ipairs(installed) do + if i.name == name and i.repo == repo and i.ver ~= ver then + if overwrite or m.may_replace then + replacing[p] = i + e.ver = i.ver .. " -> " .. ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, name, i.ver) + refused = true + end + end + end + if m.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + + check_plan(opts, gpkg_paths, {}, finish) + + local keep = next(replacing) and keep_old() or 0 + + if not confirmed and not confirm(entries) then + finish(0) + end + + local ctx = begin_staged(opts) + ctx.overwrite = overwrite and 1 or 0 + local staged = 0 + + -- Replacements: back up the installed version (from LIVE, written + -- under a .part name and only promoted after a successful commit), + -- then remove it from the stage so the new version installs into + -- a clean slot in the same transaction. + local live = live_context(opts) + local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup" + for _, old in pairs(replacing) do + if keep > 0 then + local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name) + local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver) + local part = final .. ".part" + if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then + log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + table.insert(pending_backups, { part = part, final = final, dir = dir, old = old }) + end + if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + end + + for _, gpkg_path in ipairs(gpkg_paths) do + local status = install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + local abs_path = original[gpkg_path] + + if status == 0 then + staged = staged + 1 + if (meta[gpkg_path] or {}).auto + and istore.gl_set_pkg_auto(ctx, manifest_repo, pkg_name, true) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as a dependency.", + manifest_repo, pkg_name) + abort_and_die(ctx) + end + local src = (meta[gpkg_path] or {}).src + if src and istore.gl_set_pkg_src(ctx, manifest_repo, pkg_name, src) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as built from %s.", + manifest_repo, pkg_name, src) + abort_and_die(ctx) + end + log.lg_printf(3, "%s::%s-%s: staged from %s.", + manifest_repo, pkg_name, version_str, abs_path) + elseif status == 1 then + log.lg_printf(2, "%s::%s: Failed to open package archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 2 then + log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 3 then + log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 4 then + log.lg_printf(2, "%s::%s: Failed to add entry to index.", + manifest_repo, pkg_name) + abort_and_die(ctx) + elseif status == 6 then + -- GL_INSTALL_SKIPPED: not a failure, keep going + elseif status == 7 then + -- GL_INSTALL_ERR_SCOPE: the library refused this + -- package for this scope (base-repo package under + -- user scope). The library already logged the + -- specific reason; don't second-guess it here. + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + -- Everything was skipped (-S, already up to date): the stage is + -- identical to live, so don't commit it. A commit isn't free — it + -- swaps the trees and re-links the whole store, re-printing every + -- standing link conflict for packages this command never touched. + if staged == 0 then + txn.gl_abort_transaction(ctx) + log.lg_printf(3, "Nothing to do.") + finish(0) + end + + commit_or_die(ctx) + + -- Committed: promote the backups, give each a sidecar (so it's an + -- installable, verifiable package), and keep only the newest KEEP_OLD. + for _, b in ipairs(pending_backups) do + if os.rename(b.part, b.final) then + local hex = sha256_file(b.final) + local sf = hex and io.open(b.final .. ".sha256", "w") + if sf then + sf:write("sha256:" .. hex .. "\n") + sf:close() + end + istore.gl_prune_backups(b.dir, keep) + log.lg_printf(0, "Backed up %s::%s %s to %s", + b.old.repo, b.old.name, b.old.ver, b.final) + else + log.lg_printf(1, "Could not keep the backup of %s::%s %s.", + b.old.repo, b.old.name, b.old.ver) + end + end + pending_backups = {} + + for _, p in ipairs(gpkg_paths) do + if meta[p] and meta[p].cache then os.remove(meta[p].cache) end + if meta[p] and meta[p].src then + local name, repo, ver = manifest_of(p) + build.keep(opts, p, repo, name, ver) + end + end + build.prune_kept(opts) + + report_done(ctx, finish) +end + +-- --------------------------------------------------------------------- +-- -f / -u: packages from the repositories (REPO_DESIGN.txt section 6) +-- --------------------------------------------------------------------- + +-- -1, 0 or 1 as version a is below, equal to or above b ("MAJ.MIN.PAT"). +local function vercmp(a, b) + local x = { a:match("^(%d+)%.(%d+)%.(%d+)") } + local y = { b:match("^(%d+)%.(%d+)%.(%d+)") } + for k = 1, 3 do + local m, n = tonumber(x[k]) or 0, tonumber(y[k]) or 0 + if m ~= n then return m < n and -1 or 1 end + end + return 0 +end + +-- A package's relations as an index lists them: "NAME VER\n" lines. +local function relation_lines(list, name_field, ver_field) + local out = {} + local k = 0 + while list ~= nil and list[k][name_field] ~= nil do + local v = list[k][ver_field] + table.insert(out, string.format("%s %d.%d.%d\n", + ffi.string(list[k][name_field]), v.maj, v.min, v.pat)) + k = k + 1 + end + return table.concat(out) +end + +-- Whether the manifest of `path` (read by the library) says exactly what +-- its index entry `e` of repository `repo` says: NAME, VER, PKG_REPO, +-- DEPS and CONFS. A package is from `repo` because that repo's signed +-- index lists it AND it says so, never because it says so. +local function matches_index(path, repo, e) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return false + end + local ok = ffi.string(m.pkg_name) == e.name + and ffi.string(m.pkg_repo) == repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == e.ver + and relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == e.deps + and relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == e.confs + istore.gl_free_pkg(m) + return ok +end + +-- The accepted index of every configured repository, freshly refreshed +-- (decision 10d: any failure refuses the operation). In priority order: +-- { name, url, pkgs = { { name, ver, file, sha256, size, deps, confs }... } }. +-- User scope never installs from base (the library refuses it there), +-- so base is left out; but a user's build may stack base packages as +-- layers (Everest's BUILD_ROOT names musl and busybox), so the list's +-- `layers` field is the same repositories with base included, for +-- gpkg_build's layer_plan only. base-src is left out of both. +local function load_indexes(opts) + local remotes = configured_remotes(keyring(opts.sysroot)) + if not M.refresh(opts) then + finish(1) + end + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) + end + local out, layers = {}, {} + local user = opts.scope == ffi.C.GL_SCOPE_USR + for _, r in ipairs(remotes) do + if not (user and r.name == "base-src") then + local path = ffi.string(dir) .. "/" .. r.name .. ".idx" + local text = read_capped(path, MAX_INDEX) + local idx = ffi.new("gl_index_t") + if not text or istore.gl_index_parse(text, #text, r.name, idx) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + local pkgs = {} + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + table.insert(pkgs, { + name = ffi.string(p.name), ver = ffi.string(p.ver), + file = ffi.string(p.file), sha256 = ffi.string(p.sha256), + size = tonumber(p.size), deps = ffi.string(p.deps), + confs = ffi.string(p.confs), + build_deps = ffi.string(p.build_deps), + traits = ffi.string(p.traits), + }) + end + istore.gl_index_free(idx) + -- A recipe repository, "X-src", builds packages of X. + local target = r.name:match("^(.+)%-src$") + local repo = { name = r.name, url = r.url, pkgs = pkgs, + src = target ~= nil, target = target } + if not (user and r.name == "base") then table.insert(out, repo) end + table.insert(layers, repo) + end + end + out.layers = layers + return out +end + +-- The highest version of `name` that repository `r` serves, or nil. +local function newest_in(r, name) + local best + for _, e in ipairs(r.pkgs) do + if e.name == name and (not best or vercmp(e.ver, best.ver) > 0) then + best = e + end + end + return best +end + +-- Which repository `name` comes from: the first, by priority, that +-- serves it, at its highest version. repo, entry, or nil. +local function pick(indexes, name) + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then return r, e end + end +end + +-- The first binary repository (by priority) serving `name`, at its +-- highest version: build layers come only from binaries. +local function pick_binary(indexes, name) + for _, r in ipairs(indexes) do + local e = not r.src and newest_in(r, name) + if e then return r, e end + end +end + +-- A plan item for entry `e` of repository `r`: its effective +-- dependencies (a recipe's IFs resolved against its traits) in it.deps, +-- and for a build, it.traits (gpkg_build's M.traits). +local function plan_item(r, e, name, opts) + local it = { repo = r, entry = e, name = name, deps = e.deps } + if r.src then + it.traits = build.traits(name, e.traits, opts) + it.deps = build.effective(e.deps, it.traits) + end + return it +end + +-- How a plan item is shown: "extra::curl 8.9.0", or for a build +-- "extra-src::curl 8.9.0 [+ssl -ldap] (build)". +local function item_label(it) + local s = string.format("%s::%s %s", it.repo.name, it.name, it.entry.ver) + if it.traits then + s = s .. (it.traits.show ~= "" and (" " .. it.traits.show) or "") .. " (build)" + end + return s +end + +-- Which repository a name given on the command line comes from +-- (BUILD_DESIGN.txt 1f): the only one serving it, or, with several +-- (binary or -src), the one the user picks; Enter takes the first by +-- priority. End of input or an invalid answer refuses. nil if no +-- repository serves it. +local function choose(indexes, name, opts) + local cands = {} + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then table.insert(cands, plan_item(r, e, name, opts)) end + end + if #cands <= 1 then return cands[1] end + log.lg_printf(0, "%s is available from more than one repository:", name) + for k, it in ipairs(cands) do + print(string.format(" %d) %s", k, item_label(it))) + end + io.write(string.format("Select a repository [1-%d, Enter = 1]: ", #cands)) + io.stdout:flush() + local answer = io.read("*l") + local k = answer == "" and 1 or tonumber(answer or "") + if not k or not cands[k] then + log.lg_printf(2, "Invalid selection.") + finish(1) + end + return cands[k] +end + +-- The PKG_TRAITS lines ("ssl\n-ldap\n") of installed entry `i`, from +-- the manifest saved in its version dir; "" if it has none. +local function installed_traits(ctx, i) + local path = string.format("%s/%s/%s/%s-%s/.glacier-manifest", + ffi.string(ctx.store_path), i.repo, i.name, i.name, i.ver) + local m = ffi.new("gl_pkg_t") + if istore.gl_gpm2gpkg(path, m) ~= 0 then return "" end + local t = m.pkg_traits ~= nil and ffi.string(m.pkg_traits) or "" + istore.gl_free_pkg(m) + return t +end + +-- The recipe repository an installed package was built from, or nil. +local function built_from(ctx, repo, name) + local buf = ffi.new("char[256]") + if tonumber(istore.gl_pkg_src(ctx, repo, name, buf, 256)) == 1 then + return ffi.string(buf) + end +end + +-- Add the missing dependencies of everything in `plan` (and theirs), +-- ROADMAP 2.3's closure. A dependency already met (in this scope, or +-- for a user, by the system) is left alone; one installed at too old a +-- version is upgraded from its own repository, keeping its auto or +-- explicit mark; one not installed comes from pick(), recorded auto. +-- Whatever can't be met is left for gl_check_plan to report. +local function close_deps(plan, indexes, opts) + local planned = {} + for _, it in ipairs(plan) do planned[it.name] = it end + local installed = installed_entries(opts) + local system = {} + if opts.scope == ffi.C.GL_SCOPE_USR then + system = read_index_file("/glacier/sys/index/current") + end + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local live = live_context(opts) + + local k = 1 + while k <= #plan do + for dname, dver in plan[k].deps:gmatch("(%S+) (%S+)\n") do + local met, old = planned[dname] ~= nil, nil + for _, i in ipairs(installed) do + if i.name == dname then + if vercmp(i.ver, dver) >= 0 then met = true end + old = old or i + end + end + for _, i in ipairs(system) do + if i.name == dname and vercmp(i.ver, dver) >= 0 then met = true end + end + if not met then + local r, e + if old then + -- Its own repository: the recipe one if it + -- was built from source (1k). + r = by_repo[built_from(live, old.repo, dname) or old.repo] + e = r and newest_in(r, dname) + else + r, e = pick(indexes, dname) + end + if e and vercmp(e.ver, dver) >= 0 then + local it = plan_item(r, e, dname, opts) + it.dep, it.auto, it.may_replace = true, not old or old.auto, old ~= nil + table.insert(plan, it) + planned[dname] = it + end + end + end + k = k + 1 + end +end + +-- Download `e` (an index entry of repository `r`) into the scope's +-- cache, hashing it on the way, unless a cached copy already matches. +-- Never more than the index's SIZE is read. The path, or nil plus +-- true if something was fetched but is not what the index lists. +local function download(ctx, r, e, file_mode) + local dir = ffi.new("char[4096]") + if txn.gl_scope_cache_dir(ctx, r.name, dir) ~= 0 then + finish(1) -- the library said why + end + local want = e.sha256:match("^sha256:(%x+)$") + local dest = ffi.string(dir) .. "/" .. e.file + if sha256_file(dest) == want then + return dest + end + + local src + local path = r.url:match("^file://(/.*)$") + if path then + src = io.open(path .. "/" .. e.file, "rb") + elseif r.url:match("^https://") then + src = io.popen("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 -- " .. + shell_quote(r.url .. "/" .. e.file) .. " 2>/dev/null", "r") + end + if not src then return nil end + local tmp = string.format("%s/.%s.%d", ffi.string(dir), e.file, + ffi.C.gpkg_common_getpid()) + local dst = io.open(tmp, "wb") + if not dst then + src:close() + return nil + end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + local n = 0 + while n <= e.size do + local chunk = src:read(math.min(65536, e.size + 1 - n)) + if not chunk then break end + n = n + #chunk + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + if n ~= e.size or ffi.string(hex) ~= want then + os.remove(tmp) + return nil, n > 0 + end + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 or not os.rename(tmp, dest) then + os.remove(tmp) + return nil + end + return dest +end + +-- The machine key (BUILD_DESIGN.txt section 9): base packages built +-- here are signed with it, and pass the base rule only if the admin +-- lists "local" among base's keys in repos.conf. Made the first time a +-- base-src build is planned: the public half in /etc/glacier/keys, the +-- secret one (0600) in /glacier/sys/keys. +local LOCAL_PUB = "/etc/glacier/keys/local.pub" + +local function machine_seckey() + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(live_context({ scope = ffi.C.GL_SCOPE_SYS, uid = 0 }), + "keys", dir) ~= 0 then + finish(1) -- the library said why + end + return ffi.string(dir) .. "/local.sec" +end + +-- Exits unless the machine key exists (making it if neither half +-- does) and repos.conf trusts it for base. `id` names the build. +local function require_machine_key(id) + local sec = machine_seckey() + local function present(path) + local f = io.open(path, "rb") + if f then f:close() end + return f ~= nil + end + local has_pub, has_sec = present(LOCAL_PUB), present(sec) + if not has_pub and not has_sec then + os.execute("mkdir -p -m 755 /etc/glacier/keys") + if verify.gl_sign_generate(LOCAL_PUB, sec, "glacier machine key") ~= 0 then + log.lg_printf(2, "Cannot make the machine key %s.", LOCAL_PUB) + finish(1) + end + ffi.C.gpkg_common_chmod(LOCAL_PUB, tonumber("644", 8)) + log.lg_printf(0, "Made the machine key %s.", LOCAL_PUB) + elseif has_pub ~= has_sec then + log.lg_printf(2, "%s and %s must both exist, or neither.", LOCAL_PUB, sec) + finish(1) + end + local pub = ffi.new("gl_sign_pubkey_t") + if verify.gl_sign_read_pubkey(LOCAL_PUB, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", LOCAL_PUB) + finish(1) + end + for _, k in ipairs(trusted_keys("base", HOST_KEYRING)) do + if ffi.string(k.pub.keynum, 8) == ffi.string(pub.keynum, 8) then + return sec + end + end + log.lg_printf(2, "%s needs the key \"local\" trusted for base.", id) + finish(1) +end + +-- Sign the sidecar text of a base package built here with the machine +-- key, then hold it to the base rule like any other (signed_for). +local function sign_built_base(copy, sidecar_text, name) + local side = copy .. ".sha256" + local f = io.open(side, "wb") + if not f or not f:write(sidecar_text) then + log.lg_printf(2, "Cannot write %s.", side) + finish(1) + end + f:close() + if verify.gl_sign_file(machine_seckey(), side, side .. ".sig") ~= 0 + or not signed_for(copy, sidecar_text, "base") then + log.lg_printf(2, "base::%s is not signed by a key trusted for base.", name) + finish(1) + end +end + +-- A plan with builds is shown and confirmed BEFORE anything is built +-- (builds are long): the same refusals install_copies would make +-- first, then the summary and the prompt. +local function confirm_builds(plan, indexes, opts) + build.check(opts) + local planned = {} + for _, it in ipairs(plan) do + if it.traits then planned[it.name] = { ver = it.entry.ver, deps = it.deps } end + end + for _, it in ipairs(plan) do + if it.traits then build.check_layers(it, indexes, planned, opts) end + if it.traits and it.repo.target == "base" then + require_machine_key(item_label(it)) + end + end + local installed = installed_entries(opts) + local entries, refused = {}, false + for _, it in ipairs(plan) do + local repo = it.repo.target or it.repo.name + local e = { repo = it.repo.name, name = it.name, ver = it.entry.ver } + for _, i in ipairs(installed) do + if i.name == it.name and i.repo == repo and i.ver ~= it.entry.ver then + if overwrite or it.may_replace then + e.ver = i.ver .. " -> " .. it.entry.ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, it.name, i.ver) + refused = true + end + end + end + if it.reason then e.ver = e.ver .. " (" .. it.reason .. ")" end + if it.traits then + e.ver = e.ver .. (it.traits.show ~= "" and (" " .. it.traits.show) or "") + .. " (build)" + end + if it.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + if not confirm(entries) then + finish(0) + end +end + +-- The builds of `plan` in an order where a build comes after any build +-- whose package it depends on (its output is then one of its layers). +local function build_order(plan) + local by_name, order, state = {}, {}, {} + for _, it in ipairs(plan) do + if it.traits then by_name[it.name] = it end + end + local function visit(it) + if state[it.name] then return end + state[it.name] = true + for dname in it.deps:gmatch("(%S+) %S+\n") do + if by_name[dname] then visit(by_name[dname]) end + end + table.insert(order, it) + end + for _, it in ipairs(plan) do + if it.traits then visit(it) end + end + return order +end + +-- Fetch (or build), verify and install everything in `plan` (see +-- close_deps). +local function install_plan(plan, indexes, opts) + local ctx = live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local copies, original, meta = {}, {}, {} + local refused = false + local has_builds = false + for _, it in ipairs(plan) do + has_builds = has_builds or it.traits ~= nil + end + if has_builds then + confirm_builds(plan, indexes, opts) + local built = {} + for _, it in ipairs(build_order(plan)) do + local copy, sidecar_text, hex = build.build(it, indexes, built, opts) + if it.repo.target == "base" then + sign_built_base(copy, sidecar_text, it.name) + end + built[it.name] = { ver = it.entry.ver, path = copy, sha = hex, deps = it.deps } + it.copy = copy + end + end + for _, it in ipairs(plan) do + if it.copy then + table.insert(copies, it.copy) + original[it.copy] = item_label(it) + meta[it.copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, src = it.repo.name } + goto continue + end + local e = it.entry + local id = string.format("%s::%s %s", it.repo.name, e.name, e.ver) + local cached, wrong = download(ctx, it.repo, e, file_mode) + local copy = cached and verify_and_copy(cached, e.sha256 .. "\n") + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + refused = true + elseif not copy or not matches_index(copy, it.repo.name, e) then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + refused = true + else + table.insert(copies, copy) + original[copy] = it.repo.url .. "/" .. e.file + meta[copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, cache = cached } + end + ::continue:: + end + if refused then + finish(1) + end + install_copies(copies, original, opts, meta, has_builds) +end + +--- -f NAME...: install packages by name from the repositories, with +--- whatever dependencies they are missing. Like -l otherwise: an +--- installed other version of a named package needs -O. +function M.fetch(names, opts) + local indexes = load_indexes(opts) + local plan, refused, seen = {}, false, {} + for _, name in ipairs(names) do + local it = not seen[name] and choose(indexes, name, opts) + if seen[name] then + -- named twice: once is enough + elseif it then + seen[name] = true + table.insert(plan, it) + else + log.lg_printf(2, "%s is not in any repository.", name) + refused = true + end + end + if refused then + finish(1) + end + close_deps(plan, indexes, opts) + install_plan(plan, indexes, opts) +end + +--- -u [NAME...]: replace every installed package (or those named) whose +--- repository's index has a higher version, as -lO does (backups, +--- KEEP_OLD). Packages from repositories not configured are left alone. +function M.upgrade(names, opts) + local indexes = load_indexes(opts) + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local installed = installed_entries(opts) + local live0 = live_context(opts) + + local wanted, refused = nil, false + if #names > 0 then + wanted = {} + for _, name in ipairs(names) do + local found = false + for _, i in ipairs(installed) do + if i.name == name then + found = true + if not by_repo[built_from(live0, i.repo, i.name) or i.repo] then + log.lg_printf(2, "%s::%s is not in any configured repository.", + i.repo, i.name) + refused = true + end + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + refused = true + end + wanted[name] = true + end + end + if refused then + finish(1) + end + + local live = live_context(opts) + local plan = {} + for _, i in ipairs(installed) do + -- A package built from source stays on source (1k). + local src = built_from(live, i.repo, i.name) + local r = by_repo[src or i.repo] + local e = r and (not wanted or wanted[i.name]) and newest_in(r, i.name) + local it = e and plan_item(r, e, i.name, opts) + if it and vercmp(e.ver, i.ver) < 0 then + it = nil + elseif it and vercmp(e.ver, i.ver) == 0 then + -- Same version: rebuilt only if its traits changed. + local had = src and installed_traits(live, i) + if had and it.traits and had ~= table.concat(it.traits.list, "\n") + .. (#it.traits.list > 0 and "\n" or "") then + it.reason = "traits" + else + it = nil + end + end + if it then + it.auto, it.may_replace = i.auto, true + table.insert(plan, it) + end + end + if #plan == 0 then + log.lg_printf(3, "Nothing to do.") + finish(0) + end + close_deps(plan, indexes, opts) + install_plan(plan, indexes, opts) +end + +function M.install(gpkg_paths, opts) + -- From here on, the paths are the VERIFIED PRIVATE COPIES; the + -- caller's paths are only used for messages. + local copies, original = verify_all(gpkg_paths, opts) + install_copies(copies, original, opts, {}) +end + +--- Remove every named package as ONE atomic staged transaction. +--- Does not return on failure — exits. +function M.remove(pkg_names, opts) + -- Names, not files: resolve them against what's actually installed + -- (the old summary read them as .gpkg paths and printed + -- "unknown::pkg 0.0.0"). Anything not installed fails here, before + -- the prompt, not after the user has already said yes. + local installed = installed_entries(opts) + local entries, missing = {}, false + for _, name in ipairs(pkg_names) do + local found = false + for _, e in ipairs(installed) do + if e.name == name then + table.insert(entries, e) + found = true + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + missing = true + end + end + if missing then + os.exit(1) + end + + -- A name installed from more than one repo isn't resolved until + -- after the prompt, so only unambiguous names are checked here. + local count, removes = {}, {} + for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end + for _, e in ipairs(entries) do + if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end + end + check_plan(opts, {}, removes, os.exit) + + if not confirm(entries) then + os.exit(0) + end + + local ctx = begin_staged(opts) + + for _, pkg_name in ipairs(pkg_names) do + local repo = M.resolve_repo(ctx, pkg_name) + if not repo then + log.lg_printf(2, "Failed to resolve group for %s.", pkg_name) + abort_and_die(ctx) + end + + local status = istore.gl_remove_pkg(ctx, pkg_name, repo) + + if status == ffi.C.GL_REMOVE_OK then + log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name) + elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then + log.lg_printf(2, "%s::%s not found.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then + log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_INDEX then + log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name) + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + commit_or_die(ctx) + build.prune_kept(opts) + + report_done(ctx, os.exit) +end + +-- The builder's view of this module (lib/gpkg_build.lua). +init_build = function() + build.init({ + log = log, istore = istore, txn = txn, + finish = finish, shell_quote = shell_quote, + sha256_file = sha256_file, verify_and_copy = verify_and_copy, + download = download, live_context = live_context, + relation_lines = relation_lines, vercmp = vercmp, + pick_binary = pick_binary, installed_entries = installed_entries, + built_from = built_from, + require_trusted = function(path) require_trusted(path, HOST_KEYRING) end, + quiet = function() return isQuiet end, + gsandbox_path = (so_dir or ".") .. "/gsandbox", + gsandbox = shell_quote((so_dir or ".") .. "/gsandbox"), + lib_dir = so_dir and so_dir:gsub("/glacier$", "") or "lib", + }) +end + +return M diff --git a/lib/gpkg_common.lua.old b/lib/gpkg_common.lua.old new file mode 100644 index 0000000..2f8a030 --- /dev/null +++ b/lib/gpkg_common.lua.old @@ -0,0 +1,1032 @@ +-- lib/gpkg_common.lua +-- +-- Shared machinery between gpkg (per-user scope only) and syspkg +-- (system scope only). See SECURITY_DESIGN.txt section 7. +-- +-- The interface here is deliberately COARSE-GRAINED: M.install() and +-- M.remove() own the entire staged-transaction lifecycle +-- (gl_init_stage_context -> loop -> commit/abort), rather than +-- exporting fine-grained pieces that each caller then has to sequence +-- itself. That's what keeps the sequencing — and, once Checkpoint 2's +-- verification lands, the hash refusal matrix — in exactly ONE place +-- instead of duplicated across two binaries and drifting apart. +-- +-- What callers keep for themselves: +-- * argument parsing +-- * deciding WHICH scope they're allowed to request (gpkg never +-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag +-- for it", the capability isn't in its code path at all) +-- * their own privilege model (only syspkg runs elevated) +-- +-- Callers pass a `env` table on construction with the FFI handles and +-- shared state, so this module doesn't ffi.load() anything itself and +-- doesn't care where the .so's came from. + +local ffi = require("ffi") +local bit = require("bit") +local glacier_cdef = require("lib/glacier_cdef") + +local M = {} + +-- Module-level handles, set by M.init(). Kept here rather than passed +-- through every function because every function needs them. +local log, istore, txn, verify +local argv +local isVerbose = false +local skipInstalled = false +local overwrite = false + +local txn_name = glacier_cdef.txn_name + +--- Initialise the module. Must be called before anything else. +-- env.log / env.istore / env.txn : ffi.load() handles +-- env.verify : libglacier_verify.so handle (installs) +-- env.argv : argv table (for usage messages) +function M.init(env) + log = env.log + istore = env.istore + txn = env.txn + verify = env.verify + argv = env.argv +end + +--- Toggle flags the CLIs parse but this module acts on. +function M.set_verbose(v) isVerbose = v end +function M.set_skip_installed(v) skipInstalled = v end +function M.set_overwrite(v) overwrite = v end + +-- --------------------------------------------------------------------- +-- Manifest reading +-- --------------------------------------------------------------------- + +-- Quote a string for /bin/sh: wrap in single quotes, and turn each +-- embedded ' into '\''. Package paths come from the command line and +-- manifest entry names come from the archive, and syspkg runs all of +-- this as root — an unescaped ' in either is command execution. +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +--- name, repo and version ("MAJ.MIN.PAT", as the store names versions) +--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same +--- reader gl_install_pkg uses, so what is shown, compared and installed +--- can never disagree. nil if the manifest can't be read. +local function manifest_of(path) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return nil + end + local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo) + local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) + istore.gl_free_pkg(m) + return name, repo, ver +end + +-- --------------------------------------------------------------------- +-- Integrity verification (SECURITY_DESIGN.txt sections 3-4) +-- --------------------------------------------------------------------- + +-- Private working dir for verified copies, removed by finish(). +local private_dir = nil + +-- Backups written during this transaction but not yet committed +-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that +-- were never promoted, so an aborted upgrade leaves no stray backup. +local pending_backups = {} + +--- Exit, removing the private copies (and uncommitted backups) first. +--- Every exit on the install path goes through here. +local function finish(code) + for _, b in ipairs(pending_backups) do + os.remove(b.part) + end + pending_backups = {} + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +--- sha256 of a file as "", or nil. +local function sha256_file(path) + local f = io.open(path, "rb") + if not f then return nil end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = f:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + end + f:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +--- Copy `path` into the private dir, hashing it in the same pass, and +--- check the hash against `path`.sha256. Returns the private copy's path, +--- or nil plus a reason. +--- +--- Everything after this (summary, manifest read, gl_install_pkg) reads +--- ONLY the copy. Verifying the original and then installing it would +--- leave a gap where it could be swapped — and under syspkg that's root +--- reading a file whose directory another user may control. The copy +--- lives in a mktemp -d dir only the invoking user (root, for syspkg) +--- can write. +--- +--- Refusal matrix (section 4). A missing sidecar is treated exactly like +--- a mismatch: +--- repo == base -> always refuse, no exceptions +--- scope == SYS -> always refuse, any repo +--- scope == USR, repo != base -> refuse by default; the ONLY place +--- a future bypass flag may apply +--- No bypass exists, so today every row refuses and the repo (which we +--- couldn't trust before verifying anyway) never needs consulting. A +--- bypass, if ever added, must check scope and the VERIFIED manifest's +--- repo here, before anything else reads the file. +local function verify_and_copy(path) + local sidecar = path .. ".sha256" + local sf = io.open(sidecar, "r") + if not sf then + return nil, "no sidecar " .. sidecar + end + local sidecar_text = sf:read("*a") or "" + sf:close() + local expected = sidecar_text:match("^sha256:(%x+)%s*$") + if not expected or #expected ~= 64 then + return nil, "malformed sidecar " .. sidecar + end + expected = expected:lower() + + if not private_dir then + local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + return nil, "cannot create a private working directory" + end + end + + local src = io.open(path, "rb") + if not src then + return nil, "cannot open " .. path + end + + -- Unique per argument, so two packages with the same basename + -- (from different directories) can't collide. + local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0, + path:match("([^/]+)$")) + M._ncopies = (M._ncopies or 0) + 1 + local dst = io.open(copy_path, "wb") + if not dst then + src:close() + return nil, "cannot write " .. copy_path + end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = src:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + + if ffi.string(hex) ~= expected then + return nil, "hash mismatch (sidecar says " .. expected .. + ", file is " .. ffi.string(hex) .. ")" + end + + return copy_path, nil, sidecar_text +end + +-- --------------------------------------------------------------------- +-- Signatures (REPO_DESIGN.txt section 7) +-- --------------------------------------------------------------------- + +-- The system keyring. Read only by syspkg; under -R it is still the +-- HOST's (the build host's trust, as KEEP_OLD). +local REPOS_CONF = "/etc/glacier/repos.conf" +local KEYS_DIR = "/etc/glacier/keys" + +ffi.cdef[[ +char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath"); +]] + +-- nil if `path`, every ancestor of it, and every ancestor of its real +-- path are root-owned and not group/world-writable (as syspkg's own +-- lib/: a key a non-root user could swap is no key). Else the path at +-- fault, plus true if it is missing (or can't be resolved). +local function untrusted(path) + local function chain(p) + while true do + local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null") + local line = f and f:read("*l") + if f then f:close() end + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then return p, true end + if tonumber(uid) ~= 0 + or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + return p + end + if p == "/" then return nil end + p = p:match("^(.*)/[^/]*$") + if p == "" then p = "/" end + end + end + local bad, missing = chain(path) + if bad then return bad, missing end + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_common_realpath(path, buf) == nil then return path, true end + return chain(ffi.string(buf)) +end + +-- Whether repos.conf exists, having checked it is trusted (else the run +-- stops: the admin's configuration is at fault, not a package). +local function repos_conf_present() + local f, _, code = io.open(REPOS_CONF, "r") + if f then f:close() end + if not f and code == 2 then return false end + local bad, missing = untrusted(REPOS_CONF) + if bad and missing then + log.lg_printf(2, "Cannot read %s.", bad) + finish(1) + elseif bad then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + REPOS_CONF, bad) + finish(1) + end + return true +end + +-- The public keys repos.conf trusts for `repo`, read once per run: +-- { { name, pub }... }. A missing repos.conf trusts nothing. A +-- repos.conf or listed key that is untrusted or can't be read stops the +-- run: that is the admin's configuration, not the package, at fault. +local trusted_keys_cache = {} +local function trusted_keys(repo) + if trusted_keys_cache[repo] then return trusted_keys_cache[repo] end + local keys = {} + if repos_conf_present() then + local buf = ffi.new("char[4096]") + local st = tonumber(istore.gl_conf_repo_keys(REPOS_CONF, repo, buf, 4096)) + if st == 1 or st == 3 or st == 4 or st == 5 then + log.lg_printf(2, "Malformed %s.", REPOS_CONF) + finish(1) + end + for name in ffi.string(buf):gmatch("([^\n]+)\n") do + local path = KEYS_DIR .. "/" .. name .. ".pub" + local bad_key, missing = untrusted(path) + local pub = ffi.new("gl_sign_pubkey_t") + if bad_key and missing then + log.lg_printf(2, "Cannot read %s.", bad_key) + finish(1) + elseif bad_key then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + path, bad_key) + finish(1) + elseif verify.gl_sign_read_pubkey(path, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + table.insert(keys, { name = name, pub = pub }) + end + end + trusted_keys_cache[repo] = keys + return keys +end + +-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very +-- bytes the copy was checked against) by a key trusted for `repo`. The +-- key is picked by the signature's keynum, never by trying each one. +local function signed_for(path, sidecar_text, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then + return false + end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0 + end + end + return false +end + +--- Verify every package up front, before the summary is even shown. +--- Returns the private copies, plus a copy -> original map for messages. +--- +--- In system scope, a package whose manifest says base must also have a +--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the +--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg +--- does). +local function verify_all(gpkg_paths, opts) + local copies, original = {}, {} + local refused = false + + for _, p in ipairs(gpkg_paths) do + local copy, why, sidecar_text = verify_and_copy(p) + if copy and not manifest_of(copy) then + log.lg_printf(2, "Cannot read the manifest of %s.", p) + refused = true + copy = nil + end + if copy and opts.scope == ffi.C.GL_SCOPE_SYS then + local name, repo = manifest_of(copy) + if repo == "base" and not signed_for(p, sidecar_text, repo) then + log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.", + repo, name, repo) + refused = true + copy = nil + end + end + if copy then + table.insert(copies, copy) + original[copy] = p + elseif why then + log.lg_printf(2, "Refusing %s: %s.", p, why) + refused = true + end + end + + if refused then + finish(1) + end + return copies, original +end + +-- --------------------------------------------------------------------- +-- Confirmation summary +-- --------------------------------------------------------------------- + +--- Print the summary for `entries` ({repo, name, ver} each) and ask. +local function confirm(entries) + log.lg_printf(0, "SUMMARY:") + print("==============================") + print("") + for _, e in ipairs(entries) do + print(string.format(" * %s::%s\t\t%-16s", + e.repo or "unknown", e.name, e.ver or "unknown")) + end + print("") + io.write("Proceed? (y/N): ") + io.stdout:flush() + + local response = io.read("*l") + if not response then + return false + end + response = response:lower() + return response == "y" or response == "yes" +end + +--- Installed packages, from the live index for this scope: a list of +--- {repo, name, ver, auto}. The index's `current` file holds one +--- `repo::name::version::auto|explicit` line per package (index files +--- written before 2026-10-05 stop at the version). +--- A live context for opts' scope (and install root: syspkg -R only). +local function live_context(opts) + local ctx = ffi.new("gl_context_t") + if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then + finish(1) -- the library said why + end + return ctx +end + +local function installed_entries(opts) + local ctx = live_context(opts) + local f = io.open(ffi.string(ctx.index_path) .. "/current", "r") + local out = {} + if not f then return out end + for line in f:lines() do + local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$") + if repo then + local ver, kind = rest:match("^(.-)::(%a+)$") + table.insert(out, { repo = repo, name = name, ver = ver or rest, + auto = kind == "auto" }) + end + end + f:close() + return out +end + +-- --------------------------------------------------------------------- +-- Repo resolution +-- --------------------------------------------------------------------- + +function M.resolve_repo(ctx, pkg_name) + local list = istore.gl_find_pkg_repos(ctx, pkg_name) + + if list.count == 0 then + log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name) + istore.gl_free_repo_list(list) + return nil + end + + if list.count == 1 then + local repo = ffi.string(list.repos[0]) + istore.gl_free_repo_list(list) + return repo + end + + log.lg_printf(1, "Multiple instances of %s found:", pkg_name) + for i = 0, tonumber(list.count) - 1 do + print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name)) + end + print("") + io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ") + io.stdout:flush() + local input = io.read("*l") + local choice = tonumber(input) + + if not choice or choice < 1 or choice > tonumber(list.count) then + log.lg_printf(2, "Invalid selection.") + istore.gl_free_repo_list(list) + return nil + end + + local repo = ffi.string(list.repos[choice - 1]) + istore.gl_free_repo_list(list) + return repo +end + +-- --------------------------------------------------------------------- +-- Single-package install (with reinstall-if-present handling) +-- --------------------------------------------------------------------- + +local function install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + if not pkg_name then + log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path) + finish(1) + end + + if isVerbose then + log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s", + pkg_name, version_str, manifest_repo, gpkg_path) + end + + local status = istore.gl_install_pkg(ctx, gpkg_path) + + if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then + if skipInstalled then + log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str) + return tonumber(ffi.C.GL_INSTALL_SKIPPED) + end + + log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str) + + local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo) + + if rm_status ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).", + manifest_repo, pkg_name, tostring(tonumber(rm_status))) + return tonumber(rm_status) + end + + status = istore.gl_install_pkg(ctx, gpkg_path) + if status == ffi.C.GL_INSTALL_OK then + -- M.install logs the one "staged from" line. + return 0 + else + log.lg_printf(2, "Reinstall of %s-%s failed (error %s).", + pkg_name, version_str, tostring(tonumber(status))) + return tonumber(status) + end + + elseif status == ffi.C.GL_INSTALL_OK then + return 0 + end + + return tonumber(status) +end + +-- --------------------------------------------------------------------- +-- Transaction lifecycle +-- --------------------------------------------------------------------- + +--- Open a staged transaction for the given scope. Exits on failure with +--- a scope-appropriate message. `scope_label` is used only in the +--- lock-contention message ("for UID 1000" vs "for the system scope"). +local function begin_staged(opts) + local scope_label = opts.scope_label + local ctx = ffi.new("gl_context_t") + local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") + + if txn_st ~= ffi.C.GL_TXN_OK then + if txn_st == ffi.C.GL_TXN_ERR_LOCK then + log.lg_printf(2, + "Another glacier transaction is already in progress %s.", + scope_label) + else + log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st)) + end + finish(1) + end + + ctx.strict = opts.strict and 1 or 0 + return ctx +end + +--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt. +--- The library prints each problem; this exits if there were any. The +--- commit checks again (gl_check_txn), which is what covers a removal +--- whose repo is only chosen after the prompt. +local function check_plan(opts, adds, removes, exit) + local live = live_context(opts) + live.strict = opts.strict and 1 or 0 + live.overwrite = overwrite and 1 or 0 + local a = ffi.new("const char *[?]", #adds + 1) + for i, p in ipairs(adds) do a[i - 1] = p end + local r = ffi.new("const char *[?]", #removes + 1) + for i, id in ipairs(removes) do r[i - 1] = id end + local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes)) + if problems < 0 then + log.lg_printf(2, "Cannot read the package store to check dependencies.") + end + if problems ~= 0 then exit(1) end +end + +--- Commit, or abort-and-exit on failure. +local function commit_or_die(ctx) + local commit_st = txn.gl_commit_transaction(ctx) + if commit_st == ffi.C.GL_TXN_ERR_DEPS then + -- The library already said what's wrong, one line each. + txn.gl_abort_transaction(ctx) + finish(1) + elseif commit_st ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st)) + txn.gl_abort_transaction(ctx) + finish(1) + end +end + +--- The last line of a committed transaction. If the link pass refused +--- any path (each refusal is already printed above), the transaction is +--- committed but did not fully succeed: an error, and exit status 1. +local function report_done(ctx, exit) + local n = tonumber(ctx.link_refusals) + if n > 0 then + log.lg_printf(2, "%s %s not linked.", tostring(n), + n == 1 and "path was" or "paths were") + exit(1) + end + log.lg_printf(3, "Completed with no errors.") + exit(0) +end + +--- Abort the transaction and exit non-zero. Every failure path inside a +--- staged loop goes through here so live state is never left partially +--- mutated. +local function abort_and_die(ctx) + txn.gl_abort_transaction(ctx) + finish(1) +end + +-- --------------------------------------------------------------------- +-- Repository indexes (REPO_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +ffi.cdef[[ +int gpkg_common_getpid(void) asm("getpid"); +int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod"); +int gpkg_common_close(int fd) asm("close"); +]] + +-- Largest index accepted: what gl_sign_verify will check. +local MAX_INDEX = 64 * 1024 * 1024 + +-- A whole file, or nil if it is missing, unreadable or over `max`. +local function read_capped(path, max) + local f = io.open(path, "rb") + if not f then return nil end + local data = f:read(max + 1) or "" + f:close() + if #data > max then return nil end + return data +end + +-- Fetch URL/NAME into `dest`. https goes through curl, refusing any +-- other protocol, redirects included; file:// is a plain copy of an +-- absolute path. True on success. +local function fetch(url, name, dest) + local path = url:match("^file://(/.*)$") + if path then + local data = read_capped(path .. "/" .. name, MAX_INDEX) + local f = data and io.open(dest, "wb") + if not f then return false end + local ok = f:write(data) + f:close() + return ok ~= nil + end + if not url:match("^https://") then return false end + local ok = os.execute("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 --max-filesize " .. MAX_INDEX .. + " -o " .. shell_quote(dest) .. " -- " .. + shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1") + return ok == true or ok == 0 +end + +-- Whether `text` is signed by `sig_path`, with a key trusted for `repo` +-- (picked by keynum, as signed_for). +local function index_signed(text, sig_path, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", text), #text) == 0 + end + end + return false +end + +-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the +-- gl_index_parse status. +local function parse_index(text, repo) + local idx = ffi.new("gl_index_t") + local st = tonumber(istore.gl_index_parse(text, #text, repo, idx)) + if st ~= 0 then return nil, st end + local r = { serial = idx.serial, valid_until = idx.valid_until, + npkgs = tonumber(idx.npkgs) } + istore.gl_index_free(idx) + return r +end + +-- Refresh one repository's index into `dir` (/repos): fetch, +-- verify, parse, refuse a rollback or an expired index, then rename +-- over the accepted copy. Any failure keeps the accepted copy, prints +-- one line and returns false. +local function refresh_one(repo, url, dir, file_mode) + local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid()) + local tmp_sig = tmp .. ".sig" + local function fail(fmt, ...) + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(2, fmt, ...) + return false + end + + local text + if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then + text = read_capped(tmp, MAX_INDEX) + end + if not text then + return fail("Cannot fetch the index for %s.", repo) + end + -- The signature is checked over the very bytes parsed below. + if not index_signed(text, tmp_sig, repo) then + return fail("Index for %s is not signed by a key trusted for %s.", repo, repo) + end + local new, st = parse_index(text, repo) + if st == 2 then + return fail("Index fetched for %s is the index of another repository.", repo) + elseif not new then + return fail("Malformed index for %s.", repo) + end + + local stored = dir .. "/" .. repo .. ".idx" + local old_text = read_capped(stored, MAX_INDEX) + local unchanged = false + if old_text then + local old = parse_index(old_text, repo) + if not old then + return fail("Malformed %s.", stored) + end + if new.serial < old.serial then + return fail("Index for %s is older than the one already accepted.", repo) + elseif new.serial == old.serial then + if text ~= old_text then + return fail("Index for %s has the serial of the one already accepted, but other contents.", repo) + end + unchanged = true + end + elseif io.open(stored, "rb") then + return fail("Cannot read %s.", stored) + end + if new.valid_until <= os.time() then + return fail("Index for %s has expired.", repo) + end + + local serial = string.format("%d", tonumber(new.serial)) + if unchanged then + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial) + return true + end + -- Never written in place (bug 25): renamed over the old copy. + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 + or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0 + or not os.rename(tmp_sig, stored .. ".sig") + or not os.rename(tmp, stored) then + return fail("Cannot write %s.", stored) + end + log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial, + tostring(new.npkgs), new.npkgs == 1 and "package" or "packages") + return true +end + +--- Refresh the index of every repository repos.conf gives a url +--- (REPO_DESIGN.txt section 5), into the scope's /repos, holding +--- the scope's lock. Every repository is tried; true if all succeeded. +--- Exits if there is nothing to refresh or the setup is at fault. +-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install +function M.refresh(opts) + local remotes = {} + if repos_conf_present() then + local buf = ffi.new("char[65536]") + if tonumber(istore.gl_conf_repos(REPOS_CONF, buf, 65536)) ~= 0 then + log.lg_printf(2, "Malformed %s.", REPOS_CONF) + finish(1) + end + for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then + table.insert(remotes, { name = name, url = url }) + end + end + end + if #remotes == 0 then + log.lg_printf(2, "No remote repositories are configured.") + finish(1) + end + + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) -- the library said why + end + if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Another glacier transaction is already in progress %s.", + opts.scope_label) + finish(1) + end + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local all = true + for _, r in ipairs(remotes) do + all = refresh_one(r.name, r.url, ffi.string(dir), file_mode) and all + end + ffi.C.gpkg_common_close(ctx.lock_fd) + return all +end + +-- --------------------------------------------------------------------- +-- Public: whole-batch install / remove +-- --------------------------------------------------------------------- + +--- Install every package in gpkg_paths as ONE atomic staged transaction. +--- Any failure aborts the whole batch, leaving live state untouched. +--- Does not return on failure — exits. +-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS +-- opts.uid : uid for USR scope (ignored for SYS) +-- opts.scope_label : human string for the lock-contention message +-- opts.sysroot : install root (syspkg -R; nil = the running system) +-- opts.strict : refuse, before committing, anything the link pass +-- would refuse (syspkg --strict, implied by -R) +--- KEEP_OLD from glacier.conf: how many backups of replaced versions to +--- keep per package. There is no default — it ships as 1 in +--- glacier.conf, and an operation that would replace a version refuses +--- to run if it's missing or not a whole number. +local function keep_old() + local n = ffi.new("int[1]") + local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n)) + if st == 1 then + log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.") + elseif st == 2 then + log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.") + elseif st == 3 or (st == 0 and n[0] < 0) then + log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.") + end + if st ~= 0 or n[0] < 0 then finish(1) end + return tonumber(n[0]) +end + +function M.install(gpkg_paths, opts) + -- From here on, gpkg_paths are the VERIFIED PRIVATE COPIES; the + -- caller's paths are only used for messages. + local original + gpkg_paths, original = verify_all(gpkg_paths, opts) + + -- A different version of a package that's already installed is a + -- REPLACEMENT (upgrade or downgrade). Only -O permits it; without + -- -O it's refused here, before the prompt. + local installed = installed_entries(opts) + local entries, replacing, refused = {}, {}, false + for _, p in ipairs(gpkg_paths) do + local name, repo, ver = manifest_of(p) + local e = { repo = repo, name = name, ver = ver } + for _, i in ipairs(installed) do + if i.name == name and i.repo == repo and i.ver ~= ver then + if overwrite then + replacing[p] = i + e.ver = i.ver .. " -> " .. ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, name, i.ver) + refused = true + end + end + end + table.insert(entries, e) + end + if refused then + finish(1) + end + + check_plan(opts, gpkg_paths, {}, finish) + + local keep = next(replacing) and keep_old() or 0 + + if not confirm(entries) then + finish(0) + end + + local ctx = begin_staged(opts) + ctx.overwrite = overwrite and 1 or 0 + local staged = 0 + + -- Replacements: back up the installed version (from LIVE, written + -- under a .part name and only promoted after a successful commit), + -- then remove it from the stage so the new version installs into + -- a clean slot in the same transaction. + local live = live_context(opts) + local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup" + for _, old in pairs(replacing) do + if keep > 0 then + local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name) + local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver) + local part = final .. ".part" + if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then + log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + table.insert(pending_backups, { part = part, final = final, dir = dir, old = old }) + end + if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + end + + for _, gpkg_path in ipairs(gpkg_paths) do + local status = install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + local abs_path = original[gpkg_path] + + if status == 0 then + staged = staged + 1 + log.lg_printf(3, "%s::%s-%s: staged from %s.", + manifest_repo, pkg_name, version_str, abs_path) + elseif status == 1 then + log.lg_printf(2, "%s::%s: Failed to open package archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 2 then + log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 3 then + log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 4 then + log.lg_printf(2, "%s::%s: Failed to add entry to index.", + manifest_repo, pkg_name) + abort_and_die(ctx) + elseif status == 6 then + -- GL_INSTALL_SKIPPED: not a failure, keep going + elseif status == 7 then + -- GL_INSTALL_ERR_SCOPE: the library refused this + -- package for this scope (base-repo package under + -- user scope). The library already logged the + -- specific reason; don't second-guess it here. + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + -- Everything was skipped (-S, already up to date): the stage is + -- identical to live, so don't commit it. A commit isn't free — it + -- swaps the trees and re-links the whole store, re-printing every + -- standing link conflict for packages this command never touched. + if staged == 0 then + txn.gl_abort_transaction(ctx) + log.lg_printf(3, "Nothing to do.") + finish(0) + end + + commit_or_die(ctx) + + -- Committed: promote the backups, give each a sidecar (so it's an + -- installable, verifiable package), and keep only the newest KEEP_OLD. + for _, b in ipairs(pending_backups) do + if os.rename(b.part, b.final) then + local hex = sha256_file(b.final) + local sf = hex and io.open(b.final .. ".sha256", "w") + if sf then + sf:write("sha256:" .. hex .. "\n") + sf:close() + end + istore.gl_prune_backups(b.dir, keep) + log.lg_printf(0, "Backed up %s::%s %s to %s", + b.old.repo, b.old.name, b.old.ver, b.final) + else + log.lg_printf(1, "Could not keep the backup of %s::%s %s.", + b.old.repo, b.old.name, b.old.ver) + end + end + pending_backups = {} + + report_done(ctx, finish) +end + +--- Remove every named package as ONE atomic staged transaction. +--- Does not return on failure — exits. +function M.remove(pkg_names, opts) + -- Names, not files: resolve them against what's actually installed + -- (the old summary read them as .gpkg paths and printed + -- "unknown::pkg 0.0.0"). Anything not installed fails here, before + -- the prompt, not after the user has already said yes. + local installed = installed_entries(opts) + local entries, missing = {}, false + for _, name in ipairs(pkg_names) do + local found = false + for _, e in ipairs(installed) do + if e.name == name then + table.insert(entries, e) + found = true + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + missing = true + end + end + if missing then + os.exit(1) + end + + -- A name installed from more than one repo isn't resolved until + -- after the prompt, so only unambiguous names are checked here. + local count, removes = {}, {} + for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end + for _, e in ipairs(entries) do + if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end + end + check_plan(opts, {}, removes, os.exit) + + if not confirm(entries) then + os.exit(0) + end + + local ctx = begin_staged(opts) + + for _, pkg_name in ipairs(pkg_names) do + local repo = M.resolve_repo(ctx, pkg_name) + if not repo then + log.lg_printf(2, "Failed to resolve group for %s.", pkg_name) + abort_and_die(ctx) + end + + local status = istore.gl_remove_pkg(ctx, pkg_name, repo) + + if status == ffi.C.GL_REMOVE_OK then + log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name) + elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then + log.lg_printf(2, "%s::%s not found.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then + log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_INDEX then + log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name) + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + commit_or_die(ctx) + + report_done(ctx, os.exit) +end + +return M diff --git a/lib/gpkg_common.lua.old2 b/lib/gpkg_common.lua.old2 new file mode 100644 index 0000000..0ff7bb6 --- /dev/null +++ b/lib/gpkg_common.lua.old2 @@ -0,0 +1,1396 @@ +-- lib/gpkg_common.lua +-- +-- Shared machinery between gpkg (per-user scope only) and syspkg +-- (system scope only). See SECURITY_DESIGN.txt section 7. +-- +-- The interface here is deliberately COARSE-GRAINED: M.install() and +-- M.remove() own the entire staged-transaction lifecycle +-- (gl_init_stage_context -> loop -> commit/abort), rather than +-- exporting fine-grained pieces that each caller then has to sequence +-- itself. That's what keeps the sequencing — and, once Checkpoint 2's +-- verification lands, the hash refusal matrix — in exactly ONE place +-- instead of duplicated across two binaries and drifting apart. +-- +-- What callers keep for themselves: +-- * argument parsing +-- * deciding WHICH scope they're allowed to request (gpkg never +-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag +-- for it", the capability isn't in its code path at all) +-- * their own privilege model (only syspkg runs elevated) +-- +-- Callers pass a `env` table on construction with the FFI handles and +-- shared state, so this module doesn't ffi.load() anything itself and +-- doesn't care where the .so's came from. + +local ffi = require("ffi") +local bit = require("bit") +local glacier_cdef = require("lib/glacier_cdef") + +local M = {} + +-- Module-level handles, set by M.init(). Kept here rather than passed +-- through every function because every function needs them. +local log, istore, txn, verify +local argv +local isVerbose = false +local skipInstalled = false +local overwrite = false + +local txn_name = glacier_cdef.txn_name + +--- Initialise the module. Must be called before anything else. +-- env.log / env.istore / env.txn : ffi.load() handles +-- env.verify : libglacier_verify.so handle (installs) +-- env.argv : argv table (for usage messages) +function M.init(env) + log = env.log + istore = env.istore + txn = env.txn + verify = env.verify + argv = env.argv +end + +--- Toggle flags the CLIs parse but this module acts on. +function M.set_verbose(v) isVerbose = v end +function M.set_skip_installed(v) skipInstalled = v end +function M.set_overwrite(v) overwrite = v end + +-- --------------------------------------------------------------------- +-- Manifest reading +-- --------------------------------------------------------------------- + +-- Quote a string for /bin/sh: wrap in single quotes, and turn each +-- embedded ' into '\''. Package paths come from the command line and +-- manifest entry names come from the archive, and syspkg runs all of +-- this as root — an unescaped ' in either is command execution. +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +--- name, repo and version ("MAJ.MIN.PAT", as the store names versions) +--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same +--- reader gl_install_pkg uses, so what is shown, compared and installed +--- can never disagree. nil if the manifest can't be read. +local function manifest_of(path) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return nil + end + local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo) + local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) + istore.gl_free_pkg(m) + return name, repo, ver +end + +-- --------------------------------------------------------------------- +-- Integrity verification (SECURITY_DESIGN.txt sections 3-4) +-- --------------------------------------------------------------------- + +-- Private working dir for verified copies, removed by finish(). +local private_dir = nil + +-- Backups written during this transaction but not yet committed +-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that +-- were never promoted, so an aborted upgrade leaves no stray backup. +local pending_backups = {} + +--- Exit, removing the private copies (and uncommitted backups) first. +--- Every exit on the install path goes through here. +local function finish(code) + for _, b in ipairs(pending_backups) do + os.remove(b.part) + end + pending_backups = {} + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +--- sha256 of a file as "", or nil. +local function sha256_file(path) + local f = io.open(path, "rb") + if not f then return nil end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = f:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + end + f:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +--- Copy `path` into the private dir, hashing it in the same pass, and +--- check the hash against `path`.sha256. Returns the private copy's path, +--- or nil plus a reason. +--- +--- Everything after this (summary, manifest read, gl_install_pkg) reads +--- ONLY the copy. Verifying the original and then installing it would +--- leave a gap where it could be swapped — and under syspkg that's root +--- reading a file whose directory another user may control. The copy +--- lives in a mktemp -d dir only the invoking user (root, for syspkg) +--- can write. +--- +--- Refusal matrix (section 4). A missing sidecar is treated exactly like +--- a mismatch: +--- repo == base -> always refuse, no exceptions +--- scope == SYS -> always refuse, any repo +--- scope == USR, repo != base -> refuse by default; the ONLY place +--- a future bypass flag may apply +--- No bypass exists, so today every row refuses and the repo (which we +--- couldn't trust before verifying anyway) never needs consulting. A +--- bypass, if ever added, must check scope and the VERIFIED manifest's +--- repo here, before anything else reads the file. +--- +--- A package fetched from a repository passes `vouched`, the "sha256:" +--- its signed index gives, in place of a sidecar. +local function verify_and_copy(path, vouched) + local sidecar = path .. ".sha256" + local sidecar_text = vouched + if not sidecar_text then + local sf = io.open(sidecar, "r") + if not sf then + return nil, "no sidecar " .. sidecar + end + sidecar_text = sf:read("*a") or "" + sf:close() + end + local expected = sidecar_text:match("^sha256:(%x+)%s*$") + if not expected or #expected ~= 64 then + return nil, "malformed sidecar " .. sidecar + end + expected = expected:lower() + + if not private_dir then + local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + return nil, "cannot create a private working directory" + end + end + + local src = io.open(path, "rb") + if not src then + return nil, "cannot open " .. path + end + + -- Unique per argument, so two packages with the same basename + -- (from different directories) can't collide. + local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0, + path:match("([^/]+)$")) + M._ncopies = (M._ncopies or 0) + 1 + local dst = io.open(copy_path, "wb") + if not dst then + src:close() + return nil, "cannot write " .. copy_path + end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = src:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + + if ffi.string(hex) ~= expected then + return nil, "hash mismatch (sidecar says " .. expected .. + ", file is " .. ffi.string(hex) .. ")" + end + + return copy_path, nil, sidecar_text +end + +-- --------------------------------------------------------------------- +-- Signatures (REPO_DESIGN.txt section 7) +-- --------------------------------------------------------------------- + +-- The system keyring. Read only by syspkg; under -R it is still the +-- HOST's (the build host's trust, as KEEP_OLD). +local REPOS_CONF = "/etc/glacier/repos.conf" +local KEYS_DIR = "/etc/glacier/keys" + +ffi.cdef[[ +char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath"); +]] + +-- nil if `path`, every ancestor of it, and every ancestor of its real +-- path are root-owned and not group/world-writable (as syspkg's own +-- lib/: a key a non-root user could swap is no key). Else the path at +-- fault, plus true if it is missing (or can't be resolved). +local function untrusted(path) + local function chain(p) + while true do + local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null") + local line = f and f:read("*l") + if f then f:close() end + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then return p, true end + if tonumber(uid) ~= 0 + or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + return p + end + if p == "/" then return nil end + p = p:match("^(.*)/[^/]*$") + if p == "" then p = "/" end + end + end + local bad, missing = chain(path) + if bad then return bad, missing end + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_common_realpath(path, buf) == nil then return path, true end + return chain(ffi.string(buf)) +end + +-- Whether repos.conf exists, having checked it is trusted (else the run +-- stops: the admin's configuration is at fault, not a package). +local function repos_conf_present() + local f, _, code = io.open(REPOS_CONF, "r") + if f then f:close() end + if not f and code == 2 then return false end + local bad, missing = untrusted(REPOS_CONF) + if bad and missing then + log.lg_printf(2, "Cannot read %s.", bad) + finish(1) + elseif bad then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + REPOS_CONF, bad) + finish(1) + end + return true +end + +-- The public keys repos.conf trusts for `repo`, read once per run: +-- { { name, pub }... }. A missing repos.conf trusts nothing. A +-- repos.conf or listed key that is untrusted or can't be read stops the +-- run: that is the admin's configuration, not the package, at fault. +local trusted_keys_cache = {} +local function trusted_keys(repo) + if trusted_keys_cache[repo] then return trusted_keys_cache[repo] end + local keys = {} + if repos_conf_present() then + local buf = ffi.new("char[4096]") + local st = tonumber(istore.gl_conf_repo_keys(REPOS_CONF, repo, buf, 4096)) + if st == 1 or st == 3 or st == 4 or st == 5 then + log.lg_printf(2, "Malformed %s.", REPOS_CONF) + finish(1) + end + for name in ffi.string(buf):gmatch("([^\n]+)\n") do + local path = KEYS_DIR .. "/" .. name .. ".pub" + local bad_key, missing = untrusted(path) + local pub = ffi.new("gl_sign_pubkey_t") + if bad_key and missing then + log.lg_printf(2, "Cannot read %s.", bad_key) + finish(1) + elseif bad_key then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + path, bad_key) + finish(1) + elseif verify.gl_sign_read_pubkey(path, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + table.insert(keys, { name = name, pub = pub }) + end + end + trusted_keys_cache[repo] = keys + return keys +end + +-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very +-- bytes the copy was checked against) by a key trusted for `repo`. The +-- key is picked by the signature's keynum, never by trying each one. +local function signed_for(path, sidecar_text, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then + return false + end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0 + end + end + return false +end + +--- Verify every package up front, before the summary is even shown. +--- Returns the private copies, plus a copy -> original map for messages. +--- +--- In system scope, a package whose manifest says base must also have a +--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the +--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg +--- does). +local function verify_all(gpkg_paths, opts) + local copies, original = {}, {} + local refused = false + + for _, p in ipairs(gpkg_paths) do + local copy, why, sidecar_text = verify_and_copy(p) + if copy and not manifest_of(copy) then + log.lg_printf(2, "Cannot read the manifest of %s.", p) + refused = true + copy = nil + end + if copy and opts.scope == ffi.C.GL_SCOPE_SYS then + local name, repo = manifest_of(copy) + if repo == "base" and not signed_for(p, sidecar_text, repo) then + log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.", + repo, name, repo) + refused = true + copy = nil + end + end + if copy then + table.insert(copies, copy) + original[copy] = p + elseif why then + log.lg_printf(2, "Refusing %s: %s.", p, why) + refused = true + end + end + + if refused then + finish(1) + end + return copies, original +end + +-- --------------------------------------------------------------------- +-- Confirmation summary +-- --------------------------------------------------------------------- + +--- Print the summary for `entries` ({repo, name, ver} each) and ask. +local function confirm(entries) + log.lg_printf(0, "SUMMARY:") + print("==============================") + print("") + for _, e in ipairs(entries) do + print(string.format(" * %s::%s\t\t%-16s", + e.repo or "unknown", e.name, e.ver or "unknown")) + end + print("") + io.write("Proceed? (y/N): ") + io.stdout:flush() + + local response = io.read("*l") + if not response then + return false + end + response = response:lower() + return response == "y" or response == "yes" +end + +--- Installed packages, from the live index for this scope: a list of +--- {repo, name, ver, auto}. The index's `current` file holds one +--- `repo::name::version::auto|explicit` line per package (index files +--- written before 2026-10-05 stop at the version). +--- A live context for opts' scope (and install root: syspkg -R only). +local function live_context(opts) + local ctx = ffi.new("gl_context_t") + if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then + finish(1) -- the library said why + end + return ctx +end + +-- The entries of an index `current` file ({} if there is none). +local function read_index_file(path) + local f = io.open(path, "r") + local out = {} + if not f then return out end + for line in f:lines() do + local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$") + if repo then + local ver, kind = rest:match("^(.-)::(%a+)$") + table.insert(out, { repo = repo, name = name, ver = ver or rest, + auto = kind == "auto" }) + end + end + f:close() + return out +end + +local function installed_entries(opts) + local ctx = live_context(opts) + return read_index_file(ffi.string(ctx.index_path) .. "/current") +end + +-- --------------------------------------------------------------------- +-- Repo resolution +-- --------------------------------------------------------------------- + +function M.resolve_repo(ctx, pkg_name) + local list = istore.gl_find_pkg_repos(ctx, pkg_name) + + if list.count == 0 then + log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name) + istore.gl_free_repo_list(list) + return nil + end + + if list.count == 1 then + local repo = ffi.string(list.repos[0]) + istore.gl_free_repo_list(list) + return repo + end + + log.lg_printf(1, "Multiple instances of %s found:", pkg_name) + for i = 0, tonumber(list.count) - 1 do + print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name)) + end + print("") + io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ") + io.stdout:flush() + local input = io.read("*l") + local choice = tonumber(input) + + if not choice or choice < 1 or choice > tonumber(list.count) then + log.lg_printf(2, "Invalid selection.") + istore.gl_free_repo_list(list) + return nil + end + + local repo = ffi.string(list.repos[choice - 1]) + istore.gl_free_repo_list(list) + return repo +end + +-- --------------------------------------------------------------------- +-- Single-package install (with reinstall-if-present handling) +-- --------------------------------------------------------------------- + +local function install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + if not pkg_name then + log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path) + finish(1) + end + + if isVerbose then + log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s", + pkg_name, version_str, manifest_repo, gpkg_path) + end + + local status = istore.gl_install_pkg(ctx, gpkg_path) + + if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then + if skipInstalled then + log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str) + return tonumber(ffi.C.GL_INSTALL_SKIPPED) + end + + log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str) + + local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo) + + if rm_status ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).", + manifest_repo, pkg_name, tostring(tonumber(rm_status))) + return tonumber(rm_status) + end + + status = istore.gl_install_pkg(ctx, gpkg_path) + if status == ffi.C.GL_INSTALL_OK then + -- M.install logs the one "staged from" line. + return 0 + else + log.lg_printf(2, "Reinstall of %s-%s failed (error %s).", + pkg_name, version_str, tostring(tonumber(status))) + return tonumber(status) + end + + elseif status == ffi.C.GL_INSTALL_OK then + return 0 + end + + return tonumber(status) +end + +-- --------------------------------------------------------------------- +-- Transaction lifecycle +-- --------------------------------------------------------------------- + +--- Open a staged transaction for the given scope. Exits on failure with +--- a scope-appropriate message. `scope_label` is used only in the +--- lock-contention message ("for UID 1000" vs "for the system scope"). +local function begin_staged(opts) + local scope_label = opts.scope_label + local ctx = ffi.new("gl_context_t") + local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") + + if txn_st ~= ffi.C.GL_TXN_OK then + if txn_st == ffi.C.GL_TXN_ERR_LOCK then + log.lg_printf(2, + "Another glacier transaction is already in progress %s.", + scope_label) + else + log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st)) + end + finish(1) + end + + ctx.strict = opts.strict and 1 or 0 + return ctx +end + +--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt. +--- The library prints each problem; this exits if there were any. The +--- commit checks again (gl_check_txn), which is what covers a removal +--- whose repo is only chosen after the prompt. +local function check_plan(opts, adds, removes, exit) + local live = live_context(opts) + live.strict = opts.strict and 1 or 0 + live.overwrite = overwrite and 1 or 0 + local a = ffi.new("const char *[?]", #adds + 1) + for i, p in ipairs(adds) do a[i - 1] = p end + local r = ffi.new("const char *[?]", #removes + 1) + for i, id in ipairs(removes) do r[i - 1] = id end + local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes)) + if problems < 0 then + log.lg_printf(2, "Cannot read the package store to check dependencies.") + end + if problems ~= 0 then exit(1) end +end + +--- Commit, or abort-and-exit on failure. +local function commit_or_die(ctx) + local commit_st = txn.gl_commit_transaction(ctx) + if commit_st == ffi.C.GL_TXN_ERR_DEPS then + -- The library already said what's wrong, one line each. + txn.gl_abort_transaction(ctx) + finish(1) + elseif commit_st ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st)) + txn.gl_abort_transaction(ctx) + finish(1) + end +end + +--- The last line of a committed transaction. If the link pass refused +--- any path (each refusal is already printed above), the transaction is +--- committed but did not fully succeed: an error, and exit status 1. +local function report_done(ctx, exit) + local n = tonumber(ctx.link_refusals) + if n > 0 then + log.lg_printf(2, "%s %s not linked.", tostring(n), + n == 1 and "path was" or "paths were") + exit(1) + end + log.lg_printf(3, "Completed with no errors.") + exit(0) +end + +--- Abort the transaction and exit non-zero. Every failure path inside a +--- staged loop goes through here so live state is never left partially +--- mutated. +local function abort_and_die(ctx) + txn.gl_abort_transaction(ctx) + finish(1) +end + +-- --------------------------------------------------------------------- +-- Repository indexes (REPO_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +ffi.cdef[[ +int gpkg_common_getpid(void) asm("getpid"); +int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod"); +int gpkg_common_close(int fd) asm("close"); +]] + +-- Largest index accepted: what gl_sign_verify will check. +local MAX_INDEX = 64 * 1024 * 1024 + +-- A whole file, or nil if it is missing, unreadable or over `max`. +local function read_capped(path, max) + local f = io.open(path, "rb") + if not f then return nil end + local data = f:read(max + 1) or "" + f:close() + if #data > max then return nil end + return data +end + +-- Fetch URL/NAME into `dest`. https goes through curl, refusing any +-- other protocol, redirects included; file:// is a plain copy of an +-- absolute path. True on success. +local function fetch(url, name, dest) + local path = url:match("^file://(/.*)$") + if path then + local data = read_capped(path .. "/" .. name, MAX_INDEX) + local f = data and io.open(dest, "wb") + if not f then return false end + local ok = f:write(data) + f:close() + return ok ~= nil + end + if not url:match("^https://") then return false end + local ok = os.execute("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 --max-filesize " .. MAX_INDEX .. + " -o " .. shell_quote(dest) .. " -- " .. + shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1") + return ok == true or ok == 0 +end + +-- Whether `text` is signed by `sig_path`, with a key trusted for `repo` +-- (picked by keynum, as signed_for). +local function index_signed(text, sig_path, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", text), #text) == 0 + end + end + return false +end + +-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the +-- gl_index_parse status. +local function parse_index(text, repo) + local idx = ffi.new("gl_index_t") + local st = tonumber(istore.gl_index_parse(text, #text, repo, idx)) + if st ~= 0 then return nil, st end + local r = { serial = idx.serial, valid_until = idx.valid_until, + npkgs = tonumber(idx.npkgs) } + istore.gl_index_free(idx) + return r +end + +-- Refresh one repository's index into `dir` (/repos): fetch, +-- verify, parse, refuse a rollback or an expired index, then rename +-- over the accepted copy. Any failure keeps the accepted copy, prints +-- one line and returns false. +local function refresh_one(repo, url, dir, file_mode) + local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid()) + local tmp_sig = tmp .. ".sig" + local function fail(fmt, ...) + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(2, fmt, ...) + return false + end + + local text + if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then + text = read_capped(tmp, MAX_INDEX) + end + if not text then + return fail("Cannot fetch the index for %s.", repo) + end + -- The signature is checked over the very bytes parsed below. + if not index_signed(text, tmp_sig, repo) then + return fail("Index for %s is not signed by a key trusted for %s.", repo, repo) + end + local new, st = parse_index(text, repo) + if st == 2 then + return fail("Index fetched for %s is the index of another repository.", repo) + elseif not new then + return fail("Malformed index for %s.", repo) + end + + local stored = dir .. "/" .. repo .. ".idx" + local old_text = read_capped(stored, MAX_INDEX) + local unchanged = false + if old_text then + local old = parse_index(old_text, repo) + if not old then + return fail("Malformed %s.", stored) + end + if new.serial < old.serial then + return fail("Index for %s is older than the one already accepted.", repo) + elseif new.serial == old.serial then + if text ~= old_text then + return fail("Index for %s has the serial of the one already accepted, but other contents.", repo) + end + unchanged = true + end + elseif io.open(stored, "rb") then + return fail("Cannot read %s.", stored) + end + if new.valid_until <= os.time() then + return fail("Index for %s has expired.", repo) + end + + local serial = string.format("%d", tonumber(new.serial)) + if unchanged then + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial) + return true + end + -- Never written in place (bug 25): renamed over the old copy. + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 + or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0 + or not os.rename(tmp_sig, stored .. ".sig") + or not os.rename(tmp, stored) then + return fail("Cannot write %s.", stored) + end + log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial, + tostring(new.npkgs), new.npkgs == 1 and "package" or "packages") + return true +end + +--- Refresh the index of every repository repos.conf gives a url +--- (REPO_DESIGN.txt section 5), into the scope's /repos, holding +--- the scope's lock. Every repository is tried; true if all succeeded. +--- Exits if there is nothing to refresh or the setup is at fault. +-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install +-- Every repos.conf entry with a url, in priority order: { name, url }. +-- Exits if there is none, or repos.conf is malformed. +local function configured_remotes() + local remotes = {} + if repos_conf_present() then + local buf = ffi.new("char[65536]") + if tonumber(istore.gl_conf_repos(REPOS_CONF, buf, 65536)) ~= 0 then + log.lg_printf(2, "Malformed %s.", REPOS_CONF) + finish(1) + end + for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then + table.insert(remotes, { name = name, url = url }) + end + end + end + if #remotes == 0 then + log.lg_printf(2, "No remote repositories are configured.") + finish(1) + end + return remotes +end + +function M.refresh(opts) + local remotes = configured_remotes() + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) -- the library said why + end + if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Another glacier transaction is already in progress %s.", + opts.scope_label) + finish(1) + end + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local all = true + for _, r in ipairs(remotes) do + all = refresh_one(r.name, r.url, ffi.string(dir), file_mode) and all + end + ffi.C.gpkg_common_close(ctx.lock_fd) + return all +end + +-- --------------------------------------------------------------------- +-- Public: whole-batch install / remove +-- --------------------------------------------------------------------- + +--- Install every package in gpkg_paths as ONE atomic staged transaction. +--- Any failure aborts the whole batch, leaving live state untouched. +--- Does not return on failure — exits. +-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS +-- opts.uid : uid for USR scope (ignored for SYS) +-- opts.scope_label : human string for the lock-contention message +-- opts.sysroot : install root (syspkg -R; nil = the running system) +-- opts.strict : refuse, before committing, anything the link pass +-- would refuse (syspkg --strict, implied by -R) +--- KEEP_OLD from glacier.conf: how many backups of replaced versions to +--- keep per package. There is no default — it ships as 1 in +--- glacier.conf, and an operation that would replace a version refuses +--- to run if it's missing or not a whole number. +local function keep_old() + local n = ffi.new("int[1]") + local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n)) + if st == 1 then + log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.") + elseif st == 2 then + log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.") + elseif st == 3 or (st == 0 and n[0] < 0) then + log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.") + end + if st ~= 0 or n[0] < 0 then finish(1) end + return tonumber(n[0]) +end + +-- Install verified private copies as one transaction. original[copy] +-- names each for messages. meta[copy], for packages fetched from a +-- repository (else nil): +-- auto : record it as installed as a dependency +-- may_replace : replace an installed other version without -O +-- (-u, and dependency upgrades) +-- dep : marked as a dependency in the summary +-- cache : the downloaded file, deleted once committed +local function install_copies(gpkg_paths, original, opts, meta) + -- A different version of a package that's already installed is a + -- REPLACEMENT (upgrade or downgrade). Only -O permits it; without + -- -O it's refused here, before the prompt. + local installed = installed_entries(opts) + local entries, replacing, refused = {}, {}, false + for _, p in ipairs(gpkg_paths) do + local name, repo, ver = manifest_of(p) + local m = meta[p] or {} + local e = { repo = repo, name = name, ver = ver } + for _, i in ipairs(installed) do + if i.name == name and i.repo == repo and i.ver ~= ver then + if overwrite or m.may_replace then + replacing[p] = i + e.ver = i.ver .. " -> " .. ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, name, i.ver) + refused = true + end + end + end + if m.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + + check_plan(opts, gpkg_paths, {}, finish) + + local keep = next(replacing) and keep_old() or 0 + + if not confirm(entries) then + finish(0) + end + + local ctx = begin_staged(opts) + ctx.overwrite = overwrite and 1 or 0 + local staged = 0 + + -- Replacements: back up the installed version (from LIVE, written + -- under a .part name and only promoted after a successful commit), + -- then remove it from the stage so the new version installs into + -- a clean slot in the same transaction. + local live = live_context(opts) + local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup" + for _, old in pairs(replacing) do + if keep > 0 then + local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name) + local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver) + local part = final .. ".part" + if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then + log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + table.insert(pending_backups, { part = part, final = final, dir = dir, old = old }) + end + if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + end + + for _, gpkg_path in ipairs(gpkg_paths) do + local status = install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + local abs_path = original[gpkg_path] + + if status == 0 then + staged = staged + 1 + if (meta[gpkg_path] or {}).auto + and istore.gl_set_pkg_auto(ctx, manifest_repo, pkg_name, true) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as a dependency.", + manifest_repo, pkg_name) + abort_and_die(ctx) + end + log.lg_printf(3, "%s::%s-%s: staged from %s.", + manifest_repo, pkg_name, version_str, abs_path) + elseif status == 1 then + log.lg_printf(2, "%s::%s: Failed to open package archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 2 then + log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 3 then + log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 4 then + log.lg_printf(2, "%s::%s: Failed to add entry to index.", + manifest_repo, pkg_name) + abort_and_die(ctx) + elseif status == 6 then + -- GL_INSTALL_SKIPPED: not a failure, keep going + elseif status == 7 then + -- GL_INSTALL_ERR_SCOPE: the library refused this + -- package for this scope (base-repo package under + -- user scope). The library already logged the + -- specific reason; don't second-guess it here. + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + -- Everything was skipped (-S, already up to date): the stage is + -- identical to live, so don't commit it. A commit isn't free — it + -- swaps the trees and re-links the whole store, re-printing every + -- standing link conflict for packages this command never touched. + if staged == 0 then + txn.gl_abort_transaction(ctx) + log.lg_printf(3, "Nothing to do.") + finish(0) + end + + commit_or_die(ctx) + + -- Committed: promote the backups, give each a sidecar (so it's an + -- installable, verifiable package), and keep only the newest KEEP_OLD. + for _, b in ipairs(pending_backups) do + if os.rename(b.part, b.final) then + local hex = sha256_file(b.final) + local sf = hex and io.open(b.final .. ".sha256", "w") + if sf then + sf:write("sha256:" .. hex .. "\n") + sf:close() + end + istore.gl_prune_backups(b.dir, keep) + log.lg_printf(0, "Backed up %s::%s %s to %s", + b.old.repo, b.old.name, b.old.ver, b.final) + else + log.lg_printf(1, "Could not keep the backup of %s::%s %s.", + b.old.repo, b.old.name, b.old.ver) + end + end + pending_backups = {} + + for _, p in ipairs(gpkg_paths) do + if meta[p] and meta[p].cache then os.remove(meta[p].cache) end + end + + report_done(ctx, finish) +end + +-- --------------------------------------------------------------------- +-- -f / -u: packages from the repositories (REPO_DESIGN.txt section 6) +-- --------------------------------------------------------------------- + +-- -1, 0 or 1 as version a is below, equal to or above b ("MAJ.MIN.PAT"). +local function vercmp(a, b) + local x = { a:match("^(%d+)%.(%d+)%.(%d+)") } + local y = { b:match("^(%d+)%.(%d+)%.(%d+)") } + for k = 1, 3 do + local m, n = tonumber(x[k]) or 0, tonumber(y[k]) or 0 + if m ~= n then return m < n and -1 or 1 end + end + return 0 +end + +-- A package's relations as an index lists them: "NAME VER\n" lines. +local function relation_lines(list, name_field, ver_field) + local out = {} + local k = 0 + while list ~= nil and list[k][name_field] ~= nil do + local v = list[k][ver_field] + table.insert(out, string.format("%s %d.%d.%d\n", + ffi.string(list[k][name_field]), v.maj, v.min, v.pat)) + k = k + 1 + end + return table.concat(out) +end + +-- Whether the manifest of `path` (read by the library) says exactly what +-- its index entry `e` of repository `repo` says: NAME, VER, PKG_REPO, +-- DEPS and CONFS. A package is from `repo` because that repo's signed +-- index lists it AND it says so, never because it says so. +local function matches_index(path, repo, e) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return false + end + local ok = ffi.string(m.pkg_name) == e.name + and ffi.string(m.pkg_repo) == repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == e.ver + and relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == e.deps + and relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == e.confs + istore.gl_free_pkg(m) + return ok +end + +-- The accepted index of every configured repository, freshly refreshed +-- (decision 10d: any failure refuses the operation). In priority order: +-- { name, url, pkgs = { { name, ver, file, sha256, size, deps, confs }... } }. +-- User scope never fetches from base (the library refuses it there). +local function load_indexes(opts) + local remotes = configured_remotes() + if not M.refresh(opts) then + finish(1) + end + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) + end + local out = {} + for _, r in ipairs(remotes) do + if opts.scope ~= ffi.C.GL_SCOPE_USR or r.name ~= "base" then + local path = ffi.string(dir) .. "/" .. r.name .. ".idx" + local text = read_capped(path, MAX_INDEX) + local idx = ffi.new("gl_index_t") + if not text or istore.gl_index_parse(text, #text, r.name, idx) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + local pkgs = {} + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + table.insert(pkgs, { + name = ffi.string(p.name), ver = ffi.string(p.ver), + file = ffi.string(p.file), sha256 = ffi.string(p.sha256), + size = tonumber(p.size), deps = ffi.string(p.deps), + confs = ffi.string(p.confs), + }) + end + istore.gl_index_free(idx) + table.insert(out, { name = r.name, url = r.url, pkgs = pkgs }) + end + end + return out +end + +-- The highest version of `name` that repository `r` serves, or nil. +local function newest_in(r, name) + local best + for _, e in ipairs(r.pkgs) do + if e.name == name and (not best or vercmp(e.ver, best.ver) > 0) then + best = e + end + end + return best +end + +-- Which repository `name` comes from: the first, by priority, that +-- serves it, at its highest version. repo, entry, or nil. +local function pick(indexes, name) + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then return r, e end + end +end + +-- Add the missing dependencies of everything in `plan` (and theirs), +-- ROADMAP 2.3's closure. A dependency already met (in this scope, or +-- for a user, by the system) is left alone; one installed at too old a +-- version is upgraded from its own repository, keeping its auto or +-- explicit mark; one not installed comes from pick(), recorded auto. +-- Whatever can't be met is left for gl_check_plan to report. +local function close_deps(plan, indexes, opts) + local planned = {} + for _, it in ipairs(plan) do planned[it.name] = it end + local installed = installed_entries(opts) + local system = {} + if opts.scope == ffi.C.GL_SCOPE_USR then + system = read_index_file("/glacier/sys/index/current") + end + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + + local k = 1 + while k <= #plan do + for dname, dver in plan[k].entry.deps:gmatch("(%S+) (%S+)\n") do + local met, old = planned[dname] ~= nil, nil + for _, i in ipairs(installed) do + if i.name == dname then + if vercmp(i.ver, dver) >= 0 then met = true end + old = old or i + end + end + for _, i in ipairs(system) do + if i.name == dname and vercmp(i.ver, dver) >= 0 then met = true end + end + if not met then + local r, e + if old then + r = by_repo[old.repo] + e = r and newest_in(r, dname) + else + r, e = pick(indexes, dname) + end + if e and vercmp(e.ver, dver) >= 0 then + local it = { repo = r, entry = e, name = dname, dep = true, + auto = not old or old.auto, may_replace = old ~= nil } + table.insert(plan, it) + planned[dname] = it + end + end + end + k = k + 1 + end +end + +-- Download `e` (an index entry of repository `r`) into the scope's +-- cache, hashing it on the way, unless a cached copy already matches. +-- Never more than the index's SIZE is read. The path, or nil plus +-- true if something was fetched but is not what the index lists. +local function download(ctx, r, e, file_mode) + local dir = ffi.new("char[4096]") + if txn.gl_scope_cache_dir(ctx, r.name, dir) ~= 0 then + finish(1) -- the library said why + end + local want = e.sha256:match("^sha256:(%x+)$") + local dest = ffi.string(dir) .. "/" .. e.file + if sha256_file(dest) == want then + return dest + end + + local src + local path = r.url:match("^file://(/.*)$") + if path then + src = io.open(path .. "/" .. e.file, "rb") + elseif r.url:match("^https://") then + src = io.popen("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 -- " .. + shell_quote(r.url .. "/" .. e.file) .. " 2>/dev/null", "r") + end + if not src then return nil end + local tmp = string.format("%s/.%s.%d", ffi.string(dir), e.file, + ffi.C.gpkg_common_getpid()) + local dst = io.open(tmp, "wb") + if not dst then + src:close() + return nil + end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + local n = 0 + while n <= e.size do + local chunk = src:read(math.min(65536, e.size + 1 - n)) + if not chunk then break end + n = n + #chunk + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + if n ~= e.size or ffi.string(hex) ~= want then + os.remove(tmp) + return nil, n > 0 + end + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 or not os.rename(tmp, dest) then + os.remove(tmp) + return nil + end + return dest +end + +-- Fetch, verify and install everything in `plan` (see close_deps). +local function install_plan(plan, opts) + local ctx = live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local copies, original, meta = {}, {}, {} + local refused = false + for _, it in ipairs(plan) do + local e = it.entry + local id = string.format("%s::%s %s", it.repo.name, e.name, e.ver) + local cached, wrong = download(ctx, it.repo, e, file_mode) + local copy = cached and verify_and_copy(cached, e.sha256 .. "\n") + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + refused = true + elseif not copy or not matches_index(copy, it.repo.name, e) then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + refused = true + else + table.insert(copies, copy) + original[copy] = it.repo.url .. "/" .. e.file + meta[copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, cache = cached } + end + end + if refused then + finish(1) + end + install_copies(copies, original, opts, meta) +end + +--- -f NAME...: install packages by name from the repositories, with +--- whatever dependencies they are missing. Like -l otherwise: an +--- installed other version of a named package needs -O. +function M.fetch(names, opts) + local indexes = load_indexes(opts) + local plan, refused, seen = {}, false, {} + for _, name in ipairs(names) do + local r, e = pick(indexes, name) + if seen[name] then + -- named twice: once is enough + elseif e then + seen[name] = true + table.insert(plan, { repo = r, entry = e, name = name }) + else + log.lg_printf(2, "%s is not in any repository.", name) + refused = true + end + end + if refused then + finish(1) + end + close_deps(plan, indexes, opts) + install_plan(plan, opts) +end + +--- -u [NAME...]: replace every installed package (or those named) whose +--- repository's index has a higher version, as -lO does (backups, +--- KEEP_OLD). Packages from repositories not configured are left alone. +function M.upgrade(names, opts) + local indexes = load_indexes(opts) + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local installed = installed_entries(opts) + + local wanted, refused = nil, false + if #names > 0 then + wanted = {} + for _, name in ipairs(names) do + local found = false + for _, i in ipairs(installed) do + if i.name == name then + found = true + if not by_repo[i.repo] then + log.lg_printf(2, "%s::%s is not in any configured repository.", + i.repo, i.name) + refused = true + end + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + refused = true + end + wanted[name] = true + end + end + if refused then + finish(1) + end + + local plan = {} + for _, i in ipairs(installed) do + local r = by_repo[i.repo] + local e = r and (not wanted or wanted[i.name]) and newest_in(r, i.name) + if e and vercmp(e.ver, i.ver) > 0 then + table.insert(plan, { repo = r, entry = e, name = i.name, + auto = i.auto, may_replace = true }) + end + end + if #plan == 0 then + log.lg_printf(3, "Nothing to do.") + finish(0) + end + close_deps(plan, indexes, opts) + install_plan(plan, opts) +end + +function M.install(gpkg_paths, opts) + -- From here on, the paths are the VERIFIED PRIVATE COPIES; the + -- caller's paths are only used for messages. + local copies, original = verify_all(gpkg_paths, opts) + install_copies(copies, original, opts, {}) +end + +--- Remove every named package as ONE atomic staged transaction. +--- Does not return on failure — exits. +function M.remove(pkg_names, opts) + -- Names, not files: resolve them against what's actually installed + -- (the old summary read them as .gpkg paths and printed + -- "unknown::pkg 0.0.0"). Anything not installed fails here, before + -- the prompt, not after the user has already said yes. + local installed = installed_entries(opts) + local entries, missing = {}, false + for _, name in ipairs(pkg_names) do + local found = false + for _, e in ipairs(installed) do + if e.name == name then + table.insert(entries, e) + found = true + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + missing = true + end + end + if missing then + os.exit(1) + end + + -- A name installed from more than one repo isn't resolved until + -- after the prompt, so only unambiguous names are checked here. + local count, removes = {}, {} + for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end + for _, e in ipairs(entries) do + if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end + end + check_plan(opts, {}, removes, os.exit) + + if not confirm(entries) then + os.exit(0) + end + + local ctx = begin_staged(opts) + + for _, pkg_name in ipairs(pkg_names) do + local repo = M.resolve_repo(ctx, pkg_name) + if not repo then + log.lg_printf(2, "Failed to resolve group for %s.", pkg_name) + abort_and_die(ctx) + end + + local status = istore.gl_remove_pkg(ctx, pkg_name, repo) + + if status == ffi.C.GL_REMOVE_OK then + log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name) + elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then + log.lg_printf(2, "%s::%s not found.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then + log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_INDEX then + log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name) + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + commit_or_die(ctx) + + report_done(ctx, os.exit) +end + +return M diff --git a/lib/gpkg_common.lua.old3 b/lib/gpkg_common.lua.old3 new file mode 100644 index 0000000..8d0264e --- /dev/null +++ b/lib/gpkg_common.lua.old3 @@ -0,0 +1,1399 @@ +-- lib/gpkg_common.lua +-- +-- Shared machinery between gpkg (per-user scope only) and syspkg +-- (system scope only). See SECURITY_DESIGN.txt section 7. +-- +-- The interface here is deliberately COARSE-GRAINED: M.install() and +-- M.remove() own the entire staged-transaction lifecycle +-- (gl_init_stage_context -> loop -> commit/abort), rather than +-- exporting fine-grained pieces that each caller then has to sequence +-- itself. That's what keeps the sequencing — and, once Checkpoint 2's +-- verification lands, the hash refusal matrix — in exactly ONE place +-- instead of duplicated across two binaries and drifting apart. +-- +-- What callers keep for themselves: +-- * argument parsing +-- * deciding WHICH scope they're allowed to request (gpkg never +-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag +-- for it", the capability isn't in its code path at all) +-- * their own privilege model (only syspkg runs elevated) +-- +-- Callers pass a `env` table on construction with the FFI handles and +-- shared state, so this module doesn't ffi.load() anything itself and +-- doesn't care where the .so's came from. + +local ffi = require("ffi") +local bit = require("bit") +local glacier_cdef = require("lib/glacier_cdef") + +local M = {} + +-- Module-level handles, set by M.init(). Kept here rather than passed +-- through every function because every function needs them. +local log, istore, txn, verify +local argv +local isVerbose = false +local skipInstalled = false +local overwrite = false + +local txn_name = glacier_cdef.txn_name + +--- Initialise the module. Must be called before anything else. +-- env.log / env.istore / env.txn : ffi.load() handles +-- env.verify : libglacier_verify.so handle (installs) +-- env.argv : argv table (for usage messages) +function M.init(env) + log = env.log + istore = env.istore + txn = env.txn + verify = env.verify + argv = env.argv +end + +--- Toggle flags the CLIs parse but this module acts on. +function M.set_verbose(v) isVerbose = v end +function M.set_skip_installed(v) skipInstalled = v end +function M.set_overwrite(v) overwrite = v end + +-- --------------------------------------------------------------------- +-- Manifest reading +-- --------------------------------------------------------------------- + +-- Quote a string for /bin/sh: wrap in single quotes, and turn each +-- embedded ' into '\''. Package paths come from the command line and +-- manifest entry names come from the archive, and syspkg runs all of +-- this as root — an unescaped ' in either is command execution. +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +--- name, repo and version ("MAJ.MIN.PAT", as the store names versions) +--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same +--- reader gl_install_pkg uses, so what is shown, compared and installed +--- can never disagree. nil if the manifest can't be read. +local function manifest_of(path) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return nil + end + local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo) + local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) + istore.gl_free_pkg(m) + return name, repo, ver +end + +-- --------------------------------------------------------------------- +-- Integrity verification (SECURITY_DESIGN.txt sections 3-4) +-- --------------------------------------------------------------------- + +-- Private working dir for verified copies, removed by finish(). +local private_dir = nil + +-- Backups written during this transaction but not yet committed +-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that +-- were never promoted, so an aborted upgrade leaves no stray backup. +local pending_backups = {} + +--- Exit, removing the private copies (and uncommitted backups) first. +--- Every exit on the install path goes through here. +local function finish(code) + for _, b in ipairs(pending_backups) do + os.remove(b.part) + end + pending_backups = {} + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +--- sha256 of a file as "", or nil. +local function sha256_file(path) + local f = io.open(path, "rb") + if not f then return nil end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = f:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + end + f:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +--- Copy `path` into the private dir, hashing it in the same pass, and +--- check the hash against `path`.sha256. Returns the private copy's path, +--- or nil plus a reason. +--- +--- Everything after this (summary, manifest read, gl_install_pkg) reads +--- ONLY the copy. Verifying the original and then installing it would +--- leave a gap where it could be swapped — and under syspkg that's root +--- reading a file whose directory another user may control. The copy +--- lives in a mktemp -d dir only the invoking user (root, for syspkg) +--- can write. +--- +--- Refusal matrix (section 4). A missing sidecar is treated exactly like +--- a mismatch: +--- repo == base -> always refuse, no exceptions +--- scope == SYS -> always refuse, any repo +--- scope == USR, repo != base -> refuse by default; the ONLY place +--- a future bypass flag may apply +--- No bypass exists, so today every row refuses and the repo (which we +--- couldn't trust before verifying anyway) never needs consulting. A +--- bypass, if ever added, must check scope and the VERIFIED manifest's +--- repo here, before anything else reads the file. +--- +--- A package fetched from a repository passes `vouched`, the "sha256:" +--- its signed index gives, in place of a sidecar. +local function verify_and_copy(path, vouched) + local sidecar = path .. ".sha256" + local sidecar_text = vouched + if not sidecar_text then + local sf = io.open(sidecar, "r") + if not sf then + return nil, "no sidecar " .. sidecar + end + sidecar_text = sf:read("*a") or "" + sf:close() + end + local expected = sidecar_text:match("^sha256:(%x+)%s*$") + if not expected or #expected ~= 64 then + return nil, "malformed sidecar " .. sidecar + end + expected = expected:lower() + + if not private_dir then + local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + return nil, "cannot create a private working directory" + end + end + + local src = io.open(path, "rb") + if not src then + return nil, "cannot open " .. path + end + + -- Unique per argument, so two packages with the same basename + -- (from different directories) can't collide. + local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0, + path:match("([^/]+)$")) + M._ncopies = (M._ncopies or 0) + 1 + local dst = io.open(copy_path, "wb") + if not dst then + src:close() + return nil, "cannot write " .. copy_path + end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = src:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + + if ffi.string(hex) ~= expected then + return nil, "hash mismatch (sidecar says " .. expected .. + ", file is " .. ffi.string(hex) .. ")" + end + + return copy_path, nil, sidecar_text +end + +-- --------------------------------------------------------------------- +-- Signatures (REPO_DESIGN.txt section 7) +-- --------------------------------------------------------------------- + +-- The system keyring. Read only by syspkg; under -R it is still the +-- HOST's (the build host's trust, as KEEP_OLD). +local REPOS_CONF = "/etc/glacier/repos.conf" +local KEYS_DIR = "/etc/glacier/keys" + +ffi.cdef[[ +char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath"); +]] + +-- nil if `path`, every ancestor of it, and every ancestor of its real +-- path are root-owned and not group/world-writable (as syspkg's own +-- lib/: a key a non-root user could swap is no key). Else the path at +-- fault, plus true if it is missing (or can't be resolved). +local function untrusted(path) + local function chain(p) + while true do + local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null") + local line = f and f:read("*l") + if f then f:close() end + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then return p, true end + if tonumber(uid) ~= 0 + or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + return p + end + if p == "/" then return nil end + p = p:match("^(.*)/[^/]*$") + if p == "" then p = "/" end + end + end + local bad, missing = chain(path) + if bad then return bad, missing end + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_common_realpath(path, buf) == nil then return path, true end + return chain(ffi.string(buf)) +end + +-- Whether repos.conf exists, having checked it is trusted (else the run +-- stops: the admin's configuration is at fault, not a package). +local function repos_conf_present() + local f, _, code = io.open(REPOS_CONF, "r") + if f then f:close() end + if not f and code == 2 then return false end + local bad, missing = untrusted(REPOS_CONF) + if bad and missing then + log.lg_printf(2, "Cannot read %s.", bad) + finish(1) + elseif bad then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + REPOS_CONF, bad) + finish(1) + end + return true +end + +-- The public keys repos.conf trusts for `repo`, read once per run: +-- { { name, pub }... }. A missing repos.conf trusts nothing. A +-- repos.conf or listed key that is untrusted or can't be read stops the +-- run: that is the admin's configuration, not the package, at fault. +local trusted_keys_cache = {} +local function trusted_keys(repo) + if trusted_keys_cache[repo] then return trusted_keys_cache[repo] end + local keys = {} + if repos_conf_present() then + local buf = ffi.new("char[4096]") + local st = tonumber(istore.gl_conf_repo_keys(REPOS_CONF, repo, buf, 4096)) + if st == 1 or st == 3 or st == 4 or st == 5 then + log.lg_printf(2, "Malformed %s.", REPOS_CONF) + finish(1) + end + for name in ffi.string(buf):gmatch("([^\n]+)\n") do + local path = KEYS_DIR .. "/" .. name .. ".pub" + local bad_key, missing = untrusted(path) + local pub = ffi.new("gl_sign_pubkey_t") + if bad_key and missing then + log.lg_printf(2, "Cannot read %s.", bad_key) + finish(1) + elseif bad_key then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + path, bad_key) + finish(1) + elseif verify.gl_sign_read_pubkey(path, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + table.insert(keys, { name = name, pub = pub }) + end + end + trusted_keys_cache[repo] = keys + return keys +end + +-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very +-- bytes the copy was checked against) by a key trusted for `repo`. The +-- key is picked by the signature's keynum, never by trying each one. +local function signed_for(path, sidecar_text, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then + return false + end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0 + end + end + return false +end + +--- Verify every package up front, before the summary is even shown. +--- Returns the private copies, plus a copy -> original map for messages. +--- +--- In system scope, a package whose manifest says base must also have a +--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the +--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg +--- does). +local function verify_all(gpkg_paths, opts) + local copies, original = {}, {} + local refused = false + + for _, p in ipairs(gpkg_paths) do + local copy, why, sidecar_text = verify_and_copy(p) + if copy and not manifest_of(copy) then + log.lg_printf(2, "Cannot read the manifest of %s.", p) + refused = true + copy = nil + end + if copy and opts.scope == ffi.C.GL_SCOPE_SYS then + local name, repo = manifest_of(copy) + if repo == "base" and not signed_for(p, sidecar_text, repo) then + log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.", + repo, name, repo) + refused = true + copy = nil + end + end + if copy then + table.insert(copies, copy) + original[copy] = p + elseif why then + log.lg_printf(2, "Refusing %s: %s.", p, why) + refused = true + end + end + + if refused then + finish(1) + end + return copies, original +end + +-- --------------------------------------------------------------------- +-- Confirmation summary +-- --------------------------------------------------------------------- + +--- Print the summary for `entries` ({repo, name, ver} each) and ask. +local function confirm(entries) + log.lg_printf(0, "SUMMARY:") + print("==============================") + print("") + for _, e in ipairs(entries) do + print(string.format(" * %s::%s\t\t%-16s", + e.repo or "unknown", e.name, e.ver or "unknown")) + end + print("") + io.write("Proceed? (y/N): ") + io.stdout:flush() + + local response = io.read("*l") + if not response then + return false + end + response = response:lower() + return response == "y" or response == "yes" +end + +--- Installed packages, from the live index for this scope: a list of +--- {repo, name, ver, auto}. The index's `current` file holds one +--- `repo::name::version::auto|explicit` line per package (index files +--- written before 2026-10-05 stop at the version). +--- A live context for opts' scope (and install root: syspkg -R only). +local function live_context(opts) + local ctx = ffi.new("gl_context_t") + if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then + finish(1) -- the library said why + end + return ctx +end + +-- The entries of an index `current` file ({} if there is none). +local function read_index_file(path) + local f = io.open(path, "r") + local out = {} + if not f then return out end + for line in f:lines() do + local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$") + if repo then + local ver, kind = rest:match("^(.-)::(%a+)$") + table.insert(out, { repo = repo, name = name, ver = ver or rest, + auto = kind == "auto" }) + end + end + f:close() + return out +end + +local function installed_entries(opts) + local ctx = live_context(opts) + return read_index_file(ffi.string(ctx.index_path) .. "/current") +end + +-- --------------------------------------------------------------------- +-- Repo resolution +-- --------------------------------------------------------------------- + +function M.resolve_repo(ctx, pkg_name) + local list = istore.gl_find_pkg_repos(ctx, pkg_name) + + if list.count == 0 then + log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name) + istore.gl_free_repo_list(list) + return nil + end + + if list.count == 1 then + local repo = ffi.string(list.repos[0]) + istore.gl_free_repo_list(list) + return repo + end + + log.lg_printf(1, "Multiple instances of %s found:", pkg_name) + for i = 0, tonumber(list.count) - 1 do + print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name)) + end + print("") + io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ") + io.stdout:flush() + local input = io.read("*l") + local choice = tonumber(input) + + if not choice or choice < 1 or choice > tonumber(list.count) then + log.lg_printf(2, "Invalid selection.") + istore.gl_free_repo_list(list) + return nil + end + + local repo = ffi.string(list.repos[choice - 1]) + istore.gl_free_repo_list(list) + return repo +end + +-- --------------------------------------------------------------------- +-- Single-package install (with reinstall-if-present handling) +-- --------------------------------------------------------------------- + +local function install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + if not pkg_name then + log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path) + finish(1) + end + + if isVerbose then + log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s", + pkg_name, version_str, manifest_repo, gpkg_path) + end + + local status = istore.gl_install_pkg(ctx, gpkg_path) + + if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then + if skipInstalled then + log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str) + return tonumber(ffi.C.GL_INSTALL_SKIPPED) + end + + log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str) + + local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo) + + if rm_status ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).", + manifest_repo, pkg_name, tostring(tonumber(rm_status))) + return tonumber(rm_status) + end + + status = istore.gl_install_pkg(ctx, gpkg_path) + if status == ffi.C.GL_INSTALL_OK then + -- M.install logs the one "staged from" line. + return 0 + else + log.lg_printf(2, "Reinstall of %s-%s failed (error %s).", + pkg_name, version_str, tostring(tonumber(status))) + return tonumber(status) + end + + elseif status == ffi.C.GL_INSTALL_OK then + return 0 + end + + return tonumber(status) +end + +-- --------------------------------------------------------------------- +-- Transaction lifecycle +-- --------------------------------------------------------------------- + +--- Open a staged transaction for the given scope. Exits on failure with +--- a scope-appropriate message. `scope_label` is used only in the +--- lock-contention message ("for UID 1000" vs "for the system scope"). +local function begin_staged(opts) + local scope_label = opts.scope_label + local ctx = ffi.new("gl_context_t") + local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") + + if txn_st ~= ffi.C.GL_TXN_OK then + if txn_st == ffi.C.GL_TXN_ERR_LOCK then + log.lg_printf(2, + "Another glacier transaction is already in progress %s.", + scope_label) + else + log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st)) + end + finish(1) + end + + ctx.strict = opts.strict and 1 or 0 + return ctx +end + +--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt. +--- The library prints each problem; this exits if there were any. The +--- commit checks again (gl_check_txn), which is what covers a removal +--- whose repo is only chosen after the prompt. +local function check_plan(opts, adds, removes, exit) + local live = live_context(opts) + live.strict = opts.strict and 1 or 0 + live.overwrite = overwrite and 1 or 0 + local a = ffi.new("const char *[?]", #adds + 1) + for i, p in ipairs(adds) do a[i - 1] = p end + local r = ffi.new("const char *[?]", #removes + 1) + for i, id in ipairs(removes) do r[i - 1] = id end + local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes)) + if problems < 0 then + log.lg_printf(2, "Cannot read the package store to check dependencies.") + end + if problems ~= 0 then exit(1) end +end + +--- Commit, or abort-and-exit on failure. +local function commit_or_die(ctx) + local commit_st = txn.gl_commit_transaction(ctx) + if commit_st == ffi.C.GL_TXN_ERR_DEPS then + -- The library already said what's wrong, one line each. + txn.gl_abort_transaction(ctx) + finish(1) + elseif commit_st ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st)) + txn.gl_abort_transaction(ctx) + finish(1) + end +end + +--- The last line of a committed transaction. If the link pass refused +--- any path (each refusal is already printed above), the transaction is +--- committed but did not fully succeed: an error, and exit status 1. +local function report_done(ctx, exit) + local n = tonumber(ctx.link_refusals) + if n > 0 then + log.lg_printf(2, "%s %s not linked.", tostring(n), + n == 1 and "path was" or "paths were") + exit(1) + end + log.lg_printf(3, "Completed with no errors.") + exit(0) +end + +--- Abort the transaction and exit non-zero. Every failure path inside a +--- staged loop goes through here so live state is never left partially +--- mutated. +local function abort_and_die(ctx) + txn.gl_abort_transaction(ctx) + finish(1) +end + +-- --------------------------------------------------------------------- +-- Repository indexes (REPO_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +ffi.cdef[[ +int gpkg_common_getpid(void) asm("getpid"); +int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod"); +int gpkg_common_close(int fd) asm("close"); +]] + +-- Largest index accepted: what gl_sign_verify will check. +local MAX_INDEX = 64 * 1024 * 1024 + +-- A whole file, or nil if it is missing, unreadable or over `max`. +local function read_capped(path, max) + local f = io.open(path, "rb") + if not f then return nil end + local data = f:read(max + 1) or "" + f:close() + if #data > max then return nil end + return data +end + +-- Fetch URL/NAME into `dest`. https goes through curl, refusing any +-- other protocol, redirects included; file:// is a plain copy of an +-- absolute path. True on success. +local function fetch(url, name, dest) + local path = url:match("^file://(/.*)$") + if path then + local data = read_capped(path .. "/" .. name, MAX_INDEX) + local f = data and io.open(dest, "wb") + if not f then return false end + local ok = f:write(data) + f:close() + return ok ~= nil + end + if not url:match("^https://") then return false end + local ok = os.execute("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 --max-filesize " .. MAX_INDEX .. + " -o " .. shell_quote(dest) .. " -- " .. + shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1") + return ok == true or ok == 0 +end + +-- Whether `text` is signed by `sig_path`, with a key trusted for `repo` +-- (picked by keynum, as signed_for). +local function index_signed(text, sig_path, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", text), #text) == 0 + end + end + return false +end + +-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the +-- gl_index_parse status. +local function parse_index(text, repo) + local idx = ffi.new("gl_index_t") + local st = tonumber(istore.gl_index_parse(text, #text, repo, idx)) + if st ~= 0 then return nil, st end + local r = { serial = idx.serial, valid_until = idx.valid_until, + npkgs = tonumber(idx.npkgs) } + istore.gl_index_free(idx) + return r +end + +-- Refresh one repository's index into `dir` (/repos): fetch, +-- verify, parse, refuse a rollback or an expired index, then rename +-- over the accepted copy. Any failure keeps the accepted copy, prints +-- one line and returns false. +local function refresh_one(repo, url, dir, file_mode) + local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid()) + local tmp_sig = tmp .. ".sig" + local function fail(fmt, ...) + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(2, fmt, ...) + return false + end + + local text + if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then + text = read_capped(tmp, MAX_INDEX) + end + if not text then + return fail("Cannot fetch the index for %s.", repo) + end + -- The signature is checked over the very bytes parsed below. + if not index_signed(text, tmp_sig, repo) then + return fail("Index for %s is not signed by a key trusted for %s.", repo, repo) + end + local new, st = parse_index(text, repo) + if st == 2 then + return fail("Index fetched for %s is the index of another repository.", repo) + elseif not new then + return fail("Malformed index for %s.", repo) + end + + local stored = dir .. "/" .. repo .. ".idx" + local old_text = read_capped(stored, MAX_INDEX) + local unchanged = false + if old_text then + local old = parse_index(old_text, repo) + if not old then + return fail("Malformed %s.", stored) + end + if new.serial < old.serial then + return fail("Index for %s is older than the one already accepted.", repo) + elseif new.serial == old.serial then + if text ~= old_text then + return fail("Index for %s has the serial of the one already accepted, but other contents.", repo) + end + unchanged = true + end + elseif io.open(stored, "rb") then + return fail("Cannot read %s.", stored) + end + if new.valid_until <= os.time() then + return fail("Index for %s has expired.", repo) + end + + local serial = string.format("%d", tonumber(new.serial)) + if unchanged then + os.remove(tmp) + os.remove(tmp_sig) + if isVerbose then + log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial) + end + return true + end + -- Never written in place (bug 25): renamed over the old copy. + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 + or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0 + or not os.rename(tmp_sig, stored .. ".sig") + or not os.rename(tmp, stored) then + return fail("Cannot write %s.", stored) + end + log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial, + tostring(new.npkgs), new.npkgs == 1 and "package" or "packages") + return true +end + +--- Refresh the index of every repository repos.conf gives a url +--- (REPO_DESIGN.txt section 5), into the scope's /repos, holding +--- the scope's lock. Every repository is tried; true if all succeeded. +--- Exits if there is nothing to refresh or the setup is at fault. +-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install +-- Every repos.conf entry with a url, in priority order: { name, url }. +-- Exits if there is none, or repos.conf is malformed. +local function configured_remotes() + local remotes = {} + if repos_conf_present() then + local buf = ffi.new("char[65536]") + if tonumber(istore.gl_conf_repos(REPOS_CONF, buf, 65536)) ~= 0 then + log.lg_printf(2, "Malformed %s.", REPOS_CONF) + finish(1) + end + for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then + table.insert(remotes, { name = name, url = url }) + end + end + end + if #remotes == 0 then + log.lg_printf(2, "No remote repositories are configured.") + finish(1) + end + return remotes +end + +function M.refresh(opts) + local remotes = configured_remotes() + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) -- the library said why + end + if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Another glacier transaction is already in progress %s.", + opts.scope_label) + finish(1) + end + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + log.lg_printf(0, "Syncing all repositories...") + local all = true + for _, r in ipairs(remotes) do + all = refresh_one(r.name, r.url, ffi.string(dir), file_mode) and all + end + ffi.C.gpkg_common_close(ctx.lock_fd) + return all +end + +-- --------------------------------------------------------------------- +-- Public: whole-batch install / remove +-- --------------------------------------------------------------------- + +--- Install every package in gpkg_paths as ONE atomic staged transaction. +--- Any failure aborts the whole batch, leaving live state untouched. +--- Does not return on failure — exits. +-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS +-- opts.uid : uid for USR scope (ignored for SYS) +-- opts.scope_label : human string for the lock-contention message +-- opts.sysroot : install root (syspkg -R; nil = the running system) +-- opts.strict : refuse, before committing, anything the link pass +-- would refuse (syspkg --strict, implied by -R) +--- KEEP_OLD from glacier.conf: how many backups of replaced versions to +--- keep per package. There is no default — it ships as 1 in +--- glacier.conf, and an operation that would replace a version refuses +--- to run if it's missing or not a whole number. +local function keep_old() + local n = ffi.new("int[1]") + local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n)) + if st == 1 then + log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.") + elseif st == 2 then + log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.") + elseif st == 3 or (st == 0 and n[0] < 0) then + log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.") + end + if st ~= 0 or n[0] < 0 then finish(1) end + return tonumber(n[0]) +end + +-- Install verified private copies as one transaction. original[copy] +-- names each for messages. meta[copy], for packages fetched from a +-- repository (else nil): +-- auto : record it as installed as a dependency +-- may_replace : replace an installed other version without -O +-- (-u, and dependency upgrades) +-- dep : marked as a dependency in the summary +-- cache : the downloaded file, deleted once committed +local function install_copies(gpkg_paths, original, opts, meta) + -- A different version of a package that's already installed is a + -- REPLACEMENT (upgrade or downgrade). Only -O permits it; without + -- -O it's refused here, before the prompt. + local installed = installed_entries(opts) + local entries, replacing, refused = {}, {}, false + for _, p in ipairs(gpkg_paths) do + local name, repo, ver = manifest_of(p) + local m = meta[p] or {} + local e = { repo = repo, name = name, ver = ver } + for _, i in ipairs(installed) do + if i.name == name and i.repo == repo and i.ver ~= ver then + if overwrite or m.may_replace then + replacing[p] = i + e.ver = i.ver .. " -> " .. ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, name, i.ver) + refused = true + end + end + end + if m.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + + check_plan(opts, gpkg_paths, {}, finish) + + local keep = next(replacing) and keep_old() or 0 + + if not confirm(entries) then + finish(0) + end + + local ctx = begin_staged(opts) + ctx.overwrite = overwrite and 1 or 0 + local staged = 0 + + -- Replacements: back up the installed version (from LIVE, written + -- under a .part name and only promoted after a successful commit), + -- then remove it from the stage so the new version installs into + -- a clean slot in the same transaction. + local live = live_context(opts) + local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup" + for _, old in pairs(replacing) do + if keep > 0 then + local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name) + local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver) + local part = final .. ".part" + if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then + log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + table.insert(pending_backups, { part = part, final = final, dir = dir, old = old }) + end + if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + end + + for _, gpkg_path in ipairs(gpkg_paths) do + local status = install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + local abs_path = original[gpkg_path] + + if status == 0 then + staged = staged + 1 + if (meta[gpkg_path] or {}).auto + and istore.gl_set_pkg_auto(ctx, manifest_repo, pkg_name, true) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as a dependency.", + manifest_repo, pkg_name) + abort_and_die(ctx) + end + log.lg_printf(3, "%s::%s-%s: staged from %s.", + manifest_repo, pkg_name, version_str, abs_path) + elseif status == 1 then + log.lg_printf(2, "%s::%s: Failed to open package archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 2 then + log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 3 then + log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 4 then + log.lg_printf(2, "%s::%s: Failed to add entry to index.", + manifest_repo, pkg_name) + abort_and_die(ctx) + elseif status == 6 then + -- GL_INSTALL_SKIPPED: not a failure, keep going + elseif status == 7 then + -- GL_INSTALL_ERR_SCOPE: the library refused this + -- package for this scope (base-repo package under + -- user scope). The library already logged the + -- specific reason; don't second-guess it here. + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + -- Everything was skipped (-S, already up to date): the stage is + -- identical to live, so don't commit it. A commit isn't free — it + -- swaps the trees and re-links the whole store, re-printing every + -- standing link conflict for packages this command never touched. + if staged == 0 then + txn.gl_abort_transaction(ctx) + log.lg_printf(3, "Nothing to do.") + finish(0) + end + + commit_or_die(ctx) + + -- Committed: promote the backups, give each a sidecar (so it's an + -- installable, verifiable package), and keep only the newest KEEP_OLD. + for _, b in ipairs(pending_backups) do + if os.rename(b.part, b.final) then + local hex = sha256_file(b.final) + local sf = hex and io.open(b.final .. ".sha256", "w") + if sf then + sf:write("sha256:" .. hex .. "\n") + sf:close() + end + istore.gl_prune_backups(b.dir, keep) + log.lg_printf(0, "Backed up %s::%s %s to %s", + b.old.repo, b.old.name, b.old.ver, b.final) + else + log.lg_printf(1, "Could not keep the backup of %s::%s %s.", + b.old.repo, b.old.name, b.old.ver) + end + end + pending_backups = {} + + for _, p in ipairs(gpkg_paths) do + if meta[p] and meta[p].cache then os.remove(meta[p].cache) end + end + + report_done(ctx, finish) +end + +-- --------------------------------------------------------------------- +-- -f / -u: packages from the repositories (REPO_DESIGN.txt section 6) +-- --------------------------------------------------------------------- + +-- -1, 0 or 1 as version a is below, equal to or above b ("MAJ.MIN.PAT"). +local function vercmp(a, b) + local x = { a:match("^(%d+)%.(%d+)%.(%d+)") } + local y = { b:match("^(%d+)%.(%d+)%.(%d+)") } + for k = 1, 3 do + local m, n = tonumber(x[k]) or 0, tonumber(y[k]) or 0 + if m ~= n then return m < n and -1 or 1 end + end + return 0 +end + +-- A package's relations as an index lists them: "NAME VER\n" lines. +local function relation_lines(list, name_field, ver_field) + local out = {} + local k = 0 + while list ~= nil and list[k][name_field] ~= nil do + local v = list[k][ver_field] + table.insert(out, string.format("%s %d.%d.%d\n", + ffi.string(list[k][name_field]), v.maj, v.min, v.pat)) + k = k + 1 + end + return table.concat(out) +end + +-- Whether the manifest of `path` (read by the library) says exactly what +-- its index entry `e` of repository `repo` says: NAME, VER, PKG_REPO, +-- DEPS and CONFS. A package is from `repo` because that repo's signed +-- index lists it AND it says so, never because it says so. +local function matches_index(path, repo, e) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return false + end + local ok = ffi.string(m.pkg_name) == e.name + and ffi.string(m.pkg_repo) == repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == e.ver + and relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == e.deps + and relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == e.confs + istore.gl_free_pkg(m) + return ok +end + +-- The accepted index of every configured repository, freshly refreshed +-- (decision 10d: any failure refuses the operation). In priority order: +-- { name, url, pkgs = { { name, ver, file, sha256, size, deps, confs }... } }. +-- User scope never fetches from base (the library refuses it there). +local function load_indexes(opts) + local remotes = configured_remotes() + if not M.refresh(opts) then + finish(1) + end + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) + end + local out = {} + for _, r in ipairs(remotes) do + if opts.scope ~= ffi.C.GL_SCOPE_USR or r.name ~= "base" then + local path = ffi.string(dir) .. "/" .. r.name .. ".idx" + local text = read_capped(path, MAX_INDEX) + local idx = ffi.new("gl_index_t") + if not text or istore.gl_index_parse(text, #text, r.name, idx) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + local pkgs = {} + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + table.insert(pkgs, { + name = ffi.string(p.name), ver = ffi.string(p.ver), + file = ffi.string(p.file), sha256 = ffi.string(p.sha256), + size = tonumber(p.size), deps = ffi.string(p.deps), + confs = ffi.string(p.confs), + }) + end + istore.gl_index_free(idx) + table.insert(out, { name = r.name, url = r.url, pkgs = pkgs }) + end + end + return out +end + +-- The highest version of `name` that repository `r` serves, or nil. +local function newest_in(r, name) + local best + for _, e in ipairs(r.pkgs) do + if e.name == name and (not best or vercmp(e.ver, best.ver) > 0) then + best = e + end + end + return best +end + +-- Which repository `name` comes from: the first, by priority, that +-- serves it, at its highest version. repo, entry, or nil. +local function pick(indexes, name) + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then return r, e end + end +end + +-- Add the missing dependencies of everything in `plan` (and theirs), +-- ROADMAP 2.3's closure. A dependency already met (in this scope, or +-- for a user, by the system) is left alone; one installed at too old a +-- version is upgraded from its own repository, keeping its auto or +-- explicit mark; one not installed comes from pick(), recorded auto. +-- Whatever can't be met is left for gl_check_plan to report. +local function close_deps(plan, indexes, opts) + local planned = {} + for _, it in ipairs(plan) do planned[it.name] = it end + local installed = installed_entries(opts) + local system = {} + if opts.scope == ffi.C.GL_SCOPE_USR then + system = read_index_file("/glacier/sys/index/current") + end + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + + local k = 1 + while k <= #plan do + for dname, dver in plan[k].entry.deps:gmatch("(%S+) (%S+)\n") do + local met, old = planned[dname] ~= nil, nil + for _, i in ipairs(installed) do + if i.name == dname then + if vercmp(i.ver, dver) >= 0 then met = true end + old = old or i + end + end + for _, i in ipairs(system) do + if i.name == dname and vercmp(i.ver, dver) >= 0 then met = true end + end + if not met then + local r, e + if old then + r = by_repo[old.repo] + e = r and newest_in(r, dname) + else + r, e = pick(indexes, dname) + end + if e and vercmp(e.ver, dver) >= 0 then + local it = { repo = r, entry = e, name = dname, dep = true, + auto = not old or old.auto, may_replace = old ~= nil } + table.insert(plan, it) + planned[dname] = it + end + end + end + k = k + 1 + end +end + +-- Download `e` (an index entry of repository `r`) into the scope's +-- cache, hashing it on the way, unless a cached copy already matches. +-- Never more than the index's SIZE is read. The path, or nil plus +-- true if something was fetched but is not what the index lists. +local function download(ctx, r, e, file_mode) + local dir = ffi.new("char[4096]") + if txn.gl_scope_cache_dir(ctx, r.name, dir) ~= 0 then + finish(1) -- the library said why + end + local want = e.sha256:match("^sha256:(%x+)$") + local dest = ffi.string(dir) .. "/" .. e.file + if sha256_file(dest) == want then + return dest + end + + local src + local path = r.url:match("^file://(/.*)$") + if path then + src = io.open(path .. "/" .. e.file, "rb") + elseif r.url:match("^https://") then + src = io.popen("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 -- " .. + shell_quote(r.url .. "/" .. e.file) .. " 2>/dev/null", "r") + end + if not src then return nil end + local tmp = string.format("%s/.%s.%d", ffi.string(dir), e.file, + ffi.C.gpkg_common_getpid()) + local dst = io.open(tmp, "wb") + if not dst then + src:close() + return nil + end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + local n = 0 + while n <= e.size do + local chunk = src:read(math.min(65536, e.size + 1 - n)) + if not chunk then break end + n = n + #chunk + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + if n ~= e.size or ffi.string(hex) ~= want then + os.remove(tmp) + return nil, n > 0 + end + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 or not os.rename(tmp, dest) then + os.remove(tmp) + return nil + end + return dest +end + +-- Fetch, verify and install everything in `plan` (see close_deps). +local function install_plan(plan, opts) + local ctx = live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local copies, original, meta = {}, {}, {} + local refused = false + for _, it in ipairs(plan) do + local e = it.entry + local id = string.format("%s::%s %s", it.repo.name, e.name, e.ver) + local cached, wrong = download(ctx, it.repo, e, file_mode) + local copy = cached and verify_and_copy(cached, e.sha256 .. "\n") + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + refused = true + elseif not copy or not matches_index(copy, it.repo.name, e) then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + refused = true + else + table.insert(copies, copy) + original[copy] = it.repo.url .. "/" .. e.file + meta[copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, cache = cached } + end + end + if refused then + finish(1) + end + install_copies(copies, original, opts, meta) +end + +--- -f NAME...: install packages by name from the repositories, with +--- whatever dependencies they are missing. Like -l otherwise: an +--- installed other version of a named package needs -O. +function M.fetch(names, opts) + local indexes = load_indexes(opts) + local plan, refused, seen = {}, false, {} + for _, name in ipairs(names) do + local r, e = pick(indexes, name) + if seen[name] then + -- named twice: once is enough + elseif e then + seen[name] = true + table.insert(plan, { repo = r, entry = e, name = name }) + else + log.lg_printf(2, "%s is not in any repository.", name) + refused = true + end + end + if refused then + finish(1) + end + close_deps(plan, indexes, opts) + install_plan(plan, opts) +end + +--- -u [NAME...]: replace every installed package (or those named) whose +--- repository's index has a higher version, as -lO does (backups, +--- KEEP_OLD). Packages from repositories not configured are left alone. +function M.upgrade(names, opts) + local indexes = load_indexes(opts) + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local installed = installed_entries(opts) + + local wanted, refused = nil, false + if #names > 0 then + wanted = {} + for _, name in ipairs(names) do + local found = false + for _, i in ipairs(installed) do + if i.name == name then + found = true + if not by_repo[i.repo] then + log.lg_printf(2, "%s::%s is not in any configured repository.", + i.repo, i.name) + refused = true + end + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + refused = true + end + wanted[name] = true + end + end + if refused then + finish(1) + end + + local plan = {} + for _, i in ipairs(installed) do + local r = by_repo[i.repo] + local e = r and (not wanted or wanted[i.name]) and newest_in(r, i.name) + if e and vercmp(e.ver, i.ver) > 0 then + table.insert(plan, { repo = r, entry = e, name = i.name, + auto = i.auto, may_replace = true }) + end + end + if #plan == 0 then + log.lg_printf(3, "Nothing to do.") + finish(0) + end + close_deps(plan, indexes, opts) + install_plan(plan, opts) +end + +function M.install(gpkg_paths, opts) + -- From here on, the paths are the VERIFIED PRIVATE COPIES; the + -- caller's paths are only used for messages. + local copies, original = verify_all(gpkg_paths, opts) + install_copies(copies, original, opts, {}) +end + +--- Remove every named package as ONE atomic staged transaction. +--- Does not return on failure — exits. +function M.remove(pkg_names, opts) + -- Names, not files: resolve them against what's actually installed + -- (the old summary read them as .gpkg paths and printed + -- "unknown::pkg 0.0.0"). Anything not installed fails here, before + -- the prompt, not after the user has already said yes. + local installed = installed_entries(opts) + local entries, missing = {}, false + for _, name in ipairs(pkg_names) do + local found = false + for _, e in ipairs(installed) do + if e.name == name then + table.insert(entries, e) + found = true + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + missing = true + end + end + if missing then + os.exit(1) + end + + -- A name installed from more than one repo isn't resolved until + -- after the prompt, so only unambiguous names are checked here. + local count, removes = {}, {} + for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end + for _, e in ipairs(entries) do + if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end + end + check_plan(opts, {}, removes, os.exit) + + if not confirm(entries) then + os.exit(0) + end + + local ctx = begin_staged(opts) + + for _, pkg_name in ipairs(pkg_names) do + local repo = M.resolve_repo(ctx, pkg_name) + if not repo then + log.lg_printf(2, "Failed to resolve group for %s.", pkg_name) + abort_and_die(ctx) + end + + local status = istore.gl_remove_pkg(ctx, pkg_name, repo) + + if status == ffi.C.GL_REMOVE_OK then + log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name) + elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then + log.lg_printf(2, "%s::%s not found.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then + log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_INDEX then + log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name) + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + commit_or_die(ctx) + + report_done(ctx, os.exit) +end + +return M diff --git a/lib/gpkg_common.lua.old4 b/lib/gpkg_common.lua.old4 new file mode 100644 index 0000000..6ba1c4d --- /dev/null +++ b/lib/gpkg_common.lua.old4 @@ -0,0 +1,1404 @@ +-- lib/gpkg_common.lua +-- +-- Shared machinery between gpkg (per-user scope only) and syspkg +-- (system scope only). See SECURITY_DESIGN.txt section 7. +-- +-- The interface here is deliberately COARSE-GRAINED: M.install() and +-- M.remove() own the entire staged-transaction lifecycle +-- (gl_init_stage_context -> loop -> commit/abort), rather than +-- exporting fine-grained pieces that each caller then has to sequence +-- itself. That's what keeps the sequencing — and, once Checkpoint 2's +-- verification lands, the hash refusal matrix — in exactly ONE place +-- instead of duplicated across two binaries and drifting apart. +-- +-- What callers keep for themselves: +-- * argument parsing +-- * deciding WHICH scope they're allowed to request (gpkg never +-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag +-- for it", the capability isn't in its code path at all) +-- * their own privilege model (only syspkg runs elevated) +-- +-- Callers pass a `env` table on construction with the FFI handles and +-- shared state, so this module doesn't ffi.load() anything itself and +-- doesn't care where the .so's came from. + +local ffi = require("ffi") +local bit = require("bit") +local glacier_cdef = require("lib/glacier_cdef") + +local M = {} + +-- Module-level handles, set by M.init(). Kept here rather than passed +-- through every function because every function needs them. +local log, istore, txn, verify +local argv +local isVerbose = false +local skipInstalled = false +local overwrite = false + +local txn_name = glacier_cdef.txn_name + +--- Initialise the module. Must be called before anything else. +-- env.log / env.istore / env.txn : ffi.load() handles +-- env.verify : libglacier_verify.so handle (installs) +-- env.argv : argv table (for usage messages) +function M.init(env) + log = env.log + istore = env.istore + txn = env.txn + verify = env.verify + argv = env.argv +end + +--- Toggle flags the CLIs parse but this module acts on. +function M.set_verbose(v) isVerbose = v end +function M.set_skip_installed(v) skipInstalled = v end +function M.set_overwrite(v) overwrite = v end + +-- --------------------------------------------------------------------- +-- Manifest reading +-- --------------------------------------------------------------------- + +-- Quote a string for /bin/sh: wrap in single quotes, and turn each +-- embedded ' into '\''. Package paths come from the command line and +-- manifest entry names come from the archive, and syspkg runs all of +-- this as root — an unescaped ' in either is command execution. +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +--- name, repo and version ("MAJ.MIN.PAT", as the store names versions) +--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same +--- reader gl_install_pkg uses, so what is shown, compared and installed +--- can never disagree. nil if the manifest can't be read. +local function manifest_of(path) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return nil + end + local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo) + local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) + istore.gl_free_pkg(m) + return name, repo, ver +end + +-- --------------------------------------------------------------------- +-- Integrity verification (SECURITY_DESIGN.txt sections 3-4) +-- --------------------------------------------------------------------- + +-- Private working dir for verified copies, removed by finish(). +local private_dir = nil + +-- Backups written during this transaction but not yet committed +-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that +-- were never promoted, so an aborted upgrade leaves no stray backup. +local pending_backups = {} + +--- Exit, removing the private copies (and uncommitted backups) first. +--- Every exit on the install path goes through here. +local function finish(code) + for _, b in ipairs(pending_backups) do + os.remove(b.part) + end + pending_backups = {} + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +--- sha256 of a file as "", or nil. +local function sha256_file(path) + local f = io.open(path, "rb") + if not f then return nil end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = f:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + end + f:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +--- Copy `path` into the private dir, hashing it in the same pass, and +--- check the hash against `path`.sha256. Returns the private copy's path, +--- or nil plus a reason. +--- +--- Everything after this (summary, manifest read, gl_install_pkg) reads +--- ONLY the copy. Verifying the original and then installing it would +--- leave a gap where it could be swapped — and under syspkg that's root +--- reading a file whose directory another user may control. The copy +--- lives in a mktemp -d dir only the invoking user (root, for syspkg) +--- can write. +--- +--- Refusal matrix (section 4). A missing sidecar is treated exactly like +--- a mismatch: +--- repo == base -> always refuse, no exceptions +--- scope == SYS -> always refuse, any repo +--- scope == USR, repo != base -> refuse by default; the ONLY place +--- a future bypass flag may apply +--- No bypass exists, so today every row refuses and the repo (which we +--- couldn't trust before verifying anyway) never needs consulting. A +--- bypass, if ever added, must check scope and the VERIFIED manifest's +--- repo here, before anything else reads the file. +--- +--- A package fetched from a repository passes `vouched`, the "sha256:" +--- its signed index gives, in place of a sidecar. +local function verify_and_copy(path, vouched) + local sidecar = path .. ".sha256" + local sidecar_text = vouched + if not sidecar_text then + local sf = io.open(sidecar, "r") + if not sf then + return nil, "no sidecar " .. sidecar + end + sidecar_text = sf:read("*a") or "" + sf:close() + end + local expected = sidecar_text:match("^sha256:(%x+)%s*$") + if not expected or #expected ~= 64 then + return nil, "malformed sidecar " .. sidecar + end + expected = expected:lower() + + if not private_dir then + local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + return nil, "cannot create a private working directory" + end + end + + local src = io.open(path, "rb") + if not src then + return nil, "cannot open " .. path + end + + -- Unique per argument, so two packages with the same basename + -- (from different directories) can't collide. + local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0, + path:match("([^/]+)$")) + M._ncopies = (M._ncopies or 0) + 1 + local dst = io.open(copy_path, "wb") + if not dst then + src:close() + return nil, "cannot write " .. copy_path + end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = src:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + + if ffi.string(hex) ~= expected then + return nil, "hash mismatch (sidecar says " .. expected .. + ", file is " .. ffi.string(hex) .. ")" + end + + return copy_path, nil, sidecar_text +end + +-- --------------------------------------------------------------------- +-- Signatures (REPO_DESIGN.txt section 7) +-- --------------------------------------------------------------------- + +-- The system keyring. Read only by syspkg; under -R it is still the +-- HOST's (the build host's trust, as KEEP_OLD). +local REPOS_CONF = "/etc/glacier/repos.conf" +local KEYS_DIR = "/etc/glacier/keys" + +ffi.cdef[[ +char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath"); +]] + +-- nil if `path`, every ancestor of it, and every ancestor of its real +-- path are root-owned and not group/world-writable (as syspkg's own +-- lib/: a key a non-root user could swap is no key). Else the path at +-- fault, plus true if it is missing (or can't be resolved). +local function untrusted(path) + local function chain(p) + while true do + local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null") + local line = f and f:read("*l") + if f then f:close() end + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then return p, true end + if tonumber(uid) ~= 0 + or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + return p + end + if p == "/" then return nil end + p = p:match("^(.*)/[^/]*$") + if p == "" then p = "/" end + end + end + local bad, missing = chain(path) + if bad then return bad, missing end + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_common_realpath(path, buf) == nil then return path, true end + return chain(ffi.string(buf)) +end + +-- Whether repos.conf exists, having checked it is trusted (else the run +-- stops: the admin's configuration is at fault, not a package). +local function repos_conf_present() + local f, _, code = io.open(REPOS_CONF, "r") + if f then f:close() end + if not f and code == 2 then return false end + local bad, missing = untrusted(REPOS_CONF) + if bad and missing then + log.lg_printf(2, "Cannot read %s.", bad) + finish(1) + elseif bad then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + REPOS_CONF, bad) + finish(1) + end + return true +end + +-- The public keys repos.conf trusts for `repo`, read once per run: +-- { { name, pub }... }. A missing repos.conf trusts nothing. A +-- repos.conf or listed key that is untrusted or can't be read stops the +-- run: that is the admin's configuration, not the package, at fault. +local trusted_keys_cache = {} +local function trusted_keys(repo) + if trusted_keys_cache[repo] then return trusted_keys_cache[repo] end + local keys = {} + if repos_conf_present() then + local buf = ffi.new("char[4096]") + local st = tonumber(istore.gl_conf_repo_keys(REPOS_CONF, repo, buf, 4096)) + if st == 1 or st == 3 or st == 4 or st == 5 then + log.lg_printf(2, "Malformed %s.", REPOS_CONF) + finish(1) + end + for name in ffi.string(buf):gmatch("([^\n]+)\n") do + local path = KEYS_DIR .. "/" .. name .. ".pub" + local bad_key, missing = untrusted(path) + local pub = ffi.new("gl_sign_pubkey_t") + if bad_key and missing then + log.lg_printf(2, "Cannot read %s.", bad_key) + finish(1) + elseif bad_key then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + path, bad_key) + finish(1) + elseif verify.gl_sign_read_pubkey(path, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + table.insert(keys, { name = name, pub = pub }) + end + end + trusted_keys_cache[repo] = keys + return keys +end + +-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very +-- bytes the copy was checked against) by a key trusted for `repo`. The +-- key is picked by the signature's keynum, never by trying each one. +local function signed_for(path, sidecar_text, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then + return false + end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0 + end + end + return false +end + +--- Verify every package up front, before the summary is even shown. +--- Returns the private copies, plus a copy -> original map for messages. +--- +--- In system scope, a package whose manifest says base must also have a +--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the +--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg +--- does). +local function verify_all(gpkg_paths, opts) + local copies, original = {}, {} + local refused = false + + for _, p in ipairs(gpkg_paths) do + local copy, why, sidecar_text = verify_and_copy(p) + if copy and not manifest_of(copy) then + log.lg_printf(2, "Cannot read the manifest of %s.", p) + refused = true + copy = nil + end + if copy and opts.scope == ffi.C.GL_SCOPE_SYS then + local name, repo = manifest_of(copy) + if repo == "base" and not signed_for(p, sidecar_text, repo) then + log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.", + repo, name, repo) + refused = true + copy = nil + end + end + if copy then + table.insert(copies, copy) + original[copy] = p + elseif why then + log.lg_printf(2, "Refusing %s: %s.", p, why) + refused = true + end + end + + if refused then + finish(1) + end + return copies, original +end + +-- --------------------------------------------------------------------- +-- Confirmation summary +-- --------------------------------------------------------------------- + +--- Print the summary for `entries` ({repo, name, ver} each) and ask. +local function confirm(entries) + log.lg_printf(0, "SUMMARY:") + print("==============================") + print("") + for _, e in ipairs(entries) do + print(string.format(" * %s::%s\t\t%-16s", + e.repo or "unknown", e.name, e.ver or "unknown")) + end + print("") + io.write("Proceed? (y/N): ") + io.stdout:flush() + + local response = io.read("*l") + if not response then + return false + end + response = response:lower() + return response == "y" or response == "yes" +end + +--- Installed packages, from the live index for this scope: a list of +--- {repo, name, ver, auto}. The index's `current` file holds one +--- `repo::name::version::auto|explicit` line per package (index files +--- written before 2026-10-05 stop at the version). +--- A live context for opts' scope (and install root: syspkg -R only). +local function live_context(opts) + local ctx = ffi.new("gl_context_t") + if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then + finish(1) -- the library said why + end + return ctx +end + +-- The entries of an index `current` file ({} if there is none). +local function read_index_file(path) + local f = io.open(path, "r") + local out = {} + if not f then return out end + for line in f:lines() do + local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$") + if repo then + local ver, kind = rest:match("^(.-)::(%a+)$") + table.insert(out, { repo = repo, name = name, ver = ver or rest, + auto = kind == "auto" }) + end + end + f:close() + return out +end + +local function installed_entries(opts) + local ctx = live_context(opts) + return read_index_file(ffi.string(ctx.index_path) .. "/current") +end + +-- --------------------------------------------------------------------- +-- Repo resolution +-- --------------------------------------------------------------------- + +function M.resolve_repo(ctx, pkg_name) + local list = istore.gl_find_pkg_repos(ctx, pkg_name) + + if list.count == 0 then + log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name) + istore.gl_free_repo_list(list) + return nil + end + + if list.count == 1 then + local repo = ffi.string(list.repos[0]) + istore.gl_free_repo_list(list) + return repo + end + + log.lg_printf(1, "Multiple instances of %s found:", pkg_name) + for i = 0, tonumber(list.count) - 1 do + print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name)) + end + print("") + io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ") + io.stdout:flush() + local input = io.read("*l") + local choice = tonumber(input) + + if not choice or choice < 1 or choice > tonumber(list.count) then + log.lg_printf(2, "Invalid selection.") + istore.gl_free_repo_list(list) + return nil + end + + local repo = ffi.string(list.repos[choice - 1]) + istore.gl_free_repo_list(list) + return repo +end + +-- --------------------------------------------------------------------- +-- Single-package install (with reinstall-if-present handling) +-- --------------------------------------------------------------------- + +local function install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + if not pkg_name then + log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path) + finish(1) + end + + if isVerbose then + log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s", + pkg_name, version_str, manifest_repo, gpkg_path) + end + + local status = istore.gl_install_pkg(ctx, gpkg_path) + + if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then + if skipInstalled then + log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str) + return tonumber(ffi.C.GL_INSTALL_SKIPPED) + end + + log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str) + + local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo) + + if rm_status ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).", + manifest_repo, pkg_name, tostring(tonumber(rm_status))) + return tonumber(rm_status) + end + + status = istore.gl_install_pkg(ctx, gpkg_path) + if status == ffi.C.GL_INSTALL_OK then + -- M.install logs the one "staged from" line. + return 0 + else + log.lg_printf(2, "Reinstall of %s-%s failed (error %s).", + pkg_name, version_str, tostring(tonumber(status))) + return tonumber(status) + end + + elseif status == ffi.C.GL_INSTALL_OK then + return 0 + end + + return tonumber(status) +end + +-- --------------------------------------------------------------------- +-- Transaction lifecycle +-- --------------------------------------------------------------------- + +--- Open a staged transaction for the given scope. Exits on failure with +--- a scope-appropriate message. `scope_label` is used only in the +--- lock-contention message ("for UID 1000" vs "for the system scope"). +local function begin_staged(opts) + local scope_label = opts.scope_label + local ctx = ffi.new("gl_context_t") + local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") + + if txn_st ~= ffi.C.GL_TXN_OK then + if txn_st == ffi.C.GL_TXN_ERR_LOCK then + log.lg_printf(2, + "Another glacier transaction is already in progress %s.", + scope_label) + else + log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st)) + end + finish(1) + end + + ctx.strict = opts.strict and 1 or 0 + return ctx +end + +--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt. +--- The library prints each problem; this exits if there were any. The +--- commit checks again (gl_check_txn), which is what covers a removal +--- whose repo is only chosen after the prompt. +local function check_plan(opts, adds, removes, exit) + local live = live_context(opts) + live.strict = opts.strict and 1 or 0 + live.overwrite = overwrite and 1 or 0 + local a = ffi.new("const char *[?]", #adds + 1) + for i, p in ipairs(adds) do a[i - 1] = p end + local r = ffi.new("const char *[?]", #removes + 1) + for i, id in ipairs(removes) do r[i - 1] = id end + local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes)) + if problems < 0 then + log.lg_printf(2, "Cannot read the package store to check dependencies.") + end + if problems ~= 0 then exit(1) end +end + +--- Commit, or abort-and-exit on failure. +local function commit_or_die(ctx) + local commit_st = txn.gl_commit_transaction(ctx) + if commit_st == ffi.C.GL_TXN_ERR_DEPS then + -- The library already said what's wrong, one line each. + txn.gl_abort_transaction(ctx) + finish(1) + elseif commit_st ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st)) + txn.gl_abort_transaction(ctx) + finish(1) + end +end + +--- The last line of a committed transaction. If the link pass refused +--- any path (each refusal is already printed above), the transaction is +--- committed but did not fully succeed: an error, and exit status 1. +local function report_done(ctx, exit) + local n = tonumber(ctx.link_refusals) + if n > 0 then + log.lg_printf(2, "%s %s not linked.", tostring(n), + n == 1 and "path was" or "paths were") + exit(1) + end + log.lg_printf(3, "Completed with no errors.") + exit(0) +end + +--- Abort the transaction and exit non-zero. Every failure path inside a +--- staged loop goes through here so live state is never left partially +--- mutated. +local function abort_and_die(ctx) + txn.gl_abort_transaction(ctx) + finish(1) +end + +-- --------------------------------------------------------------------- +-- Repository indexes (REPO_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +ffi.cdef[[ +int gpkg_common_getpid(void) asm("getpid"); +int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod"); +int gpkg_common_close(int fd) asm("close"); +]] + +-- Largest index accepted: what gl_sign_verify will check. +local MAX_INDEX = 64 * 1024 * 1024 + +-- A whole file, or nil if it is missing, unreadable or over `max`. +local function read_capped(path, max) + local f = io.open(path, "rb") + if not f then return nil end + local data = f:read(max + 1) or "" + f:close() + if #data > max then return nil end + return data +end + +-- Fetch URL/NAME into `dest`. https goes through curl, refusing any +-- other protocol, redirects included; file:// is a plain copy of an +-- absolute path. True on success. +local function fetch(url, name, dest) + local path = url:match("^file://(/.*)$") + if path then + local data = read_capped(path .. "/" .. name, MAX_INDEX) + local f = data and io.open(dest, "wb") + if not f then return false end + local ok = f:write(data) + f:close() + return ok ~= nil + end + if not url:match("^https://") then return false end + local ok = os.execute("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 --max-filesize " .. MAX_INDEX .. + " -o " .. shell_quote(dest) .. " -- " .. + shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1") + return ok == true or ok == 0 +end + +-- Whether `text` is signed by `sig_path`, with a key trusted for `repo` +-- (picked by keynum, as signed_for). +local function index_signed(text, sig_path, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", text), #text) == 0 + end + end + return false +end + +-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the +-- gl_index_parse status. +local function parse_index(text, repo) + local idx = ffi.new("gl_index_t") + local st = tonumber(istore.gl_index_parse(text, #text, repo, idx)) + if st ~= 0 then return nil, st end + local r = { serial = idx.serial, valid_until = idx.valid_until, + npkgs = tonumber(idx.npkgs) } + istore.gl_index_free(idx) + return r +end + +-- Refresh one repository's index into `dir` (/repos): fetch, +-- verify, parse, refuse a rollback or an expired index, then rename +-- over the accepted copy. Any failure keeps the accepted copy, prints +-- one line and returns false. +local function refresh_one(repo, url, dir, file_mode) + local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid()) + local tmp_sig = tmp .. ".sig" + local function fail(fmt, ...) + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(2, fmt, ...) + return false + end + + local text + if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then + text = read_capped(tmp, MAX_INDEX) + end + if not text then + return fail("Cannot fetch the index for %s.", repo) + end + -- The signature is checked over the very bytes parsed below. + if not index_signed(text, tmp_sig, repo) then + return fail("Index for %s is not signed by a key trusted for %s.", repo, repo) + end + local new, st = parse_index(text, repo) + if st == 2 then + return fail("Index fetched for %s is the index of another repository.", repo) + elseif not new then + return fail("Malformed index for %s.", repo) + end + + local stored = dir .. "/" .. repo .. ".idx" + local old_text = read_capped(stored, MAX_INDEX) + local unchanged = false + if old_text then + local old = parse_index(old_text, repo) + if not old then + return fail("Malformed %s.", stored) + end + if new.serial < old.serial then + return fail("Index for %s is older than the one already accepted.", repo) + elseif new.serial == old.serial then + if text ~= old_text then + return fail("Index for %s has the serial of the one already accepted, but other contents.", repo) + end + unchanged = true + end + elseif io.open(stored, "rb") then + return fail("Cannot read %s.", stored) + end + if new.valid_until <= os.time() then + return fail("Index for %s has expired.", repo) + end + + local serial = string.format("%d", tonumber(new.serial)) + if unchanged then + os.remove(tmp) + os.remove(tmp_sig) + if isVerbose then + log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial) + end + return true + end + -- Never written in place (bug 25): renamed over the old copy. + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 + or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0 + or not os.rename(tmp_sig, stored .. ".sig") + or not os.rename(tmp, stored) then + return fail("Cannot write %s.", stored) + end + if isVerbose then + log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial, + tostring(new.npkgs), new.npkgs == 1 and "package" or "packages") + end + return true +end + +--- Refresh the index of every repository repos.conf gives a url +--- (REPO_DESIGN.txt section 5), into the scope's /repos, holding +--- the scope's lock. Every repository is tried; true if all succeeded. +--- Exits if there is nothing to refresh or the setup is at fault. +-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install +-- Every repos.conf entry with a url, in priority order: { name, url }. +-- Exits if there is none, or repos.conf is malformed. +local function configured_remotes() + local remotes = {} + if repos_conf_present() then + local buf = ffi.new("char[65536]") + if tonumber(istore.gl_conf_repos(REPOS_CONF, buf, 65536)) ~= 0 then + log.lg_printf(2, "Malformed %s.", REPOS_CONF) + finish(1) + end + for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then + table.insert(remotes, { name = name, url = url }) + end + end + end + if #remotes == 0 then + log.lg_printf(2, "No remote repositories are configured.") + finish(1) + end + return remotes +end + +function M.refresh(opts) + local remotes = configured_remotes() + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) -- the library said why + end + if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Another glacier transaction is already in progress %s.", + opts.scope_label) + finish(1) + end + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + log.lg_printf(0, "Syncing all repositories...") + local all = true + for _, r in ipairs(remotes) do + all = refresh_one(r.name, r.url, ffi.string(dir), file_mode) and all + end + ffi.C.gpkg_common_close(ctx.lock_fd) + if all then + log.lg_printf(3, "All repositories synced successfully.") + end + return all +end + +-- --------------------------------------------------------------------- +-- Public: whole-batch install / remove +-- --------------------------------------------------------------------- + +--- Install every package in gpkg_paths as ONE atomic staged transaction. +--- Any failure aborts the whole batch, leaving live state untouched. +--- Does not return on failure — exits. +-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS +-- opts.uid : uid for USR scope (ignored for SYS) +-- opts.scope_label : human string for the lock-contention message +-- opts.sysroot : install root (syspkg -R; nil = the running system) +-- opts.strict : refuse, before committing, anything the link pass +-- would refuse (syspkg --strict, implied by -R) +--- KEEP_OLD from glacier.conf: how many backups of replaced versions to +--- keep per package. There is no default — it ships as 1 in +--- glacier.conf, and an operation that would replace a version refuses +--- to run if it's missing or not a whole number. +local function keep_old() + local n = ffi.new("int[1]") + local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n)) + if st == 1 then + log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.") + elseif st == 2 then + log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.") + elseif st == 3 or (st == 0 and n[0] < 0) then + log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.") + end + if st ~= 0 or n[0] < 0 then finish(1) end + return tonumber(n[0]) +end + +-- Install verified private copies as one transaction. original[copy] +-- names each for messages. meta[copy], for packages fetched from a +-- repository (else nil): +-- auto : record it as installed as a dependency +-- may_replace : replace an installed other version without -O +-- (-u, and dependency upgrades) +-- dep : marked as a dependency in the summary +-- cache : the downloaded file, deleted once committed +local function install_copies(gpkg_paths, original, opts, meta) + -- A different version of a package that's already installed is a + -- REPLACEMENT (upgrade or downgrade). Only -O permits it; without + -- -O it's refused here, before the prompt. + local installed = installed_entries(opts) + local entries, replacing, refused = {}, {}, false + for _, p in ipairs(gpkg_paths) do + local name, repo, ver = manifest_of(p) + local m = meta[p] or {} + local e = { repo = repo, name = name, ver = ver } + for _, i in ipairs(installed) do + if i.name == name and i.repo == repo and i.ver ~= ver then + if overwrite or m.may_replace then + replacing[p] = i + e.ver = i.ver .. " -> " .. ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, name, i.ver) + refused = true + end + end + end + if m.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + + check_plan(opts, gpkg_paths, {}, finish) + + local keep = next(replacing) and keep_old() or 0 + + if not confirm(entries) then + finish(0) + end + + local ctx = begin_staged(opts) + ctx.overwrite = overwrite and 1 or 0 + local staged = 0 + + -- Replacements: back up the installed version (from LIVE, written + -- under a .part name and only promoted after a successful commit), + -- then remove it from the stage so the new version installs into + -- a clean slot in the same transaction. + local live = live_context(opts) + local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup" + for _, old in pairs(replacing) do + if keep > 0 then + local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name) + local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver) + local part = final .. ".part" + if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then + log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + table.insert(pending_backups, { part = part, final = final, dir = dir, old = old }) + end + if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + end + + for _, gpkg_path in ipairs(gpkg_paths) do + local status = install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + local abs_path = original[gpkg_path] + + if status == 0 then + staged = staged + 1 + if (meta[gpkg_path] or {}).auto + and istore.gl_set_pkg_auto(ctx, manifest_repo, pkg_name, true) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as a dependency.", + manifest_repo, pkg_name) + abort_and_die(ctx) + end + log.lg_printf(3, "%s::%s-%s: staged from %s.", + manifest_repo, pkg_name, version_str, abs_path) + elseif status == 1 then + log.lg_printf(2, "%s::%s: Failed to open package archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 2 then + log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 3 then + log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 4 then + log.lg_printf(2, "%s::%s: Failed to add entry to index.", + manifest_repo, pkg_name) + abort_and_die(ctx) + elseif status == 6 then + -- GL_INSTALL_SKIPPED: not a failure, keep going + elseif status == 7 then + -- GL_INSTALL_ERR_SCOPE: the library refused this + -- package for this scope (base-repo package under + -- user scope). The library already logged the + -- specific reason; don't second-guess it here. + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + -- Everything was skipped (-S, already up to date): the stage is + -- identical to live, so don't commit it. A commit isn't free — it + -- swaps the trees and re-links the whole store, re-printing every + -- standing link conflict for packages this command never touched. + if staged == 0 then + txn.gl_abort_transaction(ctx) + log.lg_printf(3, "Nothing to do.") + finish(0) + end + + commit_or_die(ctx) + + -- Committed: promote the backups, give each a sidecar (so it's an + -- installable, verifiable package), and keep only the newest KEEP_OLD. + for _, b in ipairs(pending_backups) do + if os.rename(b.part, b.final) then + local hex = sha256_file(b.final) + local sf = hex and io.open(b.final .. ".sha256", "w") + if sf then + sf:write("sha256:" .. hex .. "\n") + sf:close() + end + istore.gl_prune_backups(b.dir, keep) + log.lg_printf(0, "Backed up %s::%s %s to %s", + b.old.repo, b.old.name, b.old.ver, b.final) + else + log.lg_printf(1, "Could not keep the backup of %s::%s %s.", + b.old.repo, b.old.name, b.old.ver) + end + end + pending_backups = {} + + for _, p in ipairs(gpkg_paths) do + if meta[p] and meta[p].cache then os.remove(meta[p].cache) end + end + + report_done(ctx, finish) +end + +-- --------------------------------------------------------------------- +-- -f / -u: packages from the repositories (REPO_DESIGN.txt section 6) +-- --------------------------------------------------------------------- + +-- -1, 0 or 1 as version a is below, equal to or above b ("MAJ.MIN.PAT"). +local function vercmp(a, b) + local x = { a:match("^(%d+)%.(%d+)%.(%d+)") } + local y = { b:match("^(%d+)%.(%d+)%.(%d+)") } + for k = 1, 3 do + local m, n = tonumber(x[k]) or 0, tonumber(y[k]) or 0 + if m ~= n then return m < n and -1 or 1 end + end + return 0 +end + +-- A package's relations as an index lists them: "NAME VER\n" lines. +local function relation_lines(list, name_field, ver_field) + local out = {} + local k = 0 + while list ~= nil and list[k][name_field] ~= nil do + local v = list[k][ver_field] + table.insert(out, string.format("%s %d.%d.%d\n", + ffi.string(list[k][name_field]), v.maj, v.min, v.pat)) + k = k + 1 + end + return table.concat(out) +end + +-- Whether the manifest of `path` (read by the library) says exactly what +-- its index entry `e` of repository `repo` says: NAME, VER, PKG_REPO, +-- DEPS and CONFS. A package is from `repo` because that repo's signed +-- index lists it AND it says so, never because it says so. +local function matches_index(path, repo, e) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return false + end + local ok = ffi.string(m.pkg_name) == e.name + and ffi.string(m.pkg_repo) == repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == e.ver + and relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == e.deps + and relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == e.confs + istore.gl_free_pkg(m) + return ok +end + +-- The accepted index of every configured repository, freshly refreshed +-- (decision 10d: any failure refuses the operation). In priority order: +-- { name, url, pkgs = { { name, ver, file, sha256, size, deps, confs }... } }. +-- User scope never fetches from base (the library refuses it there). +local function load_indexes(opts) + local remotes = configured_remotes() + if not M.refresh(opts) then + finish(1) + end + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) + end + local out = {} + for _, r in ipairs(remotes) do + if opts.scope ~= ffi.C.GL_SCOPE_USR or r.name ~= "base" then + local path = ffi.string(dir) .. "/" .. r.name .. ".idx" + local text = read_capped(path, MAX_INDEX) + local idx = ffi.new("gl_index_t") + if not text or istore.gl_index_parse(text, #text, r.name, idx) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + local pkgs = {} + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + table.insert(pkgs, { + name = ffi.string(p.name), ver = ffi.string(p.ver), + file = ffi.string(p.file), sha256 = ffi.string(p.sha256), + size = tonumber(p.size), deps = ffi.string(p.deps), + confs = ffi.string(p.confs), + }) + end + istore.gl_index_free(idx) + table.insert(out, { name = r.name, url = r.url, pkgs = pkgs }) + end + end + return out +end + +-- The highest version of `name` that repository `r` serves, or nil. +local function newest_in(r, name) + local best + for _, e in ipairs(r.pkgs) do + if e.name == name and (not best or vercmp(e.ver, best.ver) > 0) then + best = e + end + end + return best +end + +-- Which repository `name` comes from: the first, by priority, that +-- serves it, at its highest version. repo, entry, or nil. +local function pick(indexes, name) + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then return r, e end + end +end + +-- Add the missing dependencies of everything in `plan` (and theirs), +-- ROADMAP 2.3's closure. A dependency already met (in this scope, or +-- for a user, by the system) is left alone; one installed at too old a +-- version is upgraded from its own repository, keeping its auto or +-- explicit mark; one not installed comes from pick(), recorded auto. +-- Whatever can't be met is left for gl_check_plan to report. +local function close_deps(plan, indexes, opts) + local planned = {} + for _, it in ipairs(plan) do planned[it.name] = it end + local installed = installed_entries(opts) + local system = {} + if opts.scope == ffi.C.GL_SCOPE_USR then + system = read_index_file("/glacier/sys/index/current") + end + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + + local k = 1 + while k <= #plan do + for dname, dver in plan[k].entry.deps:gmatch("(%S+) (%S+)\n") do + local met, old = planned[dname] ~= nil, nil + for _, i in ipairs(installed) do + if i.name == dname then + if vercmp(i.ver, dver) >= 0 then met = true end + old = old or i + end + end + for _, i in ipairs(system) do + if i.name == dname and vercmp(i.ver, dver) >= 0 then met = true end + end + if not met then + local r, e + if old then + r = by_repo[old.repo] + e = r and newest_in(r, dname) + else + r, e = pick(indexes, dname) + end + if e and vercmp(e.ver, dver) >= 0 then + local it = { repo = r, entry = e, name = dname, dep = true, + auto = not old or old.auto, may_replace = old ~= nil } + table.insert(plan, it) + planned[dname] = it + end + end + end + k = k + 1 + end +end + +-- Download `e` (an index entry of repository `r`) into the scope's +-- cache, hashing it on the way, unless a cached copy already matches. +-- Never more than the index's SIZE is read. The path, or nil plus +-- true if something was fetched but is not what the index lists. +local function download(ctx, r, e, file_mode) + local dir = ffi.new("char[4096]") + if txn.gl_scope_cache_dir(ctx, r.name, dir) ~= 0 then + finish(1) -- the library said why + end + local want = e.sha256:match("^sha256:(%x+)$") + local dest = ffi.string(dir) .. "/" .. e.file + if sha256_file(dest) == want then + return dest + end + + local src + local path = r.url:match("^file://(/.*)$") + if path then + src = io.open(path .. "/" .. e.file, "rb") + elseif r.url:match("^https://") then + src = io.popen("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 -- " .. + shell_quote(r.url .. "/" .. e.file) .. " 2>/dev/null", "r") + end + if not src then return nil end + local tmp = string.format("%s/.%s.%d", ffi.string(dir), e.file, + ffi.C.gpkg_common_getpid()) + local dst = io.open(tmp, "wb") + if not dst then + src:close() + return nil + end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + local n = 0 + while n <= e.size do + local chunk = src:read(math.min(65536, e.size + 1 - n)) + if not chunk then break end + n = n + #chunk + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + if n ~= e.size or ffi.string(hex) ~= want then + os.remove(tmp) + return nil, n > 0 + end + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 or not os.rename(tmp, dest) then + os.remove(tmp) + return nil + end + return dest +end + +-- Fetch, verify and install everything in `plan` (see close_deps). +local function install_plan(plan, opts) + local ctx = live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local copies, original, meta = {}, {}, {} + local refused = false + for _, it in ipairs(plan) do + local e = it.entry + local id = string.format("%s::%s %s", it.repo.name, e.name, e.ver) + local cached, wrong = download(ctx, it.repo, e, file_mode) + local copy = cached and verify_and_copy(cached, e.sha256 .. "\n") + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + refused = true + elseif not copy or not matches_index(copy, it.repo.name, e) then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + refused = true + else + table.insert(copies, copy) + original[copy] = it.repo.url .. "/" .. e.file + meta[copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, cache = cached } + end + end + if refused then + finish(1) + end + install_copies(copies, original, opts, meta) +end + +--- -f NAME...: install packages by name from the repositories, with +--- whatever dependencies they are missing. Like -l otherwise: an +--- installed other version of a named package needs -O. +function M.fetch(names, opts) + local indexes = load_indexes(opts) + local plan, refused, seen = {}, false, {} + for _, name in ipairs(names) do + local r, e = pick(indexes, name) + if seen[name] then + -- named twice: once is enough + elseif e then + seen[name] = true + table.insert(plan, { repo = r, entry = e, name = name }) + else + log.lg_printf(2, "%s is not in any repository.", name) + refused = true + end + end + if refused then + finish(1) + end + close_deps(plan, indexes, opts) + install_plan(plan, opts) +end + +--- -u [NAME...]: replace every installed package (or those named) whose +--- repository's index has a higher version, as -lO does (backups, +--- KEEP_OLD). Packages from repositories not configured are left alone. +function M.upgrade(names, opts) + local indexes = load_indexes(opts) + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local installed = installed_entries(opts) + + local wanted, refused = nil, false + if #names > 0 then + wanted = {} + for _, name in ipairs(names) do + local found = false + for _, i in ipairs(installed) do + if i.name == name then + found = true + if not by_repo[i.repo] then + log.lg_printf(2, "%s::%s is not in any configured repository.", + i.repo, i.name) + refused = true + end + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + refused = true + end + wanted[name] = true + end + end + if refused then + finish(1) + end + + local plan = {} + for _, i in ipairs(installed) do + local r = by_repo[i.repo] + local e = r and (not wanted or wanted[i.name]) and newest_in(r, i.name) + if e and vercmp(e.ver, i.ver) > 0 then + table.insert(plan, { repo = r, entry = e, name = i.name, + auto = i.auto, may_replace = true }) + end + end + if #plan == 0 then + log.lg_printf(3, "Nothing to do.") + finish(0) + end + close_deps(plan, indexes, opts) + install_plan(plan, opts) +end + +function M.install(gpkg_paths, opts) + -- From here on, the paths are the VERIFIED PRIVATE COPIES; the + -- caller's paths are only used for messages. + local copies, original = verify_all(gpkg_paths, opts) + install_copies(copies, original, opts, {}) +end + +--- Remove every named package as ONE atomic staged transaction. +--- Does not return on failure — exits. +function M.remove(pkg_names, opts) + -- Names, not files: resolve them against what's actually installed + -- (the old summary read them as .gpkg paths and printed + -- "unknown::pkg 0.0.0"). Anything not installed fails here, before + -- the prompt, not after the user has already said yes. + local installed = installed_entries(opts) + local entries, missing = {}, false + for _, name in ipairs(pkg_names) do + local found = false + for _, e in ipairs(installed) do + if e.name == name then + table.insert(entries, e) + found = true + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + missing = true + end + end + if missing then + os.exit(1) + end + + -- A name installed from more than one repo isn't resolved until + -- after the prompt, so only unambiguous names are checked here. + local count, removes = {}, {} + for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end + for _, e in ipairs(entries) do + if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end + end + check_plan(opts, {}, removes, os.exit) + + if not confirm(entries) then + os.exit(0) + end + + local ctx = begin_staged(opts) + + for _, pkg_name in ipairs(pkg_names) do + local repo = M.resolve_repo(ctx, pkg_name) + if not repo then + log.lg_printf(2, "Failed to resolve group for %s.", pkg_name) + abort_and_die(ctx) + end + + local status = istore.gl_remove_pkg(ctx, pkg_name, repo) + + if status == ffi.C.GL_REMOVE_OK then + log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name) + elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then + log.lg_printf(2, "%s::%s not found.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then + log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_INDEX then + log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name) + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + commit_or_die(ctx) + + report_done(ctx, os.exit) +end + +return M diff --git a/lib/gpkg_common.lua.old5 b/lib/gpkg_common.lua.old5 new file mode 100644 index 0000000..ccc332f --- /dev/null +++ b/lib/gpkg_common.lua.old5 @@ -0,0 +1,1431 @@ +-- lib/gpkg_common.lua +-- +-- Shared machinery between gpkg (per-user scope only) and syspkg +-- (system scope only). See SECURITY_DESIGN.txt section 7. +-- +-- The interface here is deliberately COARSE-GRAINED: M.install() and +-- M.remove() own the entire staged-transaction lifecycle +-- (gl_init_stage_context -> loop -> commit/abort), rather than +-- exporting fine-grained pieces that each caller then has to sequence +-- itself. That's what keeps the sequencing — and, once Checkpoint 2's +-- verification lands, the hash refusal matrix — in exactly ONE place +-- instead of duplicated across two binaries and drifting apart. +-- +-- What callers keep for themselves: +-- * argument parsing +-- * deciding WHICH scope they're allowed to request (gpkg never +-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag +-- for it", the capability isn't in its code path at all) +-- * their own privilege model (only syspkg runs elevated) +-- +-- Callers pass a `env` table on construction with the FFI handles and +-- shared state, so this module doesn't ffi.load() anything itself and +-- doesn't care where the .so's came from. + +local ffi = require("ffi") +local bit = require("bit") +local glacier_cdef = require("lib/glacier_cdef") + +local M = {} + +-- Module-level handles, set by M.init(). Kept here rather than passed +-- through every function because every function needs them. +local log, istore, txn, verify +local argv +local isVerbose = false +local skipInstalled = false +local overwrite = false + +local txn_name = glacier_cdef.txn_name + +--- Initialise the module. Must be called before anything else. +-- env.log / env.istore / env.txn : ffi.load() handles +-- env.verify : libglacier_verify.so handle (installs) +-- env.argv : argv table (for usage messages) +function M.init(env) + log = env.log + istore = env.istore + txn = env.txn + verify = env.verify + argv = env.argv +end + +--- Toggle flags the CLIs parse but this module acts on. +function M.set_verbose(v) isVerbose = v end +function M.set_skip_installed(v) skipInstalled = v end +function M.set_overwrite(v) overwrite = v end + +-- --------------------------------------------------------------------- +-- Manifest reading +-- --------------------------------------------------------------------- + +-- Quote a string for /bin/sh: wrap in single quotes, and turn each +-- embedded ' into '\''. Package paths come from the command line and +-- manifest entry names come from the archive, and syspkg runs all of +-- this as root — an unescaped ' in either is command execution. +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +--- name, repo and version ("MAJ.MIN.PAT", as the store names versions) +--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same +--- reader gl_install_pkg uses, so what is shown, compared and installed +--- can never disagree. nil if the manifest can't be read. +local function manifest_of(path) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return nil + end + local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo) + local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) + istore.gl_free_pkg(m) + return name, repo, ver +end + +-- --------------------------------------------------------------------- +-- Integrity verification (SECURITY_DESIGN.txt sections 3-4) +-- --------------------------------------------------------------------- + +-- Private working dir for verified copies, removed by finish(). +local private_dir = nil + +-- Backups written during this transaction but not yet committed +-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that +-- were never promoted, so an aborted upgrade leaves no stray backup. +local pending_backups = {} + +--- Exit, removing the private copies (and uncommitted backups) first. +--- Every exit on the install path goes through here. +local function finish(code) + for _, b in ipairs(pending_backups) do + os.remove(b.part) + end + pending_backups = {} + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +--- sha256 of a file as "", or nil. +local function sha256_file(path) + local f = io.open(path, "rb") + if not f then return nil end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = f:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + end + f:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +--- Copy `path` into the private dir, hashing it in the same pass, and +--- check the hash against `path`.sha256. Returns the private copy's path, +--- or nil plus a reason. +--- +--- Everything after this (summary, manifest read, gl_install_pkg) reads +--- ONLY the copy. Verifying the original and then installing it would +--- leave a gap where it could be swapped — and under syspkg that's root +--- reading a file whose directory another user may control. The copy +--- lives in a mktemp -d dir only the invoking user (root, for syspkg) +--- can write. +--- +--- Refusal matrix (section 4). A missing sidecar is treated exactly like +--- a mismatch: +--- repo == base -> always refuse, no exceptions +--- scope == SYS -> always refuse, any repo +--- scope == USR, repo != base -> refuse by default; the ONLY place +--- a future bypass flag may apply +--- No bypass exists, so today every row refuses and the repo (which we +--- couldn't trust before verifying anyway) never needs consulting. A +--- bypass, if ever added, must check scope and the VERIFIED manifest's +--- repo here, before anything else reads the file. +--- +--- A package fetched from a repository passes `vouched`, the "sha256:" +--- its signed index gives, in place of a sidecar. +local function verify_and_copy(path, vouched) + local sidecar = path .. ".sha256" + local sidecar_text = vouched + if not sidecar_text then + local sf = io.open(sidecar, "r") + if not sf then + return nil, "no sidecar " .. sidecar + end + sidecar_text = sf:read("*a") or "" + sf:close() + end + local expected = sidecar_text:match("^sha256:(%x+)%s*$") + if not expected or #expected ~= 64 then + return nil, "malformed sidecar " .. sidecar + end + expected = expected:lower() + + if not private_dir then + local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + return nil, "cannot create a private working directory" + end + end + + local src = io.open(path, "rb") + if not src then + return nil, "cannot open " .. path + end + + -- Unique per argument, so two packages with the same basename + -- (from different directories) can't collide. + local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0, + path:match("([^/]+)$")) + M._ncopies = (M._ncopies or 0) + 1 + local dst = io.open(copy_path, "wb") + if not dst then + src:close() + return nil, "cannot write " .. copy_path + end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = src:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + + if ffi.string(hex) ~= expected then + return nil, "hash mismatch (sidecar says " .. expected .. + ", file is " .. ffi.string(hex) .. ")" + end + + return copy_path, nil, sidecar_text +end + +-- --------------------------------------------------------------------- +-- Signatures (REPO_DESIGN.txt section 7) +-- --------------------------------------------------------------------- + +-- A keyring: repos.conf and the keys it lists, under `sysroot` (nil or +-- "/" = the running system). Read only by syspkg (gpkg reads the +-- system's until user repos). The signature on a local base package +-- (-l) is checked with the HOST's, even under -R (the build host's +-- trust, as KEEP_OLD). Repository operations (-y/-f/-u) use the +-- keyring of the system they act on: under -R, TARGET's own, since the +-- indexes they accept are TARGET's and TARGET checks them from then on. +local function keyring(sysroot) + local root = (sysroot or "/"):gsub("/+$", "") + return { root = root, conf = root .. "/etc/glacier/repos.conf", + keys = root .. "/etc/glacier/keys" } +end +local HOST_KEYRING = keyring(nil) + +ffi.cdef[[ +char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath"); +]] + +local function realpath(path) + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_common_realpath(path, buf) == nil then return nil end + return ffi.string(buf) +end + +-- nil if `path`, every ancestor of it, and every ancestor of its real +-- path are root-owned and not group/world-writable (as syspkg's own +-- lib/: a key a non-root user could swap is no key). Else the path at +-- fault, plus true if it is missing (or can't be resolved). +local function untrusted(path) + local function chain(p) + while true do + local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null") + local line = f and f:read("*l") + if f then f:close() end + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then return p, true end + if tonumber(uid) ~= 0 + or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + return p + end + if p == "/" then return nil end + p = p:match("^(.*)/[^/]*$") + if p == "" then p = "/" end + end + end + local bad, missing = chain(path) + if bad then return bad, missing end + local real = realpath(path) + if not real then return path, true end + return chain(real) +end + +-- Stop the run unless `path`, part of keyring `kr`, is trusted (as +-- untrusted() says) and, in another root, resolves inside it: TARGET's +-- etc/glacier/repos.conf -> /etc/glacier/repos.conf would read the +-- host's file as TARGET's. +local function require_trusted(path, kr) + local bad, missing = untrusted(path) + if bad and missing then + log.lg_printf(2, "Cannot read %s.", bad) + finish(1) + elseif bad then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + path, bad) + finish(1) + end + if kr.root ~= "" then + local real, root = realpath(path), realpath(kr.root) + if not (real and root and real:sub(1, #root + 1) == root .. "/") then + log.lg_printf(2, "Refusing %s: it resolves outside %s.", path, kr.root) + finish(1) + end + end +end + +-- Whether keyring `kr`'s repos.conf exists, having checked it is +-- trusted (else the run stops: the admin's configuration is at fault, +-- not a package). +local function repos_conf_present(kr) + local f, _, code = io.open(kr.conf, "r") + if f then f:close() end + if not f and code == 2 then return false end + require_trusted(kr.conf, kr) + return true +end + +-- The public keys keyring `kr` trusts for `repo`, read once per run: +-- { { name, pub }... }. A missing repos.conf trusts nothing. A +-- repos.conf or listed key that is untrusted or can't be read stops the +-- run: that is the admin's configuration, not the package, at fault. +local trusted_keys_cache = {} +local function trusted_keys(repo, kr) + local cache_key = kr.conf .. "\n" .. repo + if trusted_keys_cache[cache_key] then return trusted_keys_cache[cache_key] end + local keys = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[4096]") + local st = tonumber(istore.gl_conf_repo_keys(kr.conf, repo, buf, 4096)) + if st == 1 or st == 3 or st == 4 or st == 5 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name in ffi.string(buf):gmatch("([^\n]+)\n") do + local path = kr.keys .. "/" .. name .. ".pub" + local pub = ffi.new("gl_sign_pubkey_t") + require_trusted(path, kr) + if verify.gl_sign_read_pubkey(path, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + table.insert(keys, { name = name, pub = pub }) + end + end + trusted_keys_cache[cache_key] = keys + return keys +end + +-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very +-- bytes the copy was checked against) by a key trusted for `repo`. The +-- key is picked by the signature's keynum, never by trying each one. +local function signed_for(path, sidecar_text, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then + return false + end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, HOST_KEYRING)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0 + end + end + return false +end + +--- Verify every package up front, before the summary is even shown. +--- Returns the private copies, plus a copy -> original map for messages. +--- +--- In system scope, a package whose manifest says base must also have a +--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the +--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg +--- does). +local function verify_all(gpkg_paths, opts) + local copies, original = {}, {} + local refused = false + + for _, p in ipairs(gpkg_paths) do + local copy, why, sidecar_text = verify_and_copy(p) + if copy and not manifest_of(copy) then + log.lg_printf(2, "Cannot read the manifest of %s.", p) + refused = true + copy = nil + end + if copy and opts.scope == ffi.C.GL_SCOPE_SYS then + local name, repo = manifest_of(copy) + if repo == "base" and not signed_for(p, sidecar_text, repo) then + log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.", + repo, name, repo) + refused = true + copy = nil + end + end + if copy then + table.insert(copies, copy) + original[copy] = p + elseif why then + log.lg_printf(2, "Refusing %s: %s.", p, why) + refused = true + end + end + + if refused then + finish(1) + end + return copies, original +end + +-- --------------------------------------------------------------------- +-- Confirmation summary +-- --------------------------------------------------------------------- + +--- Print the summary for `entries` ({repo, name, ver} each) and ask. +local function confirm(entries) + log.lg_printf(0, "SUMMARY:") + print("==============================") + print("") + for _, e in ipairs(entries) do + print(string.format(" * %s::%s\t\t%-16s", + e.repo or "unknown", e.name, e.ver or "unknown")) + end + print("") + io.write("Proceed? (y/N): ") + io.stdout:flush() + + local response = io.read("*l") + if not response then + return false + end + response = response:lower() + return response == "y" or response == "yes" +end + +--- Installed packages, from the live index for this scope: a list of +--- {repo, name, ver, auto}. The index's `current` file holds one +--- `repo::name::version::auto|explicit` line per package (index files +--- written before 2026-10-05 stop at the version). +--- A live context for opts' scope (and install root: syspkg -R only). +local function live_context(opts) + local ctx = ffi.new("gl_context_t") + if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then + finish(1) -- the library said why + end + return ctx +end + +-- The entries of an index `current` file ({} if there is none). +local function read_index_file(path) + local f = io.open(path, "r") + local out = {} + if not f then return out end + for line in f:lines() do + local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$") + if repo then + local ver, kind = rest:match("^(.-)::(%a+)$") + table.insert(out, { repo = repo, name = name, ver = ver or rest, + auto = kind == "auto" }) + end + end + f:close() + return out +end + +local function installed_entries(opts) + local ctx = live_context(opts) + return read_index_file(ffi.string(ctx.index_path) .. "/current") +end + +-- --------------------------------------------------------------------- +-- Repo resolution +-- --------------------------------------------------------------------- + +function M.resolve_repo(ctx, pkg_name) + local list = istore.gl_find_pkg_repos(ctx, pkg_name) + + if list.count == 0 then + log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name) + istore.gl_free_repo_list(list) + return nil + end + + if list.count == 1 then + local repo = ffi.string(list.repos[0]) + istore.gl_free_repo_list(list) + return repo + end + + log.lg_printf(1, "Multiple instances of %s found:", pkg_name) + for i = 0, tonumber(list.count) - 1 do + print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name)) + end + print("") + io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ") + io.stdout:flush() + local input = io.read("*l") + local choice = tonumber(input) + + if not choice or choice < 1 or choice > tonumber(list.count) then + log.lg_printf(2, "Invalid selection.") + istore.gl_free_repo_list(list) + return nil + end + + local repo = ffi.string(list.repos[choice - 1]) + istore.gl_free_repo_list(list) + return repo +end + +-- --------------------------------------------------------------------- +-- Single-package install (with reinstall-if-present handling) +-- --------------------------------------------------------------------- + +local function install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + if not pkg_name then + log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path) + finish(1) + end + + if isVerbose then + log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s", + pkg_name, version_str, manifest_repo, gpkg_path) + end + + local status = istore.gl_install_pkg(ctx, gpkg_path) + + if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then + if skipInstalled then + log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str) + return tonumber(ffi.C.GL_INSTALL_SKIPPED) + end + + log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str) + + local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo) + + if rm_status ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).", + manifest_repo, pkg_name, tostring(tonumber(rm_status))) + return tonumber(rm_status) + end + + status = istore.gl_install_pkg(ctx, gpkg_path) + if status == ffi.C.GL_INSTALL_OK then + -- M.install logs the one "staged from" line. + return 0 + else + log.lg_printf(2, "Reinstall of %s-%s failed (error %s).", + pkg_name, version_str, tostring(tonumber(status))) + return tonumber(status) + end + + elseif status == ffi.C.GL_INSTALL_OK then + return 0 + end + + return tonumber(status) +end + +-- --------------------------------------------------------------------- +-- Transaction lifecycle +-- --------------------------------------------------------------------- + +--- Open a staged transaction for the given scope. Exits on failure with +--- a scope-appropriate message. `scope_label` is used only in the +--- lock-contention message ("for UID 1000" vs "for the system scope"). +local function begin_staged(opts) + local scope_label = opts.scope_label + local ctx = ffi.new("gl_context_t") + local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") + + if txn_st ~= ffi.C.GL_TXN_OK then + if txn_st == ffi.C.GL_TXN_ERR_LOCK then + log.lg_printf(2, + "Another glacier transaction is already in progress %s.", + scope_label) + else + log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st)) + end + finish(1) + end + + ctx.strict = opts.strict and 1 or 0 + return ctx +end + +--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt. +--- The library prints each problem; this exits if there were any. The +--- commit checks again (gl_check_txn), which is what covers a removal +--- whose repo is only chosen after the prompt. +local function check_plan(opts, adds, removes, exit) + local live = live_context(opts) + live.strict = opts.strict and 1 or 0 + live.overwrite = overwrite and 1 or 0 + local a = ffi.new("const char *[?]", #adds + 1) + for i, p in ipairs(adds) do a[i - 1] = p end + local r = ffi.new("const char *[?]", #removes + 1) + for i, id in ipairs(removes) do r[i - 1] = id end + local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes)) + if problems < 0 then + log.lg_printf(2, "Cannot read the package store to check dependencies.") + end + if problems ~= 0 then exit(1) end +end + +--- Commit, or abort-and-exit on failure. +local function commit_or_die(ctx) + local commit_st = txn.gl_commit_transaction(ctx) + if commit_st == ffi.C.GL_TXN_ERR_DEPS then + -- The library already said what's wrong, one line each. + txn.gl_abort_transaction(ctx) + finish(1) + elseif commit_st ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st)) + txn.gl_abort_transaction(ctx) + finish(1) + end +end + +--- The last line of a committed transaction. If the link pass refused +--- any path (each refusal is already printed above), the transaction is +--- committed but did not fully succeed: an error, and exit status 1. +local function report_done(ctx, exit) + local n = tonumber(ctx.link_refusals) + if n > 0 then + log.lg_printf(2, "%s %s not linked.", tostring(n), + n == 1 and "path was" or "paths were") + exit(1) + end + log.lg_printf(3, "Completed with no errors.") + exit(0) +end + +--- Abort the transaction and exit non-zero. Every failure path inside a +--- staged loop goes through here so live state is never left partially +--- mutated. +local function abort_and_die(ctx) + txn.gl_abort_transaction(ctx) + finish(1) +end + +-- --------------------------------------------------------------------- +-- Repository indexes (REPO_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +ffi.cdef[[ +int gpkg_common_getpid(void) asm("getpid"); +int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod"); +int gpkg_common_close(int fd) asm("close"); +]] + +-- Largest index accepted: what gl_sign_verify will check. +local MAX_INDEX = 64 * 1024 * 1024 + +-- A whole file, or nil if it is missing, unreadable or over `max`. +local function read_capped(path, max) + local f = io.open(path, "rb") + if not f then return nil end + local data = f:read(max + 1) or "" + f:close() + if #data > max then return nil end + return data +end + +-- Fetch URL/NAME into `dest`. https goes through curl, refusing any +-- other protocol, redirects included; file:// is a plain copy of an +-- absolute path. True on success. +local function fetch(url, name, dest) + local path = url:match("^file://(/.*)$") + if path then + local data = read_capped(path .. "/" .. name, MAX_INDEX) + local f = data and io.open(dest, "wb") + if not f then return false end + local ok = f:write(data) + f:close() + return ok ~= nil + end + if not url:match("^https://") then return false end + local ok = os.execute("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 --max-filesize " .. MAX_INDEX .. + " -o " .. shell_quote(dest) .. " -- " .. + shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1") + return ok == true or ok == 0 +end + +-- Whether `text` is signed by `sig_path`, with a key keyring `kr` +-- trusts for `repo` (picked by keynum, as signed_for). +local function index_signed(text, sig_path, repo, kr) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, kr)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", text), #text) == 0 + end + end + return false +end + +-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the +-- gl_index_parse status. +local function parse_index(text, repo) + local idx = ffi.new("gl_index_t") + local st = tonumber(istore.gl_index_parse(text, #text, repo, idx)) + if st ~= 0 then return nil, st end + local r = { serial = idx.serial, valid_until = idx.valid_until, + npkgs = tonumber(idx.npkgs) } + istore.gl_index_free(idx) + return r +end + +-- Refresh one repository's index into `dir` (/repos): fetch, +-- verify, parse, refuse a rollback or an expired index, then rename +-- over the accepted copy, checking signatures with keyring `kr`. Any +-- failure keeps the accepted copy, prints one line and returns false. +local function refresh_one(repo, url, dir, file_mode, kr) + local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid()) + local tmp_sig = tmp .. ".sig" + local function fail(fmt, ...) + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(2, fmt, ...) + return false + end + + local text + if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then + text = read_capped(tmp, MAX_INDEX) + end + if not text then + return fail("Cannot fetch the index for %s.", repo) + end + -- The signature is checked over the very bytes parsed below. + if not index_signed(text, tmp_sig, repo, kr) then + return fail("Index for %s is not signed by a key trusted for %s.", repo, repo) + end + local new, st = parse_index(text, repo) + if st == 2 then + return fail("Index fetched for %s is the index of another repository.", repo) + elseif not new then + return fail("Malformed index for %s.", repo) + end + + local stored = dir .. "/" .. repo .. ".idx" + local old_text = read_capped(stored, MAX_INDEX) + local unchanged = false + if old_text then + local old = parse_index(old_text, repo) + if not old then + return fail("Malformed %s.", stored) + end + if new.serial < old.serial then + return fail("Index for %s is older than the one already accepted.", repo) + elseif new.serial == old.serial then + if text ~= old_text then + return fail("Index for %s has the serial of the one already accepted, but other contents.", repo) + end + unchanged = true + end + elseif io.open(stored, "rb") then + return fail("Cannot read %s.", stored) + end + if new.valid_until <= os.time() then + return fail("Index for %s has expired.", repo) + end + + local serial = string.format("%d", tonumber(new.serial)) + if unchanged then + os.remove(tmp) + os.remove(tmp_sig) + if isVerbose then + log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial) + end + return true + end + -- Never written in place (bug 25): renamed over the old copy. + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 + or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0 + or not os.rename(tmp_sig, stored .. ".sig") + or not os.rename(tmp, stored) then + return fail("Cannot write %s.", stored) + end + if isVerbose then + log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial, + tostring(new.npkgs), new.npkgs == 1 and "package" or "packages") + end + return true +end + +--- Refresh the index of every repository repos.conf gives a url +--- (REPO_DESIGN.txt section 5), into the scope's /repos, holding +--- the scope's lock. Every repository is tried; true if all succeeded. +--- Exits if there is nothing to refresh or the setup is at fault. +-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install +-- Every entry with a url in keyring `kr`'s repos.conf, in priority +-- order: { name, url }. Exits if there is none, or repos.conf is +-- malformed. +local function configured_remotes(kr) + local remotes = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[65536]") + if tonumber(istore.gl_conf_repos(kr.conf, buf, 65536)) ~= 0 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then + table.insert(remotes, { name = name, url = url }) + end + end + end + if #remotes == 0 then + log.lg_printf(2, "No remote repositories are configured.") + finish(1) + end + return remotes +end + +function M.refresh(opts) + local kr = keyring(opts.sysroot) + local remotes = configured_remotes(kr) + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) -- the library said why + end + if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Another glacier transaction is already in progress %s.", + opts.scope_label) + finish(1) + end + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + log.lg_printf(0, "Syncing all repositories...") + local all = true + for _, r in ipairs(remotes) do + all = refresh_one(r.name, r.url, ffi.string(dir), file_mode, kr) and all + end + ffi.C.gpkg_common_close(ctx.lock_fd) + if all then + log.lg_printf(3, "All repositories synced successfully.") + end + return all +end + +-- --------------------------------------------------------------------- +-- Public: whole-batch install / remove +-- --------------------------------------------------------------------- + +--- Install every package in gpkg_paths as ONE atomic staged transaction. +--- Any failure aborts the whole batch, leaving live state untouched. +--- Does not return on failure — exits. +-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS +-- opts.uid : uid for USR scope (ignored for SYS) +-- opts.scope_label : human string for the lock-contention message +-- opts.sysroot : install root (syspkg -R; nil = the running system) +-- opts.strict : refuse, before committing, anything the link pass +-- would refuse (syspkg --strict, implied by -R) +--- KEEP_OLD from glacier.conf: how many backups of replaced versions to +--- keep per package. There is no default — it ships as 1 in +--- glacier.conf, and an operation that would replace a version refuses +--- to run if it's missing or not a whole number. +local function keep_old() + local n = ffi.new("int[1]") + local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n)) + if st == 1 then + log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.") + elseif st == 2 then + log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.") + elseif st == 3 or (st == 0 and n[0] < 0) then + log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.") + end + if st ~= 0 or n[0] < 0 then finish(1) end + return tonumber(n[0]) +end + +-- Install verified private copies as one transaction. original[copy] +-- names each for messages. meta[copy], for packages fetched from a +-- repository (else nil): +-- auto : record it as installed as a dependency +-- may_replace : replace an installed other version without -O +-- (-u, and dependency upgrades) +-- dep : marked as a dependency in the summary +-- cache : the downloaded file, deleted once committed +local function install_copies(gpkg_paths, original, opts, meta) + -- A different version of a package that's already installed is a + -- REPLACEMENT (upgrade or downgrade). Only -O permits it; without + -- -O it's refused here, before the prompt. + local installed = installed_entries(opts) + local entries, replacing, refused = {}, {}, false + for _, p in ipairs(gpkg_paths) do + local name, repo, ver = manifest_of(p) + local m = meta[p] or {} + local e = { repo = repo, name = name, ver = ver } + for _, i in ipairs(installed) do + if i.name == name and i.repo == repo and i.ver ~= ver then + if overwrite or m.may_replace then + replacing[p] = i + e.ver = i.ver .. " -> " .. ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, name, i.ver) + refused = true + end + end + end + if m.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + + check_plan(opts, gpkg_paths, {}, finish) + + local keep = next(replacing) and keep_old() or 0 + + if not confirm(entries) then + finish(0) + end + + local ctx = begin_staged(opts) + ctx.overwrite = overwrite and 1 or 0 + local staged = 0 + + -- Replacements: back up the installed version (from LIVE, written + -- under a .part name and only promoted after a successful commit), + -- then remove it from the stage so the new version installs into + -- a clean slot in the same transaction. + local live = live_context(opts) + local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup" + for _, old in pairs(replacing) do + if keep > 0 then + local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name) + local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver) + local part = final .. ".part" + if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then + log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + table.insert(pending_backups, { part = part, final = final, dir = dir, old = old }) + end + if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + end + + for _, gpkg_path in ipairs(gpkg_paths) do + local status = install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + local abs_path = original[gpkg_path] + + if status == 0 then + staged = staged + 1 + if (meta[gpkg_path] or {}).auto + and istore.gl_set_pkg_auto(ctx, manifest_repo, pkg_name, true) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as a dependency.", + manifest_repo, pkg_name) + abort_and_die(ctx) + end + log.lg_printf(3, "%s::%s-%s: staged from %s.", + manifest_repo, pkg_name, version_str, abs_path) + elseif status == 1 then + log.lg_printf(2, "%s::%s: Failed to open package archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 2 then + log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 3 then + log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 4 then + log.lg_printf(2, "%s::%s: Failed to add entry to index.", + manifest_repo, pkg_name) + abort_and_die(ctx) + elseif status == 6 then + -- GL_INSTALL_SKIPPED: not a failure, keep going + elseif status == 7 then + -- GL_INSTALL_ERR_SCOPE: the library refused this + -- package for this scope (base-repo package under + -- user scope). The library already logged the + -- specific reason; don't second-guess it here. + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + -- Everything was skipped (-S, already up to date): the stage is + -- identical to live, so don't commit it. A commit isn't free — it + -- swaps the trees and re-links the whole store, re-printing every + -- standing link conflict for packages this command never touched. + if staged == 0 then + txn.gl_abort_transaction(ctx) + log.lg_printf(3, "Nothing to do.") + finish(0) + end + + commit_or_die(ctx) + + -- Committed: promote the backups, give each a sidecar (so it's an + -- installable, verifiable package), and keep only the newest KEEP_OLD. + for _, b in ipairs(pending_backups) do + if os.rename(b.part, b.final) then + local hex = sha256_file(b.final) + local sf = hex and io.open(b.final .. ".sha256", "w") + if sf then + sf:write("sha256:" .. hex .. "\n") + sf:close() + end + istore.gl_prune_backups(b.dir, keep) + log.lg_printf(0, "Backed up %s::%s %s to %s", + b.old.repo, b.old.name, b.old.ver, b.final) + else + log.lg_printf(1, "Could not keep the backup of %s::%s %s.", + b.old.repo, b.old.name, b.old.ver) + end + end + pending_backups = {} + + for _, p in ipairs(gpkg_paths) do + if meta[p] and meta[p].cache then os.remove(meta[p].cache) end + end + + report_done(ctx, finish) +end + +-- --------------------------------------------------------------------- +-- -f / -u: packages from the repositories (REPO_DESIGN.txt section 6) +-- --------------------------------------------------------------------- + +-- -1, 0 or 1 as version a is below, equal to or above b ("MAJ.MIN.PAT"). +local function vercmp(a, b) + local x = { a:match("^(%d+)%.(%d+)%.(%d+)") } + local y = { b:match("^(%d+)%.(%d+)%.(%d+)") } + for k = 1, 3 do + local m, n = tonumber(x[k]) or 0, tonumber(y[k]) or 0 + if m ~= n then return m < n and -1 or 1 end + end + return 0 +end + +-- A package's relations as an index lists them: "NAME VER\n" lines. +local function relation_lines(list, name_field, ver_field) + local out = {} + local k = 0 + while list ~= nil and list[k][name_field] ~= nil do + local v = list[k][ver_field] + table.insert(out, string.format("%s %d.%d.%d\n", + ffi.string(list[k][name_field]), v.maj, v.min, v.pat)) + k = k + 1 + end + return table.concat(out) +end + +-- Whether the manifest of `path` (read by the library) says exactly what +-- its index entry `e` of repository `repo` says: NAME, VER, PKG_REPO, +-- DEPS and CONFS. A package is from `repo` because that repo's signed +-- index lists it AND it says so, never because it says so. +local function matches_index(path, repo, e) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return false + end + local ok = ffi.string(m.pkg_name) == e.name + and ffi.string(m.pkg_repo) == repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == e.ver + and relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == e.deps + and relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == e.confs + istore.gl_free_pkg(m) + return ok +end + +-- The accepted index of every configured repository, freshly refreshed +-- (decision 10d: any failure refuses the operation). In priority order: +-- { name, url, pkgs = { { name, ver, file, sha256, size, deps, confs }... } }. +-- User scope never fetches from base (the library refuses it there). +local function load_indexes(opts) + local remotes = configured_remotes(keyring(opts.sysroot)) + if not M.refresh(opts) then + finish(1) + end + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) + end + local out = {} + for _, r in ipairs(remotes) do + if opts.scope ~= ffi.C.GL_SCOPE_USR or r.name ~= "base" then + local path = ffi.string(dir) .. "/" .. r.name .. ".idx" + local text = read_capped(path, MAX_INDEX) + local idx = ffi.new("gl_index_t") + if not text or istore.gl_index_parse(text, #text, r.name, idx) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + local pkgs = {} + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + table.insert(pkgs, { + name = ffi.string(p.name), ver = ffi.string(p.ver), + file = ffi.string(p.file), sha256 = ffi.string(p.sha256), + size = tonumber(p.size), deps = ffi.string(p.deps), + confs = ffi.string(p.confs), + }) + end + istore.gl_index_free(idx) + table.insert(out, { name = r.name, url = r.url, pkgs = pkgs }) + end + end + return out +end + +-- The highest version of `name` that repository `r` serves, or nil. +local function newest_in(r, name) + local best + for _, e in ipairs(r.pkgs) do + if e.name == name and (not best or vercmp(e.ver, best.ver) > 0) then + best = e + end + end + return best +end + +-- Which repository `name` comes from: the first, by priority, that +-- serves it, at its highest version. repo, entry, or nil. +local function pick(indexes, name) + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then return r, e end + end +end + +-- Add the missing dependencies of everything in `plan` (and theirs), +-- ROADMAP 2.3's closure. A dependency already met (in this scope, or +-- for a user, by the system) is left alone; one installed at too old a +-- version is upgraded from its own repository, keeping its auto or +-- explicit mark; one not installed comes from pick(), recorded auto. +-- Whatever can't be met is left for gl_check_plan to report. +local function close_deps(plan, indexes, opts) + local planned = {} + for _, it in ipairs(plan) do planned[it.name] = it end + local installed = installed_entries(opts) + local system = {} + if opts.scope == ffi.C.GL_SCOPE_USR then + system = read_index_file("/glacier/sys/index/current") + end + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + + local k = 1 + while k <= #plan do + for dname, dver in plan[k].entry.deps:gmatch("(%S+) (%S+)\n") do + local met, old = planned[dname] ~= nil, nil + for _, i in ipairs(installed) do + if i.name == dname then + if vercmp(i.ver, dver) >= 0 then met = true end + old = old or i + end + end + for _, i in ipairs(system) do + if i.name == dname and vercmp(i.ver, dver) >= 0 then met = true end + end + if not met then + local r, e + if old then + r = by_repo[old.repo] + e = r and newest_in(r, dname) + else + r, e = pick(indexes, dname) + end + if e and vercmp(e.ver, dver) >= 0 then + local it = { repo = r, entry = e, name = dname, dep = true, + auto = not old or old.auto, may_replace = old ~= nil } + table.insert(plan, it) + planned[dname] = it + end + end + end + k = k + 1 + end +end + +-- Download `e` (an index entry of repository `r`) into the scope's +-- cache, hashing it on the way, unless a cached copy already matches. +-- Never more than the index's SIZE is read. The path, or nil plus +-- true if something was fetched but is not what the index lists. +local function download(ctx, r, e, file_mode) + local dir = ffi.new("char[4096]") + if txn.gl_scope_cache_dir(ctx, r.name, dir) ~= 0 then + finish(1) -- the library said why + end + local want = e.sha256:match("^sha256:(%x+)$") + local dest = ffi.string(dir) .. "/" .. e.file + if sha256_file(dest) == want then + return dest + end + + local src + local path = r.url:match("^file://(/.*)$") + if path then + src = io.open(path .. "/" .. e.file, "rb") + elseif r.url:match("^https://") then + src = io.popen("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 -- " .. + shell_quote(r.url .. "/" .. e.file) .. " 2>/dev/null", "r") + end + if not src then return nil end + local tmp = string.format("%s/.%s.%d", ffi.string(dir), e.file, + ffi.C.gpkg_common_getpid()) + local dst = io.open(tmp, "wb") + if not dst then + src:close() + return nil + end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + local n = 0 + while n <= e.size do + local chunk = src:read(math.min(65536, e.size + 1 - n)) + if not chunk then break end + n = n + #chunk + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + if n ~= e.size or ffi.string(hex) ~= want then + os.remove(tmp) + return nil, n > 0 + end + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 or not os.rename(tmp, dest) then + os.remove(tmp) + return nil + end + return dest +end + +-- Fetch, verify and install everything in `plan` (see close_deps). +local function install_plan(plan, opts) + local ctx = live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local copies, original, meta = {}, {}, {} + local refused = false + for _, it in ipairs(plan) do + local e = it.entry + local id = string.format("%s::%s %s", it.repo.name, e.name, e.ver) + local cached, wrong = download(ctx, it.repo, e, file_mode) + local copy = cached and verify_and_copy(cached, e.sha256 .. "\n") + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + refused = true + elseif not copy or not matches_index(copy, it.repo.name, e) then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + refused = true + else + table.insert(copies, copy) + original[copy] = it.repo.url .. "/" .. e.file + meta[copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, cache = cached } + end + end + if refused then + finish(1) + end + install_copies(copies, original, opts, meta) +end + +--- -f NAME...: install packages by name from the repositories, with +--- whatever dependencies they are missing. Like -l otherwise: an +--- installed other version of a named package needs -O. +function M.fetch(names, opts) + local indexes = load_indexes(opts) + local plan, refused, seen = {}, false, {} + for _, name in ipairs(names) do + local r, e = pick(indexes, name) + if seen[name] then + -- named twice: once is enough + elseif e then + seen[name] = true + table.insert(plan, { repo = r, entry = e, name = name }) + else + log.lg_printf(2, "%s is not in any repository.", name) + refused = true + end + end + if refused then + finish(1) + end + close_deps(plan, indexes, opts) + install_plan(plan, opts) +end + +--- -u [NAME...]: replace every installed package (or those named) whose +--- repository's index has a higher version, as -lO does (backups, +--- KEEP_OLD). Packages from repositories not configured are left alone. +function M.upgrade(names, opts) + local indexes = load_indexes(opts) + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local installed = installed_entries(opts) + + local wanted, refused = nil, false + if #names > 0 then + wanted = {} + for _, name in ipairs(names) do + local found = false + for _, i in ipairs(installed) do + if i.name == name then + found = true + if not by_repo[i.repo] then + log.lg_printf(2, "%s::%s is not in any configured repository.", + i.repo, i.name) + refused = true + end + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + refused = true + end + wanted[name] = true + end + end + if refused then + finish(1) + end + + local plan = {} + for _, i in ipairs(installed) do + local r = by_repo[i.repo] + local e = r and (not wanted or wanted[i.name]) and newest_in(r, i.name) + if e and vercmp(e.ver, i.ver) > 0 then + table.insert(plan, { repo = r, entry = e, name = i.name, + auto = i.auto, may_replace = true }) + end + end + if #plan == 0 then + log.lg_printf(3, "Nothing to do.") + finish(0) + end + close_deps(plan, indexes, opts) + install_plan(plan, opts) +end + +function M.install(gpkg_paths, opts) + -- From here on, the paths are the VERIFIED PRIVATE COPIES; the + -- caller's paths are only used for messages. + local copies, original = verify_all(gpkg_paths, opts) + install_copies(copies, original, opts, {}) +end + +--- Remove every named package as ONE atomic staged transaction. +--- Does not return on failure — exits. +function M.remove(pkg_names, opts) + -- Names, not files: resolve them against what's actually installed + -- (the old summary read them as .gpkg paths and printed + -- "unknown::pkg 0.0.0"). Anything not installed fails here, before + -- the prompt, not after the user has already said yes. + local installed = installed_entries(opts) + local entries, missing = {}, false + for _, name in ipairs(pkg_names) do + local found = false + for _, e in ipairs(installed) do + if e.name == name then + table.insert(entries, e) + found = true + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + missing = true + end + end + if missing then + os.exit(1) + end + + -- A name installed from more than one repo isn't resolved until + -- after the prompt, so only unambiguous names are checked here. + local count, removes = {}, {} + for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end + for _, e in ipairs(entries) do + if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end + end + check_plan(opts, {}, removes, os.exit) + + if not confirm(entries) then + os.exit(0) + end + + local ctx = begin_staged(opts) + + for _, pkg_name in ipairs(pkg_names) do + local repo = M.resolve_repo(ctx, pkg_name) + if not repo then + log.lg_printf(2, "Failed to resolve group for %s.", pkg_name) + abort_and_die(ctx) + end + + local status = istore.gl_remove_pkg(ctx, pkg_name, repo) + + if status == ffi.C.GL_REMOVE_OK then + log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name) + elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then + log.lg_printf(2, "%s::%s not found.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then + log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_INDEX then + log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name) + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + commit_or_die(ctx) + + report_done(ctx, os.exit) +end + +return M diff --git a/lib/gpkg_common.lua.old6 b/lib/gpkg_common.lua.old6 new file mode 100644 index 0000000..7522fb1 --- /dev/null +++ b/lib/gpkg_common.lua.old6 @@ -0,0 +1,1728 @@ +-- lib/gpkg_common.lua +-- +-- Shared machinery between gpkg (per-user scope only) and syspkg +-- (system scope only). See SECURITY_DESIGN.txt section 7. +-- +-- The interface here is deliberately COARSE-GRAINED: M.install() and +-- M.remove() own the entire staged-transaction lifecycle +-- (gl_init_stage_context -> loop -> commit/abort), rather than +-- exporting fine-grained pieces that each caller then has to sequence +-- itself. That's what keeps the sequencing — and, once Checkpoint 2's +-- verification lands, the hash refusal matrix — in exactly ONE place +-- instead of duplicated across two binaries and drifting apart. +-- +-- What callers keep for themselves: +-- * argument parsing +-- * deciding WHICH scope they're allowed to request (gpkg never +-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag +-- for it", the capability isn't in its code path at all) +-- * their own privilege model (only syspkg runs elevated) +-- +-- Callers pass a `env` table on construction with the FFI handles and +-- shared state, so this module doesn't ffi.load() anything itself and +-- doesn't care where the .so's came from. + +local ffi = require("ffi") +local bit = require("bit") +local glacier_cdef = require("lib/glacier_cdef") +local build = require("lib/gpkg_build") + +local M = {} + +-- Module-level handles, set by M.init(). Kept here rather than passed +-- through every function because every function needs them. +local log, istore, txn, verify +local argv +local so_dir -- lib/glacier: the .so's and gsandbox +local init_build -- set at the end of this file +local isVerbose = false +local skipInstalled = false +local overwrite = false + +local txn_name = glacier_cdef.txn_name + +--- Initialise the module. Must be called before anything else. +-- env.log / env.istore / env.txn : ffi.load() handles +-- env.verify : libglacier_verify.so handle (installs) +-- env.argv : argv table (for usage messages) +-- env.so_dir : lib/glacier, where gsandbox is +function M.init(env) + log = env.log + istore = env.istore + txn = env.txn + verify = env.verify + argv = env.argv + so_dir = env.so_dir + init_build() +end + +--- Toggle flags the CLIs parse but this module acts on. +function M.set_verbose(v) isVerbose = v end +function M.set_skip_installed(v) skipInstalled = v end +function M.set_overwrite(v) overwrite = v end + +-- --------------------------------------------------------------------- +-- Manifest reading +-- --------------------------------------------------------------------- + +-- Quote a string for /bin/sh: wrap in single quotes, and turn each +-- embedded ' into '\''. Package paths come from the command line and +-- manifest entry names come from the archive, and syspkg runs all of +-- this as root — an unescaped ' in either is command execution. +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +--- name, repo and version ("MAJ.MIN.PAT", as the store names versions) +--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same +--- reader gl_install_pkg uses, so what is shown, compared and installed +--- can never disagree. nil if the manifest can't be read. +local function manifest_of(path) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return nil + end + local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo) + local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) + istore.gl_free_pkg(m) + return name, repo, ver +end + +-- --------------------------------------------------------------------- +-- Integrity verification (SECURITY_DESIGN.txt sections 3-4) +-- --------------------------------------------------------------------- + +-- Private working dir for verified copies, removed by finish(). +local private_dir = nil + +-- Backups written during this transaction but not yet committed +-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that +-- were never promoted, so an aborted upgrade leaves no stray backup. +local pending_backups = {} + +--- Exit, removing the private copies (and uncommitted backups) first. +--- Every exit on the install path goes through here. +local function finish(code) + for _, b in ipairs(pending_backups) do + os.remove(b.part) + end + pending_backups = {} + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +--- sha256 of a file as "", or nil. +local function sha256_file(path) + local f = io.open(path, "rb") + if not f then return nil end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = f:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + end + f:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +--- Copy `path` into the private dir, hashing it in the same pass, and +--- check the hash against `path`.sha256. Returns the private copy's path, +--- or nil plus a reason. +--- +--- Everything after this (summary, manifest read, gl_install_pkg) reads +--- ONLY the copy. Verifying the original and then installing it would +--- leave a gap where it could be swapped — and under syspkg that's root +--- reading a file whose directory another user may control. The copy +--- lives in a mktemp -d dir only the invoking user (root, for syspkg) +--- can write. +--- +--- Refusal matrix (section 4). A missing sidecar is treated exactly like +--- a mismatch: +--- repo == base -> always refuse, no exceptions +--- scope == SYS -> always refuse, any repo +--- scope == USR, repo != base -> refuse by default; the ONLY place +--- a future bypass flag may apply +--- No bypass exists, so today every row refuses and the repo (which we +--- couldn't trust before verifying anyway) never needs consulting. A +--- bypass, if ever added, must check scope and the VERIFIED manifest's +--- repo here, before anything else reads the file. +--- +--- A package fetched from a repository passes `vouched`, the "sha256:" +--- its signed index gives, in place of a sidecar. +local function verify_and_copy(path, vouched) + local sidecar = path .. ".sha256" + local sidecar_text = vouched + if not sidecar_text then + local sf = io.open(sidecar, "r") + if not sf then + return nil, "no sidecar " .. sidecar + end + sidecar_text = sf:read("*a") or "" + sf:close() + end + local expected = sidecar_text:match("^sha256:(%x+)%s*$") + if not expected or #expected ~= 64 then + return nil, "malformed sidecar " .. sidecar + end + expected = expected:lower() + + if not private_dir then + local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + return nil, "cannot create a private working directory" + end + end + + local src = io.open(path, "rb") + if not src then + return nil, "cannot open " .. path + end + + -- Unique per argument, so two packages with the same basename + -- (from different directories) can't collide. + local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0, + path:match("([^/]+)$")) + M._ncopies = (M._ncopies or 0) + 1 + local dst = io.open(copy_path, "wb") + if not dst then + src:close() + return nil, "cannot write " .. copy_path + end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = src:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + + if ffi.string(hex) ~= expected then + return nil, "hash mismatch (sidecar says " .. expected .. + ", file is " .. ffi.string(hex) .. ")" + end + + return copy_path, nil, sidecar_text +end + +-- --------------------------------------------------------------------- +-- Signatures (REPO_DESIGN.txt section 7) +-- --------------------------------------------------------------------- + +-- A keyring: repos.conf and the keys it lists, under `sysroot` (nil or +-- "/" = the running system). Read only by syspkg (gpkg reads the +-- system's until user repos). The signature on a local base package +-- (-l) is checked with the HOST's, even under -R (the build host's +-- trust, as KEEP_OLD). Repository operations (-y/-f/-u) use the +-- keyring of the system they act on: under -R, TARGET's own, since the +-- indexes they accept are TARGET's and TARGET checks them from then on. +local function keyring(sysroot) + local root = (sysroot or "/"):gsub("/+$", "") + return { root = root, conf = root .. "/etc/glacier/repos.conf", + keys = root .. "/etc/glacier/keys" } +end +local HOST_KEYRING = keyring(nil) + +ffi.cdef[[ +char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath"); +]] + +local function realpath(path) + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_common_realpath(path, buf) == nil then return nil end + return ffi.string(buf) +end + +-- nil if `path`, every ancestor of it, and every ancestor of its real +-- path are root-owned and not group/world-writable (as syspkg's own +-- lib/: a key a non-root user could swap is no key). Else the path at +-- fault, plus true if it is missing (or can't be resolved). +local function untrusted(path) + local function chain(p) + while true do + local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null") + local line = f and f:read("*l") + if f then f:close() end + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then return p, true end + if tonumber(uid) ~= 0 + or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + return p + end + if p == "/" then return nil end + p = p:match("^(.*)/[^/]*$") + if p == "" then p = "/" end + end + end + local bad, missing = chain(path) + if bad then return bad, missing end + local real = realpath(path) + if not real then return path, true end + return chain(real) +end + +-- Stop the run unless `path`, part of keyring `kr`, is trusted (as +-- untrusted() says) and, in another root, resolves inside it: TARGET's +-- etc/glacier/repos.conf -> /etc/glacier/repos.conf would read the +-- host's file as TARGET's. +local function require_trusted(path, kr) + local bad, missing = untrusted(path) + if bad and missing then + log.lg_printf(2, "Cannot read %s.", bad) + finish(1) + elseif bad then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + path, bad) + finish(1) + end + if kr.root ~= "" then + local real, root = realpath(path), realpath(kr.root) + if not (real and root and real:sub(1, #root + 1) == root .. "/") then + log.lg_printf(2, "Refusing %s: it resolves outside %s.", path, kr.root) + finish(1) + end + end +end + +-- Whether keyring `kr`'s repos.conf exists, having checked it is +-- trusted (else the run stops: the admin's configuration is at fault, +-- not a package). +local function repos_conf_present(kr) + local f, _, code = io.open(kr.conf, "r") + if f then f:close() end + if not f and code == 2 then return false end + require_trusted(kr.conf, kr) + return true +end + +-- The public keys keyring `kr` trusts for `repo`, read once per run: +-- { { name, pub }... }. A missing repos.conf trusts nothing. A +-- repos.conf or listed key that is untrusted or can't be read stops the +-- run: that is the admin's configuration, not the package, at fault. +local trusted_keys_cache = {} +local function trusted_keys(repo, kr) + local cache_key = kr.conf .. "\n" .. repo + if trusted_keys_cache[cache_key] then return trusted_keys_cache[cache_key] end + local keys = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[4096]") + local st = tonumber(istore.gl_conf_repo_keys(kr.conf, repo, buf, 4096)) + if st == 1 or st == 3 or st == 4 or st == 5 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name in ffi.string(buf):gmatch("([^\n]+)\n") do + local path = kr.keys .. "/" .. name .. ".pub" + local pub = ffi.new("gl_sign_pubkey_t") + require_trusted(path, kr) + if verify.gl_sign_read_pubkey(path, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + table.insert(keys, { name = name, pub = pub }) + end + end + trusted_keys_cache[cache_key] = keys + return keys +end + +-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very +-- bytes the copy was checked against) by a key trusted for `repo`. The +-- key is picked by the signature's keynum, never by trying each one. +local function signed_for(path, sidecar_text, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then + return false + end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, HOST_KEYRING)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0 + end + end + return false +end + +--- Verify every package up front, before the summary is even shown. +--- Returns the private copies, plus a copy -> original map for messages. +--- +--- In system scope, a package whose manifest says base must also have a +--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the +--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg +--- does). +local function verify_all(gpkg_paths, opts) + local copies, original = {}, {} + local refused = false + + for _, p in ipairs(gpkg_paths) do + local copy, why, sidecar_text = verify_and_copy(p) + if copy and not manifest_of(copy) then + log.lg_printf(2, "Cannot read the manifest of %s.", p) + refused = true + copy = nil + end + if copy and opts.scope == ffi.C.GL_SCOPE_SYS then + local name, repo = manifest_of(copy) + if repo == "base" and not signed_for(p, sidecar_text, repo) then + log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.", + repo, name, repo) + refused = true + copy = nil + end + end + if copy then + table.insert(copies, copy) + original[copy] = p + elseif why then + log.lg_printf(2, "Refusing %s: %s.", p, why) + refused = true + end + end + + if refused then + finish(1) + end + return copies, original +end + +-- --------------------------------------------------------------------- +-- Confirmation summary +-- --------------------------------------------------------------------- + +--- Print the summary for `entries` ({repo, name, ver} each) and ask. +local function confirm(entries) + log.lg_printf(0, "SUMMARY:") + print("==============================") + print("") + for _, e in ipairs(entries) do + print(string.format(" * %s::%s\t\t%-16s", + e.repo or "unknown", e.name, e.ver or "unknown")) + end + print("") + io.write("Proceed? (y/N): ") + io.stdout:flush() + + local response = io.read("*l") + if not response then + return false + end + response = response:lower() + return response == "y" or response == "yes" +end + +--- Installed packages, from the live index for this scope: a list of +--- {repo, name, ver, auto}. The index's `current` file holds one +--- `repo::name::version::auto|explicit` line per package (index files +--- written before 2026-10-05 stop at the version). +--- A live context for opts' scope (and install root: syspkg -R only). +local function live_context(opts) + local ctx = ffi.new("gl_context_t") + if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then + finish(1) -- the library said why + end + return ctx +end + +-- The entries of an index `current` file ({} if there is none). +local function read_index_file(path) + local f = io.open(path, "r") + local out = {} + if not f then return out end + for line in f:lines() do + local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$") + if repo then + local ver, kind = rest:match("^(.-)::(%a+)$") + table.insert(out, { repo = repo, name = name, ver = ver or rest, + auto = kind == "auto" }) + end + end + f:close() + return out +end + +local function installed_entries(opts) + local ctx = live_context(opts) + return read_index_file(ffi.string(ctx.index_path) .. "/current") +end + +-- --------------------------------------------------------------------- +-- Repo resolution +-- --------------------------------------------------------------------- + +function M.resolve_repo(ctx, pkg_name) + local list = istore.gl_find_pkg_repos(ctx, pkg_name) + + if list.count == 0 then + log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name) + istore.gl_free_repo_list(list) + return nil + end + + if list.count == 1 then + local repo = ffi.string(list.repos[0]) + istore.gl_free_repo_list(list) + return repo + end + + log.lg_printf(1, "Multiple instances of %s found:", pkg_name) + for i = 0, tonumber(list.count) - 1 do + print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name)) + end + print("") + io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ") + io.stdout:flush() + local input = io.read("*l") + local choice = tonumber(input) + + if not choice or choice < 1 or choice > tonumber(list.count) then + log.lg_printf(2, "Invalid selection.") + istore.gl_free_repo_list(list) + return nil + end + + local repo = ffi.string(list.repos[choice - 1]) + istore.gl_free_repo_list(list) + return repo +end + +-- --------------------------------------------------------------------- +-- Single-package install (with reinstall-if-present handling) +-- --------------------------------------------------------------------- + +local function install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + if not pkg_name then + log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path) + finish(1) + end + + if isVerbose then + log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s", + pkg_name, version_str, manifest_repo, gpkg_path) + end + + local status = istore.gl_install_pkg(ctx, gpkg_path) + + if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then + if skipInstalled then + log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str) + return tonumber(ffi.C.GL_INSTALL_SKIPPED) + end + + log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str) + + local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo) + + if rm_status ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).", + manifest_repo, pkg_name, tostring(tonumber(rm_status))) + return tonumber(rm_status) + end + + status = istore.gl_install_pkg(ctx, gpkg_path) + if status == ffi.C.GL_INSTALL_OK then + -- M.install logs the one "staged from" line. + return 0 + else + log.lg_printf(2, "Reinstall of %s-%s failed (error %s).", + pkg_name, version_str, tostring(tonumber(status))) + return tonumber(status) + end + + elseif status == ffi.C.GL_INSTALL_OK then + return 0 + end + + return tonumber(status) +end + +-- --------------------------------------------------------------------- +-- Transaction lifecycle +-- --------------------------------------------------------------------- + +--- Open a staged transaction for the given scope. Exits on failure with +--- a scope-appropriate message. `scope_label` is used only in the +--- lock-contention message ("for UID 1000" vs "for the system scope"). +local function begin_staged(opts) + local scope_label = opts.scope_label + local ctx = ffi.new("gl_context_t") + local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") + + if txn_st ~= ffi.C.GL_TXN_OK then + if txn_st == ffi.C.GL_TXN_ERR_LOCK then + log.lg_printf(2, + "Another glacier transaction is already in progress %s.", + scope_label) + else + log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st)) + end + finish(1) + end + + ctx.strict = opts.strict and 1 or 0 + return ctx +end + +--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt. +--- The library prints each problem; this exits if there were any. The +--- commit checks again (gl_check_txn), which is what covers a removal +--- whose repo is only chosen after the prompt. +local function check_plan(opts, adds, removes, exit) + local live = live_context(opts) + live.strict = opts.strict and 1 or 0 + live.overwrite = overwrite and 1 or 0 + local a = ffi.new("const char *[?]", #adds + 1) + for i, p in ipairs(adds) do a[i - 1] = p end + local r = ffi.new("const char *[?]", #removes + 1) + for i, id in ipairs(removes) do r[i - 1] = id end + local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes)) + if problems < 0 then + log.lg_printf(2, "Cannot read the package store to check dependencies.") + end + if problems ~= 0 then exit(1) end +end + +--- Commit, or abort-and-exit on failure. +local function commit_or_die(ctx) + local commit_st = txn.gl_commit_transaction(ctx) + if commit_st == ffi.C.GL_TXN_ERR_DEPS then + -- The library already said what's wrong, one line each. + txn.gl_abort_transaction(ctx) + finish(1) + elseif commit_st ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st)) + txn.gl_abort_transaction(ctx) + finish(1) + end +end + +--- The last line of a committed transaction. If the link pass refused +--- any path (each refusal is already printed above), the transaction is +--- committed but did not fully succeed: an error, and exit status 1. +local function report_done(ctx, exit) + local n = tonumber(ctx.link_refusals) + if n > 0 then + log.lg_printf(2, "%s %s not linked.", tostring(n), + n == 1 and "path was" or "paths were") + exit(1) + end + log.lg_printf(3, "Completed with no errors.") + exit(0) +end + +--- Abort the transaction and exit non-zero. Every failure path inside a +--- staged loop goes through here so live state is never left partially +--- mutated. +local function abort_and_die(ctx) + txn.gl_abort_transaction(ctx) + finish(1) +end + +-- --------------------------------------------------------------------- +-- Repository indexes (REPO_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +ffi.cdef[[ +int gpkg_common_getpid(void) asm("getpid"); +int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod"); +int gpkg_common_close(int fd) asm("close"); +]] + +-- Largest index accepted: what gl_sign_verify will check. +local MAX_INDEX = 64 * 1024 * 1024 + +-- A whole file, or nil if it is missing, unreadable or over `max`. +local function read_capped(path, max) + local f = io.open(path, "rb") + if not f then return nil end + local data = f:read(max + 1) or "" + f:close() + if #data > max then return nil end + return data +end + +-- Fetch URL/NAME into `dest`. https goes through curl, refusing any +-- other protocol, redirects included; file:// is a plain copy of an +-- absolute path. True on success. +local function fetch(url, name, dest) + local path = url:match("^file://(/.*)$") + if path then + local data = read_capped(path .. "/" .. name, MAX_INDEX) + local f = data and io.open(dest, "wb") + if not f then return false end + local ok = f:write(data) + f:close() + return ok ~= nil + end + if not url:match("^https://") then return false end + local ok = os.execute("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 --max-filesize " .. MAX_INDEX .. + " -o " .. shell_quote(dest) .. " -- " .. + shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1") + return ok == true or ok == 0 +end + +-- Whether `text` is signed by `sig_path`, with a key keyring `kr` +-- trusts for `repo` (picked by keynum, as signed_for). +local function index_signed(text, sig_path, repo, kr) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, kr)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", text), #text) == 0 + end + end + return false +end + +-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the +-- gl_index_parse status. +local function parse_index(text, repo) + local idx = ffi.new("gl_index_t") + local st = tonumber(istore.gl_index_parse(text, #text, repo, idx)) + if st ~= 0 then return nil, st end + local r = { serial = idx.serial, valid_until = idx.valid_until, + npkgs = tonumber(idx.npkgs) } + istore.gl_index_free(idx) + return r +end + +-- Refresh one repository's index into `dir` (/repos): fetch, +-- verify, parse, refuse a rollback or an expired index, then rename +-- over the accepted copy, checking signatures with keyring `kr`. Any +-- failure keeps the accepted copy, prints one line and returns false. +local function refresh_one(repo, url, dir, file_mode, kr) + local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid()) + local tmp_sig = tmp .. ".sig" + local function fail(fmt, ...) + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(2, fmt, ...) + return false + end + + local text + if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then + text = read_capped(tmp, MAX_INDEX) + end + if not text then + return fail("Cannot fetch the index for %s.", repo) + end + -- The signature is checked over the very bytes parsed below. + if not index_signed(text, tmp_sig, repo, kr) then + return fail("Index for %s is not signed by a key trusted for %s.", repo, repo) + end + local new, st = parse_index(text, repo) + if st == 2 then + return fail("Index fetched for %s is the index of another repository.", repo) + elseif not new then + return fail("Malformed index for %s.", repo) + end + + local stored = dir .. "/" .. repo .. ".idx" + local old_text = read_capped(stored, MAX_INDEX) + local unchanged = false + if old_text then + local old = parse_index(old_text, repo) + if not old then + return fail("Malformed %s.", stored) + end + if new.serial < old.serial then + return fail("Index for %s is older than the one already accepted.", repo) + elseif new.serial == old.serial then + if text ~= old_text then + return fail("Index for %s has the serial of the one already accepted, but other contents.", repo) + end + unchanged = true + end + elseif io.open(stored, "rb") then + return fail("Cannot read %s.", stored) + end + if new.valid_until <= os.time() then + return fail("Index for %s has expired.", repo) + end + + local serial = string.format("%d", tonumber(new.serial)) + if unchanged then + os.remove(tmp) + os.remove(tmp_sig) + if isVerbose then + log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial) + end + return true + end + -- Never written in place (bug 25): renamed over the old copy. + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 + or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0 + or not os.rename(tmp_sig, stored .. ".sig") + or not os.rename(tmp, stored) then + return fail("Cannot write %s.", stored) + end + if isVerbose then + log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial, + tostring(new.npkgs), new.npkgs == 1 and "package" or "packages") + end + return true +end + +--- Refresh the index of every repository repos.conf gives a url +--- (REPO_DESIGN.txt section 5), into the scope's /repos, holding +--- the scope's lock. Every repository is tried; true if all succeeded. +--- Exits if there is nothing to refresh or the setup is at fault. +-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install +-- Every entry with a url in keyring `kr`'s repos.conf, in priority +-- order: { name, url }. Exits if there is none, or repos.conf is +-- malformed. +local function configured_remotes(kr) + local remotes = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[65536]") + if tonumber(istore.gl_conf_repos(kr.conf, buf, 65536)) ~= 0 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then + table.insert(remotes, { name = name, url = url }) + end + end + end + if #remotes == 0 then + log.lg_printf(2, "No remote repositories are configured.") + finish(1) + end + return remotes +end + +function M.refresh(opts) + local kr = keyring(opts.sysroot) + local remotes = configured_remotes(kr) + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) -- the library said why + end + if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Another glacier transaction is already in progress %s.", + opts.scope_label) + finish(1) + end + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + log.lg_printf(0, "Syncing all repositories...") + local all = true + for _, r in ipairs(remotes) do + all = refresh_one(r.name, r.url, ffi.string(dir), file_mode, kr) and all + end + ffi.C.gpkg_common_close(ctx.lock_fd) + if all then + log.lg_printf(3, "All repositories synced successfully.") + end + return all +end + +-- --------------------------------------------------------------------- +-- Public: whole-batch install / remove +-- --------------------------------------------------------------------- + +--- Install every package in gpkg_paths as ONE atomic staged transaction. +--- Any failure aborts the whole batch, leaving live state untouched. +--- Does not return on failure — exits. +-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS +-- opts.uid : uid for USR scope (ignored for SYS) +-- opts.scope_label : human string for the lock-contention message +-- opts.sysroot : install root (syspkg -R; nil = the running system) +-- opts.strict : refuse, before committing, anything the link pass +-- would refuse (syspkg --strict, implied by -R) +--- KEEP_OLD from glacier.conf: how many backups of replaced versions to +--- keep per package. There is no default — it ships as 1 in +--- glacier.conf, and an operation that would replace a version refuses +--- to run if it's missing or not a whole number. +local function keep_old() + local n = ffi.new("int[1]") + local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n)) + if st == 1 then + log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.") + elseif st == 2 then + log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.") + elseif st == 3 or (st == 0 and n[0] < 0) then + log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.") + end + if st ~= 0 or n[0] < 0 then finish(1) end + return tonumber(n[0]) +end + +-- Install verified private copies as one transaction. original[copy] +-- names each for messages. meta[copy], for packages fetched from a +-- repository (else nil): +-- auto : record it as installed as a dependency +-- may_replace : replace an installed other version without -O +-- (-u, and dependency upgrades) +-- dep : marked as a dependency in the summary +-- cache : the downloaded file, deleted once committed +-- src : built from this recipe repository (.glacier-src) +-- `confirmed`: the plan was already shown and accepted (builds ask +-- before building, so not again here). +local function install_copies(gpkg_paths, original, opts, meta, confirmed) + -- A different version of a package that's already installed is a + -- REPLACEMENT (upgrade or downgrade). Only -O permits it; without + -- -O it's refused here, before the prompt. + local installed = installed_entries(opts) + local entries, replacing, refused = {}, {}, false + for _, p in ipairs(gpkg_paths) do + local name, repo, ver = manifest_of(p) + local m = meta[p] or {} + local e = { repo = repo, name = name, ver = ver } + for _, i in ipairs(installed) do + if i.name == name and i.repo == repo and i.ver ~= ver then + if overwrite or m.may_replace then + replacing[p] = i + e.ver = i.ver .. " -> " .. ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, name, i.ver) + refused = true + end + end + end + if m.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + + check_plan(opts, gpkg_paths, {}, finish) + + local keep = next(replacing) and keep_old() or 0 + + if not confirmed and not confirm(entries) then + finish(0) + end + + local ctx = begin_staged(opts) + ctx.overwrite = overwrite and 1 or 0 + local staged = 0 + + -- Replacements: back up the installed version (from LIVE, written + -- under a .part name and only promoted after a successful commit), + -- then remove it from the stage so the new version installs into + -- a clean slot in the same transaction. + local live = live_context(opts) + local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup" + for _, old in pairs(replacing) do + if keep > 0 then + local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name) + local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver) + local part = final .. ".part" + if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then + log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + table.insert(pending_backups, { part = part, final = final, dir = dir, old = old }) + end + if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + end + + for _, gpkg_path in ipairs(gpkg_paths) do + local status = install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + local abs_path = original[gpkg_path] + + if status == 0 then + staged = staged + 1 + if (meta[gpkg_path] or {}).auto + and istore.gl_set_pkg_auto(ctx, manifest_repo, pkg_name, true) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as a dependency.", + manifest_repo, pkg_name) + abort_and_die(ctx) + end + local src = (meta[gpkg_path] or {}).src + if src and istore.gl_set_pkg_src(ctx, manifest_repo, pkg_name, src) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as built from %s.", + manifest_repo, pkg_name, src) + abort_and_die(ctx) + end + log.lg_printf(3, "%s::%s-%s: staged from %s.", + manifest_repo, pkg_name, version_str, abs_path) + elseif status == 1 then + log.lg_printf(2, "%s::%s: Failed to open package archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 2 then + log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 3 then + log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 4 then + log.lg_printf(2, "%s::%s: Failed to add entry to index.", + manifest_repo, pkg_name) + abort_and_die(ctx) + elseif status == 6 then + -- GL_INSTALL_SKIPPED: not a failure, keep going + elseif status == 7 then + -- GL_INSTALL_ERR_SCOPE: the library refused this + -- package for this scope (base-repo package under + -- user scope). The library already logged the + -- specific reason; don't second-guess it here. + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + -- Everything was skipped (-S, already up to date): the stage is + -- identical to live, so don't commit it. A commit isn't free — it + -- swaps the trees and re-links the whole store, re-printing every + -- standing link conflict for packages this command never touched. + if staged == 0 then + txn.gl_abort_transaction(ctx) + log.lg_printf(3, "Nothing to do.") + finish(0) + end + + commit_or_die(ctx) + + -- Committed: promote the backups, give each a sidecar (so it's an + -- installable, verifiable package), and keep only the newest KEEP_OLD. + for _, b in ipairs(pending_backups) do + if os.rename(b.part, b.final) then + local hex = sha256_file(b.final) + local sf = hex and io.open(b.final .. ".sha256", "w") + if sf then + sf:write("sha256:" .. hex .. "\n") + sf:close() + end + istore.gl_prune_backups(b.dir, keep) + log.lg_printf(0, "Backed up %s::%s %s to %s", + b.old.repo, b.old.name, b.old.ver, b.final) + else + log.lg_printf(1, "Could not keep the backup of %s::%s %s.", + b.old.repo, b.old.name, b.old.ver) + end + end + pending_backups = {} + + for _, p in ipairs(gpkg_paths) do + if meta[p] and meta[p].cache then os.remove(meta[p].cache) end + end + + report_done(ctx, finish) +end + +-- --------------------------------------------------------------------- +-- -f / -u: packages from the repositories (REPO_DESIGN.txt section 6) +-- --------------------------------------------------------------------- + +-- -1, 0 or 1 as version a is below, equal to or above b ("MAJ.MIN.PAT"). +local function vercmp(a, b) + local x = { a:match("^(%d+)%.(%d+)%.(%d+)") } + local y = { b:match("^(%d+)%.(%d+)%.(%d+)") } + for k = 1, 3 do + local m, n = tonumber(x[k]) or 0, tonumber(y[k]) or 0 + if m ~= n then return m < n and -1 or 1 end + end + return 0 +end + +-- A package's relations as an index lists them: "NAME VER\n" lines. +local function relation_lines(list, name_field, ver_field) + local out = {} + local k = 0 + while list ~= nil and list[k][name_field] ~= nil do + local v = list[k][ver_field] + table.insert(out, string.format("%s %d.%d.%d\n", + ffi.string(list[k][name_field]), v.maj, v.min, v.pat)) + k = k + 1 + end + return table.concat(out) +end + +-- Whether the manifest of `path` (read by the library) says exactly what +-- its index entry `e` of repository `repo` says: NAME, VER, PKG_REPO, +-- DEPS and CONFS. A package is from `repo` because that repo's signed +-- index lists it AND it says so, never because it says so. +local function matches_index(path, repo, e) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return false + end + local ok = ffi.string(m.pkg_name) == e.name + and ffi.string(m.pkg_repo) == repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == e.ver + and relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == e.deps + and relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == e.confs + istore.gl_free_pkg(m) + return ok +end + +-- The accepted index of every configured repository, freshly refreshed +-- (decision 10d: any failure refuses the operation). In priority order: +-- { name, url, pkgs = { { name, ver, file, sha256, size, deps, confs }... } }. +-- User scope never fetches from base (the library refuses it there). +local function load_indexes(opts) + local remotes = configured_remotes(keyring(opts.sysroot)) + if not M.refresh(opts) then + finish(1) + end + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) + end + local out = {} + for _, r in ipairs(remotes) do + if opts.scope ~= ffi.C.GL_SCOPE_USR or (r.name ~= "base" and r.name ~= "base-src") then + local path = ffi.string(dir) .. "/" .. r.name .. ".idx" + local text = read_capped(path, MAX_INDEX) + local idx = ffi.new("gl_index_t") + if not text or istore.gl_index_parse(text, #text, r.name, idx) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + local pkgs = {} + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + table.insert(pkgs, { + name = ffi.string(p.name), ver = ffi.string(p.ver), + file = ffi.string(p.file), sha256 = ffi.string(p.sha256), + size = tonumber(p.size), deps = ffi.string(p.deps), + confs = ffi.string(p.confs), + build_deps = ffi.string(p.build_deps), + traits = ffi.string(p.traits), + }) + end + istore.gl_index_free(idx) + -- A recipe repository, "X-src", builds packages of X. + local target = r.name:match("^(.+)%-src$") + table.insert(out, { name = r.name, url = r.url, pkgs = pkgs, + src = target ~= nil, target = target }) + end + end + return out +end + +-- The highest version of `name` that repository `r` serves, or nil. +local function newest_in(r, name) + local best + for _, e in ipairs(r.pkgs) do + if e.name == name and (not best or vercmp(e.ver, best.ver) > 0) then + best = e + end + end + return best +end + +-- Which repository `name` comes from: the first, by priority, that +-- serves it, at its highest version. repo, entry, or nil. +local function pick(indexes, name) + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then return r, e end + end +end + +-- The first binary repository (by priority) serving `name`, at its +-- highest version: build layers come only from binaries. +local function pick_binary(indexes, name) + for _, r in ipairs(indexes) do + local e = not r.src and newest_in(r, name) + if e then return r, e end + end +end + +-- A plan item for entry `e` of repository `r`: its effective +-- dependencies (a recipe's IFs resolved against its traits) in it.deps, +-- and for a build, it.traits (gpkg_build's M.traits). +local function plan_item(r, e, name, opts) + local it = { repo = r, entry = e, name = name, deps = e.deps } + if r.src then + it.traits = build.traits(name, e.traits, opts) + it.deps = build.effective(e.deps, it.traits) + end + return it +end + +-- How a plan item is shown: "extra::curl 8.9.0", or for a build +-- "extra-src::curl 8.9.0 [+ssl -ldap] (build)". +local function item_label(it) + local s = string.format("%s::%s %s", it.repo.name, it.name, it.entry.ver) + if it.traits then + s = s .. (it.traits.show ~= "" and (" " .. it.traits.show) or "") .. " (build)" + end + return s +end + +-- Which repository a name given on the command line comes from +-- (BUILD_DESIGN.txt 1f): the only one serving it, or, with several +-- (binary or -src), the one the user picks; Enter takes the first by +-- priority. End of input or an invalid answer refuses. nil if no +-- repository serves it. +local function choose(indexes, name, opts) + local cands = {} + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then table.insert(cands, plan_item(r, e, name, opts)) end + end + if #cands <= 1 then return cands[1] end + log.lg_printf(0, "%s is available from more than one repository:", name) + for k, it in ipairs(cands) do + print(string.format(" %d) %s", k, item_label(it))) + end + io.write(string.format("Select a repository [1-%d, Enter = 1]: ", #cands)) + io.stdout:flush() + local answer = io.read("*l") + local k = answer == "" and 1 or tonumber(answer or "") + if not k or not cands[k] then + log.lg_printf(2, "Invalid selection.") + finish(1) + end + return cands[k] +end + +-- The PKG_TRAITS lines ("ssl\n-ldap\n") of installed entry `i`, from +-- the manifest saved in its version dir; "" if it has none. +local function installed_traits(ctx, i) + local path = string.format("%s/%s/%s/%s-%s/.glacier-manifest", + ffi.string(ctx.store_path), i.repo, i.name, i.name, i.ver) + local m = ffi.new("gl_pkg_t") + if istore.gl_gpm2gpkg(path, m) ~= 0 then return "" end + local t = m.pkg_traits ~= nil and ffi.string(m.pkg_traits) or "" + istore.gl_free_pkg(m) + return t +end + +-- The recipe repository an installed package was built from, or nil. +local function built_from(ctx, repo, name) + local buf = ffi.new("char[256]") + if tonumber(istore.gl_pkg_src(ctx, repo, name, buf, 256)) == 1 then + return ffi.string(buf) + end +end + +-- Add the missing dependencies of everything in `plan` (and theirs), +-- ROADMAP 2.3's closure. A dependency already met (in this scope, or +-- for a user, by the system) is left alone; one installed at too old a +-- version is upgraded from its own repository, keeping its auto or +-- explicit mark; one not installed comes from pick(), recorded auto. +-- Whatever can't be met is left for gl_check_plan to report. +local function close_deps(plan, indexes, opts) + local planned = {} + for _, it in ipairs(plan) do planned[it.name] = it end + local installed = installed_entries(opts) + local system = {} + if opts.scope == ffi.C.GL_SCOPE_USR then + system = read_index_file("/glacier/sys/index/current") + end + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local live = live_context(opts) + + local k = 1 + while k <= #plan do + for dname, dver in plan[k].deps:gmatch("(%S+) (%S+)\n") do + local met, old = planned[dname] ~= nil, nil + for _, i in ipairs(installed) do + if i.name == dname then + if vercmp(i.ver, dver) >= 0 then met = true end + old = old or i + end + end + for _, i in ipairs(system) do + if i.name == dname and vercmp(i.ver, dver) >= 0 then met = true end + end + if not met then + local r, e + if old then + -- Its own repository: the recipe one if it + -- was built from source (1k). + r = by_repo[built_from(live, old.repo, dname) or old.repo] + e = r and newest_in(r, dname) + else + r, e = pick(indexes, dname) + end + if e and vercmp(e.ver, dver) >= 0 then + local it = plan_item(r, e, dname, opts) + it.dep, it.auto, it.may_replace = true, not old or old.auto, old ~= nil + table.insert(plan, it) + planned[dname] = it + end + end + end + k = k + 1 + end +end + +-- Download `e` (an index entry of repository `r`) into the scope's +-- cache, hashing it on the way, unless a cached copy already matches. +-- Never more than the index's SIZE is read. The path, or nil plus +-- true if something was fetched but is not what the index lists. +local function download(ctx, r, e, file_mode) + local dir = ffi.new("char[4096]") + if txn.gl_scope_cache_dir(ctx, r.name, dir) ~= 0 then + finish(1) -- the library said why + end + local want = e.sha256:match("^sha256:(%x+)$") + local dest = ffi.string(dir) .. "/" .. e.file + if sha256_file(dest) == want then + return dest + end + + local src + local path = r.url:match("^file://(/.*)$") + if path then + src = io.open(path .. "/" .. e.file, "rb") + elseif r.url:match("^https://") then + src = io.popen("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 -- " .. + shell_quote(r.url .. "/" .. e.file) .. " 2>/dev/null", "r") + end + if not src then return nil end + local tmp = string.format("%s/.%s.%d", ffi.string(dir), e.file, + ffi.C.gpkg_common_getpid()) + local dst = io.open(tmp, "wb") + if not dst then + src:close() + return nil + end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + local n = 0 + while n <= e.size do + local chunk = src:read(math.min(65536, e.size + 1 - n)) + if not chunk then break end + n = n + #chunk + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + if n ~= e.size or ffi.string(hex) ~= want then + os.remove(tmp) + return nil, n > 0 + end + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 or not os.rename(tmp, dest) then + os.remove(tmp) + return nil + end + return dest +end + +-- The machine key (BUILD_DESIGN.txt section 9): base packages built +-- here are signed with it, and pass the base rule only if the admin +-- lists "local" among base's keys in repos.conf. Made the first time a +-- base-src build is planned: the public half in /etc/glacier/keys, the +-- secret one (0600) in /glacier/sys/keys. +local LOCAL_PUB = "/etc/glacier/keys/local.pub" + +local function machine_seckey() + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(live_context({ scope = ffi.C.GL_SCOPE_SYS, uid = 0 }), + "keys", dir) ~= 0 then + finish(1) -- the library said why + end + return ffi.string(dir) .. "/local.sec" +end + +-- Exits unless the machine key exists (making it if neither half +-- does) and repos.conf trusts it for base. `id` names the build. +local function require_machine_key(id) + local sec = machine_seckey() + local function present(path) + local f = io.open(path, "rb") + if f then f:close() end + return f ~= nil + end + local has_pub, has_sec = present(LOCAL_PUB), present(sec) + if not has_pub and not has_sec then + os.execute("mkdir -p -m 755 /etc/glacier/keys") + if verify.gl_sign_generate(LOCAL_PUB, sec, "glacier machine key") ~= 0 then + log.lg_printf(2, "Cannot make the machine key %s.", LOCAL_PUB) + finish(1) + end + ffi.C.gpkg_common_chmod(LOCAL_PUB, tonumber("644", 8)) + log.lg_printf(0, "Made the machine key %s.", LOCAL_PUB) + elseif has_pub ~= has_sec then + log.lg_printf(2, "%s and %s must both exist, or neither.", LOCAL_PUB, sec) + finish(1) + end + local pub = ffi.new("gl_sign_pubkey_t") + if verify.gl_sign_read_pubkey(LOCAL_PUB, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", LOCAL_PUB) + finish(1) + end + for _, k in ipairs(trusted_keys("base", HOST_KEYRING)) do + if ffi.string(k.pub.keynum, 8) == ffi.string(pub.keynum, 8) then + return sec + end + end + log.lg_printf(2, "%s needs the key \"local\" trusted for base.", id) + finish(1) +end + +-- Sign the sidecar text of a base package built here with the machine +-- key, then hold it to the base rule like any other (signed_for). +local function sign_built_base(copy, sidecar_text, name) + local side = copy .. ".sha256" + local f = io.open(side, "wb") + if not f or not f:write(sidecar_text) then + log.lg_printf(2, "Cannot write %s.", side) + finish(1) + end + f:close() + if verify.gl_sign_file(machine_seckey(), side, side .. ".sig") ~= 0 + or not signed_for(copy, sidecar_text, "base") then + log.lg_printf(2, "base::%s is not signed by a key trusted for base.", name) + finish(1) + end +end + +-- A plan with builds is shown and confirmed BEFORE anything is built +-- (builds are long): the same refusals install_copies would make +-- first, then the summary and the prompt. +local function confirm_builds(plan, indexes, opts) + build.check(opts) + local planned = {} + for _, it in ipairs(plan) do + if it.traits then planned[it.name] = it.entry.ver end + end + for _, it in ipairs(plan) do + if it.traits then build.check_layers(it, indexes, planned, opts) end + if it.traits and it.repo.target == "base" then + require_machine_key(item_label(it)) + end + end + local installed = installed_entries(opts) + local entries, refused = {}, false + for _, it in ipairs(plan) do + local repo = it.repo.target or it.repo.name + local e = { repo = it.repo.name, name = it.name, ver = it.entry.ver } + for _, i in ipairs(installed) do + if i.name == it.name and i.repo == repo and i.ver ~= it.entry.ver then + if overwrite or it.may_replace then + e.ver = i.ver .. " -> " .. it.entry.ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, it.name, i.ver) + refused = true + end + end + end + if it.reason then e.ver = e.ver .. " (" .. it.reason .. ")" end + if it.traits then + e.ver = e.ver .. (it.traits.show ~= "" and (" " .. it.traits.show) or "") + .. " (build)" + end + if it.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + if not confirm(entries) then + finish(0) + end +end + +-- The builds of `plan` in an order where a build comes after any build +-- whose package it depends on (its output is then one of its layers). +local function build_order(plan) + local by_name, order, state = {}, {}, {} + for _, it in ipairs(plan) do + if it.traits then by_name[it.name] = it end + end + local function visit(it) + if state[it.name] then return end + state[it.name] = true + for dname in it.deps:gmatch("(%S+) %S+\n") do + if by_name[dname] then visit(by_name[dname]) end + end + table.insert(order, it) + end + for _, it in ipairs(plan) do + if it.traits then visit(it) end + end + return order +end + +-- Fetch (or build), verify and install everything in `plan` (see +-- close_deps). +local function install_plan(plan, indexes, opts) + local ctx = live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local copies, original, meta = {}, {}, {} + local refused = false + local has_builds = false + for _, it in ipairs(plan) do + has_builds = has_builds or it.traits ~= nil + end + if has_builds then + confirm_builds(plan, indexes, opts) + local built = {} + for _, it in ipairs(build_order(plan)) do + local copy, sidecar_text, hex = build.build(it, indexes, built, opts) + if it.repo.target == "base" then + sign_built_base(copy, sidecar_text, it.name) + end + built[it.name] = { ver = it.entry.ver, path = copy, sha = hex } + it.copy = copy + end + end + for _, it in ipairs(plan) do + if it.copy then + table.insert(copies, it.copy) + original[it.copy] = item_label(it) + meta[it.copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, src = it.repo.name } + goto continue + end + local e = it.entry + local id = string.format("%s::%s %s", it.repo.name, e.name, e.ver) + local cached, wrong = download(ctx, it.repo, e, file_mode) + local copy = cached and verify_and_copy(cached, e.sha256 .. "\n") + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + refused = true + elseif not copy or not matches_index(copy, it.repo.name, e) then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + refused = true + else + table.insert(copies, copy) + original[copy] = it.repo.url .. "/" .. e.file + meta[copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, cache = cached } + end + ::continue:: + end + if refused then + finish(1) + end + install_copies(copies, original, opts, meta, has_builds) +end + +--- -f NAME...: install packages by name from the repositories, with +--- whatever dependencies they are missing. Like -l otherwise: an +--- installed other version of a named package needs -O. +function M.fetch(names, opts) + local indexes = load_indexes(opts) + local plan, refused, seen = {}, false, {} + for _, name in ipairs(names) do + local it = not seen[name] and choose(indexes, name, opts) + if seen[name] then + -- named twice: once is enough + elseif it then + seen[name] = true + table.insert(plan, it) + else + log.lg_printf(2, "%s is not in any repository.", name) + refused = true + end + end + if refused then + finish(1) + end + close_deps(plan, indexes, opts) + install_plan(plan, indexes, opts) +end + +--- -u [NAME...]: replace every installed package (or those named) whose +--- repository's index has a higher version, as -lO does (backups, +--- KEEP_OLD). Packages from repositories not configured are left alone. +function M.upgrade(names, opts) + local indexes = load_indexes(opts) + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local installed = installed_entries(opts) + local live0 = live_context(opts) + + local wanted, refused = nil, false + if #names > 0 then + wanted = {} + for _, name in ipairs(names) do + local found = false + for _, i in ipairs(installed) do + if i.name == name then + found = true + if not by_repo[built_from(live0, i.repo, i.name) or i.repo] then + log.lg_printf(2, "%s::%s is not in any configured repository.", + i.repo, i.name) + refused = true + end + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + refused = true + end + wanted[name] = true + end + end + if refused then + finish(1) + end + + local live = live_context(opts) + local plan = {} + for _, i in ipairs(installed) do + -- A package built from source stays on source (1k). + local src = built_from(live, i.repo, i.name) + local r = by_repo[src or i.repo] + local e = r and (not wanted or wanted[i.name]) and newest_in(r, i.name) + local it = e and plan_item(r, e, i.name, opts) + if it and vercmp(e.ver, i.ver) < 0 then + it = nil + elseif it and vercmp(e.ver, i.ver) == 0 then + -- Same version: rebuilt only if its traits changed. + local had = src and installed_traits(live, i) + if had and it.traits and had ~= table.concat(it.traits.list, "\n") + .. (#it.traits.list > 0 and "\n" or "") then + it.reason = "traits" + else + it = nil + end + end + if it then + it.auto, it.may_replace = i.auto, true + table.insert(plan, it) + end + end + if #plan == 0 then + log.lg_printf(3, "Nothing to do.") + finish(0) + end + close_deps(plan, indexes, opts) + install_plan(plan, indexes, opts) +end + +function M.install(gpkg_paths, opts) + -- From here on, the paths are the VERIFIED PRIVATE COPIES; the + -- caller's paths are only used for messages. + local copies, original = verify_all(gpkg_paths, opts) + install_copies(copies, original, opts, {}) +end + +--- Remove every named package as ONE atomic staged transaction. +--- Does not return on failure — exits. +function M.remove(pkg_names, opts) + -- Names, not files: resolve them against what's actually installed + -- (the old summary read them as .gpkg paths and printed + -- "unknown::pkg 0.0.0"). Anything not installed fails here, before + -- the prompt, not after the user has already said yes. + local installed = installed_entries(opts) + local entries, missing = {}, false + for _, name in ipairs(pkg_names) do + local found = false + for _, e in ipairs(installed) do + if e.name == name then + table.insert(entries, e) + found = true + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + missing = true + end + end + if missing then + os.exit(1) + end + + -- A name installed from more than one repo isn't resolved until + -- after the prompt, so only unambiguous names are checked here. + local count, removes = {}, {} + for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end + for _, e in ipairs(entries) do + if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end + end + check_plan(opts, {}, removes, os.exit) + + if not confirm(entries) then + os.exit(0) + end + + local ctx = begin_staged(opts) + + for _, pkg_name in ipairs(pkg_names) do + local repo = M.resolve_repo(ctx, pkg_name) + if not repo then + log.lg_printf(2, "Failed to resolve group for %s.", pkg_name) + abort_and_die(ctx) + end + + local status = istore.gl_remove_pkg(ctx, pkg_name, repo) + + if status == ffi.C.GL_REMOVE_OK then + log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name) + elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then + log.lg_printf(2, "%s::%s not found.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then + log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_INDEX then + log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name) + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + commit_or_die(ctx) + + report_done(ctx, os.exit) +end + +-- The builder's view of this module (lib/gpkg_build.lua). +init_build = function() + build.init({ + log = log, istore = istore, txn = txn, + finish = finish, shell_quote = shell_quote, + sha256_file = sha256_file, verify_and_copy = verify_and_copy, + download = download, live_context = live_context, + relation_lines = relation_lines, vercmp = vercmp, + pick_binary = pick_binary, + require_trusted = function(path) require_trusted(path, HOST_KEYRING) end, + verbose = function() return isVerbose end, + gsandbox_path = (so_dir or ".") .. "/gsandbox", + gsandbox = shell_quote((so_dir or ".") .. "/gsandbox"), + lib_dir = so_dir and so_dir:gsub("/glacier$", "") or "lib", + }) +end + +return M diff --git a/lib/gpkg_common.lua.old7 b/lib/gpkg_common.lua.old7 new file mode 100644 index 0000000..5b1938e --- /dev/null +++ b/lib/gpkg_common.lua.old7 @@ -0,0 +1,1735 @@ +-- lib/gpkg_common.lua +-- +-- Shared machinery between gpkg (per-user scope only) and syspkg +-- (system scope only). See SECURITY_DESIGN.txt section 7. +-- +-- The interface here is deliberately COARSE-GRAINED: M.install() and +-- M.remove() own the entire staged-transaction lifecycle +-- (gl_init_stage_context -> loop -> commit/abort), rather than +-- exporting fine-grained pieces that each caller then has to sequence +-- itself. That's what keeps the sequencing — and, once Checkpoint 2's +-- verification lands, the hash refusal matrix — in exactly ONE place +-- instead of duplicated across two binaries and drifting apart. +-- +-- What callers keep for themselves: +-- * argument parsing +-- * deciding WHICH scope they're allowed to request (gpkg never +-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag +-- for it", the capability isn't in its code path at all) +-- * their own privilege model (only syspkg runs elevated) +-- +-- Callers pass a `env` table on construction with the FFI handles and +-- shared state, so this module doesn't ffi.load() anything itself and +-- doesn't care where the .so's came from. + +local ffi = require("ffi") +local bit = require("bit") +local glacier_cdef = require("lib/glacier_cdef") +local build = require("lib/gpkg_build") + +local M = {} + +-- Module-level handles, set by M.init(). Kept here rather than passed +-- through every function because every function needs them. +local log, istore, txn, verify +local argv +local so_dir -- lib/glacier: the .so's and gsandbox +local init_build -- set at the end of this file +local isVerbose = false +local skipInstalled = false +local overwrite = false + +local txn_name = glacier_cdef.txn_name + +--- Initialise the module. Must be called before anything else. +-- env.log / env.istore / env.txn : ffi.load() handles +-- env.verify : libglacier_verify.so handle (installs) +-- env.argv : argv table (for usage messages) +-- env.so_dir : lib/glacier, where gsandbox is +function M.init(env) + log = env.log + istore = env.istore + txn = env.txn + verify = env.verify + argv = env.argv + so_dir = env.so_dir + init_build() +end + +--- Toggle flags the CLIs parse but this module acts on. +function M.set_verbose(v) isVerbose = v end +function M.set_skip_installed(v) skipInstalled = v end +function M.set_overwrite(v) overwrite = v end + +-- --------------------------------------------------------------------- +-- Manifest reading +-- --------------------------------------------------------------------- + +-- Quote a string for /bin/sh: wrap in single quotes, and turn each +-- embedded ' into '\''. Package paths come from the command line and +-- manifest entry names come from the archive, and syspkg runs all of +-- this as root — an unescaped ' in either is command execution. +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +--- name, repo and version ("MAJ.MIN.PAT", as the store names versions) +--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same +--- reader gl_install_pkg uses, so what is shown, compared and installed +--- can never disagree. nil if the manifest can't be read. +local function manifest_of(path) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return nil + end + local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo) + local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) + istore.gl_free_pkg(m) + return name, repo, ver +end + +-- --------------------------------------------------------------------- +-- Integrity verification (SECURITY_DESIGN.txt sections 3-4) +-- --------------------------------------------------------------------- + +-- Private working dir for verified copies, removed by finish(). +local private_dir = nil + +-- Backups written during this transaction but not yet committed +-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that +-- were never promoted, so an aborted upgrade leaves no stray backup. +local pending_backups = {} + +--- Exit, removing the private copies (and uncommitted backups) first. +--- Every exit on the install path goes through here. +local function finish(code) + for _, b in ipairs(pending_backups) do + os.remove(b.part) + end + pending_backups = {} + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +--- sha256 of a file as "", or nil. +local function sha256_file(path) + local f = io.open(path, "rb") + if not f then return nil end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = f:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + end + f:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +--- Copy `path` into the private dir, hashing it in the same pass, and +--- check the hash against `path`.sha256. Returns the private copy's path, +--- or nil plus a reason. +--- +--- Everything after this (summary, manifest read, gl_install_pkg) reads +--- ONLY the copy. Verifying the original and then installing it would +--- leave a gap where it could be swapped — and under syspkg that's root +--- reading a file whose directory another user may control. The copy +--- lives in a mktemp -d dir only the invoking user (root, for syspkg) +--- can write. +--- +--- Refusal matrix (section 4). A missing sidecar is treated exactly like +--- a mismatch: +--- repo == base -> always refuse, no exceptions +--- scope == SYS -> always refuse, any repo +--- scope == USR, repo != base -> refuse by default; the ONLY place +--- a future bypass flag may apply +--- No bypass exists, so today every row refuses and the repo (which we +--- couldn't trust before verifying anyway) never needs consulting. A +--- bypass, if ever added, must check scope and the VERIFIED manifest's +--- repo here, before anything else reads the file. +--- +--- A package fetched from a repository passes `vouched`, the "sha256:" +--- its signed index gives, in place of a sidecar. +local function verify_and_copy(path, vouched) + local sidecar = path .. ".sha256" + local sidecar_text = vouched + if not sidecar_text then + local sf = io.open(sidecar, "r") + if not sf then + return nil, "no sidecar " .. sidecar + end + sidecar_text = sf:read("*a") or "" + sf:close() + end + local expected = sidecar_text:match("^sha256:(%x+)%s*$") + if not expected or #expected ~= 64 then + return nil, "malformed sidecar " .. sidecar + end + expected = expected:lower() + + if not private_dir then + local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + return nil, "cannot create a private working directory" + end + end + + local src = io.open(path, "rb") + if not src then + return nil, "cannot open " .. path + end + + -- Unique per argument, so two packages with the same basename + -- (from different directories) can't collide. + local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0, + path:match("([^/]+)$")) + M._ncopies = (M._ncopies or 0) + 1 + local dst = io.open(copy_path, "wb") + if not dst then + src:close() + return nil, "cannot write " .. copy_path + end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = src:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + + if ffi.string(hex) ~= expected then + return nil, "hash mismatch (sidecar says " .. expected .. + ", file is " .. ffi.string(hex) .. ")" + end + + return copy_path, nil, sidecar_text +end + +-- --------------------------------------------------------------------- +-- Signatures (REPO_DESIGN.txt section 7) +-- --------------------------------------------------------------------- + +-- A keyring: repos.conf and the keys it lists, under `sysroot` (nil or +-- "/" = the running system). Read only by syspkg (gpkg reads the +-- system's until user repos). The signature on a local base package +-- (-l) is checked with the HOST's, even under -R (the build host's +-- trust, as KEEP_OLD). Repository operations (-y/-f/-u) use the +-- keyring of the system they act on: under -R, TARGET's own, since the +-- indexes they accept are TARGET's and TARGET checks them from then on. +local function keyring(sysroot) + local root = (sysroot or "/"):gsub("/+$", "") + return { root = root, conf = root .. "/etc/glacier/repos.conf", + keys = root .. "/etc/glacier/keys" } +end +local HOST_KEYRING = keyring(nil) + +ffi.cdef[[ +char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath"); +]] + +local function realpath(path) + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_common_realpath(path, buf) == nil then return nil end + return ffi.string(buf) +end + +-- nil if `path`, every ancestor of it, and every ancestor of its real +-- path are root-owned and not group/world-writable (as syspkg's own +-- lib/: a key a non-root user could swap is no key). Else the path at +-- fault, plus true if it is missing (or can't be resolved). +local function untrusted(path) + local function chain(p) + while true do + local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null") + local line = f and f:read("*l") + if f then f:close() end + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then return p, true end + if tonumber(uid) ~= 0 + or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + return p + end + if p == "/" then return nil end + p = p:match("^(.*)/[^/]*$") + if p == "" then p = "/" end + end + end + local bad, missing = chain(path) + if bad then return bad, missing end + local real = realpath(path) + if not real then return path, true end + return chain(real) +end + +-- Stop the run unless `path`, part of keyring `kr`, is trusted (as +-- untrusted() says) and, in another root, resolves inside it: TARGET's +-- etc/glacier/repos.conf -> /etc/glacier/repos.conf would read the +-- host's file as TARGET's. +local function require_trusted(path, kr) + local bad, missing = untrusted(path) + if bad and missing then + log.lg_printf(2, "Cannot read %s.", bad) + finish(1) + elseif bad then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + path, bad) + finish(1) + end + if kr.root ~= "" then + local real, root = realpath(path), realpath(kr.root) + if not (real and root and real:sub(1, #root + 1) == root .. "/") then + log.lg_printf(2, "Refusing %s: it resolves outside %s.", path, kr.root) + finish(1) + end + end +end + +-- Whether keyring `kr`'s repos.conf exists, having checked it is +-- trusted (else the run stops: the admin's configuration is at fault, +-- not a package). +local function repos_conf_present(kr) + local f, _, code = io.open(kr.conf, "r") + if f then f:close() end + if not f and code == 2 then return false end + require_trusted(kr.conf, kr) + return true +end + +-- The public keys keyring `kr` trusts for `repo`, read once per run: +-- { { name, pub }... }. A missing repos.conf trusts nothing. A +-- repos.conf or listed key that is untrusted or can't be read stops the +-- run: that is the admin's configuration, not the package, at fault. +local trusted_keys_cache = {} +local function trusted_keys(repo, kr) + local cache_key = kr.conf .. "\n" .. repo + if trusted_keys_cache[cache_key] then return trusted_keys_cache[cache_key] end + local keys = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[4096]") + local st = tonumber(istore.gl_conf_repo_keys(kr.conf, repo, buf, 4096)) + if st == 1 or st == 3 or st == 4 or st == 5 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name in ffi.string(buf):gmatch("([^\n]+)\n") do + local path = kr.keys .. "/" .. name .. ".pub" + local pub = ffi.new("gl_sign_pubkey_t") + require_trusted(path, kr) + if verify.gl_sign_read_pubkey(path, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + table.insert(keys, { name = name, pub = pub }) + end + end + trusted_keys_cache[cache_key] = keys + return keys +end + +-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very +-- bytes the copy was checked against) by a key trusted for `repo`. The +-- key is picked by the signature's keynum, never by trying each one. +local function signed_for(path, sidecar_text, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then + return false + end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, HOST_KEYRING)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0 + end + end + return false +end + +--- Verify every package up front, before the summary is even shown. +--- Returns the private copies, plus a copy -> original map for messages. +--- +--- In system scope, a package whose manifest says base must also have a +--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the +--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg +--- does). +local function verify_all(gpkg_paths, opts) + local copies, original = {}, {} + local refused = false + + for _, p in ipairs(gpkg_paths) do + local copy, why, sidecar_text = verify_and_copy(p) + if copy and not manifest_of(copy) then + log.lg_printf(2, "Cannot read the manifest of %s.", p) + refused = true + copy = nil + end + if copy and opts.scope == ffi.C.GL_SCOPE_SYS then + local name, repo = manifest_of(copy) + if repo == "base" and not signed_for(p, sidecar_text, repo) then + log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.", + repo, name, repo) + refused = true + copy = nil + end + end + if copy then + table.insert(copies, copy) + original[copy] = p + elseif why then + log.lg_printf(2, "Refusing %s: %s.", p, why) + refused = true + end + end + + if refused then + finish(1) + end + return copies, original +end + +-- --------------------------------------------------------------------- +-- Confirmation summary +-- --------------------------------------------------------------------- + +--- Print the summary for `entries` ({repo, name, ver} each) and ask. +local function confirm(entries) + log.lg_printf(0, "SUMMARY:") + print("==============================") + print("") + for _, e in ipairs(entries) do + print(string.format(" * %s::%s\t\t%-16s", + e.repo or "unknown", e.name, e.ver or "unknown")) + end + print("") + io.write("Proceed? (y/N): ") + io.stdout:flush() + + local response = io.read("*l") + if not response then + return false + end + response = response:lower() + return response == "y" or response == "yes" +end + +--- Installed packages, from the live index for this scope: a list of +--- {repo, name, ver, auto}. The index's `current` file holds one +--- `repo::name::version::auto|explicit` line per package (index files +--- written before 2026-10-05 stop at the version). +--- A live context for opts' scope (and install root: syspkg -R only). +local function live_context(opts) + local ctx = ffi.new("gl_context_t") + if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then + finish(1) -- the library said why + end + return ctx +end + +-- The entries of an index `current` file ({} if there is none). +local function read_index_file(path) + local f = io.open(path, "r") + local out = {} + if not f then return out end + for line in f:lines() do + local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$") + if repo then + local ver, kind = rest:match("^(.-)::(%a+)$") + table.insert(out, { repo = repo, name = name, ver = ver or rest, + auto = kind == "auto" }) + end + end + f:close() + return out +end + +local function installed_entries(opts) + local ctx = live_context(opts) + return read_index_file(ffi.string(ctx.index_path) .. "/current") +end + +-- --------------------------------------------------------------------- +-- Repo resolution +-- --------------------------------------------------------------------- + +function M.resolve_repo(ctx, pkg_name) + local list = istore.gl_find_pkg_repos(ctx, pkg_name) + + if list.count == 0 then + log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name) + istore.gl_free_repo_list(list) + return nil + end + + if list.count == 1 then + local repo = ffi.string(list.repos[0]) + istore.gl_free_repo_list(list) + return repo + end + + log.lg_printf(1, "Multiple instances of %s found:", pkg_name) + for i = 0, tonumber(list.count) - 1 do + print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name)) + end + print("") + io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ") + io.stdout:flush() + local input = io.read("*l") + local choice = tonumber(input) + + if not choice or choice < 1 or choice > tonumber(list.count) then + log.lg_printf(2, "Invalid selection.") + istore.gl_free_repo_list(list) + return nil + end + + local repo = ffi.string(list.repos[choice - 1]) + istore.gl_free_repo_list(list) + return repo +end + +-- --------------------------------------------------------------------- +-- Single-package install (with reinstall-if-present handling) +-- --------------------------------------------------------------------- + +local function install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + if not pkg_name then + log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path) + finish(1) + end + + if isVerbose then + log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s", + pkg_name, version_str, manifest_repo, gpkg_path) + end + + local status = istore.gl_install_pkg(ctx, gpkg_path) + + if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then + if skipInstalled then + log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str) + return tonumber(ffi.C.GL_INSTALL_SKIPPED) + end + + log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str) + + local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo) + + if rm_status ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).", + manifest_repo, pkg_name, tostring(tonumber(rm_status))) + return tonumber(rm_status) + end + + status = istore.gl_install_pkg(ctx, gpkg_path) + if status == ffi.C.GL_INSTALL_OK then + -- M.install logs the one "staged from" line. + return 0 + else + log.lg_printf(2, "Reinstall of %s-%s failed (error %s).", + pkg_name, version_str, tostring(tonumber(status))) + return tonumber(status) + end + + elseif status == ffi.C.GL_INSTALL_OK then + return 0 + end + + return tonumber(status) +end + +-- --------------------------------------------------------------------- +-- Transaction lifecycle +-- --------------------------------------------------------------------- + +--- Open a staged transaction for the given scope. Exits on failure with +--- a scope-appropriate message. `scope_label` is used only in the +--- lock-contention message ("for UID 1000" vs "for the system scope"). +local function begin_staged(opts) + local scope_label = opts.scope_label + local ctx = ffi.new("gl_context_t") + local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") + + if txn_st ~= ffi.C.GL_TXN_OK then + if txn_st == ffi.C.GL_TXN_ERR_LOCK then + log.lg_printf(2, + "Another glacier transaction is already in progress %s.", + scope_label) + else + log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st)) + end + finish(1) + end + + ctx.strict = opts.strict and 1 or 0 + return ctx +end + +--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt. +--- The library prints each problem; this exits if there were any. The +--- commit checks again (gl_check_txn), which is what covers a removal +--- whose repo is only chosen after the prompt. +local function check_plan(opts, adds, removes, exit) + local live = live_context(opts) + live.strict = opts.strict and 1 or 0 + live.overwrite = overwrite and 1 or 0 + local a = ffi.new("const char *[?]", #adds + 1) + for i, p in ipairs(adds) do a[i - 1] = p end + local r = ffi.new("const char *[?]", #removes + 1) + for i, id in ipairs(removes) do r[i - 1] = id end + local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes)) + if problems < 0 then + log.lg_printf(2, "Cannot read the package store to check dependencies.") + end + if problems ~= 0 then exit(1) end +end + +--- Commit, or abort-and-exit on failure. +local function commit_or_die(ctx) + local commit_st = txn.gl_commit_transaction(ctx) + if commit_st == ffi.C.GL_TXN_ERR_DEPS then + -- The library already said what's wrong, one line each. + txn.gl_abort_transaction(ctx) + finish(1) + elseif commit_st ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st)) + txn.gl_abort_transaction(ctx) + finish(1) + end +end + +--- The last line of a committed transaction. If the link pass refused +--- any path (each refusal is already printed above), the transaction is +--- committed but did not fully succeed: an error, and exit status 1. +local function report_done(ctx, exit) + local n = tonumber(ctx.link_refusals) + if n > 0 then + log.lg_printf(2, "%s %s not linked.", tostring(n), + n == 1 and "path was" or "paths were") + exit(1) + end + log.lg_printf(3, "Completed with no errors.") + exit(0) +end + +--- Abort the transaction and exit non-zero. Every failure path inside a +--- staged loop goes through here so live state is never left partially +--- mutated. +local function abort_and_die(ctx) + txn.gl_abort_transaction(ctx) + finish(1) +end + +-- --------------------------------------------------------------------- +-- Repository indexes (REPO_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +ffi.cdef[[ +int gpkg_common_getpid(void) asm("getpid"); +int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod"); +int gpkg_common_close(int fd) asm("close"); +]] + +-- Largest index accepted: what gl_sign_verify will check. +local MAX_INDEX = 64 * 1024 * 1024 + +-- A whole file, or nil if it is missing, unreadable or over `max`. +local function read_capped(path, max) + local f = io.open(path, "rb") + if not f then return nil end + local data = f:read(max + 1) or "" + f:close() + if #data > max then return nil end + return data +end + +-- Fetch URL/NAME into `dest`. https goes through curl, refusing any +-- other protocol, redirects included; file:// is a plain copy of an +-- absolute path. True on success. +local function fetch(url, name, dest) + local path = url:match("^file://(/.*)$") + if path then + local data = read_capped(path .. "/" .. name, MAX_INDEX) + local f = data and io.open(dest, "wb") + if not f then return false end + local ok = f:write(data) + f:close() + return ok ~= nil + end + if not url:match("^https://") then return false end + local ok = os.execute("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 --max-filesize " .. MAX_INDEX .. + " -o " .. shell_quote(dest) .. " -- " .. + shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1") + return ok == true or ok == 0 +end + +-- Whether `text` is signed by `sig_path`, with a key keyring `kr` +-- trusts for `repo` (picked by keynum, as signed_for). +local function index_signed(text, sig_path, repo, kr) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, kr)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", text), #text) == 0 + end + end + return false +end + +-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the +-- gl_index_parse status. +local function parse_index(text, repo) + local idx = ffi.new("gl_index_t") + local st = tonumber(istore.gl_index_parse(text, #text, repo, idx)) + if st ~= 0 then return nil, st end + local r = { serial = idx.serial, valid_until = idx.valid_until, + npkgs = tonumber(idx.npkgs) } + istore.gl_index_free(idx) + return r +end + +-- Refresh one repository's index into `dir` (/repos): fetch, +-- verify, parse, refuse a rollback or an expired index, then rename +-- over the accepted copy, checking signatures with keyring `kr`. Any +-- failure keeps the accepted copy, prints one line and returns false. +local function refresh_one(repo, url, dir, file_mode, kr) + local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid()) + local tmp_sig = tmp .. ".sig" + local function fail(fmt, ...) + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(2, fmt, ...) + return false + end + + local text + if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then + text = read_capped(tmp, MAX_INDEX) + end + if not text then + return fail("Cannot fetch the index for %s.", repo) + end + -- The signature is checked over the very bytes parsed below. + if not index_signed(text, tmp_sig, repo, kr) then + return fail("Index for %s is not signed by a key trusted for %s.", repo, repo) + end + local new, st = parse_index(text, repo) + if st == 2 then + return fail("Index fetched for %s is the index of another repository.", repo) + elseif not new then + return fail("Malformed index for %s.", repo) + end + + local stored = dir .. "/" .. repo .. ".idx" + local old_text = read_capped(stored, MAX_INDEX) + local unchanged = false + if old_text then + local old = parse_index(old_text, repo) + if not old then + return fail("Malformed %s.", stored) + end + if new.serial < old.serial then + return fail("Index for %s is older than the one already accepted.", repo) + elseif new.serial == old.serial then + if text ~= old_text then + return fail("Index for %s has the serial of the one already accepted, but other contents.", repo) + end + unchanged = true + end + elseif io.open(stored, "rb") then + return fail("Cannot read %s.", stored) + end + if new.valid_until <= os.time() then + return fail("Index for %s has expired.", repo) + end + + local serial = string.format("%d", tonumber(new.serial)) + if unchanged then + os.remove(tmp) + os.remove(tmp_sig) + if isVerbose then + log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial) + end + return true + end + -- Never written in place (bug 25): renamed over the old copy. + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 + or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0 + or not os.rename(tmp_sig, stored .. ".sig") + or not os.rename(tmp, stored) then + return fail("Cannot write %s.", stored) + end + if isVerbose then + log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial, + tostring(new.npkgs), new.npkgs == 1 and "package" or "packages") + end + return true +end + +--- Refresh the index of every repository repos.conf gives a url +--- (REPO_DESIGN.txt section 5), into the scope's /repos, holding +--- the scope's lock. Every repository is tried; true if all succeeded. +--- Exits if there is nothing to refresh or the setup is at fault. +-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install +-- Every entry with a url in keyring `kr`'s repos.conf, in priority +-- order: { name, url }. Exits if there is none, or repos.conf is +-- malformed. +local function configured_remotes(kr) + local remotes = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[65536]") + if tonumber(istore.gl_conf_repos(kr.conf, buf, 65536)) ~= 0 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then + table.insert(remotes, { name = name, url = url }) + end + end + end + if #remotes == 0 then + log.lg_printf(2, "No remote repositories are configured.") + finish(1) + end + return remotes +end + +function M.refresh(opts) + local kr = keyring(opts.sysroot) + local remotes = configured_remotes(kr) + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) -- the library said why + end + if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Another glacier transaction is already in progress %s.", + opts.scope_label) + finish(1) + end + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + log.lg_printf(0, "Syncing all repositories...") + local all = true + for _, r in ipairs(remotes) do + all = refresh_one(r.name, r.url, ffi.string(dir), file_mode, kr) and all + end + ffi.C.gpkg_common_close(ctx.lock_fd) + if all then + log.lg_printf(3, "All repositories synced successfully.") + end + return all +end + +-- --------------------------------------------------------------------- +-- Public: whole-batch install / remove +-- --------------------------------------------------------------------- + +--- Install every package in gpkg_paths as ONE atomic staged transaction. +--- Any failure aborts the whole batch, leaving live state untouched. +--- Does not return on failure — exits. +-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS +-- opts.uid : uid for USR scope (ignored for SYS) +-- opts.scope_label : human string for the lock-contention message +-- opts.sysroot : install root (syspkg -R; nil = the running system) +-- opts.strict : refuse, before committing, anything the link pass +-- would refuse (syspkg --strict, implied by -R) +--- KEEP_OLD from glacier.conf: how many backups of replaced versions to +--- keep per package. There is no default — it ships as 1 in +--- glacier.conf, and an operation that would replace a version refuses +--- to run if it's missing or not a whole number. +local function keep_old() + local n = ffi.new("int[1]") + local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n)) + if st == 1 then + log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.") + elseif st == 2 then + log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.") + elseif st == 3 or (st == 0 and n[0] < 0) then + log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.") + end + if st ~= 0 or n[0] < 0 then finish(1) end + return tonumber(n[0]) +end + +-- Install verified private copies as one transaction. original[copy] +-- names each for messages. meta[copy], for packages fetched from a +-- repository (else nil): +-- auto : record it as installed as a dependency +-- may_replace : replace an installed other version without -O +-- (-u, and dependency upgrades) +-- dep : marked as a dependency in the summary +-- cache : the downloaded file, deleted once committed +-- src : built from this recipe repository (.glacier-src) +-- `confirmed`: the plan was already shown and accepted (builds ask +-- before building, so not again here). +local function install_copies(gpkg_paths, original, opts, meta, confirmed) + -- A different version of a package that's already installed is a + -- REPLACEMENT (upgrade or downgrade). Only -O permits it; without + -- -O it's refused here, before the prompt. + local installed = installed_entries(opts) + local entries, replacing, refused = {}, {}, false + for _, p in ipairs(gpkg_paths) do + local name, repo, ver = manifest_of(p) + local m = meta[p] or {} + local e = { repo = repo, name = name, ver = ver } + for _, i in ipairs(installed) do + if i.name == name and i.repo == repo and i.ver ~= ver then + if overwrite or m.may_replace then + replacing[p] = i + e.ver = i.ver .. " -> " .. ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, name, i.ver) + refused = true + end + end + end + if m.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + + check_plan(opts, gpkg_paths, {}, finish) + + local keep = next(replacing) and keep_old() or 0 + + if not confirmed and not confirm(entries) then + finish(0) + end + + local ctx = begin_staged(opts) + ctx.overwrite = overwrite and 1 or 0 + local staged = 0 + + -- Replacements: back up the installed version (from LIVE, written + -- under a .part name and only promoted after a successful commit), + -- then remove it from the stage so the new version installs into + -- a clean slot in the same transaction. + local live = live_context(opts) + local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup" + for _, old in pairs(replacing) do + if keep > 0 then + local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name) + local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver) + local part = final .. ".part" + if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then + log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + table.insert(pending_backups, { part = part, final = final, dir = dir, old = old }) + end + if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + end + + for _, gpkg_path in ipairs(gpkg_paths) do + local status = install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + local abs_path = original[gpkg_path] + + if status == 0 then + staged = staged + 1 + if (meta[gpkg_path] or {}).auto + and istore.gl_set_pkg_auto(ctx, manifest_repo, pkg_name, true) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as a dependency.", + manifest_repo, pkg_name) + abort_and_die(ctx) + end + local src = (meta[gpkg_path] or {}).src + if src and istore.gl_set_pkg_src(ctx, manifest_repo, pkg_name, src) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as built from %s.", + manifest_repo, pkg_name, src) + abort_and_die(ctx) + end + log.lg_printf(3, "%s::%s-%s: staged from %s.", + manifest_repo, pkg_name, version_str, abs_path) + elseif status == 1 then + log.lg_printf(2, "%s::%s: Failed to open package archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 2 then + log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 3 then + log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 4 then + log.lg_printf(2, "%s::%s: Failed to add entry to index.", + manifest_repo, pkg_name) + abort_and_die(ctx) + elseif status == 6 then + -- GL_INSTALL_SKIPPED: not a failure, keep going + elseif status == 7 then + -- GL_INSTALL_ERR_SCOPE: the library refused this + -- package for this scope (base-repo package under + -- user scope). The library already logged the + -- specific reason; don't second-guess it here. + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + -- Everything was skipped (-S, already up to date): the stage is + -- identical to live, so don't commit it. A commit isn't free — it + -- swaps the trees and re-links the whole store, re-printing every + -- standing link conflict for packages this command never touched. + if staged == 0 then + txn.gl_abort_transaction(ctx) + log.lg_printf(3, "Nothing to do.") + finish(0) + end + + commit_or_die(ctx) + + -- Committed: promote the backups, give each a sidecar (so it's an + -- installable, verifiable package), and keep only the newest KEEP_OLD. + for _, b in ipairs(pending_backups) do + if os.rename(b.part, b.final) then + local hex = sha256_file(b.final) + local sf = hex and io.open(b.final .. ".sha256", "w") + if sf then + sf:write("sha256:" .. hex .. "\n") + sf:close() + end + istore.gl_prune_backups(b.dir, keep) + log.lg_printf(0, "Backed up %s::%s %s to %s", + b.old.repo, b.old.name, b.old.ver, b.final) + else + log.lg_printf(1, "Could not keep the backup of %s::%s %s.", + b.old.repo, b.old.name, b.old.ver) + end + end + pending_backups = {} + + for _, p in ipairs(gpkg_paths) do + if meta[p] and meta[p].cache then os.remove(meta[p].cache) end + if meta[p] and meta[p].src then + local name, repo, ver = manifest_of(p) + build.keep(opts, p, repo, name, ver) + end + end + build.prune_kept(opts) + + report_done(ctx, finish) +end + +-- --------------------------------------------------------------------- +-- -f / -u: packages from the repositories (REPO_DESIGN.txt section 6) +-- --------------------------------------------------------------------- + +-- -1, 0 or 1 as version a is below, equal to or above b ("MAJ.MIN.PAT"). +local function vercmp(a, b) + local x = { a:match("^(%d+)%.(%d+)%.(%d+)") } + local y = { b:match("^(%d+)%.(%d+)%.(%d+)") } + for k = 1, 3 do + local m, n = tonumber(x[k]) or 0, tonumber(y[k]) or 0 + if m ~= n then return m < n and -1 or 1 end + end + return 0 +end + +-- A package's relations as an index lists them: "NAME VER\n" lines. +local function relation_lines(list, name_field, ver_field) + local out = {} + local k = 0 + while list ~= nil and list[k][name_field] ~= nil do + local v = list[k][ver_field] + table.insert(out, string.format("%s %d.%d.%d\n", + ffi.string(list[k][name_field]), v.maj, v.min, v.pat)) + k = k + 1 + end + return table.concat(out) +end + +-- Whether the manifest of `path` (read by the library) says exactly what +-- its index entry `e` of repository `repo` says: NAME, VER, PKG_REPO, +-- DEPS and CONFS. A package is from `repo` because that repo's signed +-- index lists it AND it says so, never because it says so. +local function matches_index(path, repo, e) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return false + end + local ok = ffi.string(m.pkg_name) == e.name + and ffi.string(m.pkg_repo) == repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == e.ver + and relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == e.deps + and relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == e.confs + istore.gl_free_pkg(m) + return ok +end + +-- The accepted index of every configured repository, freshly refreshed +-- (decision 10d: any failure refuses the operation). In priority order: +-- { name, url, pkgs = { { name, ver, file, sha256, size, deps, confs }... } }. +-- User scope never fetches from base (the library refuses it there). +local function load_indexes(opts) + local remotes = configured_remotes(keyring(opts.sysroot)) + if not M.refresh(opts) then + finish(1) + end + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) + end + local out = {} + for _, r in ipairs(remotes) do + if opts.scope ~= ffi.C.GL_SCOPE_USR or (r.name ~= "base" and r.name ~= "base-src") then + local path = ffi.string(dir) .. "/" .. r.name .. ".idx" + local text = read_capped(path, MAX_INDEX) + local idx = ffi.new("gl_index_t") + if not text or istore.gl_index_parse(text, #text, r.name, idx) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + local pkgs = {} + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + table.insert(pkgs, { + name = ffi.string(p.name), ver = ffi.string(p.ver), + file = ffi.string(p.file), sha256 = ffi.string(p.sha256), + size = tonumber(p.size), deps = ffi.string(p.deps), + confs = ffi.string(p.confs), + build_deps = ffi.string(p.build_deps), + traits = ffi.string(p.traits), + }) + end + istore.gl_index_free(idx) + -- A recipe repository, "X-src", builds packages of X. + local target = r.name:match("^(.+)%-src$") + table.insert(out, { name = r.name, url = r.url, pkgs = pkgs, + src = target ~= nil, target = target }) + end + end + return out +end + +-- The highest version of `name` that repository `r` serves, or nil. +local function newest_in(r, name) + local best + for _, e in ipairs(r.pkgs) do + if e.name == name and (not best or vercmp(e.ver, best.ver) > 0) then + best = e + end + end + return best +end + +-- Which repository `name` comes from: the first, by priority, that +-- serves it, at its highest version. repo, entry, or nil. +local function pick(indexes, name) + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then return r, e end + end +end + +-- The first binary repository (by priority) serving `name`, at its +-- highest version: build layers come only from binaries. +local function pick_binary(indexes, name) + for _, r in ipairs(indexes) do + local e = not r.src and newest_in(r, name) + if e then return r, e end + end +end + +-- A plan item for entry `e` of repository `r`: its effective +-- dependencies (a recipe's IFs resolved against its traits) in it.deps, +-- and for a build, it.traits (gpkg_build's M.traits). +local function plan_item(r, e, name, opts) + local it = { repo = r, entry = e, name = name, deps = e.deps } + if r.src then + it.traits = build.traits(name, e.traits, opts) + it.deps = build.effective(e.deps, it.traits) + end + return it +end + +-- How a plan item is shown: "extra::curl 8.9.0", or for a build +-- "extra-src::curl 8.9.0 [+ssl -ldap] (build)". +local function item_label(it) + local s = string.format("%s::%s %s", it.repo.name, it.name, it.entry.ver) + if it.traits then + s = s .. (it.traits.show ~= "" and (" " .. it.traits.show) or "") .. " (build)" + end + return s +end + +-- Which repository a name given on the command line comes from +-- (BUILD_DESIGN.txt 1f): the only one serving it, or, with several +-- (binary or -src), the one the user picks; Enter takes the first by +-- priority. End of input or an invalid answer refuses. nil if no +-- repository serves it. +local function choose(indexes, name, opts) + local cands = {} + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then table.insert(cands, plan_item(r, e, name, opts)) end + end + if #cands <= 1 then return cands[1] end + log.lg_printf(0, "%s is available from more than one repository:", name) + for k, it in ipairs(cands) do + print(string.format(" %d) %s", k, item_label(it))) + end + io.write(string.format("Select a repository [1-%d, Enter = 1]: ", #cands)) + io.stdout:flush() + local answer = io.read("*l") + local k = answer == "" and 1 or tonumber(answer or "") + if not k or not cands[k] then + log.lg_printf(2, "Invalid selection.") + finish(1) + end + return cands[k] +end + +-- The PKG_TRAITS lines ("ssl\n-ldap\n") of installed entry `i`, from +-- the manifest saved in its version dir; "" if it has none. +local function installed_traits(ctx, i) + local path = string.format("%s/%s/%s/%s-%s/.glacier-manifest", + ffi.string(ctx.store_path), i.repo, i.name, i.name, i.ver) + local m = ffi.new("gl_pkg_t") + if istore.gl_gpm2gpkg(path, m) ~= 0 then return "" end + local t = m.pkg_traits ~= nil and ffi.string(m.pkg_traits) or "" + istore.gl_free_pkg(m) + return t +end + +-- The recipe repository an installed package was built from, or nil. +local function built_from(ctx, repo, name) + local buf = ffi.new("char[256]") + if tonumber(istore.gl_pkg_src(ctx, repo, name, buf, 256)) == 1 then + return ffi.string(buf) + end +end + +-- Add the missing dependencies of everything in `plan` (and theirs), +-- ROADMAP 2.3's closure. A dependency already met (in this scope, or +-- for a user, by the system) is left alone; one installed at too old a +-- version is upgraded from its own repository, keeping its auto or +-- explicit mark; one not installed comes from pick(), recorded auto. +-- Whatever can't be met is left for gl_check_plan to report. +local function close_deps(plan, indexes, opts) + local planned = {} + for _, it in ipairs(plan) do planned[it.name] = it end + local installed = installed_entries(opts) + local system = {} + if opts.scope == ffi.C.GL_SCOPE_USR then + system = read_index_file("/glacier/sys/index/current") + end + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local live = live_context(opts) + + local k = 1 + while k <= #plan do + for dname, dver in plan[k].deps:gmatch("(%S+) (%S+)\n") do + local met, old = planned[dname] ~= nil, nil + for _, i in ipairs(installed) do + if i.name == dname then + if vercmp(i.ver, dver) >= 0 then met = true end + old = old or i + end + end + for _, i in ipairs(system) do + if i.name == dname and vercmp(i.ver, dver) >= 0 then met = true end + end + if not met then + local r, e + if old then + -- Its own repository: the recipe one if it + -- was built from source (1k). + r = by_repo[built_from(live, old.repo, dname) or old.repo] + e = r and newest_in(r, dname) + else + r, e = pick(indexes, dname) + end + if e and vercmp(e.ver, dver) >= 0 then + local it = plan_item(r, e, dname, opts) + it.dep, it.auto, it.may_replace = true, not old or old.auto, old ~= nil + table.insert(plan, it) + planned[dname] = it + end + end + end + k = k + 1 + end +end + +-- Download `e` (an index entry of repository `r`) into the scope's +-- cache, hashing it on the way, unless a cached copy already matches. +-- Never more than the index's SIZE is read. The path, or nil plus +-- true if something was fetched but is not what the index lists. +local function download(ctx, r, e, file_mode) + local dir = ffi.new("char[4096]") + if txn.gl_scope_cache_dir(ctx, r.name, dir) ~= 0 then + finish(1) -- the library said why + end + local want = e.sha256:match("^sha256:(%x+)$") + local dest = ffi.string(dir) .. "/" .. e.file + if sha256_file(dest) == want then + return dest + end + + local src + local path = r.url:match("^file://(/.*)$") + if path then + src = io.open(path .. "/" .. e.file, "rb") + elseif r.url:match("^https://") then + src = io.popen("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 -- " .. + shell_quote(r.url .. "/" .. e.file) .. " 2>/dev/null", "r") + end + if not src then return nil end + local tmp = string.format("%s/.%s.%d", ffi.string(dir), e.file, + ffi.C.gpkg_common_getpid()) + local dst = io.open(tmp, "wb") + if not dst then + src:close() + return nil + end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + local n = 0 + while n <= e.size do + local chunk = src:read(math.min(65536, e.size + 1 - n)) + if not chunk then break end + n = n + #chunk + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + if n ~= e.size or ffi.string(hex) ~= want then + os.remove(tmp) + return nil, n > 0 + end + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 or not os.rename(tmp, dest) then + os.remove(tmp) + return nil + end + return dest +end + +-- The machine key (BUILD_DESIGN.txt section 9): base packages built +-- here are signed with it, and pass the base rule only if the admin +-- lists "local" among base's keys in repos.conf. Made the first time a +-- base-src build is planned: the public half in /etc/glacier/keys, the +-- secret one (0600) in /glacier/sys/keys. +local LOCAL_PUB = "/etc/glacier/keys/local.pub" + +local function machine_seckey() + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(live_context({ scope = ffi.C.GL_SCOPE_SYS, uid = 0 }), + "keys", dir) ~= 0 then + finish(1) -- the library said why + end + return ffi.string(dir) .. "/local.sec" +end + +-- Exits unless the machine key exists (making it if neither half +-- does) and repos.conf trusts it for base. `id` names the build. +local function require_machine_key(id) + local sec = machine_seckey() + local function present(path) + local f = io.open(path, "rb") + if f then f:close() end + return f ~= nil + end + local has_pub, has_sec = present(LOCAL_PUB), present(sec) + if not has_pub and not has_sec then + os.execute("mkdir -p -m 755 /etc/glacier/keys") + if verify.gl_sign_generate(LOCAL_PUB, sec, "glacier machine key") ~= 0 then + log.lg_printf(2, "Cannot make the machine key %s.", LOCAL_PUB) + finish(1) + end + ffi.C.gpkg_common_chmod(LOCAL_PUB, tonumber("644", 8)) + log.lg_printf(0, "Made the machine key %s.", LOCAL_PUB) + elseif has_pub ~= has_sec then + log.lg_printf(2, "%s and %s must both exist, or neither.", LOCAL_PUB, sec) + finish(1) + end + local pub = ffi.new("gl_sign_pubkey_t") + if verify.gl_sign_read_pubkey(LOCAL_PUB, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", LOCAL_PUB) + finish(1) + end + for _, k in ipairs(trusted_keys("base", HOST_KEYRING)) do + if ffi.string(k.pub.keynum, 8) == ffi.string(pub.keynum, 8) then + return sec + end + end + log.lg_printf(2, "%s needs the key \"local\" trusted for base.", id) + finish(1) +end + +-- Sign the sidecar text of a base package built here with the machine +-- key, then hold it to the base rule like any other (signed_for). +local function sign_built_base(copy, sidecar_text, name) + local side = copy .. ".sha256" + local f = io.open(side, "wb") + if not f or not f:write(sidecar_text) then + log.lg_printf(2, "Cannot write %s.", side) + finish(1) + end + f:close() + if verify.gl_sign_file(machine_seckey(), side, side .. ".sig") ~= 0 + or not signed_for(copy, sidecar_text, "base") then + log.lg_printf(2, "base::%s is not signed by a key trusted for base.", name) + finish(1) + end +end + +-- A plan with builds is shown and confirmed BEFORE anything is built +-- (builds are long): the same refusals install_copies would make +-- first, then the summary and the prompt. +local function confirm_builds(plan, indexes, opts) + build.check(opts) + local planned = {} + for _, it in ipairs(plan) do + if it.traits then planned[it.name] = { ver = it.entry.ver, deps = it.deps } end + end + for _, it in ipairs(plan) do + if it.traits then build.check_layers(it, indexes, planned, opts) end + if it.traits and it.repo.target == "base" then + require_machine_key(item_label(it)) + end + end + local installed = installed_entries(opts) + local entries, refused = {}, false + for _, it in ipairs(plan) do + local repo = it.repo.target or it.repo.name + local e = { repo = it.repo.name, name = it.name, ver = it.entry.ver } + for _, i in ipairs(installed) do + if i.name == it.name and i.repo == repo and i.ver ~= it.entry.ver then + if overwrite or it.may_replace then + e.ver = i.ver .. " -> " .. it.entry.ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, it.name, i.ver) + refused = true + end + end + end + if it.reason then e.ver = e.ver .. " (" .. it.reason .. ")" end + if it.traits then + e.ver = e.ver .. (it.traits.show ~= "" and (" " .. it.traits.show) or "") + .. " (build)" + end + if it.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + if not confirm(entries) then + finish(0) + end +end + +-- The builds of `plan` in an order where a build comes after any build +-- whose package it depends on (its output is then one of its layers). +local function build_order(plan) + local by_name, order, state = {}, {}, {} + for _, it in ipairs(plan) do + if it.traits then by_name[it.name] = it end + end + local function visit(it) + if state[it.name] then return end + state[it.name] = true + for dname in it.deps:gmatch("(%S+) %S+\n") do + if by_name[dname] then visit(by_name[dname]) end + end + table.insert(order, it) + end + for _, it in ipairs(plan) do + if it.traits then visit(it) end + end + return order +end + +-- Fetch (or build), verify and install everything in `plan` (see +-- close_deps). +local function install_plan(plan, indexes, opts) + local ctx = live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local copies, original, meta = {}, {}, {} + local refused = false + local has_builds = false + for _, it in ipairs(plan) do + has_builds = has_builds or it.traits ~= nil + end + if has_builds then + confirm_builds(plan, indexes, opts) + local built = {} + for _, it in ipairs(build_order(plan)) do + local copy, sidecar_text, hex = build.build(it, indexes, built, opts) + if it.repo.target == "base" then + sign_built_base(copy, sidecar_text, it.name) + end + built[it.name] = { ver = it.entry.ver, path = copy, sha = hex, deps = it.deps } + it.copy = copy + end + end + for _, it in ipairs(plan) do + if it.copy then + table.insert(copies, it.copy) + original[it.copy] = item_label(it) + meta[it.copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, src = it.repo.name } + goto continue + end + local e = it.entry + local id = string.format("%s::%s %s", it.repo.name, e.name, e.ver) + local cached, wrong = download(ctx, it.repo, e, file_mode) + local copy = cached and verify_and_copy(cached, e.sha256 .. "\n") + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + refused = true + elseif not copy or not matches_index(copy, it.repo.name, e) then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + refused = true + else + table.insert(copies, copy) + original[copy] = it.repo.url .. "/" .. e.file + meta[copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, cache = cached } + end + ::continue:: + end + if refused then + finish(1) + end + install_copies(copies, original, opts, meta, has_builds) +end + +--- -f NAME...: install packages by name from the repositories, with +--- whatever dependencies they are missing. Like -l otherwise: an +--- installed other version of a named package needs -O. +function M.fetch(names, opts) + local indexes = load_indexes(opts) + local plan, refused, seen = {}, false, {} + for _, name in ipairs(names) do + local it = not seen[name] and choose(indexes, name, opts) + if seen[name] then + -- named twice: once is enough + elseif it then + seen[name] = true + table.insert(plan, it) + else + log.lg_printf(2, "%s is not in any repository.", name) + refused = true + end + end + if refused then + finish(1) + end + close_deps(plan, indexes, opts) + install_plan(plan, indexes, opts) +end + +--- -u [NAME...]: replace every installed package (or those named) whose +--- repository's index has a higher version, as -lO does (backups, +--- KEEP_OLD). Packages from repositories not configured are left alone. +function M.upgrade(names, opts) + local indexes = load_indexes(opts) + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local installed = installed_entries(opts) + local live0 = live_context(opts) + + local wanted, refused = nil, false + if #names > 0 then + wanted = {} + for _, name in ipairs(names) do + local found = false + for _, i in ipairs(installed) do + if i.name == name then + found = true + if not by_repo[built_from(live0, i.repo, i.name) or i.repo] then + log.lg_printf(2, "%s::%s is not in any configured repository.", + i.repo, i.name) + refused = true + end + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + refused = true + end + wanted[name] = true + end + end + if refused then + finish(1) + end + + local live = live_context(opts) + local plan = {} + for _, i in ipairs(installed) do + -- A package built from source stays on source (1k). + local src = built_from(live, i.repo, i.name) + local r = by_repo[src or i.repo] + local e = r and (not wanted or wanted[i.name]) and newest_in(r, i.name) + local it = e and plan_item(r, e, i.name, opts) + if it and vercmp(e.ver, i.ver) < 0 then + it = nil + elseif it and vercmp(e.ver, i.ver) == 0 then + -- Same version: rebuilt only if its traits changed. + local had = src and installed_traits(live, i) + if had and it.traits and had ~= table.concat(it.traits.list, "\n") + .. (#it.traits.list > 0 and "\n" or "") then + it.reason = "traits" + else + it = nil + end + end + if it then + it.auto, it.may_replace = i.auto, true + table.insert(plan, it) + end + end + if #plan == 0 then + log.lg_printf(3, "Nothing to do.") + finish(0) + end + close_deps(plan, indexes, opts) + install_plan(plan, indexes, opts) +end + +function M.install(gpkg_paths, opts) + -- From here on, the paths are the VERIFIED PRIVATE COPIES; the + -- caller's paths are only used for messages. + local copies, original = verify_all(gpkg_paths, opts) + install_copies(copies, original, opts, {}) +end + +--- Remove every named package as ONE atomic staged transaction. +--- Does not return on failure — exits. +function M.remove(pkg_names, opts) + -- Names, not files: resolve them against what's actually installed + -- (the old summary read them as .gpkg paths and printed + -- "unknown::pkg 0.0.0"). Anything not installed fails here, before + -- the prompt, not after the user has already said yes. + local installed = installed_entries(opts) + local entries, missing = {}, false + for _, name in ipairs(pkg_names) do + local found = false + for _, e in ipairs(installed) do + if e.name == name then + table.insert(entries, e) + found = true + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + missing = true + end + end + if missing then + os.exit(1) + end + + -- A name installed from more than one repo isn't resolved until + -- after the prompt, so only unambiguous names are checked here. + local count, removes = {}, {} + for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end + for _, e in ipairs(entries) do + if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end + end + check_plan(opts, {}, removes, os.exit) + + if not confirm(entries) then + os.exit(0) + end + + local ctx = begin_staged(opts) + + for _, pkg_name in ipairs(pkg_names) do + local repo = M.resolve_repo(ctx, pkg_name) + if not repo then + log.lg_printf(2, "Failed to resolve group for %s.", pkg_name) + abort_and_die(ctx) + end + + local status = istore.gl_remove_pkg(ctx, pkg_name, repo) + + if status == ffi.C.GL_REMOVE_OK then + log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name) + elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then + log.lg_printf(2, "%s::%s not found.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then + log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_INDEX then + log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name) + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + commit_or_die(ctx) + build.prune_kept(opts) + + report_done(ctx, os.exit) +end + +-- The builder's view of this module (lib/gpkg_build.lua). +init_build = function() + build.init({ + log = log, istore = istore, txn = txn, + finish = finish, shell_quote = shell_quote, + sha256_file = sha256_file, verify_and_copy = verify_and_copy, + download = download, live_context = live_context, + relation_lines = relation_lines, vercmp = vercmp, + pick_binary = pick_binary, installed_entries = installed_entries, + built_from = built_from, + require_trusted = function(path) require_trusted(path, HOST_KEYRING) end, + verbose = function() return isVerbose end, + gsandbox_path = (so_dir or ".") .. "/gsandbox", + gsandbox = shell_quote((so_dir or ".") .. "/gsandbox"), + lib_dir = so_dir and so_dir:gsub("/glacier$", "") or "lib", + }) +end + +return M diff --git a/lib/gpkg_common.lua.old8 b/lib/gpkg_common.lua.old8 new file mode 100644 index 0000000..1e489a3 --- /dev/null +++ b/lib/gpkg_common.lua.old8 @@ -0,0 +1,1737 @@ +-- lib/gpkg_common.lua +-- +-- Shared machinery between gpkg (per-user scope only) and syspkg +-- (system scope only). See SECURITY_DESIGN.txt section 7. +-- +-- The interface here is deliberately COARSE-GRAINED: M.install() and +-- M.remove() own the entire staged-transaction lifecycle +-- (gl_init_stage_context -> loop -> commit/abort), rather than +-- exporting fine-grained pieces that each caller then has to sequence +-- itself. That's what keeps the sequencing — and, once Checkpoint 2's +-- verification lands, the hash refusal matrix — in exactly ONE place +-- instead of duplicated across two binaries and drifting apart. +-- +-- What callers keep for themselves: +-- * argument parsing +-- * deciding WHICH scope they're allowed to request (gpkg never +-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag +-- for it", the capability isn't in its code path at all) +-- * their own privilege model (only syspkg runs elevated) +-- +-- Callers pass a `env` table on construction with the FFI handles and +-- shared state, so this module doesn't ffi.load() anything itself and +-- doesn't care where the .so's came from. + +local ffi = require("ffi") +local bit = require("bit") +local glacier_cdef = require("lib/glacier_cdef") +local build = require("lib/gpkg_build") + +local M = {} + +-- Module-level handles, set by M.init(). Kept here rather than passed +-- through every function because every function needs them. +local log, istore, txn, verify +local argv +local so_dir -- lib/glacier: the .so's and gsandbox +local init_build -- set at the end of this file +local isVerbose = false +local isQuiet = false -- -q: build output only to the log +local skipInstalled = false +local overwrite = false + +local txn_name = glacier_cdef.txn_name + +--- Initialise the module. Must be called before anything else. +-- env.log / env.istore / env.txn : ffi.load() handles +-- env.verify : libglacier_verify.so handle (installs) +-- env.argv : argv table (for usage messages) +-- env.so_dir : lib/glacier, where gsandbox is +function M.init(env) + log = env.log + istore = env.istore + txn = env.txn + verify = env.verify + argv = env.argv + so_dir = env.so_dir + init_build() +end + +--- Toggle flags the CLIs parse but this module acts on. +function M.set_verbose(v) isVerbose = v end +function M.set_quiet(v) isQuiet = v end +function M.set_skip_installed(v) skipInstalled = v end +function M.set_overwrite(v) overwrite = v end + +-- --------------------------------------------------------------------- +-- Manifest reading +-- --------------------------------------------------------------------- + +-- Quote a string for /bin/sh: wrap in single quotes, and turn each +-- embedded ' into '\''. Package paths come from the command line and +-- manifest entry names come from the archive, and syspkg runs all of +-- this as root — an unescaped ' in either is command execution. +local function shell_quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +--- name, repo and version ("MAJ.MIN.PAT", as the store names versions) +--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same +--- reader gl_install_pkg uses, so what is shown, compared and installed +--- can never disagree. nil if the manifest can't be read. +local function manifest_of(path) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return nil + end + local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo) + local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) + istore.gl_free_pkg(m) + return name, repo, ver +end + +-- --------------------------------------------------------------------- +-- Integrity verification (SECURITY_DESIGN.txt sections 3-4) +-- --------------------------------------------------------------------- + +-- Private working dir for verified copies, removed by finish(). +local private_dir = nil + +-- Backups written during this transaction but not yet committed +-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that +-- were never promoted, so an aborted upgrade leaves no stray backup. +local pending_backups = {} + +--- Exit, removing the private copies (and uncommitted backups) first. +--- Every exit on the install path goes through here. +local function finish(code) + for _, b in ipairs(pending_backups) do + os.remove(b.part) + end + pending_backups = {} + if private_dir then + os.execute("rm -rf " .. shell_quote(private_dir)) + private_dir = nil + end + os.exit(code) +end + +--- sha256 of a file as "", or nil. +local function sha256_file(path) + local f = io.open(path, "rb") + if not f then return nil end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = f:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + end + f:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + return ffi.string(hex) +end + +--- Copy `path` into the private dir, hashing it in the same pass, and +--- check the hash against `path`.sha256. Returns the private copy's path, +--- or nil plus a reason. +--- +--- Everything after this (summary, manifest read, gl_install_pkg) reads +--- ONLY the copy. Verifying the original and then installing it would +--- leave a gap where it could be swapped — and under syspkg that's root +--- reading a file whose directory another user may control. The copy +--- lives in a mktemp -d dir only the invoking user (root, for syspkg) +--- can write. +--- +--- Refusal matrix (section 4). A missing sidecar is treated exactly like +--- a mismatch: +--- repo == base -> always refuse, no exceptions +--- scope == SYS -> always refuse, any repo +--- scope == USR, repo != base -> refuse by default; the ONLY place +--- a future bypass flag may apply +--- No bypass exists, so today every row refuses and the repo (which we +--- couldn't trust before verifying anyway) never needs consulting. A +--- bypass, if ever added, must check scope and the VERIFIED manifest's +--- repo here, before anything else reads the file. +--- +--- A package fetched from a repository passes `vouched`, the "sha256:" +--- its signed index gives, in place of a sidecar. +local function verify_and_copy(path, vouched) + local sidecar = path .. ".sha256" + local sidecar_text = vouched + if not sidecar_text then + local sf = io.open(sidecar, "r") + if not sf then + return nil, "no sidecar " .. sidecar + end + sidecar_text = sf:read("*a") or "" + sf:close() + end + local expected = sidecar_text:match("^sha256:(%x+)%s*$") + if not expected or #expected ~= 64 then + return nil, "malformed sidecar " .. sidecar + end + expected = expected:lower() + + if not private_dir then + local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null") + private_dir = mk and mk:read("*l") + if mk then mk:close() end + if not private_dir or private_dir == "" then + private_dir = nil + return nil, "cannot create a private working directory" + end + end + + local src = io.open(path, "rb") + if not src then + return nil, "cannot open " .. path + end + + -- Unique per argument, so two packages with the same basename + -- (from different directories) can't collide. + local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0, + path:match("([^/]+)$")) + M._ncopies = (M._ncopies or 0) + 1 + local dst = io.open(copy_path, "wb") + if not dst then + src:close() + return nil, "cannot write " .. copy_path + end + + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + while true do + local chunk = src:read(65536) + if not chunk then break end + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + + if ffi.string(hex) ~= expected then + return nil, "hash mismatch (sidecar says " .. expected .. + ", file is " .. ffi.string(hex) .. ")" + end + + return copy_path, nil, sidecar_text +end + +-- --------------------------------------------------------------------- +-- Signatures (REPO_DESIGN.txt section 7) +-- --------------------------------------------------------------------- + +-- A keyring: repos.conf and the keys it lists, under `sysroot` (nil or +-- "/" = the running system). Read only by syspkg (gpkg reads the +-- system's until user repos). The signature on a local base package +-- (-l) is checked with the HOST's, even under -R (the build host's +-- trust, as KEEP_OLD). Repository operations (-y/-f/-u) use the +-- keyring of the system they act on: under -R, TARGET's own, since the +-- indexes they accept are TARGET's and TARGET checks them from then on. +local function keyring(sysroot) + local root = (sysroot or "/"):gsub("/+$", "") + return { root = root, conf = root .. "/etc/glacier/repos.conf", + keys = root .. "/etc/glacier/keys" } +end +local HOST_KEYRING = keyring(nil) + +ffi.cdef[[ +char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath"); +]] + +local function realpath(path) + local buf = ffi.new("char[4096]") + if ffi.C.gpkg_common_realpath(path, buf) == nil then return nil end + return ffi.string(buf) +end + +-- nil if `path`, every ancestor of it, and every ancestor of its real +-- path are root-owned and not group/world-writable (as syspkg's own +-- lib/: a key a non-root user could swap is no key). Else the path at +-- fault, plus true if it is missing (or can't be resolved). +local function untrusted(path) + local function chain(p) + while true do + local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null") + local line = f and f:read("*l") + if f then f:close() end + local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$") + if not uid then return p, true end + if tonumber(uid) ~= 0 + or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then + return p + end + if p == "/" then return nil end + p = p:match("^(.*)/[^/]*$") + if p == "" then p = "/" end + end + end + local bad, missing = chain(path) + if bad then return bad, missing end + local real = realpath(path) + if not real then return path, true end + return chain(real) +end + +-- Stop the run unless `path`, part of keyring `kr`, is trusted (as +-- untrusted() says) and, in another root, resolves inside it: TARGET's +-- etc/glacier/repos.conf -> /etc/glacier/repos.conf would read the +-- host's file as TARGET's. +local function require_trusted(path, kr) + local bad, missing = untrusted(path) + if bad and missing then + log.lg_printf(2, "Cannot read %s.", bad) + finish(1) + elseif bad then + log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.", + path, bad) + finish(1) + end + if kr.root ~= "" then + local real, root = realpath(path), realpath(kr.root) + if not (real and root and real:sub(1, #root + 1) == root .. "/") then + log.lg_printf(2, "Refusing %s: it resolves outside %s.", path, kr.root) + finish(1) + end + end +end + +-- Whether keyring `kr`'s repos.conf exists, having checked it is +-- trusted (else the run stops: the admin's configuration is at fault, +-- not a package). +local function repos_conf_present(kr) + local f, _, code = io.open(kr.conf, "r") + if f then f:close() end + if not f and code == 2 then return false end + require_trusted(kr.conf, kr) + return true +end + +-- The public keys keyring `kr` trusts for `repo`, read once per run: +-- { { name, pub }... }. A missing repos.conf trusts nothing. A +-- repos.conf or listed key that is untrusted or can't be read stops the +-- run: that is the admin's configuration, not the package, at fault. +local trusted_keys_cache = {} +local function trusted_keys(repo, kr) + local cache_key = kr.conf .. "\n" .. repo + if trusted_keys_cache[cache_key] then return trusted_keys_cache[cache_key] end + local keys = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[4096]") + local st = tonumber(istore.gl_conf_repo_keys(kr.conf, repo, buf, 4096)) + if st == 1 or st == 3 or st == 4 or st == 5 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name in ffi.string(buf):gmatch("([^\n]+)\n") do + local path = kr.keys .. "/" .. name .. ".pub" + local pub = ffi.new("gl_sign_pubkey_t") + require_trusted(path, kr) + if verify.gl_sign_read_pubkey(path, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + table.insert(keys, { name = name, pub = pub }) + end + end + trusted_keys_cache[cache_key] = keys + return keys +end + +-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very +-- bytes the copy was checked against) by a key trusted for `repo`. The +-- key is picked by the signature's keynum, never by trying each one. +local function signed_for(path, sidecar_text, repo) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then + return false + end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, HOST_KEYRING)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0 + end + end + return false +end + +--- Verify every package up front, before the summary is even shown. +--- Returns the private copies, plus a copy -> original map for messages. +--- +--- In system scope, a package whose manifest says base must also have a +--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the +--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg +--- does). +local function verify_all(gpkg_paths, opts) + local copies, original = {}, {} + local refused = false + + for _, p in ipairs(gpkg_paths) do + local copy, why, sidecar_text = verify_and_copy(p) + if copy and not manifest_of(copy) then + log.lg_printf(2, "Cannot read the manifest of %s.", p) + refused = true + copy = nil + end + if copy and opts.scope == ffi.C.GL_SCOPE_SYS then + local name, repo = manifest_of(copy) + if repo == "base" and not signed_for(p, sidecar_text, repo) then + log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.", + repo, name, repo) + refused = true + copy = nil + end + end + if copy then + table.insert(copies, copy) + original[copy] = p + elseif why then + log.lg_printf(2, "Refusing %s: %s.", p, why) + refused = true + end + end + + if refused then + finish(1) + end + return copies, original +end + +-- --------------------------------------------------------------------- +-- Confirmation summary +-- --------------------------------------------------------------------- + +--- Print the summary for `entries` ({repo, name, ver} each) and ask. +local function confirm(entries) + log.lg_printf(0, "SUMMARY:") + print("==============================") + print("") + for _, e in ipairs(entries) do + print(string.format(" * %s::%s\t\t%-16s", + e.repo or "unknown", e.name, e.ver or "unknown")) + end + print("") + io.write("Proceed? (y/N): ") + io.stdout:flush() + + local response = io.read("*l") + if not response then + return false + end + response = response:lower() + return response == "y" or response == "yes" +end + +--- Installed packages, from the live index for this scope: a list of +--- {repo, name, ver, auto}. The index's `current` file holds one +--- `repo::name::version::auto|explicit` line per package (index files +--- written before 2026-10-05 stop at the version). +--- A live context for opts' scope (and install root: syspkg -R only). +local function live_context(opts) + local ctx = ffi.new("gl_context_t") + if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then + finish(1) -- the library said why + end + return ctx +end + +-- The entries of an index `current` file ({} if there is none). +local function read_index_file(path) + local f = io.open(path, "r") + local out = {} + if not f then return out end + for line in f:lines() do + local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$") + if repo then + local ver, kind = rest:match("^(.-)::(%a+)$") + table.insert(out, { repo = repo, name = name, ver = ver or rest, + auto = kind == "auto" }) + end + end + f:close() + return out +end + +local function installed_entries(opts) + local ctx = live_context(opts) + return read_index_file(ffi.string(ctx.index_path) .. "/current") +end + +-- --------------------------------------------------------------------- +-- Repo resolution +-- --------------------------------------------------------------------- + +function M.resolve_repo(ctx, pkg_name) + local list = istore.gl_find_pkg_repos(ctx, pkg_name) + + if list.count == 0 then + log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name) + istore.gl_free_repo_list(list) + return nil + end + + if list.count == 1 then + local repo = ffi.string(list.repos[0]) + istore.gl_free_repo_list(list) + return repo + end + + log.lg_printf(1, "Multiple instances of %s found:", pkg_name) + for i = 0, tonumber(list.count) - 1 do + print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name)) + end + print("") + io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ") + io.stdout:flush() + local input = io.read("*l") + local choice = tonumber(input) + + if not choice or choice < 1 or choice > tonumber(list.count) then + log.lg_printf(2, "Invalid selection.") + istore.gl_free_repo_list(list) + return nil + end + + local repo = ffi.string(list.repos[choice - 1]) + istore.gl_free_repo_list(list) + return repo +end + +-- --------------------------------------------------------------------- +-- Single-package install (with reinstall-if-present handling) +-- --------------------------------------------------------------------- + +local function install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + if not pkg_name then + log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path) + finish(1) + end + + if isVerbose then + log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s", + pkg_name, version_str, manifest_repo, gpkg_path) + end + + local status = istore.gl_install_pkg(ctx, gpkg_path) + + if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then + if skipInstalled then + log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str) + return tonumber(ffi.C.GL_INSTALL_SKIPPED) + end + + log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str) + + local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo) + + if rm_status ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).", + manifest_repo, pkg_name, tostring(tonumber(rm_status))) + return tonumber(rm_status) + end + + status = istore.gl_install_pkg(ctx, gpkg_path) + if status == ffi.C.GL_INSTALL_OK then + -- M.install logs the one "staged from" line. + return 0 + else + log.lg_printf(2, "Reinstall of %s-%s failed (error %s).", + pkg_name, version_str, tostring(tonumber(status))) + return tonumber(status) + end + + elseif status == ffi.C.GL_INSTALL_OK then + return 0 + end + + return tonumber(status) +end + +-- --------------------------------------------------------------------- +-- Transaction lifecycle +-- --------------------------------------------------------------------- + +--- Open a staged transaction for the given scope. Exits on failure with +--- a scope-appropriate message. `scope_label` is used only in the +--- lock-contention message ("for UID 1000" vs "for the system scope"). +local function begin_staged(opts) + local scope_label = opts.scope_label + local ctx = ffi.new("gl_context_t") + local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") + + if txn_st ~= ffi.C.GL_TXN_OK then + if txn_st == ffi.C.GL_TXN_ERR_LOCK then + log.lg_printf(2, + "Another glacier transaction is already in progress %s.", + scope_label) + else + log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st)) + end + finish(1) + end + + ctx.strict = opts.strict and 1 or 0 + return ctx +end + +--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt. +--- The library prints each problem; this exits if there were any. The +--- commit checks again (gl_check_txn), which is what covers a removal +--- whose repo is only chosen after the prompt. +local function check_plan(opts, adds, removes, exit) + local live = live_context(opts) + live.strict = opts.strict and 1 or 0 + live.overwrite = overwrite and 1 or 0 + local a = ffi.new("const char *[?]", #adds + 1) + for i, p in ipairs(adds) do a[i - 1] = p end + local r = ffi.new("const char *[?]", #removes + 1) + for i, id in ipairs(removes) do r[i - 1] = id end + local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes)) + if problems < 0 then + log.lg_printf(2, "Cannot read the package store to check dependencies.") + end + if problems ~= 0 then exit(1) end +end + +--- Commit, or abort-and-exit on failure. +local function commit_or_die(ctx) + local commit_st = txn.gl_commit_transaction(ctx) + if commit_st == ffi.C.GL_TXN_ERR_DEPS then + -- The library already said what's wrong, one line each. + txn.gl_abort_transaction(ctx) + finish(1) + elseif commit_st ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st)) + txn.gl_abort_transaction(ctx) + finish(1) + end +end + +--- The last line of a committed transaction. If the link pass refused +--- any path (each refusal is already printed above), the transaction is +--- committed but did not fully succeed: an error, and exit status 1. +local function report_done(ctx, exit) + local n = tonumber(ctx.link_refusals) + if n > 0 then + log.lg_printf(2, "%s %s not linked.", tostring(n), + n == 1 and "path was" or "paths were") + exit(1) + end + log.lg_printf(3, "Completed with no errors.") + exit(0) +end + +--- Abort the transaction and exit non-zero. Every failure path inside a +--- staged loop goes through here so live state is never left partially +--- mutated. +local function abort_and_die(ctx) + txn.gl_abort_transaction(ctx) + finish(1) +end + +-- --------------------------------------------------------------------- +-- Repository indexes (REPO_DESIGN.txt section 5) +-- --------------------------------------------------------------------- + +ffi.cdef[[ +int gpkg_common_getpid(void) asm("getpid"); +int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod"); +int gpkg_common_close(int fd) asm("close"); +]] + +-- Largest index accepted: what gl_sign_verify will check. +local MAX_INDEX = 64 * 1024 * 1024 + +-- A whole file, or nil if it is missing, unreadable or over `max`. +local function read_capped(path, max) + local f = io.open(path, "rb") + if not f then return nil end + local data = f:read(max + 1) or "" + f:close() + if #data > max then return nil end + return data +end + +-- Fetch URL/NAME into `dest`. https goes through curl, refusing any +-- other protocol, redirects included; file:// is a plain copy of an +-- absolute path. True on success. +local function fetch(url, name, dest) + local path = url:match("^file://(/.*)$") + if path then + local data = read_capped(path .. "/" .. name, MAX_INDEX) + local f = data and io.open(dest, "wb") + if not f then return false end + local ok = f:write(data) + f:close() + return ok ~= nil + end + if not url:match("^https://") then return false end + local ok = os.execute("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 --max-filesize " .. MAX_INDEX .. + " -o " .. shell_quote(dest) .. " -- " .. + shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1") + return ok == true or ok == 0 +end + +-- Whether `text` is signed by `sig_path`, with a key keyring `kr` +-- trusts for `repo` (picked by keynum, as signed_for). +local function index_signed(text, sig_path, repo, kr) + local sig = ffi.new("gl_sign_sig_t") + if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end + local keynum = ffi.string(sig.keynum, 8) + for _, k in ipairs(trusted_keys(repo, kr)) do + if ffi.string(k.pub.keynum, 8) == keynum then + return verify.gl_sign_verify(k.pub, sig, + ffi.cast("const uint8_t *", text), #text) == 0 + end + end + return false +end + +-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the +-- gl_index_parse status. +local function parse_index(text, repo) + local idx = ffi.new("gl_index_t") + local st = tonumber(istore.gl_index_parse(text, #text, repo, idx)) + if st ~= 0 then return nil, st end + local r = { serial = idx.serial, valid_until = idx.valid_until, + npkgs = tonumber(idx.npkgs) } + istore.gl_index_free(idx) + return r +end + +-- Refresh one repository's index into `dir` (/repos): fetch, +-- verify, parse, refuse a rollback or an expired index, then rename +-- over the accepted copy, checking signatures with keyring `kr`. Any +-- failure keeps the accepted copy, prints one line and returns false. +local function refresh_one(repo, url, dir, file_mode, kr) + local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid()) + local tmp_sig = tmp .. ".sig" + local function fail(fmt, ...) + os.remove(tmp) + os.remove(tmp_sig) + log.lg_printf(2, fmt, ...) + return false + end + + local text + if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then + text = read_capped(tmp, MAX_INDEX) + end + if not text then + return fail("Cannot fetch the index for %s.", repo) + end + -- The signature is checked over the very bytes parsed below. + if not index_signed(text, tmp_sig, repo, kr) then + return fail("Index for %s is not signed by a key trusted for %s.", repo, repo) + end + local new, st = parse_index(text, repo) + if st == 2 then + return fail("Index fetched for %s is the index of another repository.", repo) + elseif not new then + return fail("Malformed index for %s.", repo) + end + + local stored = dir .. "/" .. repo .. ".idx" + local old_text = read_capped(stored, MAX_INDEX) + local unchanged = false + if old_text then + local old = parse_index(old_text, repo) + if not old then + return fail("Malformed %s.", stored) + end + if new.serial < old.serial then + return fail("Index for %s is older than the one already accepted.", repo) + elseif new.serial == old.serial then + if text ~= old_text then + return fail("Index for %s has the serial of the one already accepted, but other contents.", repo) + end + unchanged = true + end + elseif io.open(stored, "rb") then + return fail("Cannot read %s.", stored) + end + if new.valid_until <= os.time() then + return fail("Index for %s has expired.", repo) + end + + local serial = string.format("%d", tonumber(new.serial)) + if unchanged then + os.remove(tmp) + os.remove(tmp_sig) + if isVerbose then + log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial) + end + return true + end + -- Never written in place (bug 25): renamed over the old copy. + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 + or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0 + or not os.rename(tmp_sig, stored .. ".sig") + or not os.rename(tmp, stored) then + return fail("Cannot write %s.", stored) + end + if isVerbose then + log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial, + tostring(new.npkgs), new.npkgs == 1 and "package" or "packages") + end + return true +end + +--- Refresh the index of every repository repos.conf gives a url +--- (REPO_DESIGN.txt section 5), into the scope's /repos, holding +--- the scope's lock. Every repository is tried; true if all succeeded. +--- Exits if there is nothing to refresh or the setup is at fault. +-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install +-- Every entry with a url in keyring `kr`'s repos.conf, in priority +-- order: { name, url }. Exits if there is none, or repos.conf is +-- malformed. +local function configured_remotes(kr) + local remotes = {} + if repos_conf_present(kr) then + local buf = ffi.new("char[65536]") + if tonumber(istore.gl_conf_repos(kr.conf, buf, 65536)) ~= 0 then + log.lg_printf(2, "Malformed %s.", kr.conf) + finish(1) + end + for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do + if url ~= "" then + table.insert(remotes, { name = name, url = url }) + end + end + end + if #remotes == 0 then + log.lg_printf(2, "No remote repositories are configured.") + finish(1) + end + return remotes +end + +function M.refresh(opts) + local kr = keyring(opts.sysroot) + local remotes = configured_remotes(kr) + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) -- the library said why + end + if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then + log.lg_printf(2, "Another glacier transaction is already in progress %s.", + opts.scope_label) + finish(1) + end + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + log.lg_printf(0, "Syncing all repositories...") + local all = true + for _, r in ipairs(remotes) do + all = refresh_one(r.name, r.url, ffi.string(dir), file_mode, kr) and all + end + ffi.C.gpkg_common_close(ctx.lock_fd) + if all then + log.lg_printf(3, "All repositories synced successfully.") + end + return all +end + +-- --------------------------------------------------------------------- +-- Public: whole-batch install / remove +-- --------------------------------------------------------------------- + +--- Install every package in gpkg_paths as ONE atomic staged transaction. +--- Any failure aborts the whole batch, leaving live state untouched. +--- Does not return on failure — exits. +-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS +-- opts.uid : uid for USR scope (ignored for SYS) +-- opts.scope_label : human string for the lock-contention message +-- opts.sysroot : install root (syspkg -R; nil = the running system) +-- opts.strict : refuse, before committing, anything the link pass +-- would refuse (syspkg --strict, implied by -R) +--- KEEP_OLD from glacier.conf: how many backups of replaced versions to +--- keep per package. There is no default — it ships as 1 in +--- glacier.conf, and an operation that would replace a version refuses +--- to run if it's missing or not a whole number. +local function keep_old() + local n = ffi.new("int[1]") + local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n)) + if st == 1 then + log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.") + elseif st == 2 then + log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.") + elseif st == 3 or (st == 0 and n[0] < 0) then + log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.") + end + if st ~= 0 or n[0] < 0 then finish(1) end + return tonumber(n[0]) +end + +-- Install verified private copies as one transaction. original[copy] +-- names each for messages. meta[copy], for packages fetched from a +-- repository (else nil): +-- auto : record it as installed as a dependency +-- may_replace : replace an installed other version without -O +-- (-u, and dependency upgrades) +-- dep : marked as a dependency in the summary +-- cache : the downloaded file, deleted once committed +-- src : built from this recipe repository (.glacier-src) +-- `confirmed`: the plan was already shown and accepted (builds ask +-- before building, so not again here). +local function install_copies(gpkg_paths, original, opts, meta, confirmed) + -- A different version of a package that's already installed is a + -- REPLACEMENT (upgrade or downgrade). Only -O permits it; without + -- -O it's refused here, before the prompt. + local installed = installed_entries(opts) + local entries, replacing, refused = {}, {}, false + for _, p in ipairs(gpkg_paths) do + local name, repo, ver = manifest_of(p) + local m = meta[p] or {} + local e = { repo = repo, name = name, ver = ver } + for _, i in ipairs(installed) do + if i.name == name and i.repo == repo and i.ver ~= ver then + if overwrite or m.may_replace then + replacing[p] = i + e.ver = i.ver .. " -> " .. ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, name, i.ver) + refused = true + end + end + end + if m.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + + check_plan(opts, gpkg_paths, {}, finish) + + local keep = next(replacing) and keep_old() or 0 + + if not confirmed and not confirm(entries) then + finish(0) + end + + local ctx = begin_staged(opts) + ctx.overwrite = overwrite and 1 or 0 + local staged = 0 + + -- Replacements: back up the installed version (from LIVE, written + -- under a .part name and only promoted after a successful commit), + -- then remove it from the stage so the new version installs into + -- a clean slot in the same transaction. + local live = live_context(opts) + local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup" + for _, old in pairs(replacing) do + if keep > 0 then + local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name) + local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver) + local part = final .. ".part" + if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then + log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + table.insert(pending_backups, { part = part, final = final, dir = dir, old = old }) + end + if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then + log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver) + abort_and_die(ctx) + end + end + + for _, gpkg_path in ipairs(gpkg_paths) do + local status = install_with_reinstall(ctx, gpkg_path) + local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path) + local abs_path = original[gpkg_path] + + if status == 0 then + staged = staged + 1 + if (meta[gpkg_path] or {}).auto + and istore.gl_set_pkg_auto(ctx, manifest_repo, pkg_name, true) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as a dependency.", + manifest_repo, pkg_name) + abort_and_die(ctx) + end + local src = (meta[gpkg_path] or {}).src + if src and istore.gl_set_pkg_src(ctx, manifest_repo, pkg_name, src) ~= 0 then + log.lg_printf(2, "Cannot record %s::%s as built from %s.", + manifest_repo, pkg_name, src) + abort_and_die(ctx) + end + log.lg_printf(3, "%s::%s-%s: staged from %s.", + manifest_repo, pkg_name, version_str, abs_path) + elseif status == 1 then + log.lg_printf(2, "%s::%s: Failed to open package archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 2 then + log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 3 then + log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.", + manifest_repo, pkg_name, abs_path) + abort_and_die(ctx) + elseif status == 4 then + log.lg_printf(2, "%s::%s: Failed to add entry to index.", + manifest_repo, pkg_name) + abort_and_die(ctx) + elseif status == 6 then + -- GL_INSTALL_SKIPPED: not a failure, keep going + elseif status == 7 then + -- GL_INSTALL_ERR_SCOPE: the library refused this + -- package for this scope (base-repo package under + -- user scope). The library already logged the + -- specific reason; don't second-guess it here. + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + -- Everything was skipped (-S, already up to date): the stage is + -- identical to live, so don't commit it. A commit isn't free — it + -- swaps the trees and re-links the whole store, re-printing every + -- standing link conflict for packages this command never touched. + if staged == 0 then + txn.gl_abort_transaction(ctx) + log.lg_printf(3, "Nothing to do.") + finish(0) + end + + commit_or_die(ctx) + + -- Committed: promote the backups, give each a sidecar (so it's an + -- installable, verifiable package), and keep only the newest KEEP_OLD. + for _, b in ipairs(pending_backups) do + if os.rename(b.part, b.final) then + local hex = sha256_file(b.final) + local sf = hex and io.open(b.final .. ".sha256", "w") + if sf then + sf:write("sha256:" .. hex .. "\n") + sf:close() + end + istore.gl_prune_backups(b.dir, keep) + log.lg_printf(0, "Backed up %s::%s %s to %s", + b.old.repo, b.old.name, b.old.ver, b.final) + else + log.lg_printf(1, "Could not keep the backup of %s::%s %s.", + b.old.repo, b.old.name, b.old.ver) + end + end + pending_backups = {} + + for _, p in ipairs(gpkg_paths) do + if meta[p] and meta[p].cache then os.remove(meta[p].cache) end + if meta[p] and meta[p].src then + local name, repo, ver = manifest_of(p) + build.keep(opts, p, repo, name, ver) + end + end + build.prune_kept(opts) + + report_done(ctx, finish) +end + +-- --------------------------------------------------------------------- +-- -f / -u: packages from the repositories (REPO_DESIGN.txt section 6) +-- --------------------------------------------------------------------- + +-- -1, 0 or 1 as version a is below, equal to or above b ("MAJ.MIN.PAT"). +local function vercmp(a, b) + local x = { a:match("^(%d+)%.(%d+)%.(%d+)") } + local y = { b:match("^(%d+)%.(%d+)%.(%d+)") } + for k = 1, 3 do + local m, n = tonumber(x[k]) or 0, tonumber(y[k]) or 0 + if m ~= n then return m < n and -1 or 1 end + end + return 0 +end + +-- A package's relations as an index lists them: "NAME VER\n" lines. +local function relation_lines(list, name_field, ver_field) + local out = {} + local k = 0 + while list ~= nil and list[k][name_field] ~= nil do + local v = list[k][ver_field] + table.insert(out, string.format("%s %d.%d.%d\n", + ffi.string(list[k][name_field]), v.maj, v.min, v.pat)) + k = k + 1 + end + return table.concat(out) +end + +-- Whether the manifest of `path` (read by the library) says exactly what +-- its index entry `e` of repository `repo` says: NAME, VER, PKG_REPO, +-- DEPS and CONFS. A package is from `repo` because that repo's signed +-- index lists it AND it says so, never because it says so. +local function matches_index(path, repo, e) + local m = ffi.new("gl_pkg_t") + if istore.gl_read_pkg_manifest(path, m) ~= 0 then + return false + end + local ok = ffi.string(m.pkg_name) == e.name + and ffi.string(m.pkg_repo) == repo + and string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat) == e.ver + and relation_lines(m.pkg_dependencies, "dep_name", "dep_ver") == e.deps + and relation_lines(m.pkg_conflicts, "conf_name", "conf_ver") == e.confs + istore.gl_free_pkg(m) + return ok +end + +-- The accepted index of every configured repository, freshly refreshed +-- (decision 10d: any failure refuses the operation). In priority order: +-- { name, url, pkgs = { { name, ver, file, sha256, size, deps, confs }... } }. +-- User scope never fetches from base (the library refuses it there). +local function load_indexes(opts) + local remotes = configured_remotes(keyring(opts.sysroot)) + if not M.refresh(opts) then + finish(1) + end + local ctx = live_context(opts) + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then + finish(1) + end + local out = {} + for _, r in ipairs(remotes) do + if opts.scope ~= ffi.C.GL_SCOPE_USR or (r.name ~= "base" and r.name ~= "base-src") then + local path = ffi.string(dir) .. "/" .. r.name .. ".idx" + local text = read_capped(path, MAX_INDEX) + local idx = ffi.new("gl_index_t") + if not text or istore.gl_index_parse(text, #text, r.name, idx) ~= 0 then + log.lg_printf(2, "Malformed %s.", path) + finish(1) + end + local pkgs = {} + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + table.insert(pkgs, { + name = ffi.string(p.name), ver = ffi.string(p.ver), + file = ffi.string(p.file), sha256 = ffi.string(p.sha256), + size = tonumber(p.size), deps = ffi.string(p.deps), + confs = ffi.string(p.confs), + build_deps = ffi.string(p.build_deps), + traits = ffi.string(p.traits), + }) + end + istore.gl_index_free(idx) + -- A recipe repository, "X-src", builds packages of X. + local target = r.name:match("^(.+)%-src$") + table.insert(out, { name = r.name, url = r.url, pkgs = pkgs, + src = target ~= nil, target = target }) + end + end + return out +end + +-- The highest version of `name` that repository `r` serves, or nil. +local function newest_in(r, name) + local best + for _, e in ipairs(r.pkgs) do + if e.name == name and (not best or vercmp(e.ver, best.ver) > 0) then + best = e + end + end + return best +end + +-- Which repository `name` comes from: the first, by priority, that +-- serves it, at its highest version. repo, entry, or nil. +local function pick(indexes, name) + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then return r, e end + end +end + +-- The first binary repository (by priority) serving `name`, at its +-- highest version: build layers come only from binaries. +local function pick_binary(indexes, name) + for _, r in ipairs(indexes) do + local e = not r.src and newest_in(r, name) + if e then return r, e end + end +end + +-- A plan item for entry `e` of repository `r`: its effective +-- dependencies (a recipe's IFs resolved against its traits) in it.deps, +-- and for a build, it.traits (gpkg_build's M.traits). +local function plan_item(r, e, name, opts) + local it = { repo = r, entry = e, name = name, deps = e.deps } + if r.src then + it.traits = build.traits(name, e.traits, opts) + it.deps = build.effective(e.deps, it.traits) + end + return it +end + +-- How a plan item is shown: "extra::curl 8.9.0", or for a build +-- "extra-src::curl 8.9.0 [+ssl -ldap] (build)". +local function item_label(it) + local s = string.format("%s::%s %s", it.repo.name, it.name, it.entry.ver) + if it.traits then + s = s .. (it.traits.show ~= "" and (" " .. it.traits.show) or "") .. " (build)" + end + return s +end + +-- Which repository a name given on the command line comes from +-- (BUILD_DESIGN.txt 1f): the only one serving it, or, with several +-- (binary or -src), the one the user picks; Enter takes the first by +-- priority. End of input or an invalid answer refuses. nil if no +-- repository serves it. +local function choose(indexes, name, opts) + local cands = {} + for _, r in ipairs(indexes) do + local e = newest_in(r, name) + if e then table.insert(cands, plan_item(r, e, name, opts)) end + end + if #cands <= 1 then return cands[1] end + log.lg_printf(0, "%s is available from more than one repository:", name) + for k, it in ipairs(cands) do + print(string.format(" %d) %s", k, item_label(it))) + end + io.write(string.format("Select a repository [1-%d, Enter = 1]: ", #cands)) + io.stdout:flush() + local answer = io.read("*l") + local k = answer == "" and 1 or tonumber(answer or "") + if not k or not cands[k] then + log.lg_printf(2, "Invalid selection.") + finish(1) + end + return cands[k] +end + +-- The PKG_TRAITS lines ("ssl\n-ldap\n") of installed entry `i`, from +-- the manifest saved in its version dir; "" if it has none. +local function installed_traits(ctx, i) + local path = string.format("%s/%s/%s/%s-%s/.glacier-manifest", + ffi.string(ctx.store_path), i.repo, i.name, i.name, i.ver) + local m = ffi.new("gl_pkg_t") + if istore.gl_gpm2gpkg(path, m) ~= 0 then return "" end + local t = m.pkg_traits ~= nil and ffi.string(m.pkg_traits) or "" + istore.gl_free_pkg(m) + return t +end + +-- The recipe repository an installed package was built from, or nil. +local function built_from(ctx, repo, name) + local buf = ffi.new("char[256]") + if tonumber(istore.gl_pkg_src(ctx, repo, name, buf, 256)) == 1 then + return ffi.string(buf) + end +end + +-- Add the missing dependencies of everything in `plan` (and theirs), +-- ROADMAP 2.3's closure. A dependency already met (in this scope, or +-- for a user, by the system) is left alone; one installed at too old a +-- version is upgraded from its own repository, keeping its auto or +-- explicit mark; one not installed comes from pick(), recorded auto. +-- Whatever can't be met is left for gl_check_plan to report. +local function close_deps(plan, indexes, opts) + local planned = {} + for _, it in ipairs(plan) do planned[it.name] = it end + local installed = installed_entries(opts) + local system = {} + if opts.scope == ffi.C.GL_SCOPE_USR then + system = read_index_file("/glacier/sys/index/current") + end + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local live = live_context(opts) + + local k = 1 + while k <= #plan do + for dname, dver in plan[k].deps:gmatch("(%S+) (%S+)\n") do + local met, old = planned[dname] ~= nil, nil + for _, i in ipairs(installed) do + if i.name == dname then + if vercmp(i.ver, dver) >= 0 then met = true end + old = old or i + end + end + for _, i in ipairs(system) do + if i.name == dname and vercmp(i.ver, dver) >= 0 then met = true end + end + if not met then + local r, e + if old then + -- Its own repository: the recipe one if it + -- was built from source (1k). + r = by_repo[built_from(live, old.repo, dname) or old.repo] + e = r and newest_in(r, dname) + else + r, e = pick(indexes, dname) + end + if e and vercmp(e.ver, dver) >= 0 then + local it = plan_item(r, e, dname, opts) + it.dep, it.auto, it.may_replace = true, not old or old.auto, old ~= nil + table.insert(plan, it) + planned[dname] = it + end + end + end + k = k + 1 + end +end + +-- Download `e` (an index entry of repository `r`) into the scope's +-- cache, hashing it on the way, unless a cached copy already matches. +-- Never more than the index's SIZE is read. The path, or nil plus +-- true if something was fetched but is not what the index lists. +local function download(ctx, r, e, file_mode) + local dir = ffi.new("char[4096]") + if txn.gl_scope_cache_dir(ctx, r.name, dir) ~= 0 then + finish(1) -- the library said why + end + local want = e.sha256:match("^sha256:(%x+)$") + local dest = ffi.string(dir) .. "/" .. e.file + if sha256_file(dest) == want then + return dest + end + + local src + local path = r.url:match("^file://(/.*)$") + if path then + src = io.open(path .. "/" .. e.file, "rb") + elseif r.url:match("^https://") then + src = io.popen("curl -sf --proto =https --proto-redir =https" .. + " --connect-timeout 30 -- " .. + shell_quote(r.url .. "/" .. e.file) .. " 2>/dev/null", "r") + end + if not src then return nil end + local tmp = string.format("%s/.%s.%d", ffi.string(dir), e.file, + ffi.C.gpkg_common_getpid()) + local dst = io.open(tmp, "wb") + if not dst then + src:close() + return nil + end + local hctx = ffi.new("gl_sha256_ctx_t") + verify.gl_sha256_init(hctx) + local n = 0 + while n <= e.size do + local chunk = src:read(math.min(65536, e.size + 1 - n)) + if not chunk then break end + n = n + #chunk + verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) + dst:write(chunk) + end + src:close() + dst:close() + local digest = ffi.new("uint8_t[32]") + local hex = ffi.new("char[65]") + verify.gl_sha256_final(hctx, digest) + verify.gl_sha256_to_hex(digest, hex) + if n ~= e.size or ffi.string(hex) ~= want then + os.remove(tmp) + return nil, n > 0 + end + if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0 or not os.rename(tmp, dest) then + os.remove(tmp) + return nil + end + return dest +end + +-- The machine key (BUILD_DESIGN.txt section 9): base packages built +-- here are signed with it, and pass the base rule only if the admin +-- lists "local" among base's keys in repos.conf. Made the first time a +-- base-src build is planned: the public half in /etc/glacier/keys, the +-- secret one (0600) in /glacier/sys/keys. +local LOCAL_PUB = "/etc/glacier/keys/local.pub" + +local function machine_seckey() + local dir = ffi.new("char[4096]") + if txn.gl_scope_state_dir(live_context({ scope = ffi.C.GL_SCOPE_SYS, uid = 0 }), + "keys", dir) ~= 0 then + finish(1) -- the library said why + end + return ffi.string(dir) .. "/local.sec" +end + +-- Exits unless the machine key exists (making it if neither half +-- does) and repos.conf trusts it for base. `id` names the build. +local function require_machine_key(id) + local sec = machine_seckey() + local function present(path) + local f = io.open(path, "rb") + if f then f:close() end + return f ~= nil + end + local has_pub, has_sec = present(LOCAL_PUB), present(sec) + if not has_pub and not has_sec then + os.execute("mkdir -p -m 755 /etc/glacier/keys") + if verify.gl_sign_generate(LOCAL_PUB, sec, "glacier machine key") ~= 0 then + log.lg_printf(2, "Cannot make the machine key %s.", LOCAL_PUB) + finish(1) + end + ffi.C.gpkg_common_chmod(LOCAL_PUB, tonumber("644", 8)) + log.lg_printf(0, "Made the machine key %s.", LOCAL_PUB) + elseif has_pub ~= has_sec then + log.lg_printf(2, "%s and %s must both exist, or neither.", LOCAL_PUB, sec) + finish(1) + end + local pub = ffi.new("gl_sign_pubkey_t") + if verify.gl_sign_read_pubkey(LOCAL_PUB, pub) ~= 0 then + log.lg_printf(2, "Malformed %s.", LOCAL_PUB) + finish(1) + end + for _, k in ipairs(trusted_keys("base", HOST_KEYRING)) do + if ffi.string(k.pub.keynum, 8) == ffi.string(pub.keynum, 8) then + return sec + end + end + log.lg_printf(2, "%s needs the key \"local\" trusted for base.", id) + finish(1) +end + +-- Sign the sidecar text of a base package built here with the machine +-- key, then hold it to the base rule like any other (signed_for). +local function sign_built_base(copy, sidecar_text, name) + local side = copy .. ".sha256" + local f = io.open(side, "wb") + if not f or not f:write(sidecar_text) then + log.lg_printf(2, "Cannot write %s.", side) + finish(1) + end + f:close() + if verify.gl_sign_file(machine_seckey(), side, side .. ".sig") ~= 0 + or not signed_for(copy, sidecar_text, "base") then + log.lg_printf(2, "base::%s is not signed by a key trusted for base.", name) + finish(1) + end +end + +-- A plan with builds is shown and confirmed BEFORE anything is built +-- (builds are long): the same refusals install_copies would make +-- first, then the summary and the prompt. +local function confirm_builds(plan, indexes, opts) + build.check(opts) + local planned = {} + for _, it in ipairs(plan) do + if it.traits then planned[it.name] = { ver = it.entry.ver, deps = it.deps } end + end + for _, it in ipairs(plan) do + if it.traits then build.check_layers(it, indexes, planned, opts) end + if it.traits and it.repo.target == "base" then + require_machine_key(item_label(it)) + end + end + local installed = installed_entries(opts) + local entries, refused = {}, false + for _, it in ipairs(plan) do + local repo = it.repo.target or it.repo.name + local e = { repo = it.repo.name, name = it.name, ver = it.entry.ver } + for _, i in ipairs(installed) do + if i.name == it.name and i.repo == repo and i.ver ~= it.entry.ver then + if overwrite or it.may_replace then + e.ver = i.ver .. " -> " .. it.entry.ver + else + log.lg_printf(2, "%s::%s %s is already installed.", + repo, it.name, i.ver) + refused = true + end + end + end + if it.reason then e.ver = e.ver .. " (" .. it.reason .. ")" end + if it.traits then + e.ver = e.ver .. (it.traits.show ~= "" and (" " .. it.traits.show) or "") + .. " (build)" + end + if it.dep then e.ver = e.ver .. " (dependency)" end + table.insert(entries, e) + end + if refused then + finish(1) + end + if not confirm(entries) then + finish(0) + end +end + +-- The builds of `plan` in an order where a build comes after any build +-- whose package it depends on (its output is then one of its layers). +local function build_order(plan) + local by_name, order, state = {}, {}, {} + for _, it in ipairs(plan) do + if it.traits then by_name[it.name] = it end + end + local function visit(it) + if state[it.name] then return end + state[it.name] = true + for dname in it.deps:gmatch("(%S+) %S+\n") do + if by_name[dname] then visit(by_name[dname]) end + end + table.insert(order, it) + end + for _, it in ipairs(plan) do + if it.traits then visit(it) end + end + return order +end + +-- Fetch (or build), verify and install everything in `plan` (see +-- close_deps). +local function install_plan(plan, indexes, opts) + local ctx = live_context(opts) + local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8) + or tonumber("600", 8) + local copies, original, meta = {}, {}, {} + local refused = false + local has_builds = false + for _, it in ipairs(plan) do + has_builds = has_builds or it.traits ~= nil + end + if has_builds then + confirm_builds(plan, indexes, opts) + local built = {} + for _, it in ipairs(build_order(plan)) do + local copy, sidecar_text, hex = build.build(it, indexes, built, opts) + if it.repo.target == "base" then + sign_built_base(copy, sidecar_text, it.name) + end + built[it.name] = { ver = it.entry.ver, path = copy, sha = hex, deps = it.deps } + it.copy = copy + end + end + for _, it in ipairs(plan) do + if it.copy then + table.insert(copies, it.copy) + original[it.copy] = item_label(it) + meta[it.copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, src = it.repo.name } + goto continue + end + local e = it.entry + local id = string.format("%s::%s %s", it.repo.name, e.name, e.ver) + local cached, wrong = download(ctx, it.repo, e, file_mode) + local copy = cached and verify_and_copy(cached, e.sha256 .. "\n") + if not cached and not wrong then + log.lg_printf(2, "Cannot fetch %s.", id) + refused = true + elseif not copy or not matches_index(copy, it.repo.name, e) then + log.lg_printf(2, "%s does not match its index.", id) + if cached then os.remove(cached) end + refused = true + else + table.insert(copies, copy) + original[copy] = it.repo.url .. "/" .. e.file + meta[copy] = { auto = it.auto, may_replace = it.may_replace, + dep = it.dep, cache = cached } + end + ::continue:: + end + if refused then + finish(1) + end + install_copies(copies, original, opts, meta, has_builds) +end + +--- -f NAME...: install packages by name from the repositories, with +--- whatever dependencies they are missing. Like -l otherwise: an +--- installed other version of a named package needs -O. +function M.fetch(names, opts) + local indexes = load_indexes(opts) + local plan, refused, seen = {}, false, {} + for _, name in ipairs(names) do + local it = not seen[name] and choose(indexes, name, opts) + if seen[name] then + -- named twice: once is enough + elseif it then + seen[name] = true + table.insert(plan, it) + else + log.lg_printf(2, "%s is not in any repository.", name) + refused = true + end + end + if refused then + finish(1) + end + close_deps(plan, indexes, opts) + install_plan(plan, indexes, opts) +end + +--- -u [NAME...]: replace every installed package (or those named) whose +--- repository's index has a higher version, as -lO does (backups, +--- KEEP_OLD). Packages from repositories not configured are left alone. +function M.upgrade(names, opts) + local indexes = load_indexes(opts) + local by_repo = {} + for _, r in ipairs(indexes) do by_repo[r.name] = r end + local installed = installed_entries(opts) + local live0 = live_context(opts) + + local wanted, refused = nil, false + if #names > 0 then + wanted = {} + for _, name in ipairs(names) do + local found = false + for _, i in ipairs(installed) do + if i.name == name then + found = true + if not by_repo[built_from(live0, i.repo, i.name) or i.repo] then + log.lg_printf(2, "%s::%s is not in any configured repository.", + i.repo, i.name) + refused = true + end + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + refused = true + end + wanted[name] = true + end + end + if refused then + finish(1) + end + + local live = live_context(opts) + local plan = {} + for _, i in ipairs(installed) do + -- A package built from source stays on source (1k). + local src = built_from(live, i.repo, i.name) + local r = by_repo[src or i.repo] + local e = r and (not wanted or wanted[i.name]) and newest_in(r, i.name) + local it = e and plan_item(r, e, i.name, opts) + if it and vercmp(e.ver, i.ver) < 0 then + it = nil + elseif it and vercmp(e.ver, i.ver) == 0 then + -- Same version: rebuilt only if its traits changed. + local had = src and installed_traits(live, i) + if had and it.traits and had ~= table.concat(it.traits.list, "\n") + .. (#it.traits.list > 0 and "\n" or "") then + it.reason = "traits" + else + it = nil + end + end + if it then + it.auto, it.may_replace = i.auto, true + table.insert(plan, it) + end + end + if #plan == 0 then + log.lg_printf(3, "Nothing to do.") + finish(0) + end + close_deps(plan, indexes, opts) + install_plan(plan, indexes, opts) +end + +function M.install(gpkg_paths, opts) + -- From here on, the paths are the VERIFIED PRIVATE COPIES; the + -- caller's paths are only used for messages. + local copies, original = verify_all(gpkg_paths, opts) + install_copies(copies, original, opts, {}) +end + +--- Remove every named package as ONE atomic staged transaction. +--- Does not return on failure — exits. +function M.remove(pkg_names, opts) + -- Names, not files: resolve them against what's actually installed + -- (the old summary read them as .gpkg paths and printed + -- "unknown::pkg 0.0.0"). Anything not installed fails here, before + -- the prompt, not after the user has already said yes. + local installed = installed_entries(opts) + local entries, missing = {}, false + for _, name in ipairs(pkg_names) do + local found = false + for _, e in ipairs(installed) do + if e.name == name then + table.insert(entries, e) + found = true + end + end + if not found then + log.lg_printf(2, "%s is not installed.", name) + missing = true + end + end + if missing then + os.exit(1) + end + + -- A name installed from more than one repo isn't resolved until + -- after the prompt, so only unambiguous names are checked here. + local count, removes = {}, {} + for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end + for _, e in ipairs(entries) do + if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end + end + check_plan(opts, {}, removes, os.exit) + + if not confirm(entries) then + os.exit(0) + end + + local ctx = begin_staged(opts) + + for _, pkg_name in ipairs(pkg_names) do + local repo = M.resolve_repo(ctx, pkg_name) + if not repo then + log.lg_printf(2, "Failed to resolve group for %s.", pkg_name) + abort_and_die(ctx) + end + + local status = istore.gl_remove_pkg(ctx, pkg_name, repo) + + if status == ffi.C.GL_REMOVE_OK then + log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name) + elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then + log.lg_printf(2, "%s::%s not found.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then + log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name) + abort_and_die(ctx) + elseif status == ffi.C.GL_REMOVE_ERR_INDEX then + log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name) + abort_and_die(ctx) + else + log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status))) + abort_and_die(ctx) + end + end + + commit_or_die(ctx) + build.prune_kept(opts) + + report_done(ctx, os.exit) +end + +-- The builder's view of this module (lib/gpkg_build.lua). +init_build = function() + build.init({ + log = log, istore = istore, txn = txn, + finish = finish, shell_quote = shell_quote, + sha256_file = sha256_file, verify_and_copy = verify_and_copy, + download = download, live_context = live_context, + relation_lines = relation_lines, vercmp = vercmp, + pick_binary = pick_binary, installed_entries = installed_entries, + built_from = built_from, + require_trusted = function(path) require_trusted(path, HOST_KEYRING) end, + quiet = function() return isQuiet end, + gsandbox_path = (so_dir or ".") .. "/gsandbox", + gsandbox = shell_quote((so_dir or ".") .. "/gsandbox"), + lib_dir = so_dir and so_dir:gsub("/glacier$", "") or "lib", + }) +end + +return M diff --git a/pkgs/basepkgs/busybox-1.37.0.gpkg b/pkgs/basepkgs/busybox-1.37.0.gpkg new file mode 100644 index 0000000..bb2232f Binary files /dev/null and b/pkgs/basepkgs/busybox-1.37.0.gpkg differ diff --git a/pkgs/basepkgs/busybox-1.37.0.gpkg.sha256 b/pkgs/basepkgs/busybox-1.37.0.gpkg.sha256 new file mode 100644 index 0000000..04cb41b --- /dev/null +++ b/pkgs/basepkgs/busybox-1.37.0.gpkg.sha256 @@ -0,0 +1 @@ +sha256:9f3b8d15fac432b51e0e43e9f53a76e0d30c7d70709aa7155ce865948aeffb6a diff --git a/pkgs/basepkgs/busybox-1.37.0.gpkg.sha256.sig b/pkgs/basepkgs/busybox-1.37.0.gpkg.sha256.sig new file mode 100644 index 0000000..dba674b --- /dev/null +++ b/pkgs/basepkgs/busybox-1.37.0.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YQ69miZJHwvuigbWfDubPXK5wa14L1G8uF0jWSlBR8+/cIB4u3u6pfgQnZkPnGgUksCVc4ih0vNnAGfgHVLb5gQ= diff --git a/pkgs/basepkgs/doas-6.8.2.gpkg b/pkgs/basepkgs/doas-6.8.2.gpkg new file mode 100644 index 0000000..f4d66b3 Binary files /dev/null and b/pkgs/basepkgs/doas-6.8.2.gpkg differ diff --git a/pkgs/basepkgs/doas-6.8.2.gpkg.sha256 b/pkgs/basepkgs/doas-6.8.2.gpkg.sha256 new file mode 100644 index 0000000..4e2e979 --- /dev/null +++ b/pkgs/basepkgs/doas-6.8.2.gpkg.sha256 @@ -0,0 +1 @@ +sha256:85907993773e4a02318e06d69f1bcdf3725bc999c1c43fdf1c6291ac42b8ba7f diff --git a/pkgs/basepkgs/doas-6.8.2.gpkg.sha256.sig b/pkgs/basepkgs/doas-6.8.2.gpkg.sha256.sig new file mode 100644 index 0000000..55372fa --- /dev/null +++ b/pkgs/basepkgs/doas-6.8.2.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YUL7xALU5l0yfMDgxzNDO3fFXJHTllFW+kDYF7+0mdLrgtlRc/29aO1EYNvFJxDptZtPTOb8CAsNYzgRqd5DWwM= diff --git a/pkgs/basepkgs/everest-bootscripts-1.0.0.gpkg b/pkgs/basepkgs/everest-bootscripts-1.0.0.gpkg new file mode 100644 index 0000000..309ad56 Binary files /dev/null and b/pkgs/basepkgs/everest-bootscripts-1.0.0.gpkg differ diff --git a/pkgs/basepkgs/everest-bootscripts-1.0.0.gpkg.sha256 b/pkgs/basepkgs/everest-bootscripts-1.0.0.gpkg.sha256 new file mode 100644 index 0000000..ad06c9a --- /dev/null +++ b/pkgs/basepkgs/everest-bootscripts-1.0.0.gpkg.sha256 @@ -0,0 +1 @@ +sha256:36e9ff127a41c605a30c701fa6702d1a2f2913c049cfdadd952eedc01a70431e diff --git a/pkgs/basepkgs/everest-bootscripts-1.1.0.gpkg b/pkgs/basepkgs/everest-bootscripts-1.1.0.gpkg new file mode 100644 index 0000000..c23b402 Binary files /dev/null and b/pkgs/basepkgs/everest-bootscripts-1.1.0.gpkg differ diff --git a/pkgs/basepkgs/everest-bootscripts-1.1.0.gpkg.sha256 b/pkgs/basepkgs/everest-bootscripts-1.1.0.gpkg.sha256 new file mode 100644 index 0000000..b7443d5 --- /dev/null +++ b/pkgs/basepkgs/everest-bootscripts-1.1.0.gpkg.sha256 @@ -0,0 +1 @@ +sha256:5bd439dc10872c03c15c00acb62f970d3c35de304dec10261571a922538ccf80 diff --git a/pkgs/basepkgs/everest-bootscripts-1.2.0.gpkg b/pkgs/basepkgs/everest-bootscripts-1.2.0.gpkg new file mode 100644 index 0000000..2a50b0f Binary files /dev/null and b/pkgs/basepkgs/everest-bootscripts-1.2.0.gpkg differ diff --git a/pkgs/basepkgs/everest-bootscripts-1.2.0.gpkg.sha256 b/pkgs/basepkgs/everest-bootscripts-1.2.0.gpkg.sha256 new file mode 100644 index 0000000..feb0f64 --- /dev/null +++ b/pkgs/basepkgs/everest-bootscripts-1.2.0.gpkg.sha256 @@ -0,0 +1 @@ +sha256:6cc45a91dca1766efd6662ca57470428cc3e739c0a2aea76ec90c3b508b3663d diff --git a/pkgs/basepkgs/everest-bootscripts-1.2.0.gpkg.sha256.sig b/pkgs/basepkgs/everest-bootscripts-1.2.0.gpkg.sha256.sig new file mode 100644 index 0000000..ce1b5d0 --- /dev/null +++ b/pkgs/basepkgs/everest-bootscripts-1.2.0.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6Ybe0RMo6HD0IvrFMBEBnqwb+QqyVMYhrWlr0CPfqCnvJgyGPiA6gCNYBLRsmytmPrUB0m2NTX79EupaCD5bonws= diff --git a/pkgs/basepkgs/everest-bootscripts-1.3.0.gpkg b/pkgs/basepkgs/everest-bootscripts-1.3.0.gpkg new file mode 100644 index 0000000..1725ef8 Binary files /dev/null and b/pkgs/basepkgs/everest-bootscripts-1.3.0.gpkg differ diff --git a/pkgs/basepkgs/everest-bootscripts-1.3.0.gpkg.sha256 b/pkgs/basepkgs/everest-bootscripts-1.3.0.gpkg.sha256 new file mode 100644 index 0000000..ea70157 --- /dev/null +++ b/pkgs/basepkgs/everest-bootscripts-1.3.0.gpkg.sha256 @@ -0,0 +1 @@ +sha256:078db1648cb9af697650cad0684c596266e53e0df9d7d94d2068bcde1f61392a diff --git a/pkgs/basepkgs/everest-bootscripts-1.3.0.gpkg.sha256.sig b/pkgs/basepkgs/everest-bootscripts-1.3.0.gpkg.sha256.sig new file mode 100644 index 0000000..0972bf7 --- /dev/null +++ b/pkgs/basepkgs/everest-bootscripts-1.3.0.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YZy13VIIa20Bl0b7eRZDLilv6hMXw2Brtbr3NtdaGyXL0WYR/yAX8YubAlpeNdrnB8TsvxObx7ejTEcuF1K75AM= diff --git a/pkgs/basepkgs/everest-repos-1.0.0.gpkg b/pkgs/basepkgs/everest-repos-1.0.0.gpkg new file mode 100644 index 0000000..3749a78 Binary files /dev/null and b/pkgs/basepkgs/everest-repos-1.0.0.gpkg differ diff --git a/pkgs/basepkgs/everest-repos-1.0.0.gpkg.sha256 b/pkgs/basepkgs/everest-repos-1.0.0.gpkg.sha256 new file mode 100644 index 0000000..0268746 --- /dev/null +++ b/pkgs/basepkgs/everest-repos-1.0.0.gpkg.sha256 @@ -0,0 +1 @@ +sha256:153cf53dbf30e7e9c6a21a4e5072727e33574f330a8933a390e29c11fdc5c548 diff --git a/pkgs/basepkgs/everest-repos-1.0.0.gpkg.sha256.sig b/pkgs/basepkgs/everest-repos-1.0.0.gpkg.sha256.sig new file mode 100644 index 0000000..4f6c617 --- /dev/null +++ b/pkgs/basepkgs/everest-repos-1.0.0.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YcSrkRAfMtSLjpuZXaxh5cotv4QVIzf7iHJVxAez1gY46D8fAuDIiNx2+vx2GfOlb8FGRKE95Mxv0x0zT7kQJQg= diff --git a/pkgs/basepkgs/glacier-ng-4.0.0.gpkg b/pkgs/basepkgs/glacier-ng-4.0.0.gpkg new file mode 100644 index 0000000..43cc790 Binary files /dev/null and b/pkgs/basepkgs/glacier-ng-4.0.0.gpkg differ diff --git a/pkgs/basepkgs/glacier-ng-4.0.0.gpkg.sha256 b/pkgs/basepkgs/glacier-ng-4.0.0.gpkg.sha256 new file mode 100644 index 0000000..51007fe --- /dev/null +++ b/pkgs/basepkgs/glacier-ng-4.0.0.gpkg.sha256 @@ -0,0 +1 @@ +sha256:ee7af7fdfeffec2c6673074273688031d06a90a83473ae46309f3b29dab3ce77 diff --git a/pkgs/basepkgs/glacier-ng-4.0.0.gpkg.sha256.sig b/pkgs/basepkgs/glacier-ng-4.0.0.gpkg.sha256.sig new file mode 100644 index 0000000..a17f0d1 --- /dev/null +++ b/pkgs/basepkgs/glacier-ng-4.0.0.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YeR6RLhjUDY9h+SF0Zvz4onqGTNgR9J9sOZ8im/jRNspUx4eWnZSdSfozQan/o1frnMKctuHK2ynjC1A04dWjQw= diff --git a/pkgs/basepkgs/libarchive-3.8.9.gpkg b/pkgs/basepkgs/libarchive-3.8.9.gpkg new file mode 100644 index 0000000..af696fd Binary files /dev/null and b/pkgs/basepkgs/libarchive-3.8.9.gpkg differ diff --git a/pkgs/basepkgs/libarchive-3.8.9.gpkg.sha256 b/pkgs/basepkgs/libarchive-3.8.9.gpkg.sha256 new file mode 100644 index 0000000..6c01972 --- /dev/null +++ b/pkgs/basepkgs/libarchive-3.8.9.gpkg.sha256 @@ -0,0 +1 @@ +sha256:1690478ea1427befa27b7815efbcc19e52e9905a53fbb455bf0c6e83656b74c7 diff --git a/pkgs/basepkgs/libarchive-3.8.9.gpkg.sha256.sig b/pkgs/basepkgs/libarchive-3.8.9.gpkg.sha256.sig new file mode 100644 index 0000000..fdfcb61 --- /dev/null +++ b/pkgs/basepkgs/libarchive-3.8.9.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YRQt36ddu7NOEwxCiPM0u+W2kdFzeEXBsK47Yxesd+DyE91lUkEhYQOcEUXn13Y+Az9o2EhrolGAbAH/zNb31gA= diff --git a/pkgs/basepkgs/libconfig-1.8.2.gpkg b/pkgs/basepkgs/libconfig-1.8.2.gpkg new file mode 100644 index 0000000..9f23c56 Binary files /dev/null and b/pkgs/basepkgs/libconfig-1.8.2.gpkg differ diff --git a/pkgs/basepkgs/libconfig-1.8.2.gpkg.sha256 b/pkgs/basepkgs/libconfig-1.8.2.gpkg.sha256 new file mode 100644 index 0000000..84cf03b --- /dev/null +++ b/pkgs/basepkgs/libconfig-1.8.2.gpkg.sha256 @@ -0,0 +1 @@ +sha256:447824813c8af135c5adcfa42a1f4ed80c7c81358c5b8df590c150941816241d diff --git a/pkgs/basepkgs/libconfig-1.8.2.gpkg.sha256.sig b/pkgs/basepkgs/libconfig-1.8.2.gpkg.sha256.sig new file mode 100644 index 0000000..cdaf300 --- /dev/null +++ b/pkgs/basepkgs/libconfig-1.8.2.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YcxL7mKJuYuHY5d4MQlNJsgaq2dVk8j7NLXaU3N5+FwSlItkwhaPIvVTId0okv/J9eMAnB5e/w2MeDdn0NIlRAg= diff --git a/pkgs/basepkgs/libglacier-ng-4.0.0.gpkg b/pkgs/basepkgs/libglacier-ng-4.0.0.gpkg new file mode 100644 index 0000000..a70cb63 Binary files /dev/null and b/pkgs/basepkgs/libglacier-ng-4.0.0.gpkg differ diff --git a/pkgs/basepkgs/libglacier-ng-4.0.0.gpkg.sha256 b/pkgs/basepkgs/libglacier-ng-4.0.0.gpkg.sha256 new file mode 100644 index 0000000..135034e --- /dev/null +++ b/pkgs/basepkgs/libglacier-ng-4.0.0.gpkg.sha256 @@ -0,0 +1 @@ +sha256:177c67f4884bfda1aef1ced8f8058056390076cef3c2cd1ed47f6399dbb90038 diff --git a/pkgs/basepkgs/libglacier-ng-4.0.0.gpkg.sha256.sig b/pkgs/basepkgs/libglacier-ng-4.0.0.gpkg.sha256.sig new file mode 100644 index 0000000..a6bec95 --- /dev/null +++ b/pkgs/basepkgs/libglacier-ng-4.0.0.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YQ7ooWHWe9tzu0p+8z5Eogun2oLZB4QS+JjAuuPiyN2YX5YFWQ5WahFecX20KA3uyc+kejeer4h3Ul8tytavcwA= diff --git a/pkgs/basepkgs/linux-6.12.112.gpkg b/pkgs/basepkgs/linux-6.12.112.gpkg new file mode 100644 index 0000000..6e274c1 Binary files /dev/null and b/pkgs/basepkgs/linux-6.12.112.gpkg differ diff --git a/pkgs/basepkgs/linux-6.12.112.gpkg.sha256 b/pkgs/basepkgs/linux-6.12.112.gpkg.sha256 new file mode 100644 index 0000000..1dd0297 --- /dev/null +++ b/pkgs/basepkgs/linux-6.12.112.gpkg.sha256 @@ -0,0 +1 @@ +sha256:f6bfe40946be49ea85ac11d8f0171102dae187beebcbbef99e3661e82de6eede diff --git a/pkgs/basepkgs/linux-6.12.112.gpkg.sha256.sig b/pkgs/basepkgs/linux-6.12.112.gpkg.sha256.sig new file mode 100644 index 0000000..5b75d4f --- /dev/null +++ b/pkgs/basepkgs/linux-6.12.112.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YQwPd28j9U0tvhCHXnTI4Y9DrWaSB8MA2ztNSTuc5wpAuvRr8P7EeBnN3ZaNJxrn4Jff0zdY37W29kf3NhZgEwE= diff --git a/pkgs/basepkgs/luajit-2.1.1788856981.gpkg b/pkgs/basepkgs/luajit-2.1.1788856981.gpkg new file mode 100644 index 0000000..3cc861c Binary files /dev/null and b/pkgs/basepkgs/luajit-2.1.1788856981.gpkg differ diff --git a/pkgs/basepkgs/luajit-2.1.1788856981.gpkg.sha256 b/pkgs/basepkgs/luajit-2.1.1788856981.gpkg.sha256 new file mode 100644 index 0000000..52b8c1b --- /dev/null +++ b/pkgs/basepkgs/luajit-2.1.1788856981.gpkg.sha256 @@ -0,0 +1 @@ +sha256:2ec41f02007e2511d1fcc7937a3ae52abd764e33e76ac2b5eb0172f56fb0f9a1 diff --git a/pkgs/basepkgs/luajit-2.1.1788856981.gpkg.sha256.sig b/pkgs/basepkgs/luajit-2.1.1788856981.gpkg.sha256.sig new file mode 100644 index 0000000..9a278e6 --- /dev/null +++ b/pkgs/basepkgs/luajit-2.1.1788856981.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YU+3yRvSnMrd0QtQdTRcPFwDU17HApYOyYN3BFuyT0s5LMpMZ1yRi+Outn0KvuIzTP5DK+C1AdlqvuhLBOwhHQ8= diff --git a/pkgs/basepkgs/musl-1.2.5.gpkg b/pkgs/basepkgs/musl-1.2.5.gpkg new file mode 100644 index 0000000..f936bd9 Binary files /dev/null and b/pkgs/basepkgs/musl-1.2.5.gpkg differ diff --git a/pkgs/basepkgs/musl-1.2.5.gpkg.sha256 b/pkgs/basepkgs/musl-1.2.5.gpkg.sha256 new file mode 100644 index 0000000..c142a06 --- /dev/null +++ b/pkgs/basepkgs/musl-1.2.5.gpkg.sha256 @@ -0,0 +1 @@ +sha256:114acd041598508725779becec06a43ec3106bab450740a102784c4ee414a39a diff --git a/pkgs/basepkgs/musl-1.2.5.gpkg.sha256.sig b/pkgs/basepkgs/musl-1.2.5.gpkg.sha256.sig new file mode 100644 index 0000000..d6bc5d3 --- /dev/null +++ b/pkgs/basepkgs/musl-1.2.5.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YVGo5e+KvMXvHFgbLK5+FGueHLJxNyBdL2guSDKOSfpGqxTZP8iQpqwDKkgJvzNPx+dCkkucIkHf8bm1DFq4CAc= diff --git a/pkgs/basepkgs/zlib-1.3.2.gpkg b/pkgs/basepkgs/zlib-1.3.2.gpkg new file mode 100644 index 0000000..277ad34 Binary files /dev/null and b/pkgs/basepkgs/zlib-1.3.2.gpkg differ diff --git a/pkgs/basepkgs/zlib-1.3.2.gpkg.sha256 b/pkgs/basepkgs/zlib-1.3.2.gpkg.sha256 new file mode 100644 index 0000000..9191d15 --- /dev/null +++ b/pkgs/basepkgs/zlib-1.3.2.gpkg.sha256 @@ -0,0 +1 @@ +sha256:d6c02491a1301577259d7595871640b781044f610d08d9df9e21674031b9bc40 diff --git a/pkgs/basepkgs/zlib-1.3.2.gpkg.sha256.sig b/pkgs/basepkgs/zlib-1.3.2.gpkg.sha256.sig new file mode 100644 index 0000000..4c47653 --- /dev/null +++ b/pkgs/basepkgs/zlib-1.3.2.gpkg.sha256.sig @@ -0,0 +1,2 @@ +untrusted comment: verify with everest-2026.pub +RWTALtzjJuR6YamI1pToWcyZuWGCyRHydHFYGjsjlpwjGKAzxKOBoJ+bHRHzeZ+kCWtU8nIoLSSba7UEPx/p0WymLGY+F72utwQ= diff --git a/pkgs/kilo-0.0.1.gpkg b/pkgs/kilo-0.0.1.gpkg new file mode 100644 index 0000000..f7e07d0 Binary files /dev/null and b/pkgs/kilo-0.0.1.gpkg differ diff --git a/pkgs/kilo-0.0.1.gpkg.sha256 b/pkgs/kilo-0.0.1.gpkg.sha256 new file mode 100644 index 0000000..765af1d --- /dev/null +++ b/pkgs/kilo-0.0.1.gpkg.sha256 @@ -0,0 +1 @@ +sha256:6671b69282c10f9929c0ae640406b46ec654b5f74db1a0368428ee59f873af9d diff --git a/pkgs/musl-1.2.5.gpkg b/pkgs/musl-1.2.5.gpkg new file mode 100644 index 0000000..dbd41ed Binary files /dev/null and b/pkgs/musl-1.2.5.gpkg differ diff --git a/pkgs/musl-1.2.5.gpkg.sha256 b/pkgs/musl-1.2.5.gpkg.sha256 new file mode 100644 index 0000000..8d57cfa --- /dev/null +++ b/pkgs/musl-1.2.5.gpkg.sha256 @@ -0,0 +1 @@ +sha256:f54dac956abd9533c6e5c6815dcff0247c474c6c762ccc58d860800b026c810d diff --git a/pkgs/sbase-0.0.1.gpkg b/pkgs/sbase-0.0.1.gpkg new file mode 100644 index 0000000..193ea41 Binary files /dev/null and b/pkgs/sbase-0.0.1.gpkg differ diff --git a/pkgs/sbase-0.0.1.gpkg.sha256 b/pkgs/sbase-0.0.1.gpkg.sha256 new file mode 100644 index 0000000..088b903 --- /dev/null +++ b/pkgs/sbase-0.0.1.gpkg.sha256 @@ -0,0 +1 @@ +sha256:e5d8caaeb2686e1358d18b0fed9b0d65b9328fb28d20f95621ddbc144bd8abdd diff --git a/run_docker.sh b/run_docker.sh new file mode 100755 index 0000000..86a7285 --- /dev/null +++ b/run_docker.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# +# ./run_docker.sh [-b] [DOCKERFILE] +# +# Builds DOCKERFILE (default Dockerfile.alpine) and starts a throwaway +# container from it. +# +# -b for building packages from source (BUILD_DESIGN.txt): gsandbox +# needs user namespaces, overlayfs and a fresh /proc, which +# Docker's seccomp and AppArmor profiles and its /proc masking +# refuse, so those are turned off; /glacier goes on a tmpfs +# (overlayfs can't sit on Docker's own overlay root); and the +# recipe tree $RECIPES (default ../everest/recipes) is mounted +# read-only at /recipes. Use it with Dockerfile.alpine_root, +# then run /app/tests/buildenv inside (see TESTING.txt). + +BUILD= +while getopts bh opt; do + case $opt in + b) BUILD=1 ;; + *) echo "usage: $0 [-b] [DOCKERFILE]" >&2; exit 1 ;; + esac +done +shift $((OPTIND - 1)) + +DOCKERFILE="${1:-Dockerfile.alpine}" +TAG="glacier-$(echo $DOCKERFILE | sed 's/Dockerfile\.//')" + +# Dockerfiles that build libglacier-ng in-container (Dockerfile.alpine_root) +# take its source from this named context; the others ignore it. +LIBGLACIER_SRC="${LIBGLACIER_SRC:-$(dirname "$0")/../libglacier-ng}" +RECIPES="${RECIPES:-$(dirname "$0")/../everest/recipes}" + +docker build -f "$DOCKERFILE" --build-context libglacier="$LIBGLACIER_SRC" -t "$TAG" . || exit 1 + +if [ -n "$BUILD" ]; then + [ -d "$RECIPES" ] || { echo "$0: no recipe tree at $RECIPES (set RECIPES)" >&2; exit 1; } + exec docker run -it --rm --network host \ + --security-opt seccomp=unconfined --security-opt apparmor=unconfined \ + --security-opt systempaths=unconfined --tmpfs /glacier:exec,mode=755 \ + -v "$(realpath "$RECIPES")":/recipes:ro "$TAG" +fi +exec docker run -it --rm --network host "$TAG" diff --git a/tests/audit_alpine.sh b/tests/audit_alpine.sh new file mode 100644 index 0000000..33da3ed --- /dev/null +++ b/tests/audit_alpine.sh @@ -0,0 +1,156 @@ +#!/bin/sh +# Fixes from the 2026-10-06 security audit: +# - a package may not ship a top-level files/.glacier-* entry: as a +# symlink, .glacier-fresh made syspkg truncate any file as root; +# .glacier-overwrite granted the package -O; .glacier-manifest +# rewrote its saved manifest; +# - a manifest with @include is refused (libconfig would read any file +# as root), and so is a dependency or conflict entry without a name; +# - what syspkg shows and compares is what the LIBRARY reads from the +# manifest: a decoy comment can't hide that a package replaces one; +# - no CLI argument reaches a format string (gstore's argv[0], gpkg +# -u's operand); gstore refuses a UID that would wrap in C; +# - root deleting a user's tree (gstore -x) never follows a symlink +# swapped in mid-walk (race test, many iterations). +# Runs INSIDE the Dockerfile.alpine_root image: +# +# docker run --rm -v "$PWD/tests/audit_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +installed() { grep -q "^$1::$2::" /glacier/sys/index/current; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +P=/srv/pkgs +mkdir -p $P && chmod 755 /srv $P + +# raw NAME VER REPO [MANIFEST_EXTRA] -> $P/NAME-VER.gpkg (+ sidecar). The +# package tree is left at $W/NAME-VER for the caller to add to first: +# call raw_dir, edit $D, then raw_pack. +raw_dir() { + W=$(mktemp -d); D=$W/$1-$2 + mkdir -p $D/files/usr/bin + printf '%sPKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_REPO = "%s";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' \ + "${4:-}" "$1" "$2" "$3" > $D/manifest.gpm.cfg + printf '#!/bin/sh\necho %s %s\n' "$1" "$2" > $D/files/usr/bin/$1 + chmod 755 $D/files/usr/bin/$1 + RAW=$P/$1-$2.gpkg +} +raw_pack() { + tar -C $W -czf $RAW "$(basename $D)" + echo "sha256:$(sha256sum $RAW | cut -c1-64)" > $RAW.sha256 + rm -rf $W +} +inst() { R sh -c "echo y | syspkg -l $*"; } + +syspkg -n >/dev/null +echo "important root data" > /root/victim && chmod 600 /root/victim + +hr "reserved .glacier-* names" +raw_dir fresh 1.0.0 extra; ln -s /root/victim $D/files/.glacier-fresh; raw_pack +inst $RAW +check "a .glacier-fresh symlink is refused" has "[x] Refusing archive entry 'fresh-1.0.0/files/.glacier-fresh': .glacier-* names are reserved." +check "...exit 1" rc 1 +check "...the file it pointed at is untouched" [ "$(cat /root/victim)" = "important root data" ] +check "...nothing installed" sh -c '! grep -q "::fresh::" /glacier/sys/index/current' +check "...no half-made version dir" [ ! -e /glacier/sys/store/extra/fresh/fresh-1.0.0 ] +raw_dir selfo 1.0.0 extra; : > $D/files/.glacier-overwrite; raw_pack +inst $RAW +check "a .glacier-overwrite (self-granted -O) is refused" has "files/.glacier-overwrite': .glacier-* names are reserved." +raw_dir man 1.0.0 extra; printf 'PKG_NAME = "x";\n' > $D/files/.glacier-manifest; raw_pack +inst $RAW +check "a .glacier-manifest is refused" has "files/.glacier-manifest': .glacier-* names are reserved." +raw_dir keep 1.0.0 extra; mkdir -p $D/files/usr/lib; : > $D/files/usr/lib/.keep; : > $D/files/.hidden; raw_pack +inst $RAW +check "other dotfiles still install" installed extra keep +adduser -D tester >/dev/null 2>&1 +U=$(id -u tester) +gstore -n "$U" >/dev/null +echo "tester data" > /srv/tester-file && chown tester /srv/tester-file +raw_dir ufresh 1.0.0 extra; ln -s /srv/tester-file $D/files/.glacier-fresh; raw_pack +R su tester -c "echo y | gpkg -l $RAW" +check "gpkg refuses one too" has "files/.glacier-fresh': .glacier-* names are reserved." +check "...leaving the user's file alone" [ "$(cat /srv/tester-file)" = "tester data" ] + +hr "hardlinks" +# Skipping a hardlink entry silently dropped a file (binutils' ld): a +# package with one is refused, whole. +raw_dir hard 1.0.0 extra; ln $D/files/usr/bin/hard $D/files/usr/bin/hard2; raw_pack +inst $RAW +check "a package with a hardlink entry is refused" sh -c 'echo "$0" | grep -q "\[x\] Refusing archive entry .hard-1.0.0/files/usr/bin/hard2\{0,1\}.: it is a hardlink."' "$OUT" +check "...exit 1" rc 1 +check "...nothing installed" sh -c '! grep -q "::hard::" /glacier/sys/index/current' +check "...no half-made version dir" [ ! -e /glacier/sys/store/extra/hard/hard-1.0.0 ] + +hr "manifests" +raw_dir incl 1.0.0 extra '@include "/etc/glacier/glacier.conf" +'; raw_pack +inst $RAW +check "@include in a manifest is refused" has "[x] Cannot read the manifest of $RAW." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ] && ! echo \"\$0\" | grep -q Proceed" "$OUT" +check "...nothing installed" sh -c '! grep -q "::incl::" /glacier/sys/index/current' +raw_dir incl2 1.0.0 extra ' @include "/etc/glacier/glacier.conf" +'; raw_pack +inst $RAW +check "...indented too" has "[x] Cannot read the manifest of $RAW." +raw_dir mail 1.0.0 extra 'PKG_MAINT = "someone@example.org"; +'; raw_pack +inst $RAW +check "an @ elsewhere (an e-mail address) is fine" installed extra mail +raw_dir noname 1.0.0 extra; sed -i 's/PKG_DEPS = ();/PKG_DEPS = ( { PKG_VER = "1.0.0"; } );/' $D/manifest.gpm.cfg; raw_pack +inst $RAW +check "a dependency without a name is refused" has "[x] Cannot read the manifest of $RAW." +raw_dir badconf 1.0.0 extra; sed -i 's#PKG_CONFS = ();#PKG_CONFS = ( { PKG_NAME = "../x"; PKG_VER = "1.0.0"; } );#' $D/manifest.gpm.cfg; raw_pack +inst $RAW +check "a conflict with an unsafe name is refused" has "[x] Cannot read the manifest of $RAW." +raw_dir dup 1.0.0 extra; raw_pack +inst $RAW +raw_dir dup 2.0.0 extra '// PKG_REPO = "community"; +'; raw_pack +inst $RAW +check "a decoy PKG_REPO comment can't hide a replacement" has "[x] extra::dup 1.0.0 is already installed." +check "...one version stays in the store" [ "$(ls /glacier/sys/store/extra/dup)" = "dup-1.0.0" ] + +hr "format strings and UIDs" +ln -s /app/gstore '/srv/gs%s%s%s%s%n' +R '/srv/gs%s%s%s%s%n' -b "$U" /srv/b.tgz +check "gstore -b run as a name full of %s%n works" rc 0 +check "...and prints it nowhere as a format" has "[✓] Successfully created backup for UID $U." +# gpkg -f/-u operands as formats: tests/fetch_alpine.sh (they need a repo). +R gstore -n 4294968296 +check "a UID above uid_t's range is refused" has "[x] Invalid UID: 4294968296" +R gstore -x -- -1 +R gstore -x -1000 +check "a negative UID is refused" sh -c "[ $RC = 1 ]" +check "...and the tester's directory survives" [ -d /glacier/usr/$U ] + +hr "races: root never follows a symlink swapped into a user's tree" +mkdir -p /root/vdir && chmod 700 /root/vdir +lost=0 +i=0 +while [ $i -lt 40 ]; do + j=0; while [ $j -lt 50 ]; do : > /root/vdir/f$j; j=$((j+1)); done + [ -d /glacier/usr/$U ] || gstore -n "$U" >/dev/null + B=/glacier/usr/$U + su tester -c "mkdir -p $B/store/d/a/b/c; j=0; while [ \$j -lt 200 ]; do : > $B/store/d/x\$j; j=\$((j+1)); done" + su tester -c "while :; do mv $B/store/d $B/store/.d 2>/dev/null; ln -s /root/vdir $B/store/d 2>/dev/null; rm -f $B/store/d; mv $B/store/.d $B/store/d 2>/dev/null; done" >/dev/null 2>&1 & + SWAP=$! + gstore -x "$U" >/dev/null 2>&1 + kill $SWAP 2>/dev/null; wait $SWAP 2>/dev/null + [ "$(ls /root/vdir | wc -l)" = 50 ] || lost=$((lost+1)) + i=$((i+1)) +done +check "gstore -x deleted nothing through a swapped symlink (40 runs, $lost with losses)" [ $lost = 0 ] + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/audit_alpine.sh.old b/tests/audit_alpine.sh.old new file mode 100644 index 0000000..57f1cdc --- /dev/null +++ b/tests/audit_alpine.sh.old @@ -0,0 +1,147 @@ +#!/bin/sh +# Fixes from the 2026-10-06 security audit: +# - a package may not ship a top-level files/.glacier-* entry: as a +# symlink, .glacier-fresh made syspkg truncate any file as root; +# .glacier-overwrite granted the package -O; .glacier-manifest +# rewrote its saved manifest; +# - a manifest with @include is refused (libconfig would read any file +# as root), and so is a dependency or conflict entry without a name; +# - what syspkg shows and compares is what the LIBRARY reads from the +# manifest: a decoy comment can't hide that a package replaces one; +# - no CLI argument reaches a format string (gstore's argv[0], gpkg +# -u's operand); gstore refuses a UID that would wrap in C; +# - root deleting a user's tree (gstore -x) never follows a symlink +# swapped in mid-walk (race test, many iterations). +# Runs INSIDE the Dockerfile.alpine_root image: +# +# docker run --rm -v "$PWD/tests/audit_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +installed() { grep -q "^$1::$2::" /glacier/sys/index/current; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +P=/srv/pkgs +mkdir -p $P && chmod 755 /srv $P + +# raw NAME VER REPO [MANIFEST_EXTRA] -> $P/NAME-VER.gpkg (+ sidecar). The +# package tree is left at $W/NAME-VER for the caller to add to first: +# call raw_dir, edit $D, then raw_pack. +raw_dir() { + W=$(mktemp -d); D=$W/$1-$2 + mkdir -p $D/files/usr/bin + printf '%sPKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_REPO = "%s";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' \ + "${4:-}" "$1" "$2" "$3" > $D/manifest.gpm.cfg + printf '#!/bin/sh\necho %s %s\n' "$1" "$2" > $D/files/usr/bin/$1 + chmod 755 $D/files/usr/bin/$1 + RAW=$P/$1-$2.gpkg +} +raw_pack() { + tar -C $W -czf $RAW "$(basename $D)" + echo "sha256:$(sha256sum $RAW | cut -c1-64)" > $RAW.sha256 + rm -rf $W +} +inst() { R sh -c "echo y | syspkg -l $*"; } + +syspkg -n >/dev/null +echo "important root data" > /root/victim && chmod 600 /root/victim + +hr "reserved .glacier-* names" +raw_dir fresh 1.0.0 extra; ln -s /root/victim $D/files/.glacier-fresh; raw_pack +inst $RAW +check "a .glacier-fresh symlink is refused" has "[x] Refusing archive entry 'fresh-1.0.0/files/.glacier-fresh': .glacier-* names are reserved." +check "...exit 1" rc 1 +check "...the file it pointed at is untouched" [ "$(cat /root/victim)" = "important root data" ] +check "...nothing installed" sh -c '! grep -q "::fresh::" /glacier/sys/index/current' +check "...no half-made version dir" [ ! -e /glacier/sys/store/extra/fresh/fresh-1.0.0 ] +raw_dir selfo 1.0.0 extra; : > $D/files/.glacier-overwrite; raw_pack +inst $RAW +check "a .glacier-overwrite (self-granted -O) is refused" has "files/.glacier-overwrite': .glacier-* names are reserved." +raw_dir man 1.0.0 extra; printf 'PKG_NAME = "x";\n' > $D/files/.glacier-manifest; raw_pack +inst $RAW +check "a .glacier-manifest is refused" has "files/.glacier-manifest': .glacier-* names are reserved." +raw_dir keep 1.0.0 extra; mkdir -p $D/files/usr/lib; : > $D/files/usr/lib/.keep; : > $D/files/.hidden; raw_pack +inst $RAW +check "other dotfiles still install" installed extra keep +adduser -D tester >/dev/null 2>&1 +U=$(id -u tester) +gstore -n "$U" >/dev/null +echo "tester data" > /srv/tester-file && chown tester /srv/tester-file +raw_dir ufresh 1.0.0 extra; ln -s /srv/tester-file $D/files/.glacier-fresh; raw_pack +R su tester -c "echo y | gpkg -l $RAW" +check "gpkg refuses one too" has "files/.glacier-fresh': .glacier-* names are reserved." +check "...leaving the user's file alone" [ "$(cat /srv/tester-file)" = "tester data" ] + +hr "manifests" +raw_dir incl 1.0.0 extra '@include "/etc/glacier/glacier.conf" +'; raw_pack +inst $RAW +check "@include in a manifest is refused" has "[x] Cannot read the manifest of $RAW." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ] && ! echo \"\$0\" | grep -q Proceed" "$OUT" +check "...nothing installed" sh -c '! grep -q "::incl::" /glacier/sys/index/current' +raw_dir incl2 1.0.0 extra ' @include "/etc/glacier/glacier.conf" +'; raw_pack +inst $RAW +check "...indented too" has "[x] Cannot read the manifest of $RAW." +raw_dir mail 1.0.0 extra 'PKG_MAINT = "someone@example.org"; +'; raw_pack +inst $RAW +check "an @ elsewhere (an e-mail address) is fine" installed extra mail +raw_dir noname 1.0.0 extra; sed -i 's/PKG_DEPS = ();/PKG_DEPS = ( { PKG_VER = "1.0.0"; } );/' $D/manifest.gpm.cfg; raw_pack +inst $RAW +check "a dependency without a name is refused" has "[x] Cannot read the manifest of $RAW." +raw_dir badconf 1.0.0 extra; sed -i 's#PKG_CONFS = ();#PKG_CONFS = ( { PKG_NAME = "../x"; PKG_VER = "1.0.0"; } );#' $D/manifest.gpm.cfg; raw_pack +inst $RAW +check "a conflict with an unsafe name is refused" has "[x] Cannot read the manifest of $RAW." +raw_dir dup 1.0.0 extra; raw_pack +inst $RAW +raw_dir dup 2.0.0 extra '// PKG_REPO = "community"; +'; raw_pack +inst $RAW +check "a decoy PKG_REPO comment can't hide a replacement" has "[x] extra::dup 1.0.0 is already installed." +check "...one version stays in the store" [ "$(ls /glacier/sys/store/extra/dup)" = "dup-1.0.0" ] + +hr "format strings and UIDs" +ln -s /app/gstore '/srv/gs%s%s%s%s%n' +R '/srv/gs%s%s%s%s%n' -b "$U" /srv/b.tgz +check "gstore -b run as a name full of %s%n works" rc 0 +check "...and prints it nowhere as a format" has "[✓] Successfully created backup for UID $U." +R su tester -c 'gpkg -u "%s%s%s%s%n"' +check "gpkg -u with %s%n as its operand" has "[x] -u is not implemented yet." +R gstore -n 4294968296 +check "a UID above uid_t's range is refused" has "[x] Invalid UID: 4294968296" +R gstore -x -- -1 +R gstore -x -1000 +check "a negative UID is refused" sh -c "[ $RC = 1 ]" +check "...and the tester's directory survives" [ -d /glacier/usr/$U ] + +hr "races: root never follows a symlink swapped into a user's tree" +mkdir -p /root/vdir && chmod 700 /root/vdir +lost=0 +i=0 +while [ $i -lt 40 ]; do + j=0; while [ $j -lt 50 ]; do : > /root/vdir/f$j; j=$((j+1)); done + [ -d /glacier/usr/$U ] || gstore -n "$U" >/dev/null + B=/glacier/usr/$U + su tester -c "mkdir -p $B/store/d/a/b/c; j=0; while [ \$j -lt 200 ]; do : > $B/store/d/x\$j; j=\$((j+1)); done" + su tester -c "while :; do mv $B/store/d $B/store/.d 2>/dev/null; ln -s /root/vdir $B/store/d 2>/dev/null; rm -f $B/store/d; mv $B/store/.d $B/store/d 2>/dev/null; done" >/dev/null 2>&1 & + SWAP=$! + gstore -x "$U" >/dev/null 2>&1 + kill $SWAP 2>/dev/null; wait $SWAP 2>/dev/null + [ "$(ls /root/vdir | wc -l)" = 50 ] || lost=$((lost+1)) + i=$((i+1)) +done +check "gstore -x deleted nothing through a swapped symlink (40 runs, $lost with losses)" [ $lost = 0 ] + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/audit_alpine.sh.old2 b/tests/audit_alpine.sh.old2 new file mode 100644 index 0000000..a99f320 --- /dev/null +++ b/tests/audit_alpine.sh.old2 @@ -0,0 +1,146 @@ +#!/bin/sh +# Fixes from the 2026-10-06 security audit: +# - a package may not ship a top-level files/.glacier-* entry: as a +# symlink, .glacier-fresh made syspkg truncate any file as root; +# .glacier-overwrite granted the package -O; .glacier-manifest +# rewrote its saved manifest; +# - a manifest with @include is refused (libconfig would read any file +# as root), and so is a dependency or conflict entry without a name; +# - what syspkg shows and compares is what the LIBRARY reads from the +# manifest: a decoy comment can't hide that a package replaces one; +# - no CLI argument reaches a format string (gstore's argv[0], gpkg +# -u's operand); gstore refuses a UID that would wrap in C; +# - root deleting a user's tree (gstore -x) never follows a symlink +# swapped in mid-walk (race test, many iterations). +# Runs INSIDE the Dockerfile.alpine_root image: +# +# docker run --rm -v "$PWD/tests/audit_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +installed() { grep -q "^$1::$2::" /glacier/sys/index/current; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +P=/srv/pkgs +mkdir -p $P && chmod 755 /srv $P + +# raw NAME VER REPO [MANIFEST_EXTRA] -> $P/NAME-VER.gpkg (+ sidecar). The +# package tree is left at $W/NAME-VER for the caller to add to first: +# call raw_dir, edit $D, then raw_pack. +raw_dir() { + W=$(mktemp -d); D=$W/$1-$2 + mkdir -p $D/files/usr/bin + printf '%sPKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_REPO = "%s";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' \ + "${4:-}" "$1" "$2" "$3" > $D/manifest.gpm.cfg + printf '#!/bin/sh\necho %s %s\n' "$1" "$2" > $D/files/usr/bin/$1 + chmod 755 $D/files/usr/bin/$1 + RAW=$P/$1-$2.gpkg +} +raw_pack() { + tar -C $W -czf $RAW "$(basename $D)" + echo "sha256:$(sha256sum $RAW | cut -c1-64)" > $RAW.sha256 + rm -rf $W +} +inst() { R sh -c "echo y | syspkg -l $*"; } + +syspkg -n >/dev/null +echo "important root data" > /root/victim && chmod 600 /root/victim + +hr "reserved .glacier-* names" +raw_dir fresh 1.0.0 extra; ln -s /root/victim $D/files/.glacier-fresh; raw_pack +inst $RAW +check "a .glacier-fresh symlink is refused" has "[x] Refusing archive entry 'fresh-1.0.0/files/.glacier-fresh': .glacier-* names are reserved." +check "...exit 1" rc 1 +check "...the file it pointed at is untouched" [ "$(cat /root/victim)" = "important root data" ] +check "...nothing installed" sh -c '! grep -q "::fresh::" /glacier/sys/index/current' +check "...no half-made version dir" [ ! -e /glacier/sys/store/extra/fresh/fresh-1.0.0 ] +raw_dir selfo 1.0.0 extra; : > $D/files/.glacier-overwrite; raw_pack +inst $RAW +check "a .glacier-overwrite (self-granted -O) is refused" has "files/.glacier-overwrite': .glacier-* names are reserved." +raw_dir man 1.0.0 extra; printf 'PKG_NAME = "x";\n' > $D/files/.glacier-manifest; raw_pack +inst $RAW +check "a .glacier-manifest is refused" has "files/.glacier-manifest': .glacier-* names are reserved." +raw_dir keep 1.0.0 extra; mkdir -p $D/files/usr/lib; : > $D/files/usr/lib/.keep; : > $D/files/.hidden; raw_pack +inst $RAW +check "other dotfiles still install" installed extra keep +adduser -D tester >/dev/null 2>&1 +U=$(id -u tester) +gstore -n "$U" >/dev/null +echo "tester data" > /srv/tester-file && chown tester /srv/tester-file +raw_dir ufresh 1.0.0 extra; ln -s /srv/tester-file $D/files/.glacier-fresh; raw_pack +R su tester -c "echo y | gpkg -l $RAW" +check "gpkg refuses one too" has "files/.glacier-fresh': .glacier-* names are reserved." +check "...leaving the user's file alone" [ "$(cat /srv/tester-file)" = "tester data" ] + +hr "manifests" +raw_dir incl 1.0.0 extra '@include "/etc/glacier/glacier.conf" +'; raw_pack +inst $RAW +check "@include in a manifest is refused" has "[x] Cannot read the manifest of $RAW." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ] && ! echo \"\$0\" | grep -q Proceed" "$OUT" +check "...nothing installed" sh -c '! grep -q "::incl::" /glacier/sys/index/current' +raw_dir incl2 1.0.0 extra ' @include "/etc/glacier/glacier.conf" +'; raw_pack +inst $RAW +check "...indented too" has "[x] Cannot read the manifest of $RAW." +raw_dir mail 1.0.0 extra 'PKG_MAINT = "someone@example.org"; +'; raw_pack +inst $RAW +check "an @ elsewhere (an e-mail address) is fine" installed extra mail +raw_dir noname 1.0.0 extra; sed -i 's/PKG_DEPS = ();/PKG_DEPS = ( { PKG_VER = "1.0.0"; } );/' $D/manifest.gpm.cfg; raw_pack +inst $RAW +check "a dependency without a name is refused" has "[x] Cannot read the manifest of $RAW." +raw_dir badconf 1.0.0 extra; sed -i 's#PKG_CONFS = ();#PKG_CONFS = ( { PKG_NAME = "../x"; PKG_VER = "1.0.0"; } );#' $D/manifest.gpm.cfg; raw_pack +inst $RAW +check "a conflict with an unsafe name is refused" has "[x] Cannot read the manifest of $RAW." +raw_dir dup 1.0.0 extra; raw_pack +inst $RAW +raw_dir dup 2.0.0 extra '// PKG_REPO = "community"; +'; raw_pack +inst $RAW +check "a decoy PKG_REPO comment can't hide a replacement" has "[x] extra::dup 1.0.0 is already installed." +check "...one version stays in the store" [ "$(ls /glacier/sys/store/extra/dup)" = "dup-1.0.0" ] + +hr "format strings and UIDs" +ln -s /app/gstore '/srv/gs%s%s%s%s%n' +R '/srv/gs%s%s%s%s%n' -b "$U" /srv/b.tgz +check "gstore -b run as a name full of %s%n works" rc 0 +check "...and prints it nowhere as a format" has "[✓] Successfully created backup for UID $U." +# gpkg -f/-u operands as formats: tests/fetch_alpine.sh (they need a repo). +R gstore -n 4294968296 +check "a UID above uid_t's range is refused" has "[x] Invalid UID: 4294968296" +R gstore -x -- -1 +R gstore -x -1000 +check "a negative UID is refused" sh -c "[ $RC = 1 ]" +check "...and the tester's directory survives" [ -d /glacier/usr/$U ] + +hr "races: root never follows a symlink swapped into a user's tree" +mkdir -p /root/vdir && chmod 700 /root/vdir +lost=0 +i=0 +while [ $i -lt 40 ]; do + j=0; while [ $j -lt 50 ]; do : > /root/vdir/f$j; j=$((j+1)); done + [ -d /glacier/usr/$U ] || gstore -n "$U" >/dev/null + B=/glacier/usr/$U + su tester -c "mkdir -p $B/store/d/a/b/c; j=0; while [ \$j -lt 200 ]; do : > $B/store/d/x\$j; j=\$((j+1)); done" + su tester -c "while :; do mv $B/store/d $B/store/.d 2>/dev/null; ln -s /root/vdir $B/store/d 2>/dev/null; rm -f $B/store/d; mv $B/store/.d $B/store/d 2>/dev/null; done" >/dev/null 2>&1 & + SWAP=$! + gstore -x "$U" >/dev/null 2>&1 + kill $SWAP 2>/dev/null; wait $SWAP 2>/dev/null + [ "$(ls /root/vdir | wc -l)" = 50 ] || lost=$((lost+1)) + i=$((i+1)) +done +check "gstore -x deleted nothing through a swapped symlink (40 runs, $lost with losses)" [ $lost = 0 ] + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/bootstrap_alpine.sh b/tests/bootstrap_alpine.sh new file mode 100644 index 0000000..5184898 --- /dev/null +++ b/tests/bootstrap_alpine.sh @@ -0,0 +1,348 @@ +#!/bin/sh +# glacier-bootstrap, local mode (ROADMAP 1.3, GLACIER_BOOTSTRAP.txt): +# - a template + PKGDIR become a chrootable system in T, as root and as +# a user through doas; the host's /usr, /glacier and /etc stay +# byte-identical; the private copies are removed; +# - every template, verification and resolution problem is reported +# (all of them, each with its own exit status) before T is touched; +# - a pin is enforced, and a tampered file never reaches syspkg; +# - T must pass syspkg -R's trust check and be fresh, or initialised +# with nothing installed (a declined prompt can be re-run); +# - one transaction: a syspkg refusal leaves T with nothing installed; +# - -n never touches T; -t fails (6) when T has no working /bin/sh; +# - repositories: T's indexes are fetched with syspkg -R T -y, from +# T's OWN repos.conf and keys (a key the host doesn't trust), into +# T only; a failed fetch exits 7 without "Bootstrapped"; no url is a +# warning; a T keyring file resolving outside T is refused; -R -f +# uses T's repositories too. +# Runs INSIDE the Dockerfile.alpine_root image: +# +# docker run --rm -v "$PWD/tests/bootstrap_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +export PATH=/app:$PATH + +# B ARGS...: run glacier-bootstrap as root, answering the prompt with $ANS +# (default y). Sets $OUT and $RC. +B() { + OUT=$( (echo "${ANS:-y}" | glacier-bootstrap "$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed 's/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +untouched() { [ -z "$(ls -A "$1")" ]; } + +P=/srv/pkgs +mkdir -p $P /srv/src + +# pkg NAME VER REPO [DEPS] [CONFS] -> $P/NAME-VER.gpkg + sidecar; files +# come from /srv/src/NAME (laid out as files/...), if it exists. +pkg() { + w=$(mktemp -d); d=$w/$1-$2 + mkdir -p $d/files + [ -d /srv/src/$1 ] && cp -a /srv/src/$1/. $d/files/ + list() { l=""; sep=""; for it in $1; do l="$l$sep{ PKG_NAME = \"${it%%:*}\"; PKG_VER = \"${it#*:}\"; }"; sep=", "; done; echo "$l"; } + printf 'PKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_DESC = "t";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "%s";\nPKG_DEPS = (%s);\nPKG_CONFS = (%s);\n' \ + "$1" "$2" "$3" "$(list "$4")" "$(list "$5")" > $d/manifest.gpm.cfg + tar czf $P/$1-$2.gpkg -C $w $1-$2 + rm -rf $w + sidecar $P/$1-$2.gpkg +} +sidecar() { printf 'sha256:%s\n' "$(sha256sum "$1" | cut -d' ' -f1)" > "$1.sha256"; gsign -S -s /root/glacier-test.sec -m "$1.sha256" >/dev/null; } +hash() { sha256sum "$1" | cut -d' ' -f1; } + +# A minimal system out of Alpine's own loader and busybox: alpmusl puts +# the loader where PT_INTERP looks (/lib -> usr/lib), abox gives /bin/sh. +mkdir -p /srv/src/alpmusl/usr/lib +cp /lib/ld-musl-x86_64.so.1 /srv/src/alpmusl/usr/lib/ +ln -s ld-musl-x86_64.so.1 /srv/src/alpmusl/usr/lib/libc.musl-x86_64.so.1 +mkdir -p /srv/src/abox/usr/bin +cp /bin/busybox /srv/src/abox/usr/bin/busybox +ln -s busybox /srv/src/abox/usr/bin/sh +mkdir -p /srv/src/abox/etc; echo "from abox" > /srv/src/abox/etc/motd +pkg alpmusl 1.2.5 base +pkg abox 1.37.0 base "alpmusl:1.2.5" +mkdir -p /srv/src/tool/usr/bin; printf '#!/bin/sh\necho tool-ok\n' > /srv/src/tool/usr/bin/tool; chmod 755 /srv/src/tool/usr/bin/tool +pkg tool 2.0.0 extra "abox:1.0.0" +# Resolution fixtures +pkg lib 1.0.0 extra +pkg app 1.0.0 extra "lib:2.0.0" +pkg needy 1.0.0 extra "ghost:1.0.0" +pkg rival 1.0.0 extra "" "abox:0.0.0" +# Collision: both ship /glacier/sys/links/bin/same +mkdir -p /srv/src/col1/usr/bin /srv/src/col2/usr/bin +echo 1 > /srv/src/col1/usr/bin/same; echo 2 > /srv/src/col2/usr/bin/same +pkg col1 1.0.0 extra; pkg col2 1.0.0 extra +# No shell at all +pkg data 1.0.0 extra + +T=/mnt/img +mkdir -p $T +cat > /srv/min.template </dev/null | sort + find /usr /glacier /etc -xdev -type f -exec sha256sum {} + 2>/dev/null | sort +} +snap > /tmp/before +ls -A /tmp > /tmp/tmp-before + +echo "== 1. bootstrap as root, with the smoke test" +B -t -d $P /srv/min.template $T +check "exits 0" rc 0 +check "syspkg's summary was shown" has "Proceed? (y/N)" +check "ends with Bootstrapped" has "[✓] Bootstrapped minimal into $T." +check "smoke test reported" has "[✓] chroot $T /bin/sh -c true succeeded." +check "no repos.conf in T: a warning" has "[!] No remote repositories are configured in $T." +check "no repos.conf in T: no refresh" lacks "Syncing" +check "the pin is shown" has " * base::alpmusl 1.2.5 (pinned)" +check "syspkg read the verified copies, not PKGDIR" lacks "staged from $P/" +check "T's index lists all three" sh -c "grep -c :: $T/glacier/sys/index/current | grep -qx 3" +check "chroot T runs a base program" sh -c "chroot $T /bin/sh -c 'echo ok' | grep -qx ok" +check "chroot T runs an extra program (sys links)" sh -c "chroot $T /glacier/sys/links/bin/tool | grep -qx tool-ok" +check "/etc was copied into T" sh -c "grep -qx 'from abox' $T/etc/motd && ! [ -L $T/etc/motd ]" +check "T's links say runtime paths" sh -c "readlink $T/usr/bin/busybox | grep -q '^/glacier/sys/store/'" +snap > /tmp/after +check "host /usr, /glacier and /etc are byte-identical" cmp -s /tmp/before /tmp/after +ls -A /tmp | grep -v '^after$' | grep -v '^tmp-after$' > /tmp/tmp-after +check "the private copies were removed" cmp -s /tmp/tmp-before /tmp/tmp-after + +echo "== 2. T already has packages: refused" +B -d $P /srv/min.template $T +check "exits 1" rc 1 +check "says so" has "[x] $T already has packages installed." + +echo "== 3. as a user, through doas" +echo "permit nopass glacier as root cmd /app/syspkg" >> /etc/doas.conf +echo "permit nopass glacier as root cmd chroot" >> /etc/doas.conf +mkdir -p /mnt/u +OUT=$(su glacier -c "PATH=/app:\$PATH; echo y | glacier-bootstrap -t -d $P /srv/min.template /mnt/u; echo rc=\$?" 2>&1 | nocolor) +echo "$OUT" | sed 's/^/ /' +check "exits 0" has "rc=0" +check "bootstrapped" has "[✓] Bootstrapped minimal into /mnt/u." +check "smoke test passed" has "succeeded." +check "T's store is root's" sh -c "[ \"\$(stat -c %u /mnt/u/glacier/sys/store)\" = 0 ]" +check "the user's private copies were removed" sh -c "! find /tmp -maxdepth 1 -user glacier | grep -q ." + +echo "== 4. template errors: all reported, exit 2, T untouched" +mkdir -p /mnt/e +cat > /srv/bad.template < /srv/noname.template +B -d $P /srv/noname.template /mnt/e +check "no NAME: exit 2" rc 2 +check "no NAME: says so" has "noname.template: No NAME." +printf 'NAME=empty\n# nothing\n' > /srv/empty.template +B -d $P /srv/empty.template /mnt/e +check "no packages: says so" has "empty.template: No packages." +B -d $P /srv/missing.template /mnt/e +check "missing template: exit 2" rc 2 + +echo "== 5. verification: all reported, exit 3, T untouched" +mkdir -p /srv/v +for f in alpmusl-1.2.5 abox-1.37.0 tool-2.0.0 lib-1.0.0; do cp $P/$f.gpkg $P/$f.gpkg.sha256 /srv/v/; done +rm /srv/v/abox-1.37.0.gpkg.sha256 +echo "sha256:nothex" > /srv/v/lib-1.0.0.gpkg.sha256 +echo junk >> /srv/v/tool-2.0.0.gpkg +cat > /srv/v.template <> /srv/w/alpmusl-1.2.5.gpkg; sidecar /srv/w/alpmusl-1.2.5.gpkg +printf 'NAME=w\nPKG=alpmusl 1.2.5 sha256:%s\n' "$(hash $P/alpmusl-1.2.5.gpkg)" > /srv/w.template +B -d /srv/w /srv/w.template /mnt/e +check "exits 3" rc 3 +check "pin vs sidecar" has "the template pins $(hash $P/alpmusl-1.2.5.gpkg), the sidecar says" +check "T untouched" untouched /mnt/e + +echo "== 7. resolution: all reported, exit 4, T untouched" +mkdir -p /srv/r; cp $P/* /srv/r/ +cp $P/lib-1.0.0.gpkg /srv/r/libx-1.0.0.gpkg; sidecar /srv/r/libx-1.0.0.gpkg +cat > /srv/r.template <= 2.0.0, but the template lists 1.0.0." +check "dependency not listed" has "[x] extra::needy requires ghost >= 1.0.0, which the template does not list." +check "conflict" has "[x] base::abox conflicts with extra::rival." +check "T untouched" untouched /mnt/e + +echo "== 8. -n: plan only" +B -n -d $P /srv/min.template /mnt/e +check "exits 0" rc 0 +check "says dry run" has "[✓] Dry run: every package verified and resolved." +check "never asks" lacks "Proceed" +check "T untouched" untouched /mnt/e + +echo "== 9. target refusals (exit 1)" +B -d $P /srv/min.template mnt/e +check "relative: exit 1" rc 1 +check "relative: says so" has "[x] TARGET must be an absolute path: mnt/e" +B -d $P /srv/min.template / +check "/: refused" has "[x] TARGET must not be /." +mkdir -p /tmp/tt +B -d $P /srv/min.template /tmp/tt +check "under /tmp: exit 1" rc 1 +check "under /tmp: the library says why" has "[x] Refusing install root /tmp/tt: /tmp is not root-owned, or is group/world-writable." +B -d $P /srv/min.template /mnt/nonexistent +check "missing: exit 1" rc 1 +B -x -d $P /srv/min.template /mnt/e +check "unknown option: exit 1" rc 1 +check "unknown option: says so" has "[x] Unknown option: -x" + +echo "== 10. declined prompt: exit 5, then re-runnable" +mkdir -p /mnt/d +ANS=n B -d $P /srv/min.template /mnt/d +check "exits 5" rc 5 +check "says nothing was installed" has "[x] Nothing was installed into /mnt/d." +check "T was initialised" test -e /mnt/d/glacier/sys/index/current +B -d $P /srv/min.template /mnt/d +check "re-run exits 0" rc 0 +check "re-run did not run -n again" lacks "Created system glacier directories" +check "re-run installed" has "[✓] Bootstrapped minimal into /mnt/d." + +echo "== 11. one transaction: a syspkg refusal installs nothing (exit 5)" +mkdir -p /mnt/c +printf 'NAME=c\nPKG=alpmusl 1.2.5\nPKG=abox 1.37.0\nPKG=col1 1.0.0\nPKG=col2 1.0.0\n' > /srv/c.template +B -d $P /srv/c.template /mnt/c +check "exits 5" rc 5 +check "syspkg reported the collision" has "both ship /glacier/sys/links/bin/same." +check "T has nothing installed" sh -c "! grep -q :: /mnt/c/glacier/sys/index/current" +check "T's /usr has no links" sh -c "[ -z \"\$(ls -A /mnt/c/usr/bin)\" ]" + +echo "== 12. -t with no shell: exit 6" +mkdir -p /mnt/s +printf 'NAME=s\nPKG=data 1.0.0\n' > /srv/s.template +B -t -d $P /srv/s.template /mnt/s +check "exits 6" rc 6 +check "says the smoke test failed" has "[x] chroot /mnt/s /bin/sh -c true failed." + +echo "== 13. syspkg not on PATH: exit 5" +mkdir -p /mnt/p +OUT=$( (echo y | PATH=/usr/bin:/bin /app/glacier-bootstrap -d $P /srv/min.template /mnt/p; echo "rc=$?") 2>&1 | nocolor) +check "exits 5" has "rc=5" +check "says so" has "[x] syspkg is not on PATH." +check "T untouched" untouched /mnt/p + +echo "== 14. repositories: T's own repos.conf and keys" +# tkey is trusted by T's repos.conf only; the host's lists glacier-test. +gsign -G -p /srv/tkey.pub -s /root/tkey.sec -c tkey >/dev/null +R=/srv/repo/base +mkdir -p $R && chmod 755 /srv/repo $R +# repos NAME URL -> package NAME 1.0.0 (base), shipping T's keyring +repos() { + rm -rf /srv/src/$1; mkdir -p /srv/src/$1/etc/glacier/keys + cp /srv/tkey.pub /srv/src/$1/etc/glacier/keys/ + printf 'repos = (\n\t{ name = "base";%s keys = [ "tkey" ]; }\n);\n' "${2:+ url = \"$2\";}" \ + > /srv/src/$1/etc/glacier/repos.conf + pkg $1 1.0.0 base +} +repos trepos file://$R +repos badrepos file:///srv/nowhere +repos keyrepos "" +cp $P/alpmusl-1.2.5.gpkg* $P/abox-1.37.0.gpkg* $P/trepos-1.0.0.gpkg* $R/ +pkg lib 1.0.0 base; cp $P/lib-1.0.0.gpkg* $R/ +grepo -s /root/tkey.sec -r base $R >/dev/null +check "grepo signed the test repo" test -f $R/repo.idx.sig +printf 'NAME=r\nPKG=alpmusl 1.2.5\nPKG=abox 1.37.0\nPKG=trepos 1.0.0\n' > /srv/repo.template +mkdir -p /mnt/r +B -d $P /srv/repo.template /mnt/r +check "exits 0" rc 0 +check "synced" has "[✓] All repositories synced successfully." +check "then Bootstrapped" has "[✓] Bootstrapped r into /mnt/r." +check "T holds the index" cmp -s $R/repo.idx /mnt/r/glacier/sys/repos/base.idx +check "and its signature" cmp -s $R/repo.idx.sig /mnt/r/glacier/sys/repos/base.idx.sig +check "the index is world-readable" sh -c "[ \"\$(stat -c %a /mnt/r/glacier/sys/repos/base.idx)\" = 644 ]" +check "the host got no index" test ! -e /glacier/sys/repos/base.idx +OUT=$( (echo y | syspkg -R /mnt/r -f lib; echo "rc=$?") 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /' +check "syspkg -R T -f uses T's repositories" has "rc=0" +check "and installed into T" sh -c "grep -q '^base::lib::1.0.0::' /mnt/r/glacier/sys/index/current" + +echo "== 15. a failed fetch: exit 7, T stays installed" +mkdir -p /mnt/f +printf 'NAME=f\nPKG=alpmusl 1.2.5\nPKG=abox 1.37.0\nPKG=badrepos 1.0.0\n' > /srv/f.template +B -d $P /srv/f.template /mnt/f +check "exits 7" rc 7 +check "says why" has "[x] Cannot fetch the index for base." +check "no Bootstrapped" lacks "Bootstrapped" +check "T is installed" sh -c "grep -q '^base::badrepos::1.0.0' /mnt/f/glacier/sys/index/current" + +echo "== 15b. T's repos.conf has no url: a warning, exit 0" +mkdir -p /mnt/k +printf 'NAME=k\nPKG=alpmusl 1.2.5\nPKG=abox 1.37.0\nPKG=keyrepos 1.0.0\n' > /srv/k.template +B -d $P /srv/k.template /mnt/k +check "exits 0" rc 0 +check "warns" has "[!] No remote repositories are configured in /mnt/k." +check "no refresh" lacks "Syncing" +check "Bootstrapped" has "[✓] Bootstrapped k into /mnt/k." + +echo "== 16. T's keyring must resolve inside T" +mkdir -p /srv/hostconf && cp /mnt/r/etc/glacier/repos.conf /srv/hostconf/ +rm /mnt/r/etc/glacier/repos.conf; ln -s /srv/hostconf/repos.conf /mnt/r/etc/glacier/repos.conf +OUT=$(syspkg -R /mnt/r -y 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /' +check "repos.conf outside T refused" has "[x] Refusing /mnt/r/etc/glacier/repos.conf: it resolves outside /mnt/r." +rm /mnt/r/etc/glacier/repos.conf; cp /srv/hostconf/repos.conf /mnt/r/etc/glacier/ +rm /mnt/r/etc/glacier/keys/tkey.pub; ln -s /srv/tkey.pub /mnt/r/etc/glacier/keys/tkey.pub +OUT=$(syspkg -R /mnt/r -y 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /' +check "a key outside T refused" has "[x] Refusing /mnt/r/etc/glacier/keys/tkey.pub: it resolves outside /mnt/r." +rm /mnt/r/etc/glacier/keys/tkey.pub; cp /srv/tkey.pub /mnt/r/etc/glacier/keys/ +OUT=$(syspkg -R /mnt/r -y 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /' +check "restored: syncs again" has "[✓] All repositories synced successfully." + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/bootstrap_alpine.sh.old b/tests/bootstrap_alpine.sh.old new file mode 100644 index 0000000..6058e91 --- /dev/null +++ b/tests/bootstrap_alpine.sh.old @@ -0,0 +1,276 @@ +#!/bin/sh +# glacier-bootstrap, local mode (ROADMAP 1.3, GLACIER_BOOTSTRAP.txt): +# - a template + PKGDIR become a chrootable system in T, as root and as +# a user through doas; the host's /usr, /glacier and /etc stay +# byte-identical; the private copies are removed; +# - every template, verification and resolution problem is reported +# (all of them, each with its own exit status) before T is touched; +# - a pin is enforced, and a tampered file never reaches syspkg; +# - T must pass syspkg -R's trust check and be fresh, or initialised +# with nothing installed (a declined prompt can be re-run); +# - one transaction: a syspkg refusal leaves T with nothing installed; +# - -n never touches T; -t fails (6) when T has no working /bin/sh. +# Runs INSIDE the Dockerfile.alpine_root image: +# +# docker run --rm -v "$PWD/tests/bootstrap_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +export PATH=/app:$PATH + +# B ARGS...: run glacier-bootstrap as root, answering the prompt with $ANS +# (default y). Sets $OUT and $RC. +B() { + OUT=$( (echo "${ANS:-y}" | glacier-bootstrap "$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed 's/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +untouched() { [ -z "$(ls -A "$1")" ]; } + +P=/srv/pkgs +mkdir -p $P /srv/src + +# pkg NAME VER REPO [DEPS] [CONFS] -> $P/NAME-VER.gpkg + sidecar; files +# come from /srv/src/NAME (laid out as files/...), if it exists. +pkg() { + w=$(mktemp -d); d=$w/$1-$2 + mkdir -p $d/files + [ -d /srv/src/$1 ] && cp -a /srv/src/$1/. $d/files/ + list() { l=""; sep=""; for it in $1; do l="$l$sep{ PKG_NAME = \"${it%%:*}\"; PKG_VER = \"${it#*:}\"; }"; sep=", "; done; echo "$l"; } + printf 'PKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_DESC = "t";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "%s";\nPKG_DEPS = (%s);\nPKG_CONFS = (%s);\n' \ + "$1" "$2" "$3" "$(list "$4")" "$(list "$5")" > $d/manifest.gpm.cfg + tar czf $P/$1-$2.gpkg -C $w $1-$2 + rm -rf $w + sidecar $P/$1-$2.gpkg +} +sidecar() { printf 'sha256:%s\n' "$(sha256sum "$1" | cut -d' ' -f1)" > "$1.sha256"; gsign -S -s /root/glacier-test.sec -m "$1.sha256" >/dev/null; } +hash() { sha256sum "$1" | cut -d' ' -f1; } + +# A minimal system out of Alpine's own loader and busybox: alpmusl puts +# the loader where PT_INTERP looks (/lib -> usr/lib), abox gives /bin/sh. +mkdir -p /srv/src/alpmusl/usr/lib +cp /lib/ld-musl-x86_64.so.1 /srv/src/alpmusl/usr/lib/ +ln -s ld-musl-x86_64.so.1 /srv/src/alpmusl/usr/lib/libc.musl-x86_64.so.1 +mkdir -p /srv/src/abox/usr/bin +cp /bin/busybox /srv/src/abox/usr/bin/busybox +ln -s busybox /srv/src/abox/usr/bin/sh +mkdir -p /srv/src/abox/etc; echo "from abox" > /srv/src/abox/etc/motd +pkg alpmusl 1.2.5 base +pkg abox 1.37.0 base "alpmusl:1.2.5" +mkdir -p /srv/src/tool/usr/bin; printf '#!/bin/sh\necho tool-ok\n' > /srv/src/tool/usr/bin/tool; chmod 755 /srv/src/tool/usr/bin/tool +pkg tool 2.0.0 extra "abox:1.0.0" +# Resolution fixtures +pkg lib 1.0.0 extra +pkg app 1.0.0 extra "lib:2.0.0" +pkg needy 1.0.0 extra "ghost:1.0.0" +pkg rival 1.0.0 extra "" "abox:0.0.0" +# Collision: both ship /glacier/sys/links/bin/same +mkdir -p /srv/src/col1/usr/bin /srv/src/col2/usr/bin +echo 1 > /srv/src/col1/usr/bin/same; echo 2 > /srv/src/col2/usr/bin/same +pkg col1 1.0.0 extra; pkg col2 1.0.0 extra +# No shell at all +pkg data 1.0.0 extra + +T=/mnt/img +mkdir -p $T +cat > /srv/min.template </dev/null | sort + find /usr /glacier /etc -xdev -type f -exec sha256sum {} + 2>/dev/null | sort +} +snap > /tmp/before +ls -A /tmp > /tmp/tmp-before + +echo "== 1. bootstrap as root, with the smoke test" +B -t -d $P /srv/min.template $T +check "exits 0" rc 0 +check "syspkg's summary was shown" has "Proceed? (y/N)" +check "ends with Bootstrapped" has "[✓] Bootstrapped minimal into $T." +check "smoke test reported" has "[✓] chroot $T /bin/sh -c true succeeded." +check "the pin is shown" has " * base::alpmusl 1.2.5 (pinned)" +check "syspkg read the verified copies, not PKGDIR" lacks "staged from $P/" +check "T's index lists all three" sh -c "grep -c :: $T/glacier/sys/index/current | grep -qx 3" +check "chroot T runs a base program" sh -c "chroot $T /bin/sh -c 'echo ok' | grep -qx ok" +check "chroot T runs an extra program (sys links)" sh -c "chroot $T /glacier/sys/links/bin/tool | grep -qx tool-ok" +check "/etc was copied into T" sh -c "grep -qx 'from abox' $T/etc/motd && ! [ -L $T/etc/motd ]" +check "T's links say runtime paths" sh -c "readlink $T/usr/bin/busybox | grep -q '^/glacier/sys/store/'" +snap > /tmp/after +check "host /usr, /glacier and /etc are byte-identical" cmp -s /tmp/before /tmp/after +ls -A /tmp | grep -v '^after$' | grep -v '^tmp-after$' > /tmp/tmp-after +check "the private copies were removed" cmp -s /tmp/tmp-before /tmp/tmp-after + +echo "== 2. T already has packages: refused" +B -d $P /srv/min.template $T +check "exits 1" rc 1 +check "says so" has "[x] $T already has packages installed." + +echo "== 3. as a user, through doas" +echo "permit nopass glacier as root cmd /app/syspkg" >> /etc/doas.conf +echo "permit nopass glacier as root cmd chroot" >> /etc/doas.conf +mkdir -p /mnt/u +OUT=$(su glacier -c "PATH=/app:\$PATH; echo y | glacier-bootstrap -t -d $P /srv/min.template /mnt/u; echo rc=\$?" 2>&1 | nocolor) +echo "$OUT" | sed 's/^/ /' +check "exits 0" has "rc=0" +check "bootstrapped" has "[✓] Bootstrapped minimal into /mnt/u." +check "smoke test passed" has "succeeded." +check "T's store is root's" sh -c "[ \"\$(stat -c %u /mnt/u/glacier/sys/store)\" = 0 ]" +check "the user's private copies were removed" sh -c "! find /tmp -maxdepth 1 -user glacier | grep -q ." + +echo "== 4. template errors: all reported, exit 2, T untouched" +mkdir -p /mnt/e +cat > /srv/bad.template < /srv/noname.template +B -d $P /srv/noname.template /mnt/e +check "no NAME: exit 2" rc 2 +check "no NAME: says so" has "noname.template: No NAME." +printf 'NAME=empty\n# nothing\n' > /srv/empty.template +B -d $P /srv/empty.template /mnt/e +check "no packages: says so" has "empty.template: No packages." +B -d $P /srv/missing.template /mnt/e +check "missing template: exit 2" rc 2 + +echo "== 5. verification: all reported, exit 3, T untouched" +mkdir -p /srv/v +for f in alpmusl-1.2.5 abox-1.37.0 tool-2.0.0 lib-1.0.0; do cp $P/$f.gpkg $P/$f.gpkg.sha256 /srv/v/; done +rm /srv/v/abox-1.37.0.gpkg.sha256 +echo "sha256:nothex" > /srv/v/lib-1.0.0.gpkg.sha256 +echo junk >> /srv/v/tool-2.0.0.gpkg +cat > /srv/v.template <> /srv/w/alpmusl-1.2.5.gpkg; sidecar /srv/w/alpmusl-1.2.5.gpkg +printf 'NAME=w\nPKG=alpmusl 1.2.5 sha256:%s\n' "$(hash $P/alpmusl-1.2.5.gpkg)" > /srv/w.template +B -d /srv/w /srv/w.template /mnt/e +check "exits 3" rc 3 +check "pin vs sidecar" has "the template pins $(hash $P/alpmusl-1.2.5.gpkg), the sidecar says" +check "T untouched" untouched /mnt/e + +echo "== 7. resolution: all reported, exit 4, T untouched" +mkdir -p /srv/r; cp $P/* /srv/r/ +cp $P/lib-1.0.0.gpkg /srv/r/libx-1.0.0.gpkg; sidecar /srv/r/libx-1.0.0.gpkg +cat > /srv/r.template <= 2.0.0, but the template lists 1.0.0." +check "dependency not listed" has "[x] extra::needy requires ghost >= 1.0.0, which the template does not list." +check "conflict" has "[x] base::abox conflicts with extra::rival." +check "T untouched" untouched /mnt/e + +echo "== 8. -n: plan only" +B -n -d $P /srv/min.template /mnt/e +check "exits 0" rc 0 +check "says dry run" has "[✓] Dry run: every package verified and resolved." +check "never asks" lacks "Proceed" +check "T untouched" untouched /mnt/e + +echo "== 9. target refusals (exit 1)" +B -d $P /srv/min.template mnt/e +check "relative: exit 1" rc 1 +check "relative: says so" has "[x] TARGET must be an absolute path: mnt/e" +B -d $P /srv/min.template / +check "/: refused" has "[x] TARGET must not be /." +mkdir -p /tmp/tt +B -d $P /srv/min.template /tmp/tt +check "under /tmp: exit 1" rc 1 +check "under /tmp: the library says why" has "[x] Refusing install root /tmp/tt: /tmp is not root-owned, or is group/world-writable." +B -d $P /srv/min.template /mnt/nonexistent +check "missing: exit 1" rc 1 +B -x -d $P /srv/min.template /mnt/e +check "unknown option: exit 1" rc 1 +check "unknown option: says so" has "[x] Unknown option: -x" + +echo "== 10. declined prompt: exit 5, then re-runnable" +mkdir -p /mnt/d +ANS=n B -d $P /srv/min.template /mnt/d +check "exits 5" rc 5 +check "says nothing was installed" has "[x] Nothing was installed into /mnt/d." +check "T was initialised" test -e /mnt/d/glacier/sys/index/current +B -d $P /srv/min.template /mnt/d +check "re-run exits 0" rc 0 +check "re-run did not run -n again" lacks "Created system glacier directories" +check "re-run installed" has "[✓] Bootstrapped minimal into /mnt/d." + +echo "== 11. one transaction: a syspkg refusal installs nothing (exit 5)" +mkdir -p /mnt/c +printf 'NAME=c\nPKG=alpmusl 1.2.5\nPKG=abox 1.37.0\nPKG=col1 1.0.0\nPKG=col2 1.0.0\n' > /srv/c.template +B -d $P /srv/c.template /mnt/c +check "exits 5" rc 5 +check "syspkg reported the collision" has "both ship /glacier/sys/links/bin/same." +check "T has nothing installed" sh -c "! grep -q :: /mnt/c/glacier/sys/index/current" +check "T's /usr has no links" sh -c "[ -z \"\$(ls -A /mnt/c/usr/bin)\" ]" + +echo "== 12. -t with no shell: exit 6" +mkdir -p /mnt/s +printf 'NAME=s\nPKG=data 1.0.0\n' > /srv/s.template +B -t -d $P /srv/s.template /mnt/s +check "exits 6" rc 6 +check "says the smoke test failed" has "[x] chroot /mnt/s /bin/sh -c true failed." + +echo "== 13. syspkg not on PATH: exit 5" +mkdir -p /mnt/p +OUT=$( (echo y | PATH=/usr/bin:/bin /app/glacier-bootstrap -d $P /srv/min.template /mnt/p; echo "rc=$?") 2>&1 | nocolor) +check "exits 5" has "rc=5" +check "says so" has "[x] syspkg is not on PATH." +check "T untouched" untouched /mnt/p + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/build_alpine.sh b/tests/build_alpine.sh new file mode 100644 index 0000000..626361b --- /dev/null +++ b/tests/build_alpine.sh @@ -0,0 +1,454 @@ +#!/bin/sh +# Source builds through syspkg/gpkg -f/-u (BUILD_DESIGN.txt; steps 3-4): +# - a recipe from a NAME-src repo is built in gsandbox and installed +# like a fetched package: summary and prompt BEFORE building, the +# patches applied, the manifest the build was handed, .glacier-src; +# - a name served by several repositories is asked about; Enter takes +# the first, a bad answer refuses; +# - TRAITS: recipe defaults, /etc/glacier/glacier.conf, per-package +# files (an unknown trait refused), the user's own files for gpkg; +# - -u stays on source, and rebuilds when the traits change; +# - syspkg builds as BUILD_USER (required), gpkg as the user; +# - PREFIX: a package is built for where its usr/ is linked +# (/glacier/sys/links, the user's links, /usr for base) and still +# packed as usr/; during the build PREFIX resolves to the layers; +# - kept packages: an installed source build's .gpkg is kept, and a +# later build uses it (and what it depends on) as a layer; kept +# only while that version is installed; +# - build output on the terminal (and in the log) unless -q/--quiet; +# - refusals: a source with the wrong hash, a failing build, a build +# that produces another package, a build dependency no binary repo +# has, an untrusted per-package file, -R. +# Needs what sandbox_alpine.sh needs, with /glacier off Docker's overlay: +# +# docker run --rm --security-opt seccomp=unconfined \ +# --security-opt apparmor=unconfined --security-opt systempaths=unconfined \ +# --tmpfs /glacier:exec,mode=755 \ +# -v "$PWD/tests/build_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +GCONF=/etc/glacier/glacier.conf +XSEC=/root/extrakey.sec +SSEC=/root/srckey.sec +E=/srv/extra +S=/srv/extra-src +SRC=/srv/sources +IDX=/glacier/sys/index/current +BUILD=/glacier/sys/build +BS=/srv/base-src +mkdir -p $E $S $SRC $BS && chmod 755 /srv $E $S $SRC $BS + +gsign -G -p $K/extrakey.pub -s $XSEC -c extrakey >/dev/null +gsign -G -p $K/srckey.pub -s $SSEC -c srckey >/dev/null +rconf() { # BASE-KEYS + printf 'repos = (\n%s\n%s\n%s\n%s\n);\n' \ + " { name = \"base\"; keys = [ $1 ]; }," \ + ' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; },' \ + ' { name = "extra-src"; url = "file:///srv/extra-src"; keys = [ "srckey" ]; },' \ + ' { name = "base-src"; url = "file:///srv/base-src"; keys = [ "srckey" ]; }' > $CONF + chmod 644 $CONF +} +rconf '"glacier-test"' +adduser -S -D -H -s /sbin/nologin gbuild +gconf() { printf 'KEEP_OLD = 1;\n%s\n' "$1" > $GCONF; chmod 644 $GCONF; } +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' + +# The binary repo: a toolchain (Alpine's build-base, busybox for /bin/sh) +# and a runtime dependency. +/app/tests/mkroot -o $E -r build-base -r busybox -p busybox toolchain 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E hidep 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E loudlib 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E both 9.0.0 extra >/dev/null +/app/tests/mkpkg -o $E twin 1.0.0 extra >/dev/null + +# A source tarball: hello prints "hello", "HELLO" with LOUD=1. +mksrc() { # NAME VER [MAKEFILE-EXTRA] + d=/tmp/src/$1-$2 + rm -rf $d && mkdir -p $d + printf '#include \nint main(void) {\n#ifdef LOUD\n\tputs("HELLO");\n#else\n\tputs("hello");\n#endif\n\treturn 0;\n}\n' > $d/hello.c + printf 'CFLAGS += $(if $(LOUD),-DLOUD)\n%s: hello.c\n\t$(CC) $(CFLAGS) -o %s hello.c\ninstall:\n\tinstall -D -m 755 %s $(DESTDIR)$(PREFIX)/bin/%s\n%s\n' \ + "$1" "$1" "$1" "$1" "${3:-}" > $d/Makefile + tar czf $SRC/$1-$2.tar.gz -C /tmp/src $1-$2 + sha256sum $SRC/$1-$2.tar.gz | cut -c1-64 +} +# A recipe bundle in the -src repo: NAME VER SHA [EXTRA-FIELDS] [BUILD-FILE] +mkrecipe() { + t=/tmp/rcp/$1-$2 + rm -rf $t && mkdir -p $t/patches + printf 'NAME = "%s"; VER = "%s"; REPO = "extra"; DESC = "test \\"%s\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/%s-%s.tar.gz"; SHA256 = "sha256:%s"; } );\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\n%s\n' \ + "$1" "$2" "$1" "$SRC" "$1" "$2" "$3" "${4:-}" > $t/recipe + [ -n "${5:-}" ] && printf '%s\n' "$5" > $t/build + rmdir $t/patches 2>/dev/null + tar czf $S/$1-$2.grcp -C /tmp/rcp $1-$2 +} +publish() { + grepo -s $XSEC -r extra $E | grep -v Wrote; grepo -s $SSEC -r extra-src $S | grep -v Wrote + grepo -s $SSEC -r base-src $BS | grep -v Wrote +} + +# hello 1.0.0, patched to greet glacier, depending on hidep. +H=$(mksrc hello 1.0.0) +t=/tmp/rcp/hello-1.0.0 +rm -rf $t && mkdir -p $t/patches +printf 'NAME = "hello"; VER = "1.0.0"; REPO = "extra"; DESC = "say \\"hi\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/hello-1.0.0.tar.gz"; SHA256 = "sha256:%s"; } );\nPATCHES = [ "01-glacier.patch" ];\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\nDEPS = ( { NAME = "hidep"; VER = "1.0.0"; }, { NAME = "loudlib"; VER = "1.0.0"; IF = "loud"; } );\n' "$SRC" "$H" > $t/recipe +cat > $t/patches/01-glacier.patch <<'EOF' +--- a/hello.c ++++ b/hello.c +@@ -5,3 +5,3 @@ + #else +- puts("hello"); ++ puts("hello, glacier"); + #endif +EOF +tar czf $S/hello-1.0.0.grcp -C /tmp/rcp hello-1.0.0 +mkrecipe both 1.0.0 "$(mksrc both 1.0.0)" +mkrecipe badhash 1.0.0 "$(printf '%064d' 0)" +mksrc badhash 1.0.0 >/dev/null +mkrecipe broken 1.0.0 "$(mksrc broken 1.0.0 'broken: ; false')" '' 'compile() { make broken; }' +mkrecipe evil 1.0.0 "$(mksrc evil 1.0.0)" '' 'package() { + mkdir -p /tmp/p/evil-1.0.0/files/usr/bin + echo x > /tmp/p/evil-1.0.0/files/usr/bin/evil + printf "PKG_NAME = \"evil\"; PKG_VER = \"1.0.0\"; PKG_REPO = \"base\"; PKG_DEPS = (); PKG_CONFS = ();\n" > /tmp/p/evil-1.0.0/manifest.gpm.cfg + tar czf /.glacier/out/evil-1.0.0.gpkg -C /tmp/p evil-1.0.0 + exit 0 +}' +mkrecipe core 1.0.0 "$(mksrc core 1.0.0)" '' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR$PREFIX/share" && echo "$PREFIX" > "$DESTDIR$PREFIX/share/core.prefix" +}' +sed -i 's/REPO = "extra"/REPO = "base"/' /tmp/rcp/core-1.0.0/recipe +tar czf $BS/core-1.0.0.grcp -C /tmp/rcp core-1.0.0 && rm $S/core-1.0.0.grcp +# where: a script with its data file's path compiled in. Its prepare +# fails unless PREFIX leads to the layers during the build. +mkrecipe where 1.0.0 "$(mksrc where 1.0.0)" 'BUILD = "hooks";' 'prepare() { [ -x "$PREFIX/bin/make" ]; } +package() { + mkdir -p "$DESTDIR$PREFIX/bin" "$DESTDIR$PREFIX/share/where" + echo here > "$DESTDIR$PREFIX/share/where/data" + printf "#!/bin/sh\ncat %s/share/where/data\n" "$PREFIX" > "$DESTDIR$PREFIX/bin/where" + chmod 755 "$DESTDIR$PREFIX/bin/where" +}' +sed -i 's/^BUILD = "make";$//' /tmp/rcp/where-1.0.0/recipe && tar czf $S/where-1.0.0.grcp -C /tmp/rcp where-1.0.0 +mkrecipe split 1.0.0 "$(mksrc split 1.0.0)" '' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR/usr/share" && echo x > "$DESTDIR/usr/share/split" +}' +# srclib: only a recipe, depending on hidep. srcapp needs both in its +# layers to build. +mkrecipe srclib 1.0.0 "$(mksrc srclib 1.0.0)" 'DEPS = ( { NAME = "hidep"; VER = "1.0.0"; } );' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR$PREFIX/share/srclib" && echo yes > "$DESTDIR$PREFIX/share/srclib/marker" +}' +mkrecipe srcapp 1.0.0 "$(mksrc srcapp 1.0.0)" 'DEPS = ( { NAME = "srclib"; VER = "1.0.0"; } );' 'prepare() { [ -f /usr/share/srclib/marker ] && [ -x /usr/bin/hidep ]; }' +mkrecipe twin 1.0.0 "$(mksrc twin 1.0.0)" +mkrecipe needy 1.0.0 "$(mksrc needy 1.0.0)" 'BUILD_DEPS = ( { NAME = "nothere"; VER = "1.0.0"; } );' +publish + +syspkg -n >/dev/null +yes_to() { sh -c "printf '$1' | $2"; } + +hr "syspkg -f of a recipe" +R yes_to 'y\n' 'syspkg -f hello' +check "built and installed" has "[✓] Completed with no errors." +check "...exit 0" rc 0 +check "the summary marks the build, its traits off by default" has " * extra-src::hello 1.0.0 [-loud] (build)" +check "...and the binary dependency" has " * extra::hidep 1.0.0 (dependency)" +check "...the prompt came before the build" sh -c 'echo "$0" | grep -n "Proceed\|Building extra-src" | head -1 | grep -q Proceed' "$OUT" +check "the build is announced" has "[i] Building extra-src::hello 1.0.0 [-loud]..." +check "...and done" has "[✓] Built extra-src::hello 1.0.0." +check "installed as extra::hello" grep -q "^extra::hello::1.0.0::explicit$" $IDX +check "...with its dependency, auto" grep -q "^extra::hidep::1.0.0::auto$" $IDX +check "...not the one only loud needs" sh -c "! grep -q loudlib $IDX" +check "...the patch applied" [ "$(/glacier/sys/links/bin/hello)" = "hello, glacier" ] +V=/glacier/sys/store/extra/hello/hello-1.0.0 +check "...recorded as built from extra-src" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...its manifest has PKG_TRAITS" grep -qF 'PKG_TRAITS = [ "-loud" ];' $V/.glacier-manifest +check "...and the recipe's DESC, quoted" grep -qF 'PKG_DESC = "say \"hi\"";' $V/.glacier-manifest +check "the layer belongs to BUILD_USER" [ "$(stat -c %U $BUILD/layers/toolchain-1.0.0-*)" = gbuild ] +check "...which owns layers/, 0700" [ "$(stat -c '%U %a' $BUILD/layers)" = "gbuild 700" ] +check "the build's in/work/out dirs are gone" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +check "the log is kept" grep -q "==> Done" $BUILD/logs/hello-1.0.0.log +check "...and the build's output was on the terminal" has "==> Applying 01-glacier.patch" +check "...the sources cached by hash" [ -f $BUILD/sources/$H ] +check "the cached bundle is deleted" [ ! -e /glacier/sys/cache/extra-src/hello-1.0.0.grcp ] +check "the store copy is root's, as any install" [ "$(stat -c %u /glacier/sys/store/extra/hello/hello-1.0.0/usr/bin/hello)" = 0 ] + +hr "declining builds nothing" +rm $BUILD/logs/hello-1.0.0.log +R yes_to 'n\n' 'syspkg -f -O hello' +check "nothing built" sh -c "[ ! -e $BUILD/logs/hello-1.0.0.log ]" +check "...nothing said about building" lacks "Building" + +hr "traits" +mkdir -p /etc/glacier/config +printf 'TRAITS = [ "lod" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u hello' +check "an unknown trait in a per-package file is refused" has "[x] /etc/glacier/config/hello.conf: hello has no trait lod." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ]" && check "...no prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud", "x11" ];' +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "the per-package file beats glacier.conf: nothing to rebuild" has "Nothing to do." +rm /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "glacier.conf turns loud on (x11, unknown to the recipe, ignored): a rebuild" has " * extra-src::hello 1.0.0 (traits) [+loud] (build)" +check "...installed" rc 0 +check "...built with LOUD" [ "$(/glacier/sys/links/bin/hello)" = "HELLO" ] +check "...with the dependency loud needs" grep -q "^extra::loudlib::1.0.0::auto$" $IDX +check "...in its manifest" grep -qF '{ PKG_NAME = "loudlib"; PKG_VER = "1.0.0"; }' $V/.glacier-manifest +check "...still marked as built from source" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...PKG_TRAITS updated" grep -qF 'PKG_TRAITS = [ "loud" ];' $V/.glacier-manifest +R yes_to 'y\n' 'syspkg -u' +check "unchanged traits: nothing to do" has "Nothing to do." +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +chmod 666 /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a world-writable per-package file is refused" has "[x] Refusing /etc/glacier/config/hello.conf: /etc/glacier/config/hello.conf is not root-owned, or is group/world-writable." +rm /etc/glacier/config/hello.conf +printf 'TRAITS = [ "loud" ]; COLOR = "red";\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a per-package file with an unknown key is malformed" has "[x] Malformed /etc/glacier/config/hello.conf." +rm /etc/glacier/config/hello.conf + +hr "-u stays on source" +H11=$(mksrc hello 1.1.0) +sed "s/1\.0\.0/1.1.0/g; s/$H/$H11/" /tmp/rcp/hello-1.0.0/recipe > /tmp/r.new +rm -rf /tmp/rcp/hello-1.1.0 && cp -a /tmp/rcp/hello-1.0.0 /tmp/rcp/hello-1.1.0 && mv /tmp/r.new /tmp/rcp/hello-1.1.0/recipe +sed -i 's/VER = "1.1.0"; }/VER = "1.0.0"; }/g; s/VER = "1.1.0"; IF/VER = "1.0.0"; IF/' /tmp/rcp/hello-1.1.0/recipe +tar czf $S/hello-1.1.0.grcp -C /tmp/rcp hello-1.1.0 +/app/tests/mkpkg -o $E hello 2.0.0 extra >/dev/null +publish +R yes_to 'y\n' 'syspkg -u hello' +check "a newer recipe is built, not extra's binary 2.0.0" has " * extra-src::hello 1.0.0 -> 1.1.0 [+loud] (build)" +check "...installed" grep -q "^extra::hello::1.1.0::explicit$" $IDX +check "...the old version backed up" [ -f /glacier/sys/backup/extra/hello/hello-1.0.0.gpkg ] +check "...its new package kept for builds" [ -f $BUILD/packages/extra@hello-1.1.0.gpkg ] +check "...the old one's deleted" [ ! -e $BUILD/packages/extra@hello-1.0.0.gpkg ] +check "...still on source" [ "$(cat /glacier/sys/store/extra/hello/hello-1.1.0/.glacier-src)" = extra-src ] + +hr "PREFIX" +R yes_to 'y\n' 'syspkg -f where' +check "built for /glacier/sys/links: finds its data through the links" [ "$(/glacier/sys/links/bin/where)" = here ] +check "...the path compiled in" grep -q "^cat /glacier/sys/links/share/where/data$" /glacier/sys/links/bin/where +check "...packed as usr/, as any package" [ -f /glacier/sys/store/extra/where/where-1.0.0/usr/share/where/data ] +check "...nothing else at the top" [ "$(ls /glacier/sys/store/extra/where/where-1.0.0)" = usr ] +R yes_to 'y\n' 'syspkg -f split' +check "a build installing into PREFIX and /usr both fails" has "[x] Building extra-src::split 1.0.0 failed." +check "...the log says why" grep -q "split installed into both /glacier/sys/links and /usr" $BUILD/logs/split-1.0.0.log + +hr "kept packages" +P=$BUILD/packages +check "a source build's package is kept, root's 0644" [ "$(stat -c '%u %a' $P/extra@where-1.0.0.gpkg)" = "0 644" ] +check "...byte for byte what was installed" sh -c "tar xzOf $P/extra@where-1.0.0.gpkg where-1.0.0/files/usr/bin/where | cmp -s - /glacier/sys/store/extra/where/where-1.0.0/usr/bin/where" +check "...not a failed one" [ ! -e $P/extra@split-1.0.0.gpkg ] +R yes_to 'y\n' 'syspkg -q -f srclib' +check "srclib (no binary anywhere) built and installed" rc 0 +check "...-q: no build output on the terminal" lacks "==> " +check "...but the build is still announced" has "[✓] Built extra-src::srclib 1.0.0." +check "...and logged" grep -q "==> Done" $BUILD/logs/srclib-1.0.0.log +R yes_to 'y\n' 'syspkg --quiet -f srcapp' +check "--quiet too" lacks "==> " +check "a build needing an installed source build: built" has "[✓] Built extra-src::srcapp 1.0.0." +check "...installed" grep -q "^extra::srcapp::1.0.0::explicit$" $IDX +check "...the kept package was its layer" sh -c "ls $BUILD/layers | grep -q '^srclib-1.0.0-'" +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/srcapp.conf +R yes_to 'y\n' 'syspkg -u srcapp' +check "-u rebuilds it (traits changed)" has " * extra-src::srcapp 1.0.0 (traits) [-loud] (build)" +check "...exit 0" rc 0 +mv $P/extra@srclib-1.0.0.gpkg /root/kept.bak +rm /etc/glacier/config/srcapp.conf +R yes_to 'y\n' 'syspkg -u srcapp' +mv /root/kept.bak $P/extra@srclib-1.0.0.gpkg +check "without its kept package, srclib can't be a layer" has "[x] extra-src::srcapp 1.0.0 needs srclib 1.0.0 or later to build, and no binary repository has it." +R yes_to 'y\n' 'syspkg -x srcapp' +check "removing srcapp deletes its kept package" [ ! -e $P/extra@srcapp-1.0.0.gpkg ] +check "...not srclib's, still installed" [ -f $P/extra@srclib-1.0.0.gpkg ] +R yes_to 'y\n' 'syspkg -x srclib' +check "removing srclib deletes its own" [ ! -e $P/extra@srclib-1.0.0.gpkg ] +check "...others stay" [ -f $P/extra@where-1.0.0.gpkg ] +R yes_to '2\ny\n' 'syspkg -f twin' +check "twin built from source: kept" [ -f $P/extra@twin-1.0.0.gpkg ] +R yes_to '1\ny\n' 'syspkg -f -O twin' +check "the same version reinstalled from the binary repo" [ "$(/glacier/sys/links/bin/twin)" = "twin 1.0.0 says hi" ] +check "...no longer kept" [ ! -e $P/extra@twin-1.0.0.gpkg ] + +hr "the repository question" +R yes_to '\ny\n' 'syspkg -f both' +check "both repos serving a name: asked" has "[i] both is available from more than one repository:" +check "...the binary first (repos.conf order)" has " 1) extra::both 9.0.0" +check "...then the recipe" has " 2) extra-src::both 1.0.0 [+loud] (build)" +check "...Enter takes the first" grep -q "^extra::both::9.0.0::explicit$" $IDX +check "...not marked as built" [ ! -e /glacier/sys/store/extra/both/both-9.0.0/.glacier-src ] +check "...nor kept" [ ! -e $BUILD/packages/extra@both-9.0.0.gpkg ] +R yes_to '2\ny\n' 'syspkg -f -O both' +check "2 builds the recipe (replacing the binary under -O)" grep -q "^extra::both::1.0.0::explicit$" $IDX +check "...marked as built" [ "$(cat /glacier/sys/store/extra/both/both-1.0.0/.glacier-src)" = extra-src ] +check "...and kept" [ -f $BUILD/packages/extra@both-1.0.0.gpkg ] +R yes_to '3\n' 'syspkg -f -O both' +check "an answer out of range is refused" has "[x] Invalid selection." +check "...exit 1" rc 1 +R yes_to 'x\n' 'syspkg -f -O both' +check "a non-number is refused" has "[x] Invalid selection." +R sh -c 'syspkg -f -O both < /dev/null' +check "end of input is refused" has "[x] Invalid selection." + +hr "refused builds" +R yes_to 'y\n' 'syspkg -f badhash' +check "a source with the wrong hash" has "[x] A source of extra-src::badhash 1.0.0 does not match its hash." +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q badhash $IDX" +R yes_to 'y\n' 'syspkg -f broken' +check "a failing build" has "[x] Building extra-src::broken 1.0.0 failed. Log: $BUILD/logs/broken-1.0.0.log" +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q broken $IDX" +check "...the log says why" grep -q "Error\|error" $BUILD/logs/broken-1.0.0.log +check "...its dirs removed" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +R yes_to 'y\n' 'syspkg -f evil' +check "a build that produces another package" has "[x] extra-src::evil 1.0.0: the build produced another package." +check "...nothing installed" sh -c "! grep -q evil $IDX && [ ! -e /usr/bin/evil ]" +# An index entry that disagrees with its bundle's recipe (signed all +# the same): the recipe has a dependency the index left out. +mkrecipe liar 1.0.0 "$(mksrc liar 1.0.0)" 'DEPS = ( { NAME = "hidep"; VER = "1.0.0"; } );' +publish +SER=$(sed -n 's/^SERIAL = \([0-9]*\)L;$/\1/p' $S/repo.idx) +awk -v s=$((SER + 1)) '/^SERIAL/ { print "SERIAL = " s "L;"; next } /NAME = "liar"/ { liar = 1 } liar && /DEPS = / { sub(/DEPS = \(.*\);/, "DEPS = ();"); liar = 0 } { print }' $S/repo.idx > /tmp/idx && mv /tmp/idx $S/repo.idx +gsign -S -s $SSEC -m $S/repo.idx >/dev/null +R yes_to 'y\n' 'syspkg -f liar' +check "a recipe that disagrees with its index entry" has "[x] extra-src::liar 1.0.0 does not match its index." +check "...nothing installed" sh -c "! grep -q liar $IDX" +chmod 666 /app/lib/build-driver.sh +R yes_to '2\ny\n' 'syspkg -f -O hello' +chmod 644 /app/lib/build-driver.sh +check "a world-writable build driver is refused" has "[x] Refusing /app/lib/build-driver.sh: /app/lib/build-driver.sh is not root-owned, or is group/world-writable." +check "...before the prompt" lacks "Proceed?" +R yes_to 'y\n' 'syspkg -f needy' +check "a build dependency no binary repo has" has "[x] extra-src::needy 1.0.0 needs nothere 1.0.0 or later to build, and no binary repository has it." +check "...refused before the prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ];' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER unset: refused" has "[x] BUILD_USER is not set in /etc/glacier/glacier.conf." +check "...before the prompt" lacks "Proceed?" +gconf 'BUILD_USER = "gbuild";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_ROOT unset: refused" has "[x] BUILD_ROOT is not set in /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "root";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER = root: refused" has "[x] BUILD_USER in /etc/glacier/glacier.conf must not be root." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "nosuchuser";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER not a user: refused" has "[x] BUILD_USER nosuchuser in /etc/glacier/glacier.conf is not a user." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; JOBS = 0;' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "JOBS = 0: glacier.conf is malformed" has "[x] Malformed /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' +mkdir -p /mnt/t && syspkg -R /mnt/t -n >/dev/null +cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/ 2>/dev/null || { mkdir -p /mnt/t/etc/glacier && cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/; } +R yes_to '2\ny\n' 'syspkg -R /mnt/t -f both' +check "building under -R is refused" has "[x] Building from source under -R is not supported." + +hr "base-src and the machine key" +R yes_to 'y\n' 'syspkg -f core' +check "a base build without the machine key trusted for base is refused" has '[x] base-src::core 1.0.0 [-loud] (build) needs the key "local" trusted for base.' +check "...before the prompt" lacks "Proceed?" +check "...having made the machine key" has "[i] Made the machine key /etc/glacier/keys/local.pub." +check "...its public half 0644" [ "$(stat -c '%u %a' /etc/glacier/keys/local.pub)" = "0 644" ] +check "...its secret half root's 0600" [ "$(stat -c '%u %a' /glacier/sys/keys/local.sec)" = "0 600" ] +R yes_to 'y\n' 'syspkg -f core' +check "...made once" lacks "Made the machine key" +rconf '"glacier-test", "local"' +R yes_to 'y\n' 'syspkg -f core' +check "listed for base: built and installed" grep -q "^base::core::1.0.0::explicit$" $IDX +check "...linked into /usr, as base is" [ "$(/usr/bin/core)" = hello ] +check "...marked as built from base-src" [ "$(cat /glacier/sys/store/base/core/core-1.0.0/.glacier-src)" = base-src ] +check "...built for /usr" [ "$(cat /usr/share/core.prefix)" = /usr ] +mv /glacier/sys/keys/local.sec /root/local.sec.bak +printf 'TRAITS = [ "loud" ];\n' > /etc/glacier/config/core.conf +R yes_to 'y\n' 'syspkg -u core' +rm /etc/glacier/config/core.conf +rconf '"glacier-test"' +mv /root/local.sec.bak /glacier/sys/keys/local.sec +check "a missing secret half is refused" has "[x] /etc/glacier/keys/local.pub and /glacier/sys/keys/local.sec must both exist, or neither." + +hr "hardlinks in a build's output" +mkrecipe hard 1.0.0 "$(mksrc hard 1.0.0)" '' 'package() { + make install DESTDIR="$DESTDIR" PREFIX="$PREFIX" + ln "$DESTDIR$PREFIX/bin/hard" "$DESTDIR$PREFIX/bin/hard2" +}' +publish +R yes_to 'y\n' 'syspkg -f hard' +check "a build whose install makes a hardlink packs it as a file" has "[✓] Completed with no errors." +check "...both names installed and run" sh -c '[ "$(/glacier/sys/links/bin/hard)" = hello ] && [ "$(/glacier/sys/links/bin/hard2)" = hello ]' + +hr "gpkg: the user's own build" +U=/glacier/usr/1000 +su glacier -c 'doas /app/gstore -n' >/dev/null 2>&1 +check "gstore -n makes the user's config dir" [ "$(stat -c '%U %a' $U/config)" = "glacier 700" ] +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud" ];' +R su glacier -c "printf '2\ny\n' | /app/gpkg -f both" +check "gpkg builds it" has "[✓] Built extra-src::both 1.0.0." +check "...the system's TRAITS apply" has "[i] Building extra-src::both 1.0.0 [+loud]..." +check "...installed for the user" grep -q "^extra::both::1.0.0::explicit$" $U/index/current +check "...the layers are the user's" [ "$(stat -c %U $U/build/layers/toolchain-1.0.0-*)" = glacier ] +check "...the log too" [ "$(stat -c '%U %a' $U/build/logs/both-1.0.0.log)" = "glacier 600" ] +check "...it runs" [ "$(su glacier -c "$U/links/bin/both")" = HELLO ] +check "...kept in the user's base, 0600" [ "$(stat -c '%U %a' $U/build/packages/extra@both-1.0.0.gpkg)" = "glacier 600" ] +R su glacier -c "printf 'y\n' | /app/gpkg -f where" +check "gpkg shows the build's output" has "==> Packing where-1.0.0.gpkg" +R su glacier -c "printf 'y\n' | /app/gpkg -fqO where" +check "gpkg -q (in a bundle) hides it" lacks "==> " +check "...and rebuilds" has "[✓] Built extra-src::where 1.0.0." +R su glacier -c "printf 'y\n' | /app/gpkg --quiet -fO where" +check "gpkg --quiet too" sh -c '! echo "$0" | grep -q "==> " && echo "$0" | grep -q "Built extra-src::where"' "$OUT" +R syspkg -h +check "syspkg -h lists -q" has "{-q --quiet} Hide build output" +R su glacier -c "/app/gpkg -h" +check "gpkg -h lists -q" has "{-q --quiet} Hide build output" +check "gpkg builds for the user's links" [ "$(su glacier -c "$U/links/bin/where")" = here ] +check "...the path compiled in" grep -q "^cat $U/links/share/where/data$" $U/links/bin/where +su glacier -c "printf 'TRAITS = [ \"-loud\" ];\n' > $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "the user's per-package file wins: rebuilt without loud" has " * extra-src::both 1.0.0 (traits) [-loud] (build)" +check "...installed" [ "$(su glacier -c "$U/links/bin/both")" = hello ] +su glacier -c "printf 'TRAITS = [ \"loud\" ];\n' > $U/config/glacier.conf; rm $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "...the user's glacier.conf too" has "[+loud] (build)" +R su glacier -c "printf 'y\n' | /app/gpkg -f core" +check "gpkg never builds from base-src" has "[x] core is not in any repository." + +hr "gpkg: base packages as build layers" +# Everest's BUILD_ROOT names base packages (musl, busybox): a user's +# build stacks them from base's signed index, which gpkg never +# installs from. +B=/srv/base +mkdir -p $B && chmod 755 $B +/app/tests/mkroot -o $B -r build-base -r busybox -p busybox basetc 1.0.0 base >/dev/null +grepo -s /root/glacier-test.sec -r base $B | grep -v Wrote +sed -i 's|{ name = "base"; keys|{ name = "base"; url = "file:///srv/base"; keys|' $CONF +gconf 'BUILD_ROOT = [ "basetc" ]; BUILD_USER = "gbuild";' +rm -f $U/config/glacier.conf +R su glacier -c "printf 'y\n' | /app/gpkg -fqO where" +check "a user's build stacks a base package as a layer" has "[✓] Built extra-src::where 1.0.0." +check "...extracted for the user" [ "$(stat -c %U $U/build/layers/basetc-1.0.0-*)" = glacier ] +R su glacier -c "printf 'y\n' | /app/gpkg -f basetc" +check "...but gpkg still never installs from base" has "[x] basetc is not in any repository." +rconf '"glacier-test"' +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud" ];' + +su glacier -c "printf 'BUILD_USER = \"x\";\n' > $U/config/glacier.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "BUILD_USER in a user's glacier.conf is malformed" has "[x] Malformed $U/config/glacier.conf." + +echo +if [ $FAILS -eq 0 ]; then echo "ALL PASSED"; else echo "$FAILS FAILED"; fi +[ $FAILS -eq 0 ] diff --git a/tests/build_alpine.sh.old b/tests/build_alpine.sh.old new file mode 100644 index 0000000..8d3667d --- /dev/null +++ b/tests/build_alpine.sh.old @@ -0,0 +1,325 @@ +#!/bin/sh +# Source builds through syspkg/gpkg -f/-u (BUILD_DESIGN.txt; steps 3-4): +# - a recipe from a NAME-src repo is built in gsandbox and installed +# like a fetched package: summary and prompt BEFORE building, the +# patches applied, the manifest the build was handed, .glacier-src; +# - a name served by several repositories is asked about; Enter takes +# the first, a bad answer refuses; +# - TRAITS: recipe defaults, /etc/glacier/glacier.conf, per-package +# files (an unknown trait refused), the user's own files for gpkg; +# - -u stays on source, and rebuilds when the traits change; +# - syspkg builds as BUILD_USER (required), gpkg as the user; +# - refusals: a source with the wrong hash, a failing build, a build +# that produces another package, a build dependency no binary repo +# has, an untrusted per-package file, -R. +# Needs what sandbox_alpine.sh needs, with /glacier off Docker's overlay: +# +# docker run --rm --security-opt seccomp=unconfined \ +# --security-opt apparmor=unconfined --security-opt systempaths=unconfined \ +# --tmpfs /glacier:exec,mode=755 \ +# -v "$PWD/tests/build_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +GCONF=/etc/glacier/glacier.conf +XSEC=/root/extrakey.sec +SSEC=/root/srckey.sec +E=/srv/extra +S=/srv/extra-src +SRC=/srv/sources +IDX=/glacier/sys/index/current +BUILD=/glacier/sys/build +BS=/srv/base-src +mkdir -p $E $S $SRC $BS && chmod 755 /srv $E $S $SRC $BS + +gsign -G -p $K/extrakey.pub -s $XSEC -c extrakey >/dev/null +gsign -G -p $K/srckey.pub -s $SSEC -c srckey >/dev/null +rconf() { # BASE-KEYS + printf 'repos = (\n%s\n%s\n%s\n%s\n);\n' \ + " { name = \"base\"; keys = [ $1 ]; }," \ + ' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; },' \ + ' { name = "extra-src"; url = "file:///srv/extra-src"; keys = [ "srckey" ]; },' \ + ' { name = "base-src"; url = "file:///srv/base-src"; keys = [ "srckey" ]; }' > $CONF + chmod 644 $CONF +} +rconf '"glacier-test"' +adduser -S -D -H -s /sbin/nologin gbuild +gconf() { printf 'KEEP_OLD = 1;\n%s\n' "$1" > $GCONF; chmod 644 $GCONF; } +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' + +# The binary repo: a toolchain (Alpine's build-base, busybox for /bin/sh) +# and a runtime dependency. +/app/tests/mkroot -o $E -r build-base -r busybox -p busybox toolchain 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E hidep 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E loudlib 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E both 9.0.0 extra >/dev/null + +# A source tarball: hello prints "hello", "HELLO" with LOUD=1. +mksrc() { # NAME VER [MAKEFILE-EXTRA] + d=/tmp/src/$1-$2 + rm -rf $d && mkdir -p $d + printf '#include \nint main(void) {\n#ifdef LOUD\n\tputs("HELLO");\n#else\n\tputs("hello");\n#endif\n\treturn 0;\n}\n' > $d/hello.c + printf 'CFLAGS += $(if $(LOUD),-DLOUD)\n%s: hello.c\n\t$(CC) $(CFLAGS) -o %s hello.c\ninstall:\n\tinstall -D -m 755 %s $(DESTDIR)$(PREFIX)/bin/%s\n%s\n' \ + "$1" "$1" "$1" "$1" "${3:-}" > $d/Makefile + tar czf $SRC/$1-$2.tar.gz -C /tmp/src $1-$2 + sha256sum $SRC/$1-$2.tar.gz | cut -c1-64 +} +# A recipe bundle in the -src repo: NAME VER SHA [EXTRA-FIELDS] [BUILD-FILE] +mkrecipe() { + t=/tmp/rcp/$1-$2 + rm -rf $t && mkdir -p $t/patches + printf 'NAME = "%s"; VER = "%s"; REPO = "extra"; DESC = "test \\"%s\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/%s-%s.tar.gz"; SHA256 = "sha256:%s"; } );\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\n%s\n' \ + "$1" "$2" "$1" "$SRC" "$1" "$2" "$3" "${4:-}" > $t/recipe + [ -n "${5:-}" ] && printf '%s\n' "$5" > $t/build + rmdir $t/patches 2>/dev/null + tar czf $S/$1-$2.grcp -C /tmp/rcp $1-$2 +} +publish() { + grepo -s $XSEC -r extra $E | grep -v Wrote; grepo -s $SSEC -r extra-src $S | grep -v Wrote + grepo -s $SSEC -r base-src $BS | grep -v Wrote +} + +# hello 1.0.0, patched to greet glacier, depending on hidep. +H=$(mksrc hello 1.0.0) +t=/tmp/rcp/hello-1.0.0 +rm -rf $t && mkdir -p $t/patches +printf 'NAME = "hello"; VER = "1.0.0"; REPO = "extra"; DESC = "say \\"hi\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/hello-1.0.0.tar.gz"; SHA256 = "sha256:%s"; } );\nPATCHES = [ "01-glacier.patch" ];\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\nDEPS = ( { NAME = "hidep"; VER = "1.0.0"; }, { NAME = "loudlib"; VER = "1.0.0"; IF = "loud"; } );\n' "$SRC" "$H" > $t/recipe +cat > $t/patches/01-glacier.patch <<'EOF' +--- a/hello.c ++++ b/hello.c +@@ -5,3 +5,3 @@ + #else +- puts("hello"); ++ puts("hello, glacier"); + #endif +EOF +tar czf $S/hello-1.0.0.grcp -C /tmp/rcp hello-1.0.0 +mkrecipe both 1.0.0 "$(mksrc both 1.0.0)" +mkrecipe badhash 1.0.0 "$(printf '%064d' 0)" +mksrc badhash 1.0.0 >/dev/null +mkrecipe broken 1.0.0 "$(mksrc broken 1.0.0 'broken: ; false')" '' 'compile() { make broken; }' +mkrecipe evil 1.0.0 "$(mksrc evil 1.0.0)" '' 'package() { + mkdir -p /tmp/p/evil-1.0.0/files/usr/bin + echo x > /tmp/p/evil-1.0.0/files/usr/bin/evil + printf "PKG_NAME = \"evil\"; PKG_VER = \"1.0.0\"; PKG_REPO = \"base\"; PKG_DEPS = (); PKG_CONFS = ();\n" > /tmp/p/evil-1.0.0/manifest.gpm.cfg + tar czf /.glacier/out/evil-1.0.0.gpkg -C /tmp/p evil-1.0.0 + exit 0 +}' +mkrecipe core 1.0.0 "$(mksrc core 1.0.0)" +sed -i 's/REPO = "extra"/REPO = "base"/' /tmp/rcp/core-1.0.0/recipe +tar czf $BS/core-1.0.0.grcp -C /tmp/rcp core-1.0.0 && rm $S/core-1.0.0.grcp +mkrecipe needy 1.0.0 "$(mksrc needy 1.0.0)" 'BUILD_DEPS = ( { NAME = "nothere"; VER = "1.0.0"; } );' +publish + +syspkg -n >/dev/null +yes_to() { sh -c "printf '$1' | $2"; } + +hr "syspkg -f of a recipe" +R yes_to 'y\n' 'syspkg -f hello' +check "built and installed" has "[✓] Completed with no errors." +check "...exit 0" rc 0 +check "the summary marks the build, its traits off by default" has " * extra-src::hello 1.0.0 [-loud] (build)" +check "...and the binary dependency" has " * extra::hidep 1.0.0 (dependency)" +check "...the prompt came before the build" sh -c 'echo "$0" | grep -n "Proceed\|Building extra-src" | head -1 | grep -q Proceed' "$OUT" +check "the build is announced" has "[i] Building extra-src::hello 1.0.0 [-loud]..." +check "...and done" has "[✓] Built extra-src::hello 1.0.0." +check "installed as extra::hello" grep -q "^extra::hello::1.0.0::explicit$" $IDX +check "...with its dependency, auto" grep -q "^extra::hidep::1.0.0::auto$" $IDX +check "...not the one only loud needs" sh -c "! grep -q loudlib $IDX" +check "...the patch applied" [ "$(/glacier/sys/links/bin/hello)" = "hello, glacier" ] +V=/glacier/sys/store/extra/hello/hello-1.0.0 +check "...recorded as built from extra-src" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...its manifest has PKG_TRAITS" grep -qF 'PKG_TRAITS = [ "-loud" ];' $V/.glacier-manifest +check "...and the recipe's DESC, quoted" grep -qF 'PKG_DESC = "say \"hi\"";' $V/.glacier-manifest +check "the layer belongs to BUILD_USER" [ "$(stat -c %U $BUILD/layers/toolchain-1.0.0-*)" = gbuild ] +check "...which owns layers/, 0700" [ "$(stat -c '%U %a' $BUILD/layers)" = "gbuild 700" ] +check "the build's in/work/out dirs are gone" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +check "the log is kept" grep -q "==> Done" $BUILD/logs/hello-1.0.0.log +check "...the sources cached by hash" [ -f $BUILD/sources/$H ] +check "the cached bundle is deleted" [ ! -e /glacier/sys/cache/extra-src/hello-1.0.0.grcp ] +check "the store copy is root's, as any install" [ "$(stat -c %u /glacier/sys/store/extra/hello/hello-1.0.0/usr/bin/hello)" = 0 ] + +hr "declining builds nothing" +rm $BUILD/logs/hello-1.0.0.log +R yes_to 'n\n' 'syspkg -f -O hello' +check "nothing built" sh -c "[ ! -e $BUILD/logs/hello-1.0.0.log ]" +check "...nothing said about building" lacks "Building" + +hr "traits" +mkdir -p /etc/glacier/config +printf 'TRAITS = [ "lod" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u hello' +check "an unknown trait in a per-package file is refused" has "[x] /etc/glacier/config/hello.conf: hello has no trait lod." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ]" && check "...no prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud", "x11" ];' +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "the per-package file beats glacier.conf: nothing to rebuild" has "Nothing to do." +rm /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "glacier.conf turns loud on (x11, unknown to the recipe, ignored): a rebuild" has " * extra-src::hello 1.0.0 (traits) [+loud] (build)" +check "...installed" rc 0 +check "...built with LOUD" [ "$(/glacier/sys/links/bin/hello)" = "HELLO" ] +check "...with the dependency loud needs" grep -q "^extra::loudlib::1.0.0::auto$" $IDX +check "...in its manifest" grep -qF '{ PKG_NAME = "loudlib"; PKG_VER = "1.0.0"; }' $V/.glacier-manifest +check "...still marked as built from source" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...PKG_TRAITS updated" grep -qF 'PKG_TRAITS = [ "loud" ];' $V/.glacier-manifest +R yes_to 'y\n' 'syspkg -u' +check "unchanged traits: nothing to do" has "Nothing to do." +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +chmod 666 /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a world-writable per-package file is refused" has "[x] Refusing /etc/glacier/config/hello.conf: /etc/glacier/config/hello.conf is not root-owned, or is group/world-writable." +rm /etc/glacier/config/hello.conf +printf 'TRAITS = [ "loud" ]; COLOR = "red";\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a per-package file with an unknown key is malformed" has "[x] Malformed /etc/glacier/config/hello.conf." +rm /etc/glacier/config/hello.conf + +hr "-u stays on source" +H11=$(mksrc hello 1.1.0) +sed "s/1\.0\.0/1.1.0/g; s/$H/$H11/" /tmp/rcp/hello-1.0.0/recipe > /tmp/r.new +rm -rf /tmp/rcp/hello-1.1.0 && cp -a /tmp/rcp/hello-1.0.0 /tmp/rcp/hello-1.1.0 && mv /tmp/r.new /tmp/rcp/hello-1.1.0/recipe +sed -i 's/VER = "1.1.0"; }/VER = "1.0.0"; }/g; s/VER = "1.1.0"; IF/VER = "1.0.0"; IF/' /tmp/rcp/hello-1.1.0/recipe +tar czf $S/hello-1.1.0.grcp -C /tmp/rcp hello-1.1.0 +/app/tests/mkpkg -o $E hello 2.0.0 extra >/dev/null +publish +R yes_to 'y\n' 'syspkg -u hello' +check "a newer recipe is built, not extra's binary 2.0.0" has " * extra-src::hello 1.0.0 -> 1.1.0 [+loud] (build)" +check "...installed" grep -q "^extra::hello::1.1.0::explicit$" $IDX +check "...the old version backed up" [ -f /glacier/sys/backup/extra/hello/hello-1.0.0.gpkg ] +check "...still on source" [ "$(cat /glacier/sys/store/extra/hello/hello-1.1.0/.glacier-src)" = extra-src ] + +hr "the repository question" +R yes_to '\ny\n' 'syspkg -f both' +check "both repos serving a name: asked" has "[i] both is available from more than one repository:" +check "...the binary first (repos.conf order)" has " 1) extra::both 9.0.0" +check "...then the recipe" has " 2) extra-src::both 1.0.0 [+loud] (build)" +check "...Enter takes the first" grep -q "^extra::both::9.0.0::explicit$" $IDX +check "...not marked as built" [ ! -e /glacier/sys/store/extra/both/both-9.0.0/.glacier-src ] +R yes_to '2\ny\n' 'syspkg -f -O both' +check "2 builds the recipe (replacing the binary under -O)" grep -q "^extra::both::1.0.0::explicit$" $IDX +check "...marked as built" [ "$(cat /glacier/sys/store/extra/both/both-1.0.0/.glacier-src)" = extra-src ] +R yes_to '3\n' 'syspkg -f -O both' +check "an answer out of range is refused" has "[x] Invalid selection." +check "...exit 1" rc 1 +R yes_to 'x\n' 'syspkg -f -O both' +check "a non-number is refused" has "[x] Invalid selection." +R sh -c 'syspkg -f -O both < /dev/null' +check "end of input is refused" has "[x] Invalid selection." + +hr "refused builds" +R yes_to 'y\n' 'syspkg -f badhash' +check "a source with the wrong hash" has "[x] A source of extra-src::badhash 1.0.0 does not match its hash." +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q badhash $IDX" +R yes_to 'y\n' 'syspkg -f broken' +check "a failing build" has "[x] Building extra-src::broken 1.0.0 failed. Log: $BUILD/logs/broken-1.0.0.log" +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q broken $IDX" +check "...the log says why" grep -q "Error\|error" $BUILD/logs/broken-1.0.0.log +check "...its dirs removed" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +R yes_to 'y\n' 'syspkg -f evil' +check "a build that produces another package" has "[x] extra-src::evil 1.0.0: the build produced another package." +check "...nothing installed" sh -c "! grep -q evil $IDX && [ ! -e /usr/bin/evil ]" +# An index entry that disagrees with its bundle's recipe (signed all +# the same): the recipe has a dependency the index left out. +mkrecipe liar 1.0.0 "$(mksrc liar 1.0.0)" 'DEPS = ( { NAME = "hidep"; VER = "1.0.0"; } );' +publish +SER=$(sed -n 's/^SERIAL = \([0-9]*\)L;$/\1/p' $S/repo.idx) +awk -v s=$((SER + 1)) '/^SERIAL/ { print "SERIAL = " s "L;"; next } /NAME = "liar"/ { liar = 1 } liar && /DEPS = / { sub(/DEPS = \(.*\);/, "DEPS = ();"); liar = 0 } { print }' $S/repo.idx > /tmp/idx && mv /tmp/idx $S/repo.idx +gsign -S -s $SSEC -m $S/repo.idx >/dev/null +R yes_to 'y\n' 'syspkg -f liar' +check "a recipe that disagrees with its index entry" has "[x] extra-src::liar 1.0.0 does not match its index." +check "...nothing installed" sh -c "! grep -q liar $IDX" +chmod 666 /app/lib/build-driver.sh +R yes_to '2\ny\n' 'syspkg -f -O hello' +chmod 644 /app/lib/build-driver.sh +check "a world-writable build driver is refused" has "[x] Refusing /app/lib/build-driver.sh: /app/lib/build-driver.sh is not root-owned, or is group/world-writable." +check "...before the prompt" lacks "Proceed?" +R yes_to 'y\n' 'syspkg -f needy' +check "a build dependency no binary repo has" has "[x] extra-src::needy 1.0.0 needs nothere 1.0.0 or later to build, and no binary repository has it." +check "...refused before the prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ];' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER unset: refused" has "[x] BUILD_USER is not set in /etc/glacier/glacier.conf." +check "...before the prompt" lacks "Proceed?" +gconf 'BUILD_USER = "gbuild";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_ROOT unset: refused" has "[x] BUILD_ROOT is not set in /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "root";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER = root: refused" has "[x] BUILD_USER in /etc/glacier/glacier.conf must not be root." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "nosuchuser";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER not a user: refused" has "[x] BUILD_USER nosuchuser in /etc/glacier/glacier.conf is not a user." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; JOBS = 0;' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "JOBS = 0: glacier.conf is malformed" has "[x] Malformed /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' +mkdir -p /mnt/t && syspkg -R /mnt/t -n >/dev/null +cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/ 2>/dev/null || { mkdir -p /mnt/t/etc/glacier && cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/; } +R yes_to '2\ny\n' 'syspkg -R /mnt/t -f both' +check "building under -R is refused" has "[x] Building from source under -R is not supported." + +hr "base-src and the machine key" +R yes_to 'y\n' 'syspkg -f core' +check "a base build without the machine key trusted for base is refused" has '[x] base-src::core 1.0.0 [-loud] (build) needs the key "local" trusted for base.' +check "...before the prompt" lacks "Proceed?" +check "...having made the machine key" has "[i] Made the machine key /etc/glacier/keys/local.pub." +check "...its public half 0644" [ "$(stat -c '%u %a' /etc/glacier/keys/local.pub)" = "0 644" ] +check "...its secret half root's 0600" [ "$(stat -c '%u %a' /glacier/sys/keys/local.sec)" = "0 600" ] +R yes_to 'y\n' 'syspkg -f core' +check "...made once" lacks "Made the machine key" +rconf '"glacier-test", "local"' +R yes_to 'y\n' 'syspkg -f core' +check "listed for base: built and installed" grep -q "^base::core::1.0.0::explicit$" $IDX +check "...linked into /usr, as base is" [ "$(/usr/bin/core)" = hello ] +check "...marked as built from base-src" [ "$(cat /glacier/sys/store/base/core/core-1.0.0/.glacier-src)" = base-src ] +mv /glacier/sys/keys/local.sec /root/local.sec.bak +printf 'TRAITS = [ "loud" ];\n' > /etc/glacier/config/core.conf +R yes_to 'y\n' 'syspkg -u core' +rm /etc/glacier/config/core.conf +rconf '"glacier-test"' +mv /root/local.sec.bak /glacier/sys/keys/local.sec +check "a missing secret half is refused" has "[x] /etc/glacier/keys/local.pub and /glacier/sys/keys/local.sec must both exist, or neither." + +hr "gpkg: the user's own build" +U=/glacier/usr/1000 +su glacier -c 'doas /app/gstore -n' >/dev/null 2>&1 +check "gstore -n makes the user's config dir" [ "$(stat -c '%U %a' $U/config)" = "glacier 700" ] +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud" ];' +R su glacier -c "printf '2\ny\n' | /app/gpkg -f both" +check "gpkg builds it" has "[✓] Built extra-src::both 1.0.0." +check "...the system's TRAITS apply" has "[i] Building extra-src::both 1.0.0 [+loud]..." +check "...installed for the user" grep -q "^extra::both::1.0.0::explicit$" $U/index/current +check "...the layers are the user's" [ "$(stat -c %U $U/build/layers/toolchain-1.0.0-*)" = glacier ] +check "...the log too" [ "$(stat -c '%U %a' $U/build/logs/both-1.0.0.log)" = "glacier 600" ] +check "...it runs" [ "$(su glacier -c "$U/links/bin/both")" = HELLO ] +su glacier -c "printf 'TRAITS = [ \"-loud\" ];\n' > $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "the user's per-package file wins: rebuilt without loud" has " * extra-src::both 1.0.0 (traits) [-loud] (build)" +check "...installed" [ "$(su glacier -c "$U/links/bin/both")" = hello ] +su glacier -c "printf 'TRAITS = [ \"loud\" ];\n' > $U/config/glacier.conf; rm $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "...the user's glacier.conf too" has "[+loud] (build)" +R su glacier -c "printf 'y\n' | /app/gpkg -f core" +check "gpkg never builds from base-src" has "[x] core is not in any repository." +su glacier -c "printf 'BUILD_USER = \"x\";\n' > $U/config/glacier.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "BUILD_USER in a user's glacier.conf is malformed" has "[x] Malformed $U/config/glacier.conf." + +echo +if [ $FAILS -eq 0 ]; then echo "ALL PASSED"; else echo "$FAILS FAILED"; fi +[ $FAILS -eq 0 ] diff --git a/tests/build_alpine.sh.old2 b/tests/build_alpine.sh.old2 new file mode 100644 index 0000000..4c5e280 --- /dev/null +++ b/tests/build_alpine.sh.old2 @@ -0,0 +1,359 @@ +#!/bin/sh +# Source builds through syspkg/gpkg -f/-u (BUILD_DESIGN.txt; steps 3-4): +# - a recipe from a NAME-src repo is built in gsandbox and installed +# like a fetched package: summary and prompt BEFORE building, the +# patches applied, the manifest the build was handed, .glacier-src; +# - a name served by several repositories is asked about; Enter takes +# the first, a bad answer refuses; +# - TRAITS: recipe defaults, /etc/glacier/glacier.conf, per-package +# files (an unknown trait refused), the user's own files for gpkg; +# - -u stays on source, and rebuilds when the traits change; +# - syspkg builds as BUILD_USER (required), gpkg as the user; +# - PREFIX: a package is built for where its usr/ is linked +# (/glacier/sys/links, the user's links, /usr for base) and still +# packed as usr/; during the build PREFIX resolves to the layers; +# - refusals: a source with the wrong hash, a failing build, a build +# that produces another package, a build dependency no binary repo +# has, an untrusted per-package file, -R. +# Needs what sandbox_alpine.sh needs, with /glacier off Docker's overlay: +# +# docker run --rm --security-opt seccomp=unconfined \ +# --security-opt apparmor=unconfined --security-opt systempaths=unconfined \ +# --tmpfs /glacier:exec,mode=755 \ +# -v "$PWD/tests/build_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +GCONF=/etc/glacier/glacier.conf +XSEC=/root/extrakey.sec +SSEC=/root/srckey.sec +E=/srv/extra +S=/srv/extra-src +SRC=/srv/sources +IDX=/glacier/sys/index/current +BUILD=/glacier/sys/build +BS=/srv/base-src +mkdir -p $E $S $SRC $BS && chmod 755 /srv $E $S $SRC $BS + +gsign -G -p $K/extrakey.pub -s $XSEC -c extrakey >/dev/null +gsign -G -p $K/srckey.pub -s $SSEC -c srckey >/dev/null +rconf() { # BASE-KEYS + printf 'repos = (\n%s\n%s\n%s\n%s\n);\n' \ + " { name = \"base\"; keys = [ $1 ]; }," \ + ' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; },' \ + ' { name = "extra-src"; url = "file:///srv/extra-src"; keys = [ "srckey" ]; },' \ + ' { name = "base-src"; url = "file:///srv/base-src"; keys = [ "srckey" ]; }' > $CONF + chmod 644 $CONF +} +rconf '"glacier-test"' +adduser -S -D -H -s /sbin/nologin gbuild +gconf() { printf 'KEEP_OLD = 1;\n%s\n' "$1" > $GCONF; chmod 644 $GCONF; } +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' + +# The binary repo: a toolchain (Alpine's build-base, busybox for /bin/sh) +# and a runtime dependency. +/app/tests/mkroot -o $E -r build-base -r busybox -p busybox toolchain 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E hidep 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E loudlib 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E both 9.0.0 extra >/dev/null + +# A source tarball: hello prints "hello", "HELLO" with LOUD=1. +mksrc() { # NAME VER [MAKEFILE-EXTRA] + d=/tmp/src/$1-$2 + rm -rf $d && mkdir -p $d + printf '#include \nint main(void) {\n#ifdef LOUD\n\tputs("HELLO");\n#else\n\tputs("hello");\n#endif\n\treturn 0;\n}\n' > $d/hello.c + printf 'CFLAGS += $(if $(LOUD),-DLOUD)\n%s: hello.c\n\t$(CC) $(CFLAGS) -o %s hello.c\ninstall:\n\tinstall -D -m 755 %s $(DESTDIR)$(PREFIX)/bin/%s\n%s\n' \ + "$1" "$1" "$1" "$1" "${3:-}" > $d/Makefile + tar czf $SRC/$1-$2.tar.gz -C /tmp/src $1-$2 + sha256sum $SRC/$1-$2.tar.gz | cut -c1-64 +} +# A recipe bundle in the -src repo: NAME VER SHA [EXTRA-FIELDS] [BUILD-FILE] +mkrecipe() { + t=/tmp/rcp/$1-$2 + rm -rf $t && mkdir -p $t/patches + printf 'NAME = "%s"; VER = "%s"; REPO = "extra"; DESC = "test \\"%s\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/%s-%s.tar.gz"; SHA256 = "sha256:%s"; } );\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\n%s\n' \ + "$1" "$2" "$1" "$SRC" "$1" "$2" "$3" "${4:-}" > $t/recipe + [ -n "${5:-}" ] && printf '%s\n' "$5" > $t/build + rmdir $t/patches 2>/dev/null + tar czf $S/$1-$2.grcp -C /tmp/rcp $1-$2 +} +publish() { + grepo -s $XSEC -r extra $E | grep -v Wrote; grepo -s $SSEC -r extra-src $S | grep -v Wrote + grepo -s $SSEC -r base-src $BS | grep -v Wrote +} + +# hello 1.0.0, patched to greet glacier, depending on hidep. +H=$(mksrc hello 1.0.0) +t=/tmp/rcp/hello-1.0.0 +rm -rf $t && mkdir -p $t/patches +printf 'NAME = "hello"; VER = "1.0.0"; REPO = "extra"; DESC = "say \\"hi\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/hello-1.0.0.tar.gz"; SHA256 = "sha256:%s"; } );\nPATCHES = [ "01-glacier.patch" ];\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\nDEPS = ( { NAME = "hidep"; VER = "1.0.0"; }, { NAME = "loudlib"; VER = "1.0.0"; IF = "loud"; } );\n' "$SRC" "$H" > $t/recipe +cat > $t/patches/01-glacier.patch <<'EOF' +--- a/hello.c ++++ b/hello.c +@@ -5,3 +5,3 @@ + #else +- puts("hello"); ++ puts("hello, glacier"); + #endif +EOF +tar czf $S/hello-1.0.0.grcp -C /tmp/rcp hello-1.0.0 +mkrecipe both 1.0.0 "$(mksrc both 1.0.0)" +mkrecipe badhash 1.0.0 "$(printf '%064d' 0)" +mksrc badhash 1.0.0 >/dev/null +mkrecipe broken 1.0.0 "$(mksrc broken 1.0.0 'broken: ; false')" '' 'compile() { make broken; }' +mkrecipe evil 1.0.0 "$(mksrc evil 1.0.0)" '' 'package() { + mkdir -p /tmp/p/evil-1.0.0/files/usr/bin + echo x > /tmp/p/evil-1.0.0/files/usr/bin/evil + printf "PKG_NAME = \"evil\"; PKG_VER = \"1.0.0\"; PKG_REPO = \"base\"; PKG_DEPS = (); PKG_CONFS = ();\n" > /tmp/p/evil-1.0.0/manifest.gpm.cfg + tar czf /.glacier/out/evil-1.0.0.gpkg -C /tmp/p evil-1.0.0 + exit 0 +}' +mkrecipe core 1.0.0 "$(mksrc core 1.0.0)" '' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR$PREFIX/share" && echo "$PREFIX" > "$DESTDIR$PREFIX/share/core.prefix" +}' +sed -i 's/REPO = "extra"/REPO = "base"/' /tmp/rcp/core-1.0.0/recipe +tar czf $BS/core-1.0.0.grcp -C /tmp/rcp core-1.0.0 && rm $S/core-1.0.0.grcp +# where: a script with its data file's path compiled in. Its prepare +# fails unless PREFIX leads to the layers during the build. +mkrecipe where 1.0.0 "$(mksrc where 1.0.0)" 'BUILD = "hooks";' 'prepare() { [ -x "$PREFIX/bin/make" ]; } +package() { + mkdir -p "$DESTDIR$PREFIX/bin" "$DESTDIR$PREFIX/share/where" + echo here > "$DESTDIR$PREFIX/share/where/data" + printf "#!/bin/sh\ncat %s/share/where/data\n" "$PREFIX" > "$DESTDIR$PREFIX/bin/where" + chmod 755 "$DESTDIR$PREFIX/bin/where" +}' +sed -i 's/^BUILD = "make";$//' /tmp/rcp/where-1.0.0/recipe && tar czf $S/where-1.0.0.grcp -C /tmp/rcp where-1.0.0 +mkrecipe split 1.0.0 "$(mksrc split 1.0.0)" '' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR/usr/share" && echo x > "$DESTDIR/usr/share/split" +}' +mkrecipe needy 1.0.0 "$(mksrc needy 1.0.0)" 'BUILD_DEPS = ( { NAME = "nothere"; VER = "1.0.0"; } );' +publish + +syspkg -n >/dev/null +yes_to() { sh -c "printf '$1' | $2"; } + +hr "syspkg -f of a recipe" +R yes_to 'y\n' 'syspkg -f hello' +check "built and installed" has "[✓] Completed with no errors." +check "...exit 0" rc 0 +check "the summary marks the build, its traits off by default" has " * extra-src::hello 1.0.0 [-loud] (build)" +check "...and the binary dependency" has " * extra::hidep 1.0.0 (dependency)" +check "...the prompt came before the build" sh -c 'echo "$0" | grep -n "Proceed\|Building extra-src" | head -1 | grep -q Proceed' "$OUT" +check "the build is announced" has "[i] Building extra-src::hello 1.0.0 [-loud]..." +check "...and done" has "[✓] Built extra-src::hello 1.0.0." +check "installed as extra::hello" grep -q "^extra::hello::1.0.0::explicit$" $IDX +check "...with its dependency, auto" grep -q "^extra::hidep::1.0.0::auto$" $IDX +check "...not the one only loud needs" sh -c "! grep -q loudlib $IDX" +check "...the patch applied" [ "$(/glacier/sys/links/bin/hello)" = "hello, glacier" ] +V=/glacier/sys/store/extra/hello/hello-1.0.0 +check "...recorded as built from extra-src" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...its manifest has PKG_TRAITS" grep -qF 'PKG_TRAITS = [ "-loud" ];' $V/.glacier-manifest +check "...and the recipe's DESC, quoted" grep -qF 'PKG_DESC = "say \"hi\"";' $V/.glacier-manifest +check "the layer belongs to BUILD_USER" [ "$(stat -c %U $BUILD/layers/toolchain-1.0.0-*)" = gbuild ] +check "...which owns layers/, 0700" [ "$(stat -c '%U %a' $BUILD/layers)" = "gbuild 700" ] +check "the build's in/work/out dirs are gone" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +check "the log is kept" grep -q "==> Done" $BUILD/logs/hello-1.0.0.log +check "...the sources cached by hash" [ -f $BUILD/sources/$H ] +check "the cached bundle is deleted" [ ! -e /glacier/sys/cache/extra-src/hello-1.0.0.grcp ] +check "the store copy is root's, as any install" [ "$(stat -c %u /glacier/sys/store/extra/hello/hello-1.0.0/usr/bin/hello)" = 0 ] + +hr "declining builds nothing" +rm $BUILD/logs/hello-1.0.0.log +R yes_to 'n\n' 'syspkg -f -O hello' +check "nothing built" sh -c "[ ! -e $BUILD/logs/hello-1.0.0.log ]" +check "...nothing said about building" lacks "Building" + +hr "traits" +mkdir -p /etc/glacier/config +printf 'TRAITS = [ "lod" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u hello' +check "an unknown trait in a per-package file is refused" has "[x] /etc/glacier/config/hello.conf: hello has no trait lod." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ]" && check "...no prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud", "x11" ];' +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "the per-package file beats glacier.conf: nothing to rebuild" has "Nothing to do." +rm /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "glacier.conf turns loud on (x11, unknown to the recipe, ignored): a rebuild" has " * extra-src::hello 1.0.0 (traits) [+loud] (build)" +check "...installed" rc 0 +check "...built with LOUD" [ "$(/glacier/sys/links/bin/hello)" = "HELLO" ] +check "...with the dependency loud needs" grep -q "^extra::loudlib::1.0.0::auto$" $IDX +check "...in its manifest" grep -qF '{ PKG_NAME = "loudlib"; PKG_VER = "1.0.0"; }' $V/.glacier-manifest +check "...still marked as built from source" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...PKG_TRAITS updated" grep -qF 'PKG_TRAITS = [ "loud" ];' $V/.glacier-manifest +R yes_to 'y\n' 'syspkg -u' +check "unchanged traits: nothing to do" has "Nothing to do." +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +chmod 666 /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a world-writable per-package file is refused" has "[x] Refusing /etc/glacier/config/hello.conf: /etc/glacier/config/hello.conf is not root-owned, or is group/world-writable." +rm /etc/glacier/config/hello.conf +printf 'TRAITS = [ "loud" ]; COLOR = "red";\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a per-package file with an unknown key is malformed" has "[x] Malformed /etc/glacier/config/hello.conf." +rm /etc/glacier/config/hello.conf + +hr "-u stays on source" +H11=$(mksrc hello 1.1.0) +sed "s/1\.0\.0/1.1.0/g; s/$H/$H11/" /tmp/rcp/hello-1.0.0/recipe > /tmp/r.new +rm -rf /tmp/rcp/hello-1.1.0 && cp -a /tmp/rcp/hello-1.0.0 /tmp/rcp/hello-1.1.0 && mv /tmp/r.new /tmp/rcp/hello-1.1.0/recipe +sed -i 's/VER = "1.1.0"; }/VER = "1.0.0"; }/g; s/VER = "1.1.0"; IF/VER = "1.0.0"; IF/' /tmp/rcp/hello-1.1.0/recipe +tar czf $S/hello-1.1.0.grcp -C /tmp/rcp hello-1.1.0 +/app/tests/mkpkg -o $E hello 2.0.0 extra >/dev/null +publish +R yes_to 'y\n' 'syspkg -u hello' +check "a newer recipe is built, not extra's binary 2.0.0" has " * extra-src::hello 1.0.0 -> 1.1.0 [+loud] (build)" +check "...installed" grep -q "^extra::hello::1.1.0::explicit$" $IDX +check "...the old version backed up" [ -f /glacier/sys/backup/extra/hello/hello-1.0.0.gpkg ] +check "...still on source" [ "$(cat /glacier/sys/store/extra/hello/hello-1.1.0/.glacier-src)" = extra-src ] + +hr "PREFIX" +R yes_to 'y\n' 'syspkg -f where' +check "built for /glacier/sys/links: finds its data through the links" [ "$(/glacier/sys/links/bin/where)" = here ] +check "...the path compiled in" grep -q "^cat /glacier/sys/links/share/where/data$" /glacier/sys/links/bin/where +check "...packed as usr/, as any package" [ -f /glacier/sys/store/extra/where/where-1.0.0/usr/share/where/data ] +check "...nothing else at the top" [ "$(ls /glacier/sys/store/extra/where/where-1.0.0)" = usr ] +R yes_to 'y\n' 'syspkg -f split' +check "a build installing into PREFIX and /usr both fails" has "[x] Building extra-src::split 1.0.0 failed." +check "...the log says why" grep -q "split installed into both /glacier/sys/links and /usr" $BUILD/logs/split-1.0.0.log + +hr "the repository question" +R yes_to '\ny\n' 'syspkg -f both' +check "both repos serving a name: asked" has "[i] both is available from more than one repository:" +check "...the binary first (repos.conf order)" has " 1) extra::both 9.0.0" +check "...then the recipe" has " 2) extra-src::both 1.0.0 [+loud] (build)" +check "...Enter takes the first" grep -q "^extra::both::9.0.0::explicit$" $IDX +check "...not marked as built" [ ! -e /glacier/sys/store/extra/both/both-9.0.0/.glacier-src ] +R yes_to '2\ny\n' 'syspkg -f -O both' +check "2 builds the recipe (replacing the binary under -O)" grep -q "^extra::both::1.0.0::explicit$" $IDX +check "...marked as built" [ "$(cat /glacier/sys/store/extra/both/both-1.0.0/.glacier-src)" = extra-src ] +R yes_to '3\n' 'syspkg -f -O both' +check "an answer out of range is refused" has "[x] Invalid selection." +check "...exit 1" rc 1 +R yes_to 'x\n' 'syspkg -f -O both' +check "a non-number is refused" has "[x] Invalid selection." +R sh -c 'syspkg -f -O both < /dev/null' +check "end of input is refused" has "[x] Invalid selection." + +hr "refused builds" +R yes_to 'y\n' 'syspkg -f badhash' +check "a source with the wrong hash" has "[x] A source of extra-src::badhash 1.0.0 does not match its hash." +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q badhash $IDX" +R yes_to 'y\n' 'syspkg -f broken' +check "a failing build" has "[x] Building extra-src::broken 1.0.0 failed. Log: $BUILD/logs/broken-1.0.0.log" +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q broken $IDX" +check "...the log says why" grep -q "Error\|error" $BUILD/logs/broken-1.0.0.log +check "...its dirs removed" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +R yes_to 'y\n' 'syspkg -f evil' +check "a build that produces another package" has "[x] extra-src::evil 1.0.0: the build produced another package." +check "...nothing installed" sh -c "! grep -q evil $IDX && [ ! -e /usr/bin/evil ]" +# An index entry that disagrees with its bundle's recipe (signed all +# the same): the recipe has a dependency the index left out. +mkrecipe liar 1.0.0 "$(mksrc liar 1.0.0)" 'DEPS = ( { NAME = "hidep"; VER = "1.0.0"; } );' +publish +SER=$(sed -n 's/^SERIAL = \([0-9]*\)L;$/\1/p' $S/repo.idx) +awk -v s=$((SER + 1)) '/^SERIAL/ { print "SERIAL = " s "L;"; next } /NAME = "liar"/ { liar = 1 } liar && /DEPS = / { sub(/DEPS = \(.*\);/, "DEPS = ();"); liar = 0 } { print }' $S/repo.idx > /tmp/idx && mv /tmp/idx $S/repo.idx +gsign -S -s $SSEC -m $S/repo.idx >/dev/null +R yes_to 'y\n' 'syspkg -f liar' +check "a recipe that disagrees with its index entry" has "[x] extra-src::liar 1.0.0 does not match its index." +check "...nothing installed" sh -c "! grep -q liar $IDX" +chmod 666 /app/lib/build-driver.sh +R yes_to '2\ny\n' 'syspkg -f -O hello' +chmod 644 /app/lib/build-driver.sh +check "a world-writable build driver is refused" has "[x] Refusing /app/lib/build-driver.sh: /app/lib/build-driver.sh is not root-owned, or is group/world-writable." +check "...before the prompt" lacks "Proceed?" +R yes_to 'y\n' 'syspkg -f needy' +check "a build dependency no binary repo has" has "[x] extra-src::needy 1.0.0 needs nothere 1.0.0 or later to build, and no binary repository has it." +check "...refused before the prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ];' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER unset: refused" has "[x] BUILD_USER is not set in /etc/glacier/glacier.conf." +check "...before the prompt" lacks "Proceed?" +gconf 'BUILD_USER = "gbuild";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_ROOT unset: refused" has "[x] BUILD_ROOT is not set in /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "root";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER = root: refused" has "[x] BUILD_USER in /etc/glacier/glacier.conf must not be root." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "nosuchuser";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER not a user: refused" has "[x] BUILD_USER nosuchuser in /etc/glacier/glacier.conf is not a user." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; JOBS = 0;' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "JOBS = 0: glacier.conf is malformed" has "[x] Malformed /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' +mkdir -p /mnt/t && syspkg -R /mnt/t -n >/dev/null +cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/ 2>/dev/null || { mkdir -p /mnt/t/etc/glacier && cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/; } +R yes_to '2\ny\n' 'syspkg -R /mnt/t -f both' +check "building under -R is refused" has "[x] Building from source under -R is not supported." + +hr "base-src and the machine key" +R yes_to 'y\n' 'syspkg -f core' +check "a base build without the machine key trusted for base is refused" has '[x] base-src::core 1.0.0 [-loud] (build) needs the key "local" trusted for base.' +check "...before the prompt" lacks "Proceed?" +check "...having made the machine key" has "[i] Made the machine key /etc/glacier/keys/local.pub." +check "...its public half 0644" [ "$(stat -c '%u %a' /etc/glacier/keys/local.pub)" = "0 644" ] +check "...its secret half root's 0600" [ "$(stat -c '%u %a' /glacier/sys/keys/local.sec)" = "0 600" ] +R yes_to 'y\n' 'syspkg -f core' +check "...made once" lacks "Made the machine key" +rconf '"glacier-test", "local"' +R yes_to 'y\n' 'syspkg -f core' +check "listed for base: built and installed" grep -q "^base::core::1.0.0::explicit$" $IDX +check "...linked into /usr, as base is" [ "$(/usr/bin/core)" = hello ] +check "...marked as built from base-src" [ "$(cat /glacier/sys/store/base/core/core-1.0.0/.glacier-src)" = base-src ] +check "...built for /usr" [ "$(cat /usr/share/core.prefix)" = /usr ] +mv /glacier/sys/keys/local.sec /root/local.sec.bak +printf 'TRAITS = [ "loud" ];\n' > /etc/glacier/config/core.conf +R yes_to 'y\n' 'syspkg -u core' +rm /etc/glacier/config/core.conf +rconf '"glacier-test"' +mv /root/local.sec.bak /glacier/sys/keys/local.sec +check "a missing secret half is refused" has "[x] /etc/glacier/keys/local.pub and /glacier/sys/keys/local.sec must both exist, or neither." + +hr "gpkg: the user's own build" +U=/glacier/usr/1000 +su glacier -c 'doas /app/gstore -n' >/dev/null 2>&1 +check "gstore -n makes the user's config dir" [ "$(stat -c '%U %a' $U/config)" = "glacier 700" ] +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud" ];' +R su glacier -c "printf '2\ny\n' | /app/gpkg -f both" +check "gpkg builds it" has "[✓] Built extra-src::both 1.0.0." +check "...the system's TRAITS apply" has "[i] Building extra-src::both 1.0.0 [+loud]..." +check "...installed for the user" grep -q "^extra::both::1.0.0::explicit$" $U/index/current +check "...the layers are the user's" [ "$(stat -c %U $U/build/layers/toolchain-1.0.0-*)" = glacier ] +check "...the log too" [ "$(stat -c '%U %a' $U/build/logs/both-1.0.0.log)" = "glacier 600" ] +check "...it runs" [ "$(su glacier -c "$U/links/bin/both")" = HELLO ] +R su glacier -c "printf 'y\n' | /app/gpkg -f where" +check "gpkg builds for the user's links" [ "$(su glacier -c "$U/links/bin/where")" = here ] +check "...the path compiled in" grep -q "^cat $U/links/share/where/data$" $U/links/bin/where +su glacier -c "printf 'TRAITS = [ \"-loud\" ];\n' > $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "the user's per-package file wins: rebuilt without loud" has " * extra-src::both 1.0.0 (traits) [-loud] (build)" +check "...installed" [ "$(su glacier -c "$U/links/bin/both")" = hello ] +su glacier -c "printf 'TRAITS = [ \"loud\" ];\n' > $U/config/glacier.conf; rm $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "...the user's glacier.conf too" has "[+loud] (build)" +R su glacier -c "printf 'y\n' | /app/gpkg -f core" +check "gpkg never builds from base-src" has "[x] core is not in any repository." +su glacier -c "printf 'BUILD_USER = \"x\";\n' > $U/config/glacier.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "BUILD_USER in a user's glacier.conf is malformed" has "[x] Malformed $U/config/glacier.conf." + +echo +if [ $FAILS -eq 0 ]; then echo "ALL PASSED"; else echo "$FAILS FAILED"; fi +[ $FAILS -eq 0 ] diff --git a/tests/build_alpine.sh.old3 b/tests/build_alpine.sh.old3 new file mode 100644 index 0000000..800b2ae --- /dev/null +++ b/tests/build_alpine.sh.old3 @@ -0,0 +1,408 @@ +#!/bin/sh +# Source builds through syspkg/gpkg -f/-u (BUILD_DESIGN.txt; steps 3-4): +# - a recipe from a NAME-src repo is built in gsandbox and installed +# like a fetched package: summary and prompt BEFORE building, the +# patches applied, the manifest the build was handed, .glacier-src; +# - a name served by several repositories is asked about; Enter takes +# the first, a bad answer refuses; +# - TRAITS: recipe defaults, /etc/glacier/glacier.conf, per-package +# files (an unknown trait refused), the user's own files for gpkg; +# - -u stays on source, and rebuilds when the traits change; +# - syspkg builds as BUILD_USER (required), gpkg as the user; +# - PREFIX: a package is built for where its usr/ is linked +# (/glacier/sys/links, the user's links, /usr for base) and still +# packed as usr/; during the build PREFIX resolves to the layers; +# - kept packages: an installed source build's .gpkg is kept, and a +# later build uses it (and what it depends on) as a layer; kept +# only while that version is installed; +# - refusals: a source with the wrong hash, a failing build, a build +# that produces another package, a build dependency no binary repo +# has, an untrusted per-package file, -R. +# Needs what sandbox_alpine.sh needs, with /glacier off Docker's overlay: +# +# docker run --rm --security-opt seccomp=unconfined \ +# --security-opt apparmor=unconfined --security-opt systempaths=unconfined \ +# --tmpfs /glacier:exec,mode=755 \ +# -v "$PWD/tests/build_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +GCONF=/etc/glacier/glacier.conf +XSEC=/root/extrakey.sec +SSEC=/root/srckey.sec +E=/srv/extra +S=/srv/extra-src +SRC=/srv/sources +IDX=/glacier/sys/index/current +BUILD=/glacier/sys/build +BS=/srv/base-src +mkdir -p $E $S $SRC $BS && chmod 755 /srv $E $S $SRC $BS + +gsign -G -p $K/extrakey.pub -s $XSEC -c extrakey >/dev/null +gsign -G -p $K/srckey.pub -s $SSEC -c srckey >/dev/null +rconf() { # BASE-KEYS + printf 'repos = (\n%s\n%s\n%s\n%s\n);\n' \ + " { name = \"base\"; keys = [ $1 ]; }," \ + ' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; },' \ + ' { name = "extra-src"; url = "file:///srv/extra-src"; keys = [ "srckey" ]; },' \ + ' { name = "base-src"; url = "file:///srv/base-src"; keys = [ "srckey" ]; }' > $CONF + chmod 644 $CONF +} +rconf '"glacier-test"' +adduser -S -D -H -s /sbin/nologin gbuild +gconf() { printf 'KEEP_OLD = 1;\n%s\n' "$1" > $GCONF; chmod 644 $GCONF; } +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' + +# The binary repo: a toolchain (Alpine's build-base, busybox for /bin/sh) +# and a runtime dependency. +/app/tests/mkroot -o $E -r build-base -r busybox -p busybox toolchain 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E hidep 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E loudlib 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E both 9.0.0 extra >/dev/null +/app/tests/mkpkg -o $E twin 1.0.0 extra >/dev/null + +# A source tarball: hello prints "hello", "HELLO" with LOUD=1. +mksrc() { # NAME VER [MAKEFILE-EXTRA] + d=/tmp/src/$1-$2 + rm -rf $d && mkdir -p $d + printf '#include \nint main(void) {\n#ifdef LOUD\n\tputs("HELLO");\n#else\n\tputs("hello");\n#endif\n\treturn 0;\n}\n' > $d/hello.c + printf 'CFLAGS += $(if $(LOUD),-DLOUD)\n%s: hello.c\n\t$(CC) $(CFLAGS) -o %s hello.c\ninstall:\n\tinstall -D -m 755 %s $(DESTDIR)$(PREFIX)/bin/%s\n%s\n' \ + "$1" "$1" "$1" "$1" "${3:-}" > $d/Makefile + tar czf $SRC/$1-$2.tar.gz -C /tmp/src $1-$2 + sha256sum $SRC/$1-$2.tar.gz | cut -c1-64 +} +# A recipe bundle in the -src repo: NAME VER SHA [EXTRA-FIELDS] [BUILD-FILE] +mkrecipe() { + t=/tmp/rcp/$1-$2 + rm -rf $t && mkdir -p $t/patches + printf 'NAME = "%s"; VER = "%s"; REPO = "extra"; DESC = "test \\"%s\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/%s-%s.tar.gz"; SHA256 = "sha256:%s"; } );\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\n%s\n' \ + "$1" "$2" "$1" "$SRC" "$1" "$2" "$3" "${4:-}" > $t/recipe + [ -n "${5:-}" ] && printf '%s\n' "$5" > $t/build + rmdir $t/patches 2>/dev/null + tar czf $S/$1-$2.grcp -C /tmp/rcp $1-$2 +} +publish() { + grepo -s $XSEC -r extra $E | grep -v Wrote; grepo -s $SSEC -r extra-src $S | grep -v Wrote + grepo -s $SSEC -r base-src $BS | grep -v Wrote +} + +# hello 1.0.0, patched to greet glacier, depending on hidep. +H=$(mksrc hello 1.0.0) +t=/tmp/rcp/hello-1.0.0 +rm -rf $t && mkdir -p $t/patches +printf 'NAME = "hello"; VER = "1.0.0"; REPO = "extra"; DESC = "say \\"hi\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/hello-1.0.0.tar.gz"; SHA256 = "sha256:%s"; } );\nPATCHES = [ "01-glacier.patch" ];\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\nDEPS = ( { NAME = "hidep"; VER = "1.0.0"; }, { NAME = "loudlib"; VER = "1.0.0"; IF = "loud"; } );\n' "$SRC" "$H" > $t/recipe +cat > $t/patches/01-glacier.patch <<'EOF' +--- a/hello.c ++++ b/hello.c +@@ -5,3 +5,3 @@ + #else +- puts("hello"); ++ puts("hello, glacier"); + #endif +EOF +tar czf $S/hello-1.0.0.grcp -C /tmp/rcp hello-1.0.0 +mkrecipe both 1.0.0 "$(mksrc both 1.0.0)" +mkrecipe badhash 1.0.0 "$(printf '%064d' 0)" +mksrc badhash 1.0.0 >/dev/null +mkrecipe broken 1.0.0 "$(mksrc broken 1.0.0 'broken: ; false')" '' 'compile() { make broken; }' +mkrecipe evil 1.0.0 "$(mksrc evil 1.0.0)" '' 'package() { + mkdir -p /tmp/p/evil-1.0.0/files/usr/bin + echo x > /tmp/p/evil-1.0.0/files/usr/bin/evil + printf "PKG_NAME = \"evil\"; PKG_VER = \"1.0.0\"; PKG_REPO = \"base\"; PKG_DEPS = (); PKG_CONFS = ();\n" > /tmp/p/evil-1.0.0/manifest.gpm.cfg + tar czf /.glacier/out/evil-1.0.0.gpkg -C /tmp/p evil-1.0.0 + exit 0 +}' +mkrecipe core 1.0.0 "$(mksrc core 1.0.0)" '' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR$PREFIX/share" && echo "$PREFIX" > "$DESTDIR$PREFIX/share/core.prefix" +}' +sed -i 's/REPO = "extra"/REPO = "base"/' /tmp/rcp/core-1.0.0/recipe +tar czf $BS/core-1.0.0.grcp -C /tmp/rcp core-1.0.0 && rm $S/core-1.0.0.grcp +# where: a script with its data file's path compiled in. Its prepare +# fails unless PREFIX leads to the layers during the build. +mkrecipe where 1.0.0 "$(mksrc where 1.0.0)" 'BUILD = "hooks";' 'prepare() { [ -x "$PREFIX/bin/make" ]; } +package() { + mkdir -p "$DESTDIR$PREFIX/bin" "$DESTDIR$PREFIX/share/where" + echo here > "$DESTDIR$PREFIX/share/where/data" + printf "#!/bin/sh\ncat %s/share/where/data\n" "$PREFIX" > "$DESTDIR$PREFIX/bin/where" + chmod 755 "$DESTDIR$PREFIX/bin/where" +}' +sed -i 's/^BUILD = "make";$//' /tmp/rcp/where-1.0.0/recipe && tar czf $S/where-1.0.0.grcp -C /tmp/rcp where-1.0.0 +mkrecipe split 1.0.0 "$(mksrc split 1.0.0)" '' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR/usr/share" && echo x > "$DESTDIR/usr/share/split" +}' +# srclib: only a recipe, depending on hidep. srcapp needs both in its +# layers to build. +mkrecipe srclib 1.0.0 "$(mksrc srclib 1.0.0)" 'DEPS = ( { NAME = "hidep"; VER = "1.0.0"; } );' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR$PREFIX/share/srclib" && echo yes > "$DESTDIR$PREFIX/share/srclib/marker" +}' +mkrecipe srcapp 1.0.0 "$(mksrc srcapp 1.0.0)" 'DEPS = ( { NAME = "srclib"; VER = "1.0.0"; } );' 'prepare() { [ -f /usr/share/srclib/marker ] && [ -x /usr/bin/hidep ]; }' +mkrecipe twin 1.0.0 "$(mksrc twin 1.0.0)" +mkrecipe needy 1.0.0 "$(mksrc needy 1.0.0)" 'BUILD_DEPS = ( { NAME = "nothere"; VER = "1.0.0"; } );' +publish + +syspkg -n >/dev/null +yes_to() { sh -c "printf '$1' | $2"; } + +hr "syspkg -f of a recipe" +R yes_to 'y\n' 'syspkg -f hello' +check "built and installed" has "[✓] Completed with no errors." +check "...exit 0" rc 0 +check "the summary marks the build, its traits off by default" has " * extra-src::hello 1.0.0 [-loud] (build)" +check "...and the binary dependency" has " * extra::hidep 1.0.0 (dependency)" +check "...the prompt came before the build" sh -c 'echo "$0" | grep -n "Proceed\|Building extra-src" | head -1 | grep -q Proceed' "$OUT" +check "the build is announced" has "[i] Building extra-src::hello 1.0.0 [-loud]..." +check "...and done" has "[✓] Built extra-src::hello 1.0.0." +check "installed as extra::hello" grep -q "^extra::hello::1.0.0::explicit$" $IDX +check "...with its dependency, auto" grep -q "^extra::hidep::1.0.0::auto$" $IDX +check "...not the one only loud needs" sh -c "! grep -q loudlib $IDX" +check "...the patch applied" [ "$(/glacier/sys/links/bin/hello)" = "hello, glacier" ] +V=/glacier/sys/store/extra/hello/hello-1.0.0 +check "...recorded as built from extra-src" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...its manifest has PKG_TRAITS" grep -qF 'PKG_TRAITS = [ "-loud" ];' $V/.glacier-manifest +check "...and the recipe's DESC, quoted" grep -qF 'PKG_DESC = "say \"hi\"";' $V/.glacier-manifest +check "the layer belongs to BUILD_USER" [ "$(stat -c %U $BUILD/layers/toolchain-1.0.0-*)" = gbuild ] +check "...which owns layers/, 0700" [ "$(stat -c '%U %a' $BUILD/layers)" = "gbuild 700" ] +check "the build's in/work/out dirs are gone" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +check "the log is kept" grep -q "==> Done" $BUILD/logs/hello-1.0.0.log +check "...the sources cached by hash" [ -f $BUILD/sources/$H ] +check "the cached bundle is deleted" [ ! -e /glacier/sys/cache/extra-src/hello-1.0.0.grcp ] +check "the store copy is root's, as any install" [ "$(stat -c %u /glacier/sys/store/extra/hello/hello-1.0.0/usr/bin/hello)" = 0 ] + +hr "declining builds nothing" +rm $BUILD/logs/hello-1.0.0.log +R yes_to 'n\n' 'syspkg -f -O hello' +check "nothing built" sh -c "[ ! -e $BUILD/logs/hello-1.0.0.log ]" +check "...nothing said about building" lacks "Building" + +hr "traits" +mkdir -p /etc/glacier/config +printf 'TRAITS = [ "lod" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u hello' +check "an unknown trait in a per-package file is refused" has "[x] /etc/glacier/config/hello.conf: hello has no trait lod." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ]" && check "...no prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud", "x11" ];' +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "the per-package file beats glacier.conf: nothing to rebuild" has "Nothing to do." +rm /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "glacier.conf turns loud on (x11, unknown to the recipe, ignored): a rebuild" has " * extra-src::hello 1.0.0 (traits) [+loud] (build)" +check "...installed" rc 0 +check "...built with LOUD" [ "$(/glacier/sys/links/bin/hello)" = "HELLO" ] +check "...with the dependency loud needs" grep -q "^extra::loudlib::1.0.0::auto$" $IDX +check "...in its manifest" grep -qF '{ PKG_NAME = "loudlib"; PKG_VER = "1.0.0"; }' $V/.glacier-manifest +check "...still marked as built from source" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...PKG_TRAITS updated" grep -qF 'PKG_TRAITS = [ "loud" ];' $V/.glacier-manifest +R yes_to 'y\n' 'syspkg -u' +check "unchanged traits: nothing to do" has "Nothing to do." +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +chmod 666 /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a world-writable per-package file is refused" has "[x] Refusing /etc/glacier/config/hello.conf: /etc/glacier/config/hello.conf is not root-owned, or is group/world-writable." +rm /etc/glacier/config/hello.conf +printf 'TRAITS = [ "loud" ]; COLOR = "red";\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a per-package file with an unknown key is malformed" has "[x] Malformed /etc/glacier/config/hello.conf." +rm /etc/glacier/config/hello.conf + +hr "-u stays on source" +H11=$(mksrc hello 1.1.0) +sed "s/1\.0\.0/1.1.0/g; s/$H/$H11/" /tmp/rcp/hello-1.0.0/recipe > /tmp/r.new +rm -rf /tmp/rcp/hello-1.1.0 && cp -a /tmp/rcp/hello-1.0.0 /tmp/rcp/hello-1.1.0 && mv /tmp/r.new /tmp/rcp/hello-1.1.0/recipe +sed -i 's/VER = "1.1.0"; }/VER = "1.0.0"; }/g; s/VER = "1.1.0"; IF/VER = "1.0.0"; IF/' /tmp/rcp/hello-1.1.0/recipe +tar czf $S/hello-1.1.0.grcp -C /tmp/rcp hello-1.1.0 +/app/tests/mkpkg -o $E hello 2.0.0 extra >/dev/null +publish +R yes_to 'y\n' 'syspkg -u hello' +check "a newer recipe is built, not extra's binary 2.0.0" has " * extra-src::hello 1.0.0 -> 1.1.0 [+loud] (build)" +check "...installed" grep -q "^extra::hello::1.1.0::explicit$" $IDX +check "...the old version backed up" [ -f /glacier/sys/backup/extra/hello/hello-1.0.0.gpkg ] +check "...its new package kept for builds" [ -f $BUILD/packages/extra@hello-1.1.0.gpkg ] +check "...the old one's deleted" [ ! -e $BUILD/packages/extra@hello-1.0.0.gpkg ] +check "...still on source" [ "$(cat /glacier/sys/store/extra/hello/hello-1.1.0/.glacier-src)" = extra-src ] + +hr "PREFIX" +R yes_to 'y\n' 'syspkg -f where' +check "built for /glacier/sys/links: finds its data through the links" [ "$(/glacier/sys/links/bin/where)" = here ] +check "...the path compiled in" grep -q "^cat /glacier/sys/links/share/where/data$" /glacier/sys/links/bin/where +check "...packed as usr/, as any package" [ -f /glacier/sys/store/extra/where/where-1.0.0/usr/share/where/data ] +check "...nothing else at the top" [ "$(ls /glacier/sys/store/extra/where/where-1.0.0)" = usr ] +R yes_to 'y\n' 'syspkg -f split' +check "a build installing into PREFIX and /usr both fails" has "[x] Building extra-src::split 1.0.0 failed." +check "...the log says why" grep -q "split installed into both /glacier/sys/links and /usr" $BUILD/logs/split-1.0.0.log + +hr "kept packages" +P=$BUILD/packages +check "a source build's package is kept, root's 0644" [ "$(stat -c '%u %a' $P/extra@where-1.0.0.gpkg)" = "0 644" ] +check "...byte for byte what was installed" sh -c "tar xzOf $P/extra@where-1.0.0.gpkg where-1.0.0/files/usr/bin/where | cmp -s - /glacier/sys/store/extra/where/where-1.0.0/usr/bin/where" +check "...not a failed one" [ ! -e $P/extra@split-1.0.0.gpkg ] +R yes_to 'y\n' 'syspkg -f srclib' +check "srclib (no binary anywhere) built and installed" rc 0 +R yes_to 'y\n' 'syspkg -f srcapp' +check "a build needing an installed source build: built" has "[✓] Built extra-src::srcapp 1.0.0." +check "...installed" grep -q "^extra::srcapp::1.0.0::explicit$" $IDX +check "...the kept package was its layer" sh -c "ls $BUILD/layers | grep -q '^srclib-1.0.0-'" +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/srcapp.conf +R yes_to 'y\n' 'syspkg -u srcapp' +check "-u rebuilds it (traits changed)" has " * extra-src::srcapp 1.0.0 (traits) [-loud] (build)" +check "...exit 0" rc 0 +mv $P/extra@srclib-1.0.0.gpkg /root/kept.bak +rm /etc/glacier/config/srcapp.conf +R yes_to 'y\n' 'syspkg -u srcapp' +mv /root/kept.bak $P/extra@srclib-1.0.0.gpkg +check "without its kept package, srclib can't be a layer" has "[x] extra-src::srcapp 1.0.0 needs srclib 1.0.0 or later to build, and no binary repository has it." +R yes_to 'y\n' 'syspkg -x srcapp' +check "removing srcapp deletes its kept package" [ ! -e $P/extra@srcapp-1.0.0.gpkg ] +check "...not srclib's, still installed" [ -f $P/extra@srclib-1.0.0.gpkg ] +R yes_to 'y\n' 'syspkg -x srclib' +check "removing srclib deletes its own" [ ! -e $P/extra@srclib-1.0.0.gpkg ] +check "...others stay" [ -f $P/extra@where-1.0.0.gpkg ] +R yes_to '2\ny\n' 'syspkg -f twin' +check "twin built from source: kept" [ -f $P/extra@twin-1.0.0.gpkg ] +R yes_to '1\ny\n' 'syspkg -f -O twin' +check "the same version reinstalled from the binary repo" [ "$(/glacier/sys/links/bin/twin)" = "twin 1.0.0 says hi" ] +check "...no longer kept" [ ! -e $P/extra@twin-1.0.0.gpkg ] + +hr "the repository question" +R yes_to '\ny\n' 'syspkg -f both' +check "both repos serving a name: asked" has "[i] both is available from more than one repository:" +check "...the binary first (repos.conf order)" has " 1) extra::both 9.0.0" +check "...then the recipe" has " 2) extra-src::both 1.0.0 [+loud] (build)" +check "...Enter takes the first" grep -q "^extra::both::9.0.0::explicit$" $IDX +check "...not marked as built" [ ! -e /glacier/sys/store/extra/both/both-9.0.0/.glacier-src ] +check "...nor kept" [ ! -e $BUILD/packages/extra@both-9.0.0.gpkg ] +R yes_to '2\ny\n' 'syspkg -f -O both' +check "2 builds the recipe (replacing the binary under -O)" grep -q "^extra::both::1.0.0::explicit$" $IDX +check "...marked as built" [ "$(cat /glacier/sys/store/extra/both/both-1.0.0/.glacier-src)" = extra-src ] +check "...and kept" [ -f $BUILD/packages/extra@both-1.0.0.gpkg ] +R yes_to '3\n' 'syspkg -f -O both' +check "an answer out of range is refused" has "[x] Invalid selection." +check "...exit 1" rc 1 +R yes_to 'x\n' 'syspkg -f -O both' +check "a non-number is refused" has "[x] Invalid selection." +R sh -c 'syspkg -f -O both < /dev/null' +check "end of input is refused" has "[x] Invalid selection." + +hr "refused builds" +R yes_to 'y\n' 'syspkg -f badhash' +check "a source with the wrong hash" has "[x] A source of extra-src::badhash 1.0.0 does not match its hash." +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q badhash $IDX" +R yes_to 'y\n' 'syspkg -f broken' +check "a failing build" has "[x] Building extra-src::broken 1.0.0 failed. Log: $BUILD/logs/broken-1.0.0.log" +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q broken $IDX" +check "...the log says why" grep -q "Error\|error" $BUILD/logs/broken-1.0.0.log +check "...its dirs removed" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +R yes_to 'y\n' 'syspkg -f evil' +check "a build that produces another package" has "[x] extra-src::evil 1.0.0: the build produced another package." +check "...nothing installed" sh -c "! grep -q evil $IDX && [ ! -e /usr/bin/evil ]" +# An index entry that disagrees with its bundle's recipe (signed all +# the same): the recipe has a dependency the index left out. +mkrecipe liar 1.0.0 "$(mksrc liar 1.0.0)" 'DEPS = ( { NAME = "hidep"; VER = "1.0.0"; } );' +publish +SER=$(sed -n 's/^SERIAL = \([0-9]*\)L;$/\1/p' $S/repo.idx) +awk -v s=$((SER + 1)) '/^SERIAL/ { print "SERIAL = " s "L;"; next } /NAME = "liar"/ { liar = 1 } liar && /DEPS = / { sub(/DEPS = \(.*\);/, "DEPS = ();"); liar = 0 } { print }' $S/repo.idx > /tmp/idx && mv /tmp/idx $S/repo.idx +gsign -S -s $SSEC -m $S/repo.idx >/dev/null +R yes_to 'y\n' 'syspkg -f liar' +check "a recipe that disagrees with its index entry" has "[x] extra-src::liar 1.0.0 does not match its index." +check "...nothing installed" sh -c "! grep -q liar $IDX" +chmod 666 /app/lib/build-driver.sh +R yes_to '2\ny\n' 'syspkg -f -O hello' +chmod 644 /app/lib/build-driver.sh +check "a world-writable build driver is refused" has "[x] Refusing /app/lib/build-driver.sh: /app/lib/build-driver.sh is not root-owned, or is group/world-writable." +check "...before the prompt" lacks "Proceed?" +R yes_to 'y\n' 'syspkg -f needy' +check "a build dependency no binary repo has" has "[x] extra-src::needy 1.0.0 needs nothere 1.0.0 or later to build, and no binary repository has it." +check "...refused before the prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ];' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER unset: refused" has "[x] BUILD_USER is not set in /etc/glacier/glacier.conf." +check "...before the prompt" lacks "Proceed?" +gconf 'BUILD_USER = "gbuild";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_ROOT unset: refused" has "[x] BUILD_ROOT is not set in /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "root";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER = root: refused" has "[x] BUILD_USER in /etc/glacier/glacier.conf must not be root." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "nosuchuser";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER not a user: refused" has "[x] BUILD_USER nosuchuser in /etc/glacier/glacier.conf is not a user." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; JOBS = 0;' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "JOBS = 0: glacier.conf is malformed" has "[x] Malformed /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' +mkdir -p /mnt/t && syspkg -R /mnt/t -n >/dev/null +cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/ 2>/dev/null || { mkdir -p /mnt/t/etc/glacier && cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/; } +R yes_to '2\ny\n' 'syspkg -R /mnt/t -f both' +check "building under -R is refused" has "[x] Building from source under -R is not supported." + +hr "base-src and the machine key" +R yes_to 'y\n' 'syspkg -f core' +check "a base build without the machine key trusted for base is refused" has '[x] base-src::core 1.0.0 [-loud] (build) needs the key "local" trusted for base.' +check "...before the prompt" lacks "Proceed?" +check "...having made the machine key" has "[i] Made the machine key /etc/glacier/keys/local.pub." +check "...its public half 0644" [ "$(stat -c '%u %a' /etc/glacier/keys/local.pub)" = "0 644" ] +check "...its secret half root's 0600" [ "$(stat -c '%u %a' /glacier/sys/keys/local.sec)" = "0 600" ] +R yes_to 'y\n' 'syspkg -f core' +check "...made once" lacks "Made the machine key" +rconf '"glacier-test", "local"' +R yes_to 'y\n' 'syspkg -f core' +check "listed for base: built and installed" grep -q "^base::core::1.0.0::explicit$" $IDX +check "...linked into /usr, as base is" [ "$(/usr/bin/core)" = hello ] +check "...marked as built from base-src" [ "$(cat /glacier/sys/store/base/core/core-1.0.0/.glacier-src)" = base-src ] +check "...built for /usr" [ "$(cat /usr/share/core.prefix)" = /usr ] +mv /glacier/sys/keys/local.sec /root/local.sec.bak +printf 'TRAITS = [ "loud" ];\n' > /etc/glacier/config/core.conf +R yes_to 'y\n' 'syspkg -u core' +rm /etc/glacier/config/core.conf +rconf '"glacier-test"' +mv /root/local.sec.bak /glacier/sys/keys/local.sec +check "a missing secret half is refused" has "[x] /etc/glacier/keys/local.pub and /glacier/sys/keys/local.sec must both exist, or neither." + +hr "gpkg: the user's own build" +U=/glacier/usr/1000 +su glacier -c 'doas /app/gstore -n' >/dev/null 2>&1 +check "gstore -n makes the user's config dir" [ "$(stat -c '%U %a' $U/config)" = "glacier 700" ] +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud" ];' +R su glacier -c "printf '2\ny\n' | /app/gpkg -f both" +check "gpkg builds it" has "[✓] Built extra-src::both 1.0.0." +check "...the system's TRAITS apply" has "[i] Building extra-src::both 1.0.0 [+loud]..." +check "...installed for the user" grep -q "^extra::both::1.0.0::explicit$" $U/index/current +check "...the layers are the user's" [ "$(stat -c %U $U/build/layers/toolchain-1.0.0-*)" = glacier ] +check "...the log too" [ "$(stat -c '%U %a' $U/build/logs/both-1.0.0.log)" = "glacier 600" ] +check "...it runs" [ "$(su glacier -c "$U/links/bin/both")" = HELLO ] +check "...kept in the user's base, 0600" [ "$(stat -c '%U %a' $U/build/packages/extra@both-1.0.0.gpkg)" = "glacier 600" ] +R su glacier -c "printf 'y\n' | /app/gpkg -f where" +check "gpkg builds for the user's links" [ "$(su glacier -c "$U/links/bin/where")" = here ] +check "...the path compiled in" grep -q "^cat $U/links/share/where/data$" $U/links/bin/where +su glacier -c "printf 'TRAITS = [ \"-loud\" ];\n' > $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "the user's per-package file wins: rebuilt without loud" has " * extra-src::both 1.0.0 (traits) [-loud] (build)" +check "...installed" [ "$(su glacier -c "$U/links/bin/both")" = hello ] +su glacier -c "printf 'TRAITS = [ \"loud\" ];\n' > $U/config/glacier.conf; rm $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "...the user's glacier.conf too" has "[+loud] (build)" +R su glacier -c "printf 'y\n' | /app/gpkg -f core" +check "gpkg never builds from base-src" has "[x] core is not in any repository." +su glacier -c "printf 'BUILD_USER = \"x\";\n' > $U/config/glacier.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "BUILD_USER in a user's glacier.conf is malformed" has "[x] Malformed $U/config/glacier.conf." + +echo +if [ $FAILS -eq 0 ]; then echo "ALL PASSED"; else echo "$FAILS FAILED"; fi +[ $FAILS -eq 0 ] diff --git a/tests/build_alpine.sh.old4 b/tests/build_alpine.sh.old4 new file mode 100644 index 0000000..8dca453 --- /dev/null +++ b/tests/build_alpine.sh.old4 @@ -0,0 +1,424 @@ +#!/bin/sh +# Source builds through syspkg/gpkg -f/-u (BUILD_DESIGN.txt; steps 3-4): +# - a recipe from a NAME-src repo is built in gsandbox and installed +# like a fetched package: summary and prompt BEFORE building, the +# patches applied, the manifest the build was handed, .glacier-src; +# - a name served by several repositories is asked about; Enter takes +# the first, a bad answer refuses; +# - TRAITS: recipe defaults, /etc/glacier/glacier.conf, per-package +# files (an unknown trait refused), the user's own files for gpkg; +# - -u stays on source, and rebuilds when the traits change; +# - syspkg builds as BUILD_USER (required), gpkg as the user; +# - PREFIX: a package is built for where its usr/ is linked +# (/glacier/sys/links, the user's links, /usr for base) and still +# packed as usr/; during the build PREFIX resolves to the layers; +# - kept packages: an installed source build's .gpkg is kept, and a +# later build uses it (and what it depends on) as a layer; kept +# only while that version is installed; +# - build output on the terminal (and in the log) unless -q/--quiet; +# - refusals: a source with the wrong hash, a failing build, a build +# that produces another package, a build dependency no binary repo +# has, an untrusted per-package file, -R. +# Needs what sandbox_alpine.sh needs, with /glacier off Docker's overlay: +# +# docker run --rm --security-opt seccomp=unconfined \ +# --security-opt apparmor=unconfined --security-opt systempaths=unconfined \ +# --tmpfs /glacier:exec,mode=755 \ +# -v "$PWD/tests/build_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +GCONF=/etc/glacier/glacier.conf +XSEC=/root/extrakey.sec +SSEC=/root/srckey.sec +E=/srv/extra +S=/srv/extra-src +SRC=/srv/sources +IDX=/glacier/sys/index/current +BUILD=/glacier/sys/build +BS=/srv/base-src +mkdir -p $E $S $SRC $BS && chmod 755 /srv $E $S $SRC $BS + +gsign -G -p $K/extrakey.pub -s $XSEC -c extrakey >/dev/null +gsign -G -p $K/srckey.pub -s $SSEC -c srckey >/dev/null +rconf() { # BASE-KEYS + printf 'repos = (\n%s\n%s\n%s\n%s\n);\n' \ + " { name = \"base\"; keys = [ $1 ]; }," \ + ' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; },' \ + ' { name = "extra-src"; url = "file:///srv/extra-src"; keys = [ "srckey" ]; },' \ + ' { name = "base-src"; url = "file:///srv/base-src"; keys = [ "srckey" ]; }' > $CONF + chmod 644 $CONF +} +rconf '"glacier-test"' +adduser -S -D -H -s /sbin/nologin gbuild +gconf() { printf 'KEEP_OLD = 1;\n%s\n' "$1" > $GCONF; chmod 644 $GCONF; } +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' + +# The binary repo: a toolchain (Alpine's build-base, busybox for /bin/sh) +# and a runtime dependency. +/app/tests/mkroot -o $E -r build-base -r busybox -p busybox toolchain 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E hidep 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E loudlib 1.0.0 extra >/dev/null +/app/tests/mkpkg -o $E both 9.0.0 extra >/dev/null +/app/tests/mkpkg -o $E twin 1.0.0 extra >/dev/null + +# A source tarball: hello prints "hello", "HELLO" with LOUD=1. +mksrc() { # NAME VER [MAKEFILE-EXTRA] + d=/tmp/src/$1-$2 + rm -rf $d && mkdir -p $d + printf '#include \nint main(void) {\n#ifdef LOUD\n\tputs("HELLO");\n#else\n\tputs("hello");\n#endif\n\treturn 0;\n}\n' > $d/hello.c + printf 'CFLAGS += $(if $(LOUD),-DLOUD)\n%s: hello.c\n\t$(CC) $(CFLAGS) -o %s hello.c\ninstall:\n\tinstall -D -m 755 %s $(DESTDIR)$(PREFIX)/bin/%s\n%s\n' \ + "$1" "$1" "$1" "$1" "${3:-}" > $d/Makefile + tar czf $SRC/$1-$2.tar.gz -C /tmp/src $1-$2 + sha256sum $SRC/$1-$2.tar.gz | cut -c1-64 +} +# A recipe bundle in the -src repo: NAME VER SHA [EXTRA-FIELDS] [BUILD-FILE] +mkrecipe() { + t=/tmp/rcp/$1-$2 + rm -rf $t && mkdir -p $t/patches + printf 'NAME = "%s"; VER = "%s"; REPO = "extra"; DESC = "test \\"%s\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/%s-%s.tar.gz"; SHA256 = "sha256:%s"; } );\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\n%s\n' \ + "$1" "$2" "$1" "$SRC" "$1" "$2" "$3" "${4:-}" > $t/recipe + [ -n "${5:-}" ] && printf '%s\n' "$5" > $t/build + rmdir $t/patches 2>/dev/null + tar czf $S/$1-$2.grcp -C /tmp/rcp $1-$2 +} +publish() { + grepo -s $XSEC -r extra $E | grep -v Wrote; grepo -s $SSEC -r extra-src $S | grep -v Wrote + grepo -s $SSEC -r base-src $BS | grep -v Wrote +} + +# hello 1.0.0, patched to greet glacier, depending on hidep. +H=$(mksrc hello 1.0.0) +t=/tmp/rcp/hello-1.0.0 +rm -rf $t && mkdir -p $t/patches +printf 'NAME = "hello"; VER = "1.0.0"; REPO = "extra"; DESC = "say \\"hi\\""; MAINT = "m@x"; COPYRIGHT = "MIT";\nSOURCES = ( { URL = "file://%s/hello-1.0.0.tar.gz"; SHA256 = "sha256:%s"; } );\nPATCHES = [ "01-glacier.patch" ];\nBUILD = "make";\nTRAITS = ( { NAME = "loud"; DEFAULT = false; ON = [ "LOUD=1" ]; } );\nDEPS = ( { NAME = "hidep"; VER = "1.0.0"; }, { NAME = "loudlib"; VER = "1.0.0"; IF = "loud"; } );\n' "$SRC" "$H" > $t/recipe +cat > $t/patches/01-glacier.patch <<'EOF' +--- a/hello.c ++++ b/hello.c +@@ -5,3 +5,3 @@ + #else +- puts("hello"); ++ puts("hello, glacier"); + #endif +EOF +tar czf $S/hello-1.0.0.grcp -C /tmp/rcp hello-1.0.0 +mkrecipe both 1.0.0 "$(mksrc both 1.0.0)" +mkrecipe badhash 1.0.0 "$(printf '%064d' 0)" +mksrc badhash 1.0.0 >/dev/null +mkrecipe broken 1.0.0 "$(mksrc broken 1.0.0 'broken: ; false')" '' 'compile() { make broken; }' +mkrecipe evil 1.0.0 "$(mksrc evil 1.0.0)" '' 'package() { + mkdir -p /tmp/p/evil-1.0.0/files/usr/bin + echo x > /tmp/p/evil-1.0.0/files/usr/bin/evil + printf "PKG_NAME = \"evil\"; PKG_VER = \"1.0.0\"; PKG_REPO = \"base\"; PKG_DEPS = (); PKG_CONFS = ();\n" > /tmp/p/evil-1.0.0/manifest.gpm.cfg + tar czf /.glacier/out/evil-1.0.0.gpkg -C /tmp/p evil-1.0.0 + exit 0 +}' +mkrecipe core 1.0.0 "$(mksrc core 1.0.0)" '' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR$PREFIX/share" && echo "$PREFIX" > "$DESTDIR$PREFIX/share/core.prefix" +}' +sed -i 's/REPO = "extra"/REPO = "base"/' /tmp/rcp/core-1.0.0/recipe +tar czf $BS/core-1.0.0.grcp -C /tmp/rcp core-1.0.0 && rm $S/core-1.0.0.grcp +# where: a script with its data file's path compiled in. Its prepare +# fails unless PREFIX leads to the layers during the build. +mkrecipe where 1.0.0 "$(mksrc where 1.0.0)" 'BUILD = "hooks";' 'prepare() { [ -x "$PREFIX/bin/make" ]; } +package() { + mkdir -p "$DESTDIR$PREFIX/bin" "$DESTDIR$PREFIX/share/where" + echo here > "$DESTDIR$PREFIX/share/where/data" + printf "#!/bin/sh\ncat %s/share/where/data\n" "$PREFIX" > "$DESTDIR$PREFIX/bin/where" + chmod 755 "$DESTDIR$PREFIX/bin/where" +}' +sed -i 's/^BUILD = "make";$//' /tmp/rcp/where-1.0.0/recipe && tar czf $S/where-1.0.0.grcp -C /tmp/rcp where-1.0.0 +mkrecipe split 1.0.0 "$(mksrc split 1.0.0)" '' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR/usr/share" && echo x > "$DESTDIR/usr/share/split" +}' +# srclib: only a recipe, depending on hidep. srcapp needs both in its +# layers to build. +mkrecipe srclib 1.0.0 "$(mksrc srclib 1.0.0)" 'DEPS = ( { NAME = "hidep"; VER = "1.0.0"; } );' 'package() { + make install PREFIX="$PREFIX" DESTDIR="$DESTDIR" + mkdir -p "$DESTDIR$PREFIX/share/srclib" && echo yes > "$DESTDIR$PREFIX/share/srclib/marker" +}' +mkrecipe srcapp 1.0.0 "$(mksrc srcapp 1.0.0)" 'DEPS = ( { NAME = "srclib"; VER = "1.0.0"; } );' 'prepare() { [ -f /usr/share/srclib/marker ] && [ -x /usr/bin/hidep ]; }' +mkrecipe twin 1.0.0 "$(mksrc twin 1.0.0)" +mkrecipe needy 1.0.0 "$(mksrc needy 1.0.0)" 'BUILD_DEPS = ( { NAME = "nothere"; VER = "1.0.0"; } );' +publish + +syspkg -n >/dev/null +yes_to() { sh -c "printf '$1' | $2"; } + +hr "syspkg -f of a recipe" +R yes_to 'y\n' 'syspkg -f hello' +check "built and installed" has "[✓] Completed with no errors." +check "...exit 0" rc 0 +check "the summary marks the build, its traits off by default" has " * extra-src::hello 1.0.0 [-loud] (build)" +check "...and the binary dependency" has " * extra::hidep 1.0.0 (dependency)" +check "...the prompt came before the build" sh -c 'echo "$0" | grep -n "Proceed\|Building extra-src" | head -1 | grep -q Proceed' "$OUT" +check "the build is announced" has "[i] Building extra-src::hello 1.0.0 [-loud]..." +check "...and done" has "[✓] Built extra-src::hello 1.0.0." +check "installed as extra::hello" grep -q "^extra::hello::1.0.0::explicit$" $IDX +check "...with its dependency, auto" grep -q "^extra::hidep::1.0.0::auto$" $IDX +check "...not the one only loud needs" sh -c "! grep -q loudlib $IDX" +check "...the patch applied" [ "$(/glacier/sys/links/bin/hello)" = "hello, glacier" ] +V=/glacier/sys/store/extra/hello/hello-1.0.0 +check "...recorded as built from extra-src" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...its manifest has PKG_TRAITS" grep -qF 'PKG_TRAITS = [ "-loud" ];' $V/.glacier-manifest +check "...and the recipe's DESC, quoted" grep -qF 'PKG_DESC = "say \"hi\"";' $V/.glacier-manifest +check "the layer belongs to BUILD_USER" [ "$(stat -c %U $BUILD/layers/toolchain-1.0.0-*)" = gbuild ] +check "...which owns layers/, 0700" [ "$(stat -c '%U %a' $BUILD/layers)" = "gbuild 700" ] +check "the build's in/work/out dirs are gone" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +check "the log is kept" grep -q "==> Done" $BUILD/logs/hello-1.0.0.log +check "...and the build's output was on the terminal" has "==> Applying 01-glacier.patch" +check "...the sources cached by hash" [ -f $BUILD/sources/$H ] +check "the cached bundle is deleted" [ ! -e /glacier/sys/cache/extra-src/hello-1.0.0.grcp ] +check "the store copy is root's, as any install" [ "$(stat -c %u /glacier/sys/store/extra/hello/hello-1.0.0/usr/bin/hello)" = 0 ] + +hr "declining builds nothing" +rm $BUILD/logs/hello-1.0.0.log +R yes_to 'n\n' 'syspkg -f -O hello' +check "nothing built" sh -c "[ ! -e $BUILD/logs/hello-1.0.0.log ]" +check "...nothing said about building" lacks "Building" + +hr "traits" +mkdir -p /etc/glacier/config +printf 'TRAITS = [ "lod" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u hello' +check "an unknown trait in a per-package file is refused" has "[x] /etc/glacier/config/hello.conf: hello has no trait lod." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ]" && check "...no prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud", "x11" ];' +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "the per-package file beats glacier.conf: nothing to rebuild" has "Nothing to do." +rm /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "glacier.conf turns loud on (x11, unknown to the recipe, ignored): a rebuild" has " * extra-src::hello 1.0.0 (traits) [+loud] (build)" +check "...installed" rc 0 +check "...built with LOUD" [ "$(/glacier/sys/links/bin/hello)" = "HELLO" ] +check "...with the dependency loud needs" grep -q "^extra::loudlib::1.0.0::auto$" $IDX +check "...in its manifest" grep -qF '{ PKG_NAME = "loudlib"; PKG_VER = "1.0.0"; }' $V/.glacier-manifest +check "...still marked as built from source" [ "$(cat $V/.glacier-src)" = extra-src ] +check "...PKG_TRAITS updated" grep -qF 'PKG_TRAITS = [ "loud" ];' $V/.glacier-manifest +R yes_to 'y\n' 'syspkg -u' +check "unchanged traits: nothing to do" has "Nothing to do." +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/hello.conf +chmod 666 /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a world-writable per-package file is refused" has "[x] Refusing /etc/glacier/config/hello.conf: /etc/glacier/config/hello.conf is not root-owned, or is group/world-writable." +rm /etc/glacier/config/hello.conf +printf 'TRAITS = [ "loud" ]; COLOR = "red";\n' > /etc/glacier/config/hello.conf +R yes_to 'y\n' 'syspkg -u' +check "a per-package file with an unknown key is malformed" has "[x] Malformed /etc/glacier/config/hello.conf." +rm /etc/glacier/config/hello.conf + +hr "-u stays on source" +H11=$(mksrc hello 1.1.0) +sed "s/1\.0\.0/1.1.0/g; s/$H/$H11/" /tmp/rcp/hello-1.0.0/recipe > /tmp/r.new +rm -rf /tmp/rcp/hello-1.1.0 && cp -a /tmp/rcp/hello-1.0.0 /tmp/rcp/hello-1.1.0 && mv /tmp/r.new /tmp/rcp/hello-1.1.0/recipe +sed -i 's/VER = "1.1.0"; }/VER = "1.0.0"; }/g; s/VER = "1.1.0"; IF/VER = "1.0.0"; IF/' /tmp/rcp/hello-1.1.0/recipe +tar czf $S/hello-1.1.0.grcp -C /tmp/rcp hello-1.1.0 +/app/tests/mkpkg -o $E hello 2.0.0 extra >/dev/null +publish +R yes_to 'y\n' 'syspkg -u hello' +check "a newer recipe is built, not extra's binary 2.0.0" has " * extra-src::hello 1.0.0 -> 1.1.0 [+loud] (build)" +check "...installed" grep -q "^extra::hello::1.1.0::explicit$" $IDX +check "...the old version backed up" [ -f /glacier/sys/backup/extra/hello/hello-1.0.0.gpkg ] +check "...its new package kept for builds" [ -f $BUILD/packages/extra@hello-1.1.0.gpkg ] +check "...the old one's deleted" [ ! -e $BUILD/packages/extra@hello-1.0.0.gpkg ] +check "...still on source" [ "$(cat /glacier/sys/store/extra/hello/hello-1.1.0/.glacier-src)" = extra-src ] + +hr "PREFIX" +R yes_to 'y\n' 'syspkg -f where' +check "built for /glacier/sys/links: finds its data through the links" [ "$(/glacier/sys/links/bin/where)" = here ] +check "...the path compiled in" grep -q "^cat /glacier/sys/links/share/where/data$" /glacier/sys/links/bin/where +check "...packed as usr/, as any package" [ -f /glacier/sys/store/extra/where/where-1.0.0/usr/share/where/data ] +check "...nothing else at the top" [ "$(ls /glacier/sys/store/extra/where/where-1.0.0)" = usr ] +R yes_to 'y\n' 'syspkg -f split' +check "a build installing into PREFIX and /usr both fails" has "[x] Building extra-src::split 1.0.0 failed." +check "...the log says why" grep -q "split installed into both /glacier/sys/links and /usr" $BUILD/logs/split-1.0.0.log + +hr "kept packages" +P=$BUILD/packages +check "a source build's package is kept, root's 0644" [ "$(stat -c '%u %a' $P/extra@where-1.0.0.gpkg)" = "0 644" ] +check "...byte for byte what was installed" sh -c "tar xzOf $P/extra@where-1.0.0.gpkg where-1.0.0/files/usr/bin/where | cmp -s - /glacier/sys/store/extra/where/where-1.0.0/usr/bin/where" +check "...not a failed one" [ ! -e $P/extra@split-1.0.0.gpkg ] +R yes_to 'y\n' 'syspkg -q -f srclib' +check "srclib (no binary anywhere) built and installed" rc 0 +check "...-q: no build output on the terminal" lacks "==> " +check "...but the build is still announced" has "[✓] Built extra-src::srclib 1.0.0." +check "...and logged" grep -q "==> Done" $BUILD/logs/srclib-1.0.0.log +R yes_to 'y\n' 'syspkg --quiet -f srcapp' +check "--quiet too" lacks "==> " +check "a build needing an installed source build: built" has "[✓] Built extra-src::srcapp 1.0.0." +check "...installed" grep -q "^extra::srcapp::1.0.0::explicit$" $IDX +check "...the kept package was its layer" sh -c "ls $BUILD/layers | grep -q '^srclib-1.0.0-'" +printf 'TRAITS = [ "-loud" ];\n' > /etc/glacier/config/srcapp.conf +R yes_to 'y\n' 'syspkg -u srcapp' +check "-u rebuilds it (traits changed)" has " * extra-src::srcapp 1.0.0 (traits) [-loud] (build)" +check "...exit 0" rc 0 +mv $P/extra@srclib-1.0.0.gpkg /root/kept.bak +rm /etc/glacier/config/srcapp.conf +R yes_to 'y\n' 'syspkg -u srcapp' +mv /root/kept.bak $P/extra@srclib-1.0.0.gpkg +check "without its kept package, srclib can't be a layer" has "[x] extra-src::srcapp 1.0.0 needs srclib 1.0.0 or later to build, and no binary repository has it." +R yes_to 'y\n' 'syspkg -x srcapp' +check "removing srcapp deletes its kept package" [ ! -e $P/extra@srcapp-1.0.0.gpkg ] +check "...not srclib's, still installed" [ -f $P/extra@srclib-1.0.0.gpkg ] +R yes_to 'y\n' 'syspkg -x srclib' +check "removing srclib deletes its own" [ ! -e $P/extra@srclib-1.0.0.gpkg ] +check "...others stay" [ -f $P/extra@where-1.0.0.gpkg ] +R yes_to '2\ny\n' 'syspkg -f twin' +check "twin built from source: kept" [ -f $P/extra@twin-1.0.0.gpkg ] +R yes_to '1\ny\n' 'syspkg -f -O twin' +check "the same version reinstalled from the binary repo" [ "$(/glacier/sys/links/bin/twin)" = "twin 1.0.0 says hi" ] +check "...no longer kept" [ ! -e $P/extra@twin-1.0.0.gpkg ] + +hr "the repository question" +R yes_to '\ny\n' 'syspkg -f both' +check "both repos serving a name: asked" has "[i] both is available from more than one repository:" +check "...the binary first (repos.conf order)" has " 1) extra::both 9.0.0" +check "...then the recipe" has " 2) extra-src::both 1.0.0 [+loud] (build)" +check "...Enter takes the first" grep -q "^extra::both::9.0.0::explicit$" $IDX +check "...not marked as built" [ ! -e /glacier/sys/store/extra/both/both-9.0.0/.glacier-src ] +check "...nor kept" [ ! -e $BUILD/packages/extra@both-9.0.0.gpkg ] +R yes_to '2\ny\n' 'syspkg -f -O both' +check "2 builds the recipe (replacing the binary under -O)" grep -q "^extra::both::1.0.0::explicit$" $IDX +check "...marked as built" [ "$(cat /glacier/sys/store/extra/both/both-1.0.0/.glacier-src)" = extra-src ] +check "...and kept" [ -f $BUILD/packages/extra@both-1.0.0.gpkg ] +R yes_to '3\n' 'syspkg -f -O both' +check "an answer out of range is refused" has "[x] Invalid selection." +check "...exit 1" rc 1 +R yes_to 'x\n' 'syspkg -f -O both' +check "a non-number is refused" has "[x] Invalid selection." +R sh -c 'syspkg -f -O both < /dev/null' +check "end of input is refused" has "[x] Invalid selection." + +hr "refused builds" +R yes_to 'y\n' 'syspkg -f badhash' +check "a source with the wrong hash" has "[x] A source of extra-src::badhash 1.0.0 does not match its hash." +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q badhash $IDX" +R yes_to 'y\n' 'syspkg -f broken' +check "a failing build" has "[x] Building extra-src::broken 1.0.0 failed. Log: $BUILD/logs/broken-1.0.0.log" +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q broken $IDX" +check "...the log says why" grep -q "Error\|error" $BUILD/logs/broken-1.0.0.log +check "...its dirs removed" [ -z "$(ls $BUILD | grep -E '^(in|work|out)-')" ] +R yes_to 'y\n' 'syspkg -f evil' +check "a build that produces another package" has "[x] extra-src::evil 1.0.0: the build produced another package." +check "...nothing installed" sh -c "! grep -q evil $IDX && [ ! -e /usr/bin/evil ]" +# An index entry that disagrees with its bundle's recipe (signed all +# the same): the recipe has a dependency the index left out. +mkrecipe liar 1.0.0 "$(mksrc liar 1.0.0)" 'DEPS = ( { NAME = "hidep"; VER = "1.0.0"; } );' +publish +SER=$(sed -n 's/^SERIAL = \([0-9]*\)L;$/\1/p' $S/repo.idx) +awk -v s=$((SER + 1)) '/^SERIAL/ { print "SERIAL = " s "L;"; next } /NAME = "liar"/ { liar = 1 } liar && /DEPS = / { sub(/DEPS = \(.*\);/, "DEPS = ();"); liar = 0 } { print }' $S/repo.idx > /tmp/idx && mv /tmp/idx $S/repo.idx +gsign -S -s $SSEC -m $S/repo.idx >/dev/null +R yes_to 'y\n' 'syspkg -f liar' +check "a recipe that disagrees with its index entry" has "[x] extra-src::liar 1.0.0 does not match its index." +check "...nothing installed" sh -c "! grep -q liar $IDX" +chmod 666 /app/lib/build-driver.sh +R yes_to '2\ny\n' 'syspkg -f -O hello' +chmod 644 /app/lib/build-driver.sh +check "a world-writable build driver is refused" has "[x] Refusing /app/lib/build-driver.sh: /app/lib/build-driver.sh is not root-owned, or is group/world-writable." +check "...before the prompt" lacks "Proceed?" +R yes_to 'y\n' 'syspkg -f needy' +check "a build dependency no binary repo has" has "[x] extra-src::needy 1.0.0 needs nothere 1.0.0 or later to build, and no binary repository has it." +check "...refused before the prompt" lacks "Proceed?" +gconf 'BUILD_ROOT = [ "toolchain" ];' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER unset: refused" has "[x] BUILD_USER is not set in /etc/glacier/glacier.conf." +check "...before the prompt" lacks "Proceed?" +gconf 'BUILD_USER = "gbuild";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_ROOT unset: refused" has "[x] BUILD_ROOT is not set in /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "root";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER = root: refused" has "[x] BUILD_USER in /etc/glacier/glacier.conf must not be root." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "nosuchuser";' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "BUILD_USER not a user: refused" has "[x] BUILD_USER nosuchuser in /etc/glacier/glacier.conf is not a user." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; JOBS = 0;' +R yes_to '2\ny\n' 'syspkg -f -O hello' +check "JOBS = 0: glacier.conf is malformed" has "[x] Malformed /etc/glacier/glacier.conf." +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild";' +mkdir -p /mnt/t && syspkg -R /mnt/t -n >/dev/null +cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/ 2>/dev/null || { mkdir -p /mnt/t/etc/glacier && cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/t/etc/glacier/; } +R yes_to '2\ny\n' 'syspkg -R /mnt/t -f both' +check "building under -R is refused" has "[x] Building from source under -R is not supported." + +hr "base-src and the machine key" +R yes_to 'y\n' 'syspkg -f core' +check "a base build without the machine key trusted for base is refused" has '[x] base-src::core 1.0.0 [-loud] (build) needs the key "local" trusted for base.' +check "...before the prompt" lacks "Proceed?" +check "...having made the machine key" has "[i] Made the machine key /etc/glacier/keys/local.pub." +check "...its public half 0644" [ "$(stat -c '%u %a' /etc/glacier/keys/local.pub)" = "0 644" ] +check "...its secret half root's 0600" [ "$(stat -c '%u %a' /glacier/sys/keys/local.sec)" = "0 600" ] +R yes_to 'y\n' 'syspkg -f core' +check "...made once" lacks "Made the machine key" +rconf '"glacier-test", "local"' +R yes_to 'y\n' 'syspkg -f core' +check "listed for base: built and installed" grep -q "^base::core::1.0.0::explicit$" $IDX +check "...linked into /usr, as base is" [ "$(/usr/bin/core)" = hello ] +check "...marked as built from base-src" [ "$(cat /glacier/sys/store/base/core/core-1.0.0/.glacier-src)" = base-src ] +check "...built for /usr" [ "$(cat /usr/share/core.prefix)" = /usr ] +mv /glacier/sys/keys/local.sec /root/local.sec.bak +printf 'TRAITS = [ "loud" ];\n' > /etc/glacier/config/core.conf +R yes_to 'y\n' 'syspkg -u core' +rm /etc/glacier/config/core.conf +rconf '"glacier-test"' +mv /root/local.sec.bak /glacier/sys/keys/local.sec +check "a missing secret half is refused" has "[x] /etc/glacier/keys/local.pub and /glacier/sys/keys/local.sec must both exist, or neither." + +hr "gpkg: the user's own build" +U=/glacier/usr/1000 +su glacier -c 'doas /app/gstore -n' >/dev/null 2>&1 +check "gstore -n makes the user's config dir" [ "$(stat -c '%U %a' $U/config)" = "glacier 700" ] +gconf 'BUILD_ROOT = [ "toolchain" ]; BUILD_USER = "gbuild"; TRAITS = [ "loud" ];' +R su glacier -c "printf '2\ny\n' | /app/gpkg -f both" +check "gpkg builds it" has "[✓] Built extra-src::both 1.0.0." +check "...the system's TRAITS apply" has "[i] Building extra-src::both 1.0.0 [+loud]..." +check "...installed for the user" grep -q "^extra::both::1.0.0::explicit$" $U/index/current +check "...the layers are the user's" [ "$(stat -c %U $U/build/layers/toolchain-1.0.0-*)" = glacier ] +check "...the log too" [ "$(stat -c '%U %a' $U/build/logs/both-1.0.0.log)" = "glacier 600" ] +check "...it runs" [ "$(su glacier -c "$U/links/bin/both")" = HELLO ] +check "...kept in the user's base, 0600" [ "$(stat -c '%U %a' $U/build/packages/extra@both-1.0.0.gpkg)" = "glacier 600" ] +R su glacier -c "printf 'y\n' | /app/gpkg -f where" +check "gpkg shows the build's output" has "==> Packing where-1.0.0.gpkg" +R su glacier -c "printf 'y\n' | /app/gpkg -fqO where" +check "gpkg -q (in a bundle) hides it" lacks "==> " +check "...and rebuilds" has "[✓] Built extra-src::where 1.0.0." +R su glacier -c "printf 'y\n' | /app/gpkg --quiet -fO where" +check "gpkg --quiet too" sh -c '! echo "$0" | grep -q "==> " && echo "$0" | grep -q "Built extra-src::where"' "$OUT" +R syspkg -h +check "syspkg -h lists -q" has "{-q --quiet} Hide build output" +R su glacier -c "/app/gpkg -h" +check "gpkg -h lists -q" has "{-q --quiet} Hide build output" +check "gpkg builds for the user's links" [ "$(su glacier -c "$U/links/bin/where")" = here ] +check "...the path compiled in" grep -q "^cat $U/links/share/where/data$" $U/links/bin/where +su glacier -c "printf 'TRAITS = [ \"-loud\" ];\n' > $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "the user's per-package file wins: rebuilt without loud" has " * extra-src::both 1.0.0 (traits) [-loud] (build)" +check "...installed" [ "$(su glacier -c "$U/links/bin/both")" = hello ] +su glacier -c "printf 'TRAITS = [ \"loud\" ];\n' > $U/config/glacier.conf; rm $U/config/both.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "...the user's glacier.conf too" has "[+loud] (build)" +R su glacier -c "printf 'y\n' | /app/gpkg -f core" +check "gpkg never builds from base-src" has "[x] core is not in any repository." +su glacier -c "printf 'BUILD_USER = \"x\";\n' > $U/config/glacier.conf" +R su glacier -c "printf 'y\n' | /app/gpkg -u" +check "BUILD_USER in a user's glacier.conf is malformed" has "[x] Malformed $U/config/glacier.conf." + +echo +if [ $FAILS -eq 0 ]; then echo "ALL PASSED"; else echo "$FAILS FAILED"; fi +[ $FAILS -eq 0 ] diff --git a/tests/buildenv b/tests/buildenv new file mode 100755 index 0000000..5a2fd99 --- /dev/null +++ b/tests/buildenv @@ -0,0 +1,57 @@ +#!/bin/sh +# buildenv: set up THIS container (glacier-alpine_root, started with +# `./run_docker.sh -b Dockerfile.alpine_root`) to build packages from +# source, with local repositories: +# +# buildenv [RECIPES] +# +# RECIPES a directory of NAME/ recipe dirs (default +# /recipes/extra-src, which run_docker.sh -b mounts) +# +# It makes, once: the system (syspkg -n), the build user gbuild, a +# signing key "repokey", /srv/extra with a toolchain package made from +# Alpine's build-base (tests/mkroot; Everest has no toolchain packages +# yet), BUILD_ROOT/BUILD_USER/JOBS in /etc/glacier/glacier.conf, and +# /etc/glacier/repos.conf listing extra and extra-src. Every run packs +# RECIPES into /srv/extra-src (tests/mkgrcp), signs both indexes and +# syncs, so rerun it after editing a recipe. + +set -e +recipes=${1:-/recipes/extra-src} +t=$(dirname "$(realpath "$0")") +export PATH="/app:$PATH" + +[ -d "$recipes" ] || { echo "buildenv: no recipe directory $recipes" >&2; exit 1; } +[ -d /glacier/sys ] || syspkg -n +id gbuild >/dev/null 2>&1 || adduser -S -D -H gbuild +mkdir -p /srv/extra /srv/extra-src +chmod 755 /srv /srv/extra /srv/extra-src + +if [ ! -f /srv/extra/toolchain-1.0.0.gpkg ]; then + echo "Packing the toolchain (Alpine's build-base)..." + "$t/mkroot" -o /srv/extra -r build-base -r busybox -p busybox toolchain 1.0.0 extra +fi + +rm -f /srv/extra-src/*.grcp +"$t/mkgrcp" -o /srv/extra-src "$recipes"/*/ + +[ -f /root/repokey.sec ] || + gsign -G -p /etc/glacier/keys/repokey.pub -s /root/repokey.sec -c repokey +grepo -s /root/repokey.sec -r extra /srv/extra +grepo -s /root/repokey.sec -r extra-src /srv/extra-src + +cat > /etc/glacier/repos.conf <<'EOR' +repos = ( + { name = "base"; keys = [ "glacier-test" ]; }, + { name = "extra"; url = "file:///srv/extra"; keys = [ "repokey" ]; }, + { name = "extra-src"; url = "file:///srv/extra-src"; keys = [ "repokey" ]; } +); +EOR +chmod 644 /etc/glacier/repos.conf + +c=/etc/glacier/glacier.conf +grep -q '^BUILD_ROOT' $c || echo 'BUILD_ROOT = [ "toolchain" ];' >> $c +grep -q '^BUILD_USER' $c || echo 'BUILD_USER = "gbuild";' >> $c +grep -q '^JOBS' $c || echo "JOBS = $(nproc);" >> $c + +syspkg -y diff --git a/tests/deps_alpine.sh b/tests/deps_alpine.sh new file mode 100644 index 0000000..6e875fc --- /dev/null +++ b/tests/deps_alpine.sh @@ -0,0 +1,196 @@ +#!/bin/sh +# Dependencies and conflicts (ROADMAP 2.3): minimum versions, conflicts +# both ways by name, every problem reported before the prompt, removal of +# a dependency refused, user deps met by system packages, the library's +# own enforcement at commit and for live contexts, and the index's +# auto|explicit field. Runs INSIDE the Dockerfile.alpine_root image: +# +# ./run_docker.sh Dockerfile.alpine_root # builds glacier-alpine_root +# docker run --rm -v "$PWD/tests/deps_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +has() { echo "$OUT" | grep -qxF "$1"; } +hasnt() { ! echo "$OUT" | grep -qF "$1"; } +inst() { grep -q "^$1::" /glacier/sys/index/current; } +SP() { OUT=$(echo y | ./syspkg "$@" 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /'; } + +# mkpkg NAME VER REPO [DEPS] [CONFS] -> /srv/NAME-VER.gpkg (+ sidecar) +# DEPS / CONFS: space-separated name:version +mkpkg() { + w=$(mktemp -d); d=$w/$1-$2 + mkdir -p $d/files/usr/share/$1 + echo "$1 $2" > $d/files/usr/share/$1/data + { + printf 'PKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_DESC = "t";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "%s";\n' "$1" "$2" "$3" + for list in DEPS CONFS; do + [ $list = DEPS ] && items=$4 || items=$5 + printf 'PKG_%s = (' $list; sep="" + for it in $items; do + printf '%s{ PKG_NAME = "%s"; PKG_VER = "%s"; }' "$sep" "${it%%:*}" "${it#*:}"; sep=", " + done + printf ');\n' + done + } > $d/manifest.gpm.cfg + tar czf /srv/$1-$2.gpkg -C $w $1-$2 + printf 'sha256:%s\n' "$(sha256sum /srv/$1-$2.gpkg | cut -d' ' -f1)" > /srv/$1-$2.gpkg.sha256 + gsign -S -s /root/glacier-test.sec -m /srv/$1-$2.gpkg.sha256 >/dev/null + chmod 644 /srv/$1-$2.gpkg /srv/$1-$2.gpkg.sha256 /srv/$1-$2.gpkg.sha256.sig + rm -rf $w +} +mkdir -p /srv; chmod 755 /srv +mkpkg lib 1.0.0 extra +mkpkg lib 1.3.0 extra +mkpkg app 1.0.0 extra "lib:1.2.0" +mkpkg multi 1.0.0 extra "ghost:2.0.0 phantom:0.1.0" +mkpkg core 1.0.0 base +mkpkg usescore 1.0.0 extra "core:1.0.0" +mkpkg x 1.0.0 extra "" "y:9.9.9" +mkpkg y 1.0.0 extra +mkpkg w 1.0.0 community +mkpkg x2 1.0.0 extra "" "w:1.0.0" +mkpkg other 1.0.0 extra +mkpkg uapp 1.0.0 extra "core:1.0.0" +mkpkg unoway 1.0.0 extra "nowhere:1.0.0" + +cd /app && ./syspkg -n >/dev/null 2>&1 + +echo "== 1. missing dependency: refused before the prompt" +SP -l /srv/app-1.0.0.gpkg +check "message names the dependency and its minimum" has "[x] extra::app requires lib >= 1.2.0, which is not installed." +check "refused before the prompt" hasnt "Proceed?" +check "app not installed" sh -c '! grep -q "^extra::app::" /glacier/sys/index/current' + +echo "== 2. dependency installed but too old" +SP -l /srv/lib-1.0.0.gpkg +SP -l /srv/app-1.0.0.gpkg +check "too-old version refused" has "[x] extra::app requires lib >= 1.2.0, which is not installed." +check "still not installed" sh -c '! grep -q "^extra::app::" /glacier/sys/index/current' + +echo "== 3. every problem reported, one line each" +SP -l /srv/multi-1.0.0.gpkg +check "first missing dep" has "[x] extra::multi requires ghost >= 2.0.0, which is not installed." +check "second missing dep" has "[x] extra::multi requires phantom >= 0.1.0, which is not installed." + +echo "== 4. a batch satisfies itself, in any order (with -O replacing lib 1.0.0)" +SP -lO /srv/app-1.0.0.gpkg /srv/lib-1.3.0.gpkg +check "batch completed" has "[✓] Completed with no errors." +check "app installed" inst extra::app +check "lib upgraded to 1.3.0" grep -q "^extra::lib::1.3.0" /glacier/sys/index/current + +echo "== 5. removing a dependency is refused" +SP -x lib +check "removal refused with the dependent named" has "[x] Removing extra::lib breaks extra::app." +check "refused before the prompt" hasnt "Proceed?" +check "lib still installed" inst extra::lib + +echo "== 6. a downgrade below a dependent's minimum is refused" +SP -lO /srv/lib-1.0.0.gpkg +check "downgrade refused" has "[x] extra::app requires lib >= 1.2.0, which is not installed." +check "lib still 1.3.0" grep -q "^extra::lib::1.3.0" /glacier/sys/index/current + +echo "== 7. removing the dependent and the dependency together is fine" +SP -x app lib +check "both removed" sh -c '! grep -q "^extra::\(app\|lib\)::" /glacier/sys/index/current' + +echo "== 8. a dependency is met from any repo" +SP -l /srv/core-1.0.0.gpkg /srv/usescore-1.0.0.gpkg +check "extra package depending on a base package installs" inst extra::usescore + +echo "== 9. conflicts, both directions, version ignored" +SP -l /srv/y-1.0.0.gpkg +SP -l /srv/x-1.0.0.gpkg +check "new package listing an installed one" has "[x] extra::x conflicts with extra::y." +SP -l /srv/w-1.0.0.gpkg +SP -l /srv/x2-1.0.0.gpkg +check "new package listing an installed one, other repo" has "[x] extra::x2 conflicts with community::w." +SP -x w +SP -l /srv/x2-1.0.0.gpkg +SP -l /srv/w-1.0.0.gpkg +check "installed package listing the new one" has "[x] community::w conflicts with extra::x2." +SP -x x2 +SP -l /srv/x2-1.0.0.gpkg /srv/w-1.0.0.gpkg +check "a conflicting pair in one batch is reported once" test "$(echo "$OUT" | grep -c 'conflicts with')" = 1 + +echo "== 10. an already-inconsistent store doesn't block unrelated work" +M=$(ls -d /glacier/sys/store/extra/usescore/usescore-*)/.glacier-manifest +sed -i 's/^PKG_DEPS = (\(.*\));/PKG_DEPS = (\1, { PKG_NAME = "ghost"; PKG_VER = "1.0.0"; });/' $M +grep -q ghost $M || echo " (manifest edit failed)" +SP -l /srv/other-1.0.0.gpkg +check "unrelated install still works" inst extra::other + +echo "== 11. index: auto|explicit field, and the CLIs still parse it" +check "index lines carry ::explicit" grep -q "^extra::other::1.0.0::explicit$" /glacier/sys/index/current +cat > /tmp/auto.lua <<'EOF' +package.path = "/app/?.lua;" .. package.path +local ffi = require("ffi"); require("lib/glacier_cdef") +local istore = ffi.load("/app/lib/glacier/libglacier_istoreutils.so") +local txn = ffi.load("/app/lib/glacier/libglacier_transaction.so") +local live = ffi.new("gl_context_t") +txn.gl_init_live_context(live, ffi.C.GL_SCOPE_SYS, 0) +os.exit(istore.gl_set_pkg_auto(live, "extra", "other", true) == 0 and 0 or 1) +EOF +check "gl_set_pkg_auto succeeds" luajit /tmp/auto.lua +check "index line now ::auto" grep -q "^extra::other::1.0.0::auto$" /glacier/sys/index/current +SP -x other +check "-x summary shows the plain version" sh -c 'echo "$1" | grep -q "extra::other.*1\.0\.0 *$"' _ "$OUT" +check "auto package removed by name" sh -c '! grep -q "^extra::other::" /glacier/sys/index/current' + +echo "== 12. the library enforces the rules itself (no CLI pre-check)" +cat > /tmp/lib.lua <<'EOF' +package.path = "/app/?.lua;" .. package.path +local ffi = require("ffi"); require("lib/glacier_cdef") +local istore = ffi.load("/app/lib/glacier/libglacier_istoreutils.so") +local txn = ffi.load("/app/lib/glacier/libglacier_transaction.so") +local what = arg[1] +local ctx = ffi.new("gl_context_t") +if what == "stage-install" or what == "stage-remove" then + assert(txn.gl_init_stage_context(ctx, ffi.C.GL_SCOPE_SYS, 0) == 0) + if what == "stage-install" then + assert(istore.gl_install_pkg(ctx, "/srv/app-1.0.0.gpkg") == 0) + else + assert(istore.gl_remove_pkg(ctx, "core", "base") == 0) + end + local st = txn.gl_commit_transaction(ctx) + txn.gl_abort_transaction(ctx) + print(tonumber(st)) +else + txn.gl_init_live_context(ctx, ffi.C.GL_SCOPE_SYS, 0) + if what == "live-install" then + print(tonumber(istore.gl_install_pkg(ctx, "/srv/app-1.0.0.gpkg"))) + else + print(tonumber(istore.gl_remove_pkg(ctx, "core", "base"))) + end +end +EOF +OUT=$(luajit /tmp/lib.lua stage-install 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /' +check "staged install with a missing dep: commit refuses (GL_TXN_ERR_DEPS)" has "9" +check "and says why" has "[x] extra::app requires lib >= 1.2.0, which is not installed." +check "app not committed" sh -c '! grep -q "^extra::app::" /glacier/sys/index/current' +OUT=$(luajit /tmp/lib.lua stage-remove 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /' +check "staged removal of a dependency: commit refuses" has "9" +check "and says why" has "[x] Removing base::core breaks extra::usescore." +check "core still installed" inst base::core +OUT=$(luajit /tmp/lib.lua live-install 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /' +check "live install with a missing dep: GL_INSTALL_ERR_DEPS" has "8" +check "app not in the live store" test ! -e /glacier/sys/store/extra/app +OUT=$(luajit /tmp/lib.lua live-remove 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /' +check "live removal of a dependency: GL_REMOVE_ERR_DEPS" has "4" +check "core still in the live store" test -d /glacier/sys/store/base/core + +echo "== 13. user scope: deps met by system packages; system ignores users" +U() { OUT=$(su glacier -c "cd /app && echo y | ./gpkg $*" 2>&1 | nocolor); echo "$OUT" | sed 's/^/ /'; } +su glacier -c "doas /app/gstore -n" >/dev/null 2>&1 +U -l /srv/uapp-1.0.0.gpkg +check "user package depending on a system package installs" has "[✓] Completed with no errors." +U -l /srv/unoway-1.0.0.gpkg +check "user package with a missing dep refused" has "[x] extra::unoway requires nowhere >= 1.0.0, which is not installed." +SP -x usescore +SP -x core +check "syspkg -x ignores user-scope dependents" has "[✓] Completed with no errors." +U -x uapp +check "user can still remove their package" has "[✓] Completed with no errors." + +echo +[ $FAILS -eq 0 ] && echo "ALL PASSED" || echo "$FAILS FAILED" +exit $FAILS diff --git a/tests/fetch_alpine.sh b/tests/fetch_alpine.sh new file mode 100755 index 0000000..f78950a --- /dev/null +++ b/tests/fetch_alpine.sh @@ -0,0 +1,307 @@ +#!/bin/sh +# -f and -u from repositories (REPO_DESIGN.txt section 6, step 4): +# - every -f/-u refreshes every index first; any failure refuses; +# - -f NAME takes the first repo (by repos.conf order) serving NAME, +# at its highest version; a name nobody serves is refused; +# - missing dependencies are added (auto, marked in the summary); one +# installed too old is upgraded from its own repo, keeping its mark; +# one that can't be met is refused by the 2.3 check; +# - downloads go to /cache/REPO (scope owner and modes), are +# hashed against the index (size capped), the manifest must say what +# the index says (name, version, REPO, deps, conflicts), and a base +# package needs no .sig of its own; files are deleted once committed; +# - -u replaces what an index has newer (backups, KEEP_OLD), -u NAME +# only those; -f of an installed other version needs -O, like -l; +# - gpkg -f/-u: user scope, never from base, system packages meet deps; +# - syspkg -R DIR -f installs into DIR, with DIR's own repos.conf. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/fetch_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +empty() { [ -z "$(find "$@" -type f)" ]; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +XSEC=/root/extrakey.sec +B=/srv/base +E=/srv/extra +C=/srv/community +IDX=/glacier/sys/index/current +CACHE=/glacier/sys/cache +mkdir -p $B $E $C && chmod 755 /srv $B $E $C + +gsign -G -p $K/extrakey.pub -s $XSEC -c extrakey >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; },' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; },' +COMM_E=' { name = "community"; url = "file:///srv/community"; keys = [ "extrakey" ]; }' +conf "$BASE_E +$EXTRA_E +$COMM_E" +# mkpkg into a repo dir, without a sidecar signature: the index vouches. +pk() { d=$1; shift; /app/tests/mkpkg -o "$d" "$@" >/dev/null; } +publish() { + grepo -s $TEST_SEC -r base $B >/dev/null && + grepo -s $XSEC -r extra $E >/dev/null && + grepo -s $XSEC -r community $C >/dev/null +} +line() { grep -q "^$1\$" $IDX; } +yes_to() { sh -c "echo y | $*"; } +no_to() { sh -c "echo n | $*"; } + +syspkg -n >/dev/null + +pk $B core 1.0.0 base +pk $B core 1.1.0 base +pk $E lib 1.0.0 extra +pk $E lib 2.0.0 extra +pk $E -d lib:2.0.0 -d core:1.0.0 app 1.0.0 extra +pk $E dup 1.0.0 extra +pk $C dup 9.0.0 community +pk $C only 1.0.0 community +pk $E -d ghost:1.0.0 lonely 1.0.0 extra +pk $E -d lib:9.0.0 greedy 1.0.0 extra +pk $E -c app:0.0.0 rival 1.0.0 extra +publish + +hr "refusals before anything is fetched" +R syspkg -f nosuch +check "a name no repository serves is refused" has "[x] nosuch is not in any repository." +check "...exit 1" rc 1 +check "...after refreshing every index" has "[✓] All repositories synced successfully." +R syspkg -f +check "-f needs a name" has " -f PKG..." +R syspkg -f app -x lib +check "-f and -x are mutually exclusive" has "[x] -n, -l, -f, -u, -x and -y are mutually exclusive." +mv $E/repo.idx.sig /srv/sig.bak +R yes_to syspkg -f app +check "a failed refresh refuses -f" has "[x] Cannot fetch the index for extra." +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q app $IDX" +mv /srv/sig.bak $E/repo.idx.sig +su nobody -s /bin/sh -c 'syspkg -f app' >/srv/np.out 2>&1 +check "syspkg -f as non-root is refused" grep -qF "Cannot open system index: Permission denied" /srv/np.out + +hr "an installed dependency too old is upgraded" +R yes_to syspkg -l $E/lib-1.0.0.gpkg +check "lib 1.0.0 installed locally" line "extra::lib::1.0.0::explicit" +R no_to syspkg -f app +check "the summary lists app" has " * extra::app 1.0.0" +check "...lib's upgrade, as a dependency" has " * extra::lib 1.0.0 -> 2.0.0 (dependency)" +check "...and core, the newest base has, as a dependency" has " * base::core 1.1.0 (dependency)" +check "declining installs nothing" sh -c "! grep -q app $IDX" +check "...the downloads stay in the cache" [ -f $CACHE/extra/app-1.0.0.gpkg -a -f $CACHE/base/core-1.1.0.gpkg ] +check "...cache dirs are root's, 0755" [ "$(stat -c '%u %a' $CACHE $CACHE/extra)" = "0 755 +0 755" ] +check "...cached files are 0644" [ "$(stat -c %a $CACHE/extra/app-1.0.0.gpkg)" = 644 ] +check "...no temporary files" [ -z "$(find $CACHE -name '.*' -type f)" ] +printf 'garbage' > $CACHE/extra/app-1.0.0.gpkg +R yes_to syspkg -f app +check "-f app completes" has "[✓] Completed with no errors." +check "...a corrupt cached file is fetched again" rc 0 +check "app is explicit" line "extra::app::1.0.0::explicit" +check "lib was upgraded and stays explicit" line "extra::lib::2.0.0::explicit" +check "core is recorded as a dependency" line "base::core::1.1.0::auto" +check "lib 1.0.0 was backed up (KEEP_OLD)" [ -f /glacier/sys/backup/extra/lib/lib-1.0.0.gpkg ] +check "base::core installed with no .sig of its own" [ ! -e $B/core-1.1.0.gpkg.sha256.sig -a -x /usr/bin/core ] +check "the cache is emptied once committed" empty $CACHE +check "staged from the repository" has "base::core-1.1.0: staged from file:///srv/base/core-1.1.0.gpkg." + +hr "choosing a repository" +# A named package several repos serve is asked about (BUILD_DESIGN.txt +# 1f); Enter takes the first by priority. +R sh -c "printf '\ny\n' | syspkg -f dup" +check "a name two repos serve: asked" has "[i] dup is available from more than one repository:" +check "...in repos.conf order, each at its highest version" sh -c 'echo "$0" | grep -A2 "more than one" | tr "\n" "|" | grep -qF " 1) extra::dup 1.0.0| 2) community::dup 9.0.0|"' "$OUT" +check "...Enter takes the first, though community's is higher" line "extra::dup::1.0.0::explicit" +check "...community's 9.0.0 is not installed" sh -c "! grep -q community::dup $IDX" +R yes_to syspkg -f only +check "a name only a later repo serves comes from it, unasked" line "community::only::1.0.0::explicit" +check "...no question" lacks "more than one repository" +R sh -c "printf '\ny\n' | syspkg -f dup dup" +check "a name given twice is asked about and fetched once" sh -c "[ $(echo "$OUT" | grep -c 'extra::dup ') = 1 ] && [ $(echo "$OUT" | grep -c 'more than one') = 1 ]" + +hr "dependencies that can't be met" +R yes_to syspkg -f lonely +check "a dependency no repo serves is refused" has "[x] extra::lonely requires ghost >= 1.0.0, which is not installed." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ]" && check "...no prompt" lacks "Proceed?" +R yes_to syspkg -f greedy +check "a dependency no repo has new enough is refused" has "[x] extra::greedy requires lib >= 9.0.0, which is not installed." +R yes_to syspkg -f rival +check "a conflict is refused" has "[x] extra::rival conflicts with extra::app." +check "...nothing installed" sh -c "! grep -q rival $IDX" + +hr "what the index says must be what the package says" +# extrakey signs an index listing a package that claims to be base: +# a key trusted for extra must not be able to put anything into /usr. +forge() { # forge NAME VER FILE: put FILE in extra as NAME-VER.gpkg, re-sign + cp "$3" $E/$1-$2.gpkg + sha=$(sha256sum $E/$1-$2.gpkg | cut -c1-64); size=$(wc -c < $E/$1-$2.gpkg) + awk -v n="$1" -v s="$sha" -v z="$size" ' + hit { sub(/SHA256 = "[^"]*"; SIZE = [0-9]*L;/, "SHA256 = \"sha256:" s "\"; SIZE = " z "L;"); hit = 0 } + index($0, "NAME = \"" n "\";") { hit = 1 } { print }' $E/repo.idx > /srv/idx.new + serial=$(sed -n 's/^SERIAL = \([0-9]*\)L;$/\1/p' $E/repo.idx) + sed "s/^SERIAL = .*/SERIAL = $((serial + 1))L;/" /srv/idx.new > $E/repo.idx + gsign -S -s $XSEC -m $E/repo.idx +} +mkdir -p /srv/evil +pk $E evil 1.0.0 extra +pk /srv/evil evil 1.0.0 base +pk $E plain 1.0.0 extra +pk /srv/evil -d core:1.0.0 plain 1.0.0 extra +publish +forge evil 1.0.0 /srv/evil/evil-1.0.0.gpkg +forge plain 1.0.0 /srv/evil/plain-1.0.0.gpkg +R yes_to syspkg -f evil +check "a package claiming base from extra's index is refused" has "[x] extra::evil 1.0.0 does not match its index." +check "...exit 1, nothing in /usr" sh -c "[ $RC = 1 ] && [ ! -e /usr/bin/evil ] && ! grep -q evil $IDX" +R yes_to syspkg -f plain +check "dependencies the index doesn't list are refused" has "[x] extra::plain 1.0.0 does not match its index." +# grepo would refuse the forged files: back to honest ones. +rm $E/evil-1.0.0.gpkg* $E/plain-1.0.0.gpkg* +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +printf 'X' >> $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a download bigger than the index says is refused" has "[x] extra::needslib 1.0.0 does not match its index." +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +head -c 100 $E/needslib-1.0.0.gpkg > /srv/short && cp /srv/short $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a truncated one too" has "[x] extra::needslib 1.0.0 does not match its index." +check "...nothing half-fetched is left in the cache" [ ! -e $CACHE/extra/needslib-1.0.0.gpkg -a -z "$(find $CACHE -name '.*' -type f)" ] +check "packages whose manifest contradicts the index are not kept" [ ! -e $CACHE/extra/evil-1.0.0.gpkg -a ! -e $CACHE/extra/plain-1.0.0.gpkg ] +check "...refused but genuine ones are, until installed" [ -f $CACHE/extra/rival-1.0.0.gpkg ] +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +rm $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a file the repository lacks cannot be fetched" has "[x] Cannot fetch extra::needslib 1.0.0." +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish + +# A "package" that never ends: only SIZE bytes (+1) may ever be read. +pk $E endless 1.0.0 extra +publish +ln -sf /dev/zero $E/endless-1.0.0.gpkg +R sh -c 'echo y | timeout -s KILL 30 syspkg -f endless' +check "a download that never ends is cut off at the index's size" has "[x] extra::endless 1.0.0 does not match its index." +check "...promptly" [ "$RC" = 1 ] +check "...and nothing of it is left" [ -z "$(find $CACHE -name '*endless*')" ] +rm $E/endless-1.0.0.gpkg* +publish + +hr "the cache directory" +chmod 777 $CACHE/community +R yes_to syspkg -f only +check "a loosened cache dir is refused" has "[x] Refusing $CACHE/community: not a directory owned by UID 0 with mode 755." +check "...exit 1" rc 1 +chmod 755 $CACHE/community +mv $CACHE/community /srv/realcache && ln -s /srv/realcache $CACHE/community +R yes_to syspkg -f only +check "a symlinked cache dir is refused" has "[x] Refusing $CACHE/community: not a directory owned by UID 0 with mode 755." +rm $CACHE/community && mv /srv/realcache $CACHE/community +chmod 777 $CACHE +R yes_to syspkg -f only +check "a loosened cache is refused" has "[x] Refusing $CACHE: not a directory owned by UID 0 with mode 755." +chmod 755 $CACHE + +hr "-f of an installed other version" +pk $E dup 1.1.0 extra +publish +R sh -c "printf '1\ny\n' | syspkg -f dup" +check "needs -O, like -l" has "[x] extra::dup 1.0.0 is already installed." +R sh -c "printf '1\ny\n' | syspkg -fO dup" +check "-fO replaces it" line "extra::dup::1.1.0::explicit" + +hr "-u" +R yes_to syspkg -u +check "nothing newer: nothing to do" has "[✓] Nothing to do." +check "...exit 0" rc 0 +pk $E lib 2.1.0 extra +pk $B core 1.2.0 base +publish +R no_to syspkg -u +check "-u lists lib" has " * extra::lib 2.0.0 -> 2.1.0" +check "...and core" has " * base::core 1.1.0 -> 1.2.0" +check "...not app, which has nothing newer" lacks "extra::app " +R yes_to syspkg -u lib +check "-u lib upgrades lib" line "extra::lib::2.1.0::explicit" +check "...and only lib" line "base::core::1.1.0::auto" +R yes_to syspkg -u +check "-u upgrades the rest" line "base::core::1.2.0::auto" +check "...keeping core's dependency mark" line "base::core::1.2.0::auto" +check "...the old core is backed up" [ -f /glacier/sys/backup/base/core/core-1.1.0.gpkg ] +pk $E -d newdep:1.0.0 app 1.1.0 extra +pk $E newdep 1.0.0 extra +publish +R yes_to syspkg -u app +check "an upgrade's new dependency is added" line "extra::newdep::1.0.0::auto" +check "...with the upgrade" line "extra::app::1.1.0::explicit" +R syspkg -u nosuch +check "-u of a name not installed is refused" has "[x] nosuch is not installed." +conf "$BASE_E +$EXTRA_E" +R syspkg -u only +check "-u of a package whose repo isn't configured is refused" has "[x] community::only is not in any configured repository." +R yes_to syspkg -u +check "...and plain -u leaves it alone" line "community::only::1.0.0::explicit" +conf "$BASE_E +$EXTRA_E +$COMM_E" + +hr "gpkg -f / -u (user scope)" +adduser -D tester >/dev/null 2>&1 +U=$(id -u tester) +gstore -n "$U" >/dev/null +UB=/glacier/usr/$U +pk $E -d core:1.0.0 userapp 1.0.0 extra +publish +R su tester -c 'gpkg -f core' +check "gpkg never fetches from base" has "[x] core is not in any repository." +R su tester -c 'echo y | gpkg -f userapp' +check "gpkg -f installs into the user's scope" grep -q "^extra::userapp::1.0.0::explicit\$" $UB/index/current +check "...core, installed in the system, meets its dependency" sh -c "! grep -q core $UB/index/current" +check "...the user's cache is theirs, 0700" [ "$(stat -c '%u %a' $UB/cache $UB/cache/extra)" = "$U 700 +$U 700" ] +check "...and emptied" empty $UB/cache +check "...the user's indexes are theirs" [ "$(stat -c %u $UB/repos/extra.idx)" = "$U" ] +R su tester -c 'gpkg -f "%s%s%s%s%n"' +check "gpkg -f with %s%n as its operand" has "[x] %s%s%s%s%n is not in any repository." +R su tester -c 'gpkg -u "%s%s%s%s%n"' +check "gpkg -u with %s%n as its operand" has "[x] %s%s%s%s%n is not installed." +pk $E -d core:1.0.0 userapp 1.1.0 extra +publish +R su tester -c 'echo y | gpkg -u' +check "gpkg -u upgrades the user's package" grep -q "^extra::userapp::1.1.0::explicit\$" $UB/index/current +check "...the system's are untouched" line "extra::lib::2.1.0::explicit" +R su tester -c 'gpkg -f' +check "gpkg -f needs a name" has " -f PKG..." + +hr "syspkg -R DIR -f" +mkdir -p /mnt/img +syspkg -R /mnt/img -n >/dev/null +# -R uses the image's own keyring, as a package would ship it. +mkdir -p /mnt/img/etc/glacier && cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/img/etc/glacier/ +R yes_to syspkg -R /mnt/img -f app +check "-R -f installs into the image" grep -q "^extra::app::1.1.0::explicit\$" /mnt/img/glacier/sys/index/current +check "...with its dependencies" grep -q "^extra::newdep::1.0.0::auto\$" /mnt/img/glacier/sys/index/current +check "...indexes and cache under the image" [ -f /mnt/img/glacier/sys/repos/extra.idx -a -d /mnt/img/glacier/sys/cache/extra ] +check "...the host's store is untouched" line "extra::app::1.1.0::explicit" + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/fetch_alpine.sh.old b/tests/fetch_alpine.sh.old new file mode 100755 index 0000000..89b6ec6 --- /dev/null +++ b/tests/fetch_alpine.sh.old @@ -0,0 +1,300 @@ +#!/bin/sh +# -f and -u from repositories (REPO_DESIGN.txt section 6, step 4): +# - every -f/-u refreshes every index first; any failure refuses; +# - -f NAME takes the first repo (by repos.conf order) serving NAME, +# at its highest version; a name nobody serves is refused; +# - missing dependencies are added (auto, marked in the summary); one +# installed too old is upgraded from its own repo, keeping its mark; +# one that can't be met is refused by the 2.3 check; +# - downloads go to /cache/REPO (scope owner and modes), are +# hashed against the index (size capped), the manifest must say what +# the index says (name, version, REPO, deps, conflicts), and a base +# package needs no .sig of its own; files are deleted once committed; +# - -u replaces what an index has newer (backups, KEEP_OLD), -u NAME +# only those; -f of an installed other version needs -O, like -l; +# - gpkg -f/-u: user scope, never from base, system packages meet deps; +# - syspkg -R DIR -f installs into DIR. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/fetch_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +empty() { [ -z "$(find "$@" -type f)" ]; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +XSEC=/root/extrakey.sec +B=/srv/base +E=/srv/extra +C=/srv/community +IDX=/glacier/sys/index/current +CACHE=/glacier/sys/cache +mkdir -p $B $E $C && chmod 755 /srv $B $E $C + +gsign -G -p $K/extrakey.pub -s $XSEC -c extrakey >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; },' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; },' +COMM_E=' { name = "community"; url = "file:///srv/community"; keys = [ "extrakey" ]; }' +conf "$BASE_E +$EXTRA_E +$COMM_E" +# mkpkg into a repo dir, without a sidecar signature: the index vouches. +pk() { d=$1; shift; /app/tests/mkpkg -o "$d" "$@" >/dev/null; } +publish() { + grepo -s $TEST_SEC -r base $B >/dev/null && + grepo -s $XSEC -r extra $E >/dev/null && + grepo -s $XSEC -r community $C >/dev/null +} +line() { grep -q "^$1\$" $IDX; } +yes_to() { sh -c "echo y | $*"; } +no_to() { sh -c "echo n | $*"; } + +syspkg -n >/dev/null + +pk $B core 1.0.0 base +pk $B core 1.1.0 base +pk $E lib 1.0.0 extra +pk $E lib 2.0.0 extra +pk $E -d lib:2.0.0 -d core:1.0.0 app 1.0.0 extra +pk $E dup 1.0.0 extra +pk $C dup 9.0.0 community +pk $C only 1.0.0 community +pk $E -d ghost:1.0.0 lonely 1.0.0 extra +pk $E -d lib:9.0.0 greedy 1.0.0 extra +pk $E -c app:0.0.0 rival 1.0.0 extra +publish + +hr "refusals before anything is fetched" +R syspkg -f nosuch +check "a name no repository serves is refused" has "[x] nosuch is not in any repository." +check "...exit 1" rc 1 +check "...after refreshing every index" has "[✓] Index for community:" +R syspkg -f +check "-f needs a name" has " -f PKG..." +R syspkg -f app -x lib +check "-f and -x are mutually exclusive" has "[x] -n, -l, -f, -u, -x and -y are mutually exclusive." +mv $E/repo.idx.sig /srv/sig.bak +R yes_to syspkg -f app +check "a failed refresh refuses -f" has "[x] Cannot fetch the index for extra." +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q app $IDX" +mv /srv/sig.bak $E/repo.idx.sig +su nobody -s /bin/sh -c 'syspkg -f app' >/srv/np.out 2>&1 +check "syspkg -f as non-root is refused" grep -qF "Cannot open system index: Permission denied" /srv/np.out + +hr "an installed dependency too old is upgraded" +R yes_to syspkg -l $E/lib-1.0.0.gpkg +check "lib 1.0.0 installed locally" line "extra::lib::1.0.0::explicit" +R no_to syspkg -f app +check "the summary lists app" has " * extra::app 1.0.0" +check "...lib's upgrade, as a dependency" has " * extra::lib 1.0.0 -> 2.0.0 (dependency)" +check "...and core, the newest base has, as a dependency" has " * base::core 1.1.0 (dependency)" +check "declining installs nothing" sh -c "! grep -q app $IDX" +check "...the downloads stay in the cache" [ -f $CACHE/extra/app-1.0.0.gpkg -a -f $CACHE/base/core-1.1.0.gpkg ] +check "...cache dirs are root's, 0755" [ "$(stat -c '%u %a' $CACHE $CACHE/extra)" = "0 755 +0 755" ] +check "...cached files are 0644" [ "$(stat -c %a $CACHE/extra/app-1.0.0.gpkg)" = 644 ] +check "...no temporary files" [ -z "$(find $CACHE -name '.*' -type f)" ] +printf 'garbage' > $CACHE/extra/app-1.0.0.gpkg +R yes_to syspkg -f app +check "-f app completes" has "[✓] Completed with no errors." +check "...a corrupt cached file is fetched again" rc 0 +check "app is explicit" line "extra::app::1.0.0::explicit" +check "lib was upgraded and stays explicit" line "extra::lib::2.0.0::explicit" +check "core is recorded as a dependency" line "base::core::1.1.0::auto" +check "lib 1.0.0 was backed up (KEEP_OLD)" [ -f /glacier/sys/backup/extra/lib/lib-1.0.0.gpkg ] +check "base::core installed with no .sig of its own" [ ! -e $B/core-1.1.0.gpkg.sha256.sig -a -x /usr/bin/core ] +check "the cache is emptied once committed" empty $CACHE +check "staged from the repository" has "base::core-1.1.0: staged from file:///srv/base/core-1.1.0.gpkg." + +hr "choosing a repository" +R yes_to syspkg -f dup +check "the first repo serving a name wins over a higher version elsewhere" line "extra::dup::1.0.0::explicit" +check "...community's 9.0.0 is not installed" sh -c "! grep -q community::dup $IDX" +R yes_to syspkg -f only +check "a name only a later repo serves comes from it" line "community::only::1.0.0::explicit" +R yes_to syspkg -f dup dup +check "a name given twice is fetched once" sh -c "[ $(echo "$OUT" | grep -c 'extra::dup ') = 1 ]" + +hr "dependencies that can't be met" +R yes_to syspkg -f lonely +check "a dependency no repo serves is refused" has "[x] extra::lonely requires ghost >= 1.0.0, which is not installed." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ]" && check "...no prompt" lacks "Proceed?" +R yes_to syspkg -f greedy +check "a dependency no repo has new enough is refused" has "[x] extra::greedy requires lib >= 9.0.0, which is not installed." +R yes_to syspkg -f rival +check "a conflict is refused" has "[x] extra::rival conflicts with extra::app." +check "...nothing installed" sh -c "! grep -q rival $IDX" + +hr "what the index says must be what the package says" +# extrakey signs an index listing a package that claims to be base: +# a key trusted for extra must not be able to put anything into /usr. +forge() { # forge NAME VER FILE: put FILE in extra as NAME-VER.gpkg, re-sign + cp "$3" $E/$1-$2.gpkg + sha=$(sha256sum $E/$1-$2.gpkg | cut -c1-64); size=$(wc -c < $E/$1-$2.gpkg) + awk -v n="$1" -v s="$sha" -v z="$size" ' + hit { sub(/SHA256 = "[^"]*"; SIZE = [0-9]*L;/, "SHA256 = \"sha256:" s "\"; SIZE = " z "L;"); hit = 0 } + index($0, "NAME = \"" n "\";") { hit = 1 } { print }' $E/repo.idx > /srv/idx.new + serial=$(sed -n 's/^SERIAL = \([0-9]*\)L;$/\1/p' $E/repo.idx) + sed "s/^SERIAL = .*/SERIAL = $((serial + 1))L;/" /srv/idx.new > $E/repo.idx + gsign -S -s $XSEC -m $E/repo.idx +} +mkdir -p /srv/evil +pk $E evil 1.0.0 extra +pk /srv/evil evil 1.0.0 base +pk $E plain 1.0.0 extra +pk /srv/evil -d core:1.0.0 plain 1.0.0 extra +publish +forge evil 1.0.0 /srv/evil/evil-1.0.0.gpkg +forge plain 1.0.0 /srv/evil/plain-1.0.0.gpkg +R yes_to syspkg -f evil +check "a package claiming base from extra's index is refused" has "[x] extra::evil 1.0.0 does not match its index." +check "...exit 1, nothing in /usr" sh -c "[ $RC = 1 ] && [ ! -e /usr/bin/evil ] && ! grep -q evil $IDX" +R yes_to syspkg -f plain +check "dependencies the index doesn't list are refused" has "[x] extra::plain 1.0.0 does not match its index." +# grepo would refuse the forged files: back to honest ones. +rm $E/evil-1.0.0.gpkg* $E/plain-1.0.0.gpkg* +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +printf 'X' >> $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a download bigger than the index says is refused" has "[x] extra::needslib 1.0.0 does not match its index." +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +head -c 100 $E/needslib-1.0.0.gpkg > /srv/short && cp /srv/short $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a truncated one too" has "[x] extra::needslib 1.0.0 does not match its index." +check "...nothing half-fetched is left in the cache" [ ! -e $CACHE/extra/needslib-1.0.0.gpkg -a -z "$(find $CACHE -name '.*' -type f)" ] +check "packages whose manifest contradicts the index are not kept" [ ! -e $CACHE/extra/evil-1.0.0.gpkg -a ! -e $CACHE/extra/plain-1.0.0.gpkg ] +check "...refused but genuine ones are, until installed" [ -f $CACHE/extra/rival-1.0.0.gpkg ] +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +rm $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a file the repository lacks cannot be fetched" has "[x] Cannot fetch extra::needslib 1.0.0." +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish + +# A "package" that never ends: only SIZE bytes (+1) may ever be read. +pk $E endless 1.0.0 extra +publish +ln -sf /dev/zero $E/endless-1.0.0.gpkg +R sh -c 'echo y | timeout -s KILL 30 syspkg -f endless' +check "a download that never ends is cut off at the index's size" has "[x] extra::endless 1.0.0 does not match its index." +check "...promptly" [ "$RC" = 1 ] +check "...and nothing of it is left" [ -z "$(find $CACHE -name '*endless*')" ] +rm $E/endless-1.0.0.gpkg* +publish + +hr "the cache directory" +chmod 777 $CACHE/community +R yes_to syspkg -f only +check "a loosened cache dir is refused" has "[x] Refusing $CACHE/community: not a directory owned by UID 0 with mode 755." +check "...exit 1" rc 1 +chmod 755 $CACHE/community +mv $CACHE/community /srv/realcache && ln -s /srv/realcache $CACHE/community +R yes_to syspkg -f only +check "a symlinked cache dir is refused" has "[x] Refusing $CACHE/community: not a directory owned by UID 0 with mode 755." +rm $CACHE/community && mv /srv/realcache $CACHE/community +chmod 777 $CACHE +R yes_to syspkg -f only +check "a loosened cache is refused" has "[x] Refusing $CACHE: not a directory owned by UID 0 with mode 755." +chmod 755 $CACHE + +hr "-f of an installed other version" +pk $E dup 1.1.0 extra +publish +R yes_to syspkg -f dup +check "needs -O, like -l" has "[x] extra::dup 1.0.0 is already installed." +R yes_to syspkg -fO dup +check "-fO replaces it" line "extra::dup::1.1.0::explicit" + +hr "-u" +R yes_to syspkg -u +check "nothing newer: nothing to do" has "[✓] Nothing to do." +check "...exit 0" rc 0 +pk $E lib 2.1.0 extra +pk $B core 1.2.0 base +publish +R no_to syspkg -u +check "-u lists lib" has " * extra::lib 2.0.0 -> 2.1.0" +check "...and core" has " * base::core 1.1.0 -> 1.2.0" +check "...not app, which has nothing newer" lacks "extra::app " +R yes_to syspkg -u lib +check "-u lib upgrades lib" line "extra::lib::2.1.0::explicit" +check "...and only lib" line "base::core::1.1.0::auto" +R yes_to syspkg -u +check "-u upgrades the rest" line "base::core::1.2.0::auto" +check "...keeping core's dependency mark" line "base::core::1.2.0::auto" +check "...the old core is backed up" [ -f /glacier/sys/backup/base/core/core-1.1.0.gpkg ] +pk $E -d newdep:1.0.0 app 1.1.0 extra +pk $E newdep 1.0.0 extra +publish +R yes_to syspkg -u app +check "an upgrade's new dependency is added" line "extra::newdep::1.0.0::auto" +check "...with the upgrade" line "extra::app::1.1.0::explicit" +R syspkg -u nosuch +check "-u of a name not installed is refused" has "[x] nosuch is not installed." +conf "$BASE_E +$EXTRA_E" +R syspkg -u only +check "-u of a package whose repo isn't configured is refused" has "[x] community::only is not in any configured repository." +R yes_to syspkg -u +check "...and plain -u leaves it alone" line "community::only::1.0.0::explicit" +conf "$BASE_E +$EXTRA_E +$COMM_E" + +hr "gpkg -f / -u (user scope)" +adduser -D tester >/dev/null 2>&1 +U=$(id -u tester) +gstore -n "$U" >/dev/null +UB=/glacier/usr/$U +pk $E -d core:1.0.0 userapp 1.0.0 extra +publish +R su tester -c 'gpkg -f core' +check "gpkg never fetches from base" has "[x] core is not in any repository." +R su tester -c 'echo y | gpkg -f userapp' +check "gpkg -f installs into the user's scope" grep -q "^extra::userapp::1.0.0::explicit\$" $UB/index/current +check "...core, installed in the system, meets its dependency" sh -c "! grep -q core $UB/index/current" +check "...the user's cache is theirs, 0700" [ "$(stat -c '%u %a' $UB/cache $UB/cache/extra)" = "$U 700 +$U 700" ] +check "...and emptied" empty $UB/cache +check "...the user's indexes are theirs" [ "$(stat -c %u $UB/repos/extra.idx)" = "$U" ] +R su tester -c 'gpkg -f "%s%s%s%s%n"' +check "gpkg -f with %s%n as its operand" has "[x] %s%s%s%s%n is not in any repository." +R su tester -c 'gpkg -u "%s%s%s%s%n"' +check "gpkg -u with %s%n as its operand" has "[x] %s%s%s%s%n is not installed." +pk $E -d core:1.0.0 userapp 1.1.0 extra +publish +R su tester -c 'echo y | gpkg -u' +check "gpkg -u upgrades the user's package" grep -q "^extra::userapp::1.1.0::explicit\$" $UB/index/current +check "...the system's are untouched" line "extra::lib::2.1.0::explicit" +R su tester -c 'gpkg -f' +check "gpkg -f needs a name" has " -f PKG..." + +hr "syspkg -R DIR -f" +mkdir -p /mnt/img +syspkg -R /mnt/img -n >/dev/null +R yes_to syspkg -R /mnt/img -f app +check "-R -f installs into the image" grep -q "^extra::app::1.1.0::explicit\$" /mnt/img/glacier/sys/index/current +check "...with its dependencies" grep -q "^extra::newdep::1.0.0::auto\$" /mnt/img/glacier/sys/index/current +check "...indexes and cache under the image" [ -f /mnt/img/glacier/sys/repos/extra.idx -a -d /mnt/img/glacier/sys/cache/extra ] +check "...the host's store is untouched" line "extra::app::1.1.0::explicit" + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/fetch_alpine.sh.old2 b/tests/fetch_alpine.sh.old2 new file mode 100755 index 0000000..1e40b5a --- /dev/null +++ b/tests/fetch_alpine.sh.old2 @@ -0,0 +1,300 @@ +#!/bin/sh +# -f and -u from repositories (REPO_DESIGN.txt section 6, step 4): +# - every -f/-u refreshes every index first; any failure refuses; +# - -f NAME takes the first repo (by repos.conf order) serving NAME, +# at its highest version; a name nobody serves is refused; +# - missing dependencies are added (auto, marked in the summary); one +# installed too old is upgraded from its own repo, keeping its mark; +# one that can't be met is refused by the 2.3 check; +# - downloads go to /cache/REPO (scope owner and modes), are +# hashed against the index (size capped), the manifest must say what +# the index says (name, version, REPO, deps, conflicts), and a base +# package needs no .sig of its own; files are deleted once committed; +# - -u replaces what an index has newer (backups, KEEP_OLD), -u NAME +# only those; -f of an installed other version needs -O, like -l; +# - gpkg -f/-u: user scope, never from base, system packages meet deps; +# - syspkg -R DIR -f installs into DIR. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/fetch_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +empty() { [ -z "$(find "$@" -type f)" ]; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +XSEC=/root/extrakey.sec +B=/srv/base +E=/srv/extra +C=/srv/community +IDX=/glacier/sys/index/current +CACHE=/glacier/sys/cache +mkdir -p $B $E $C && chmod 755 /srv $B $E $C + +gsign -G -p $K/extrakey.pub -s $XSEC -c extrakey >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; },' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; },' +COMM_E=' { name = "community"; url = "file:///srv/community"; keys = [ "extrakey" ]; }' +conf "$BASE_E +$EXTRA_E +$COMM_E" +# mkpkg into a repo dir, without a sidecar signature: the index vouches. +pk() { d=$1; shift; /app/tests/mkpkg -o "$d" "$@" >/dev/null; } +publish() { + grepo -s $TEST_SEC -r base $B >/dev/null && + grepo -s $XSEC -r extra $E >/dev/null && + grepo -s $XSEC -r community $C >/dev/null +} +line() { grep -q "^$1\$" $IDX; } +yes_to() { sh -c "echo y | $*"; } +no_to() { sh -c "echo n | $*"; } + +syspkg -n >/dev/null + +pk $B core 1.0.0 base +pk $B core 1.1.0 base +pk $E lib 1.0.0 extra +pk $E lib 2.0.0 extra +pk $E -d lib:2.0.0 -d core:1.0.0 app 1.0.0 extra +pk $E dup 1.0.0 extra +pk $C dup 9.0.0 community +pk $C only 1.0.0 community +pk $E -d ghost:1.0.0 lonely 1.0.0 extra +pk $E -d lib:9.0.0 greedy 1.0.0 extra +pk $E -c app:0.0.0 rival 1.0.0 extra +publish + +hr "refusals before anything is fetched" +R syspkg -f nosuch +check "a name no repository serves is refused" has "[x] nosuch is not in any repository." +check "...exit 1" rc 1 +check "...after refreshing every index" has "[✓] All repositories synced successfully." +R syspkg -f +check "-f needs a name" has " -f PKG..." +R syspkg -f app -x lib +check "-f and -x are mutually exclusive" has "[x] -n, -l, -f, -u, -x and -y are mutually exclusive." +mv $E/repo.idx.sig /srv/sig.bak +R yes_to syspkg -f app +check "a failed refresh refuses -f" has "[x] Cannot fetch the index for extra." +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q app $IDX" +mv /srv/sig.bak $E/repo.idx.sig +su nobody -s /bin/sh -c 'syspkg -f app' >/srv/np.out 2>&1 +check "syspkg -f as non-root is refused" grep -qF "Cannot open system index: Permission denied" /srv/np.out + +hr "an installed dependency too old is upgraded" +R yes_to syspkg -l $E/lib-1.0.0.gpkg +check "lib 1.0.0 installed locally" line "extra::lib::1.0.0::explicit" +R no_to syspkg -f app +check "the summary lists app" has " * extra::app 1.0.0" +check "...lib's upgrade, as a dependency" has " * extra::lib 1.0.0 -> 2.0.0 (dependency)" +check "...and core, the newest base has, as a dependency" has " * base::core 1.1.0 (dependency)" +check "declining installs nothing" sh -c "! grep -q app $IDX" +check "...the downloads stay in the cache" [ -f $CACHE/extra/app-1.0.0.gpkg -a -f $CACHE/base/core-1.1.0.gpkg ] +check "...cache dirs are root's, 0755" [ "$(stat -c '%u %a' $CACHE $CACHE/extra)" = "0 755 +0 755" ] +check "...cached files are 0644" [ "$(stat -c %a $CACHE/extra/app-1.0.0.gpkg)" = 644 ] +check "...no temporary files" [ -z "$(find $CACHE -name '.*' -type f)" ] +printf 'garbage' > $CACHE/extra/app-1.0.0.gpkg +R yes_to syspkg -f app +check "-f app completes" has "[✓] Completed with no errors." +check "...a corrupt cached file is fetched again" rc 0 +check "app is explicit" line "extra::app::1.0.0::explicit" +check "lib was upgraded and stays explicit" line "extra::lib::2.0.0::explicit" +check "core is recorded as a dependency" line "base::core::1.1.0::auto" +check "lib 1.0.0 was backed up (KEEP_OLD)" [ -f /glacier/sys/backup/extra/lib/lib-1.0.0.gpkg ] +check "base::core installed with no .sig of its own" [ ! -e $B/core-1.1.0.gpkg.sha256.sig -a -x /usr/bin/core ] +check "the cache is emptied once committed" empty $CACHE +check "staged from the repository" has "base::core-1.1.0: staged from file:///srv/base/core-1.1.0.gpkg." + +hr "choosing a repository" +R yes_to syspkg -f dup +check "the first repo serving a name wins over a higher version elsewhere" line "extra::dup::1.0.0::explicit" +check "...community's 9.0.0 is not installed" sh -c "! grep -q community::dup $IDX" +R yes_to syspkg -f only +check "a name only a later repo serves comes from it" line "community::only::1.0.0::explicit" +R yes_to syspkg -f dup dup +check "a name given twice is fetched once" sh -c "[ $(echo "$OUT" | grep -c 'extra::dup ') = 1 ]" + +hr "dependencies that can't be met" +R yes_to syspkg -f lonely +check "a dependency no repo serves is refused" has "[x] extra::lonely requires ghost >= 1.0.0, which is not installed." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ]" && check "...no prompt" lacks "Proceed?" +R yes_to syspkg -f greedy +check "a dependency no repo has new enough is refused" has "[x] extra::greedy requires lib >= 9.0.0, which is not installed." +R yes_to syspkg -f rival +check "a conflict is refused" has "[x] extra::rival conflicts with extra::app." +check "...nothing installed" sh -c "! grep -q rival $IDX" + +hr "what the index says must be what the package says" +# extrakey signs an index listing a package that claims to be base: +# a key trusted for extra must not be able to put anything into /usr. +forge() { # forge NAME VER FILE: put FILE in extra as NAME-VER.gpkg, re-sign + cp "$3" $E/$1-$2.gpkg + sha=$(sha256sum $E/$1-$2.gpkg | cut -c1-64); size=$(wc -c < $E/$1-$2.gpkg) + awk -v n="$1" -v s="$sha" -v z="$size" ' + hit { sub(/SHA256 = "[^"]*"; SIZE = [0-9]*L;/, "SHA256 = \"sha256:" s "\"; SIZE = " z "L;"); hit = 0 } + index($0, "NAME = \"" n "\";") { hit = 1 } { print }' $E/repo.idx > /srv/idx.new + serial=$(sed -n 's/^SERIAL = \([0-9]*\)L;$/\1/p' $E/repo.idx) + sed "s/^SERIAL = .*/SERIAL = $((serial + 1))L;/" /srv/idx.new > $E/repo.idx + gsign -S -s $XSEC -m $E/repo.idx +} +mkdir -p /srv/evil +pk $E evil 1.0.0 extra +pk /srv/evil evil 1.0.0 base +pk $E plain 1.0.0 extra +pk /srv/evil -d core:1.0.0 plain 1.0.0 extra +publish +forge evil 1.0.0 /srv/evil/evil-1.0.0.gpkg +forge plain 1.0.0 /srv/evil/plain-1.0.0.gpkg +R yes_to syspkg -f evil +check "a package claiming base from extra's index is refused" has "[x] extra::evil 1.0.0 does not match its index." +check "...exit 1, nothing in /usr" sh -c "[ $RC = 1 ] && [ ! -e /usr/bin/evil ] && ! grep -q evil $IDX" +R yes_to syspkg -f plain +check "dependencies the index doesn't list are refused" has "[x] extra::plain 1.0.0 does not match its index." +# grepo would refuse the forged files: back to honest ones. +rm $E/evil-1.0.0.gpkg* $E/plain-1.0.0.gpkg* +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +printf 'X' >> $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a download bigger than the index says is refused" has "[x] extra::needslib 1.0.0 does not match its index." +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +head -c 100 $E/needslib-1.0.0.gpkg > /srv/short && cp /srv/short $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a truncated one too" has "[x] extra::needslib 1.0.0 does not match its index." +check "...nothing half-fetched is left in the cache" [ ! -e $CACHE/extra/needslib-1.0.0.gpkg -a -z "$(find $CACHE -name '.*' -type f)" ] +check "packages whose manifest contradicts the index are not kept" [ ! -e $CACHE/extra/evil-1.0.0.gpkg -a ! -e $CACHE/extra/plain-1.0.0.gpkg ] +check "...refused but genuine ones are, until installed" [ -f $CACHE/extra/rival-1.0.0.gpkg ] +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +rm $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a file the repository lacks cannot be fetched" has "[x] Cannot fetch extra::needslib 1.0.0." +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish + +# A "package" that never ends: only SIZE bytes (+1) may ever be read. +pk $E endless 1.0.0 extra +publish +ln -sf /dev/zero $E/endless-1.0.0.gpkg +R sh -c 'echo y | timeout -s KILL 30 syspkg -f endless' +check "a download that never ends is cut off at the index's size" has "[x] extra::endless 1.0.0 does not match its index." +check "...promptly" [ "$RC" = 1 ] +check "...and nothing of it is left" [ -z "$(find $CACHE -name '*endless*')" ] +rm $E/endless-1.0.0.gpkg* +publish + +hr "the cache directory" +chmod 777 $CACHE/community +R yes_to syspkg -f only +check "a loosened cache dir is refused" has "[x] Refusing $CACHE/community: not a directory owned by UID 0 with mode 755." +check "...exit 1" rc 1 +chmod 755 $CACHE/community +mv $CACHE/community /srv/realcache && ln -s /srv/realcache $CACHE/community +R yes_to syspkg -f only +check "a symlinked cache dir is refused" has "[x] Refusing $CACHE/community: not a directory owned by UID 0 with mode 755." +rm $CACHE/community && mv /srv/realcache $CACHE/community +chmod 777 $CACHE +R yes_to syspkg -f only +check "a loosened cache is refused" has "[x] Refusing $CACHE: not a directory owned by UID 0 with mode 755." +chmod 755 $CACHE + +hr "-f of an installed other version" +pk $E dup 1.1.0 extra +publish +R yes_to syspkg -f dup +check "needs -O, like -l" has "[x] extra::dup 1.0.0 is already installed." +R yes_to syspkg -fO dup +check "-fO replaces it" line "extra::dup::1.1.0::explicit" + +hr "-u" +R yes_to syspkg -u +check "nothing newer: nothing to do" has "[✓] Nothing to do." +check "...exit 0" rc 0 +pk $E lib 2.1.0 extra +pk $B core 1.2.0 base +publish +R no_to syspkg -u +check "-u lists lib" has " * extra::lib 2.0.0 -> 2.1.0" +check "...and core" has " * base::core 1.1.0 -> 1.2.0" +check "...not app, which has nothing newer" lacks "extra::app " +R yes_to syspkg -u lib +check "-u lib upgrades lib" line "extra::lib::2.1.0::explicit" +check "...and only lib" line "base::core::1.1.0::auto" +R yes_to syspkg -u +check "-u upgrades the rest" line "base::core::1.2.0::auto" +check "...keeping core's dependency mark" line "base::core::1.2.0::auto" +check "...the old core is backed up" [ -f /glacier/sys/backup/base/core/core-1.1.0.gpkg ] +pk $E -d newdep:1.0.0 app 1.1.0 extra +pk $E newdep 1.0.0 extra +publish +R yes_to syspkg -u app +check "an upgrade's new dependency is added" line "extra::newdep::1.0.0::auto" +check "...with the upgrade" line "extra::app::1.1.0::explicit" +R syspkg -u nosuch +check "-u of a name not installed is refused" has "[x] nosuch is not installed." +conf "$BASE_E +$EXTRA_E" +R syspkg -u only +check "-u of a package whose repo isn't configured is refused" has "[x] community::only is not in any configured repository." +R yes_to syspkg -u +check "...and plain -u leaves it alone" line "community::only::1.0.0::explicit" +conf "$BASE_E +$EXTRA_E +$COMM_E" + +hr "gpkg -f / -u (user scope)" +adduser -D tester >/dev/null 2>&1 +U=$(id -u tester) +gstore -n "$U" >/dev/null +UB=/glacier/usr/$U +pk $E -d core:1.0.0 userapp 1.0.0 extra +publish +R su tester -c 'gpkg -f core' +check "gpkg never fetches from base" has "[x] core is not in any repository." +R su tester -c 'echo y | gpkg -f userapp' +check "gpkg -f installs into the user's scope" grep -q "^extra::userapp::1.0.0::explicit\$" $UB/index/current +check "...core, installed in the system, meets its dependency" sh -c "! grep -q core $UB/index/current" +check "...the user's cache is theirs, 0700" [ "$(stat -c '%u %a' $UB/cache $UB/cache/extra)" = "$U 700 +$U 700" ] +check "...and emptied" empty $UB/cache +check "...the user's indexes are theirs" [ "$(stat -c %u $UB/repos/extra.idx)" = "$U" ] +R su tester -c 'gpkg -f "%s%s%s%s%n"' +check "gpkg -f with %s%n as its operand" has "[x] %s%s%s%s%n is not in any repository." +R su tester -c 'gpkg -u "%s%s%s%s%n"' +check "gpkg -u with %s%n as its operand" has "[x] %s%s%s%s%n is not installed." +pk $E -d core:1.0.0 userapp 1.1.0 extra +publish +R su tester -c 'echo y | gpkg -u' +check "gpkg -u upgrades the user's package" grep -q "^extra::userapp::1.1.0::explicit\$" $UB/index/current +check "...the system's are untouched" line "extra::lib::2.1.0::explicit" +R su tester -c 'gpkg -f' +check "gpkg -f needs a name" has " -f PKG..." + +hr "syspkg -R DIR -f" +mkdir -p /mnt/img +syspkg -R /mnt/img -n >/dev/null +R yes_to syspkg -R /mnt/img -f app +check "-R -f installs into the image" grep -q "^extra::app::1.1.0::explicit\$" /mnt/img/glacier/sys/index/current +check "...with its dependencies" grep -q "^extra::newdep::1.0.0::auto\$" /mnt/img/glacier/sys/index/current +check "...indexes and cache under the image" [ -f /mnt/img/glacier/sys/repos/extra.idx -a -d /mnt/img/glacier/sys/cache/extra ] +check "...the host's store is untouched" line "extra::app::1.1.0::explicit" + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/fetch_alpine.sh.old3 b/tests/fetch_alpine.sh.old3 new file mode 100755 index 0000000..f0c5184 --- /dev/null +++ b/tests/fetch_alpine.sh.old3 @@ -0,0 +1,302 @@ +#!/bin/sh +# -f and -u from repositories (REPO_DESIGN.txt section 6, step 4): +# - every -f/-u refreshes every index first; any failure refuses; +# - -f NAME takes the first repo (by repos.conf order) serving NAME, +# at its highest version; a name nobody serves is refused; +# - missing dependencies are added (auto, marked in the summary); one +# installed too old is upgraded from its own repo, keeping its mark; +# one that can't be met is refused by the 2.3 check; +# - downloads go to /cache/REPO (scope owner and modes), are +# hashed against the index (size capped), the manifest must say what +# the index says (name, version, REPO, deps, conflicts), and a base +# package needs no .sig of its own; files are deleted once committed; +# - -u replaces what an index has newer (backups, KEEP_OLD), -u NAME +# only those; -f of an installed other version needs -O, like -l; +# - gpkg -f/-u: user scope, never from base, system packages meet deps; +# - syspkg -R DIR -f installs into DIR, with DIR's own repos.conf. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/fetch_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +empty() { [ -z "$(find "$@" -type f)" ]; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +XSEC=/root/extrakey.sec +B=/srv/base +E=/srv/extra +C=/srv/community +IDX=/glacier/sys/index/current +CACHE=/glacier/sys/cache +mkdir -p $B $E $C && chmod 755 /srv $B $E $C + +gsign -G -p $K/extrakey.pub -s $XSEC -c extrakey >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; },' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; },' +COMM_E=' { name = "community"; url = "file:///srv/community"; keys = [ "extrakey" ]; }' +conf "$BASE_E +$EXTRA_E +$COMM_E" +# mkpkg into a repo dir, without a sidecar signature: the index vouches. +pk() { d=$1; shift; /app/tests/mkpkg -o "$d" "$@" >/dev/null; } +publish() { + grepo -s $TEST_SEC -r base $B >/dev/null && + grepo -s $XSEC -r extra $E >/dev/null && + grepo -s $XSEC -r community $C >/dev/null +} +line() { grep -q "^$1\$" $IDX; } +yes_to() { sh -c "echo y | $*"; } +no_to() { sh -c "echo n | $*"; } + +syspkg -n >/dev/null + +pk $B core 1.0.0 base +pk $B core 1.1.0 base +pk $E lib 1.0.0 extra +pk $E lib 2.0.0 extra +pk $E -d lib:2.0.0 -d core:1.0.0 app 1.0.0 extra +pk $E dup 1.0.0 extra +pk $C dup 9.0.0 community +pk $C only 1.0.0 community +pk $E -d ghost:1.0.0 lonely 1.0.0 extra +pk $E -d lib:9.0.0 greedy 1.0.0 extra +pk $E -c app:0.0.0 rival 1.0.0 extra +publish + +hr "refusals before anything is fetched" +R syspkg -f nosuch +check "a name no repository serves is refused" has "[x] nosuch is not in any repository." +check "...exit 1" rc 1 +check "...after refreshing every index" has "[✓] All repositories synced successfully." +R syspkg -f +check "-f needs a name" has " -f PKG..." +R syspkg -f app -x lib +check "-f and -x are mutually exclusive" has "[x] -n, -l, -f, -u, -x and -y are mutually exclusive." +mv $E/repo.idx.sig /srv/sig.bak +R yes_to syspkg -f app +check "a failed refresh refuses -f" has "[x] Cannot fetch the index for extra." +check "...exit 1, nothing installed" sh -c "[ $RC = 1 ] && ! grep -q app $IDX" +mv /srv/sig.bak $E/repo.idx.sig +su nobody -s /bin/sh -c 'syspkg -f app' >/srv/np.out 2>&1 +check "syspkg -f as non-root is refused" grep -qF "Cannot open system index: Permission denied" /srv/np.out + +hr "an installed dependency too old is upgraded" +R yes_to syspkg -l $E/lib-1.0.0.gpkg +check "lib 1.0.0 installed locally" line "extra::lib::1.0.0::explicit" +R no_to syspkg -f app +check "the summary lists app" has " * extra::app 1.0.0" +check "...lib's upgrade, as a dependency" has " * extra::lib 1.0.0 -> 2.0.0 (dependency)" +check "...and core, the newest base has, as a dependency" has " * base::core 1.1.0 (dependency)" +check "declining installs nothing" sh -c "! grep -q app $IDX" +check "...the downloads stay in the cache" [ -f $CACHE/extra/app-1.0.0.gpkg -a -f $CACHE/base/core-1.1.0.gpkg ] +check "...cache dirs are root's, 0755" [ "$(stat -c '%u %a' $CACHE $CACHE/extra)" = "0 755 +0 755" ] +check "...cached files are 0644" [ "$(stat -c %a $CACHE/extra/app-1.0.0.gpkg)" = 644 ] +check "...no temporary files" [ -z "$(find $CACHE -name '.*' -type f)" ] +printf 'garbage' > $CACHE/extra/app-1.0.0.gpkg +R yes_to syspkg -f app +check "-f app completes" has "[✓] Completed with no errors." +check "...a corrupt cached file is fetched again" rc 0 +check "app is explicit" line "extra::app::1.0.0::explicit" +check "lib was upgraded and stays explicit" line "extra::lib::2.0.0::explicit" +check "core is recorded as a dependency" line "base::core::1.1.0::auto" +check "lib 1.0.0 was backed up (KEEP_OLD)" [ -f /glacier/sys/backup/extra/lib/lib-1.0.0.gpkg ] +check "base::core installed with no .sig of its own" [ ! -e $B/core-1.1.0.gpkg.sha256.sig -a -x /usr/bin/core ] +check "the cache is emptied once committed" empty $CACHE +check "staged from the repository" has "base::core-1.1.0: staged from file:///srv/base/core-1.1.0.gpkg." + +hr "choosing a repository" +R yes_to syspkg -f dup +check "the first repo serving a name wins over a higher version elsewhere" line "extra::dup::1.0.0::explicit" +check "...community's 9.0.0 is not installed" sh -c "! grep -q community::dup $IDX" +R yes_to syspkg -f only +check "a name only a later repo serves comes from it" line "community::only::1.0.0::explicit" +R yes_to syspkg -f dup dup +check "a name given twice is fetched once" sh -c "[ $(echo "$OUT" | grep -c 'extra::dup ') = 1 ]" + +hr "dependencies that can't be met" +R yes_to syspkg -f lonely +check "a dependency no repo serves is refused" has "[x] extra::lonely requires ghost >= 1.0.0, which is not installed." +check "...exit 1, before the prompt" sh -c "[ $RC = 1 ]" && check "...no prompt" lacks "Proceed?" +R yes_to syspkg -f greedy +check "a dependency no repo has new enough is refused" has "[x] extra::greedy requires lib >= 9.0.0, which is not installed." +R yes_to syspkg -f rival +check "a conflict is refused" has "[x] extra::rival conflicts with extra::app." +check "...nothing installed" sh -c "! grep -q rival $IDX" + +hr "what the index says must be what the package says" +# extrakey signs an index listing a package that claims to be base: +# a key trusted for extra must not be able to put anything into /usr. +forge() { # forge NAME VER FILE: put FILE in extra as NAME-VER.gpkg, re-sign + cp "$3" $E/$1-$2.gpkg + sha=$(sha256sum $E/$1-$2.gpkg | cut -c1-64); size=$(wc -c < $E/$1-$2.gpkg) + awk -v n="$1" -v s="$sha" -v z="$size" ' + hit { sub(/SHA256 = "[^"]*"; SIZE = [0-9]*L;/, "SHA256 = \"sha256:" s "\"; SIZE = " z "L;"); hit = 0 } + index($0, "NAME = \"" n "\";") { hit = 1 } { print }' $E/repo.idx > /srv/idx.new + serial=$(sed -n 's/^SERIAL = \([0-9]*\)L;$/\1/p' $E/repo.idx) + sed "s/^SERIAL = .*/SERIAL = $((serial + 1))L;/" /srv/idx.new > $E/repo.idx + gsign -S -s $XSEC -m $E/repo.idx +} +mkdir -p /srv/evil +pk $E evil 1.0.0 extra +pk /srv/evil evil 1.0.0 base +pk $E plain 1.0.0 extra +pk /srv/evil -d core:1.0.0 plain 1.0.0 extra +publish +forge evil 1.0.0 /srv/evil/evil-1.0.0.gpkg +forge plain 1.0.0 /srv/evil/plain-1.0.0.gpkg +R yes_to syspkg -f evil +check "a package claiming base from extra's index is refused" has "[x] extra::evil 1.0.0 does not match its index." +check "...exit 1, nothing in /usr" sh -c "[ $RC = 1 ] && [ ! -e /usr/bin/evil ] && ! grep -q evil $IDX" +R yes_to syspkg -f plain +check "dependencies the index doesn't list are refused" has "[x] extra::plain 1.0.0 does not match its index." +# grepo would refuse the forged files: back to honest ones. +rm $E/evil-1.0.0.gpkg* $E/plain-1.0.0.gpkg* +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +printf 'X' >> $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a download bigger than the index says is refused" has "[x] extra::needslib 1.0.0 does not match its index." +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +head -c 100 $E/needslib-1.0.0.gpkg > /srv/short && cp /srv/short $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a truncated one too" has "[x] extra::needslib 1.0.0 does not match its index." +check "...nothing half-fetched is left in the cache" [ ! -e $CACHE/extra/needslib-1.0.0.gpkg -a -z "$(find $CACHE -name '.*' -type f)" ] +check "packages whose manifest contradicts the index are not kept" [ ! -e $CACHE/extra/evil-1.0.0.gpkg -a ! -e $CACHE/extra/plain-1.0.0.gpkg ] +check "...refused but genuine ones are, until installed" [ -f $CACHE/extra/rival-1.0.0.gpkg ] +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish +rm $E/needslib-1.0.0.gpkg +R yes_to syspkg -f needslib +check "a file the repository lacks cannot be fetched" has "[x] Cannot fetch extra::needslib 1.0.0." +pk $E -d lib:2.0.0 needslib 1.0.0 extra +publish + +# A "package" that never ends: only SIZE bytes (+1) may ever be read. +pk $E endless 1.0.0 extra +publish +ln -sf /dev/zero $E/endless-1.0.0.gpkg +R sh -c 'echo y | timeout -s KILL 30 syspkg -f endless' +check "a download that never ends is cut off at the index's size" has "[x] extra::endless 1.0.0 does not match its index." +check "...promptly" [ "$RC" = 1 ] +check "...and nothing of it is left" [ -z "$(find $CACHE -name '*endless*')" ] +rm $E/endless-1.0.0.gpkg* +publish + +hr "the cache directory" +chmod 777 $CACHE/community +R yes_to syspkg -f only +check "a loosened cache dir is refused" has "[x] Refusing $CACHE/community: not a directory owned by UID 0 with mode 755." +check "...exit 1" rc 1 +chmod 755 $CACHE/community +mv $CACHE/community /srv/realcache && ln -s /srv/realcache $CACHE/community +R yes_to syspkg -f only +check "a symlinked cache dir is refused" has "[x] Refusing $CACHE/community: not a directory owned by UID 0 with mode 755." +rm $CACHE/community && mv /srv/realcache $CACHE/community +chmod 777 $CACHE +R yes_to syspkg -f only +check "a loosened cache is refused" has "[x] Refusing $CACHE: not a directory owned by UID 0 with mode 755." +chmod 755 $CACHE + +hr "-f of an installed other version" +pk $E dup 1.1.0 extra +publish +R yes_to syspkg -f dup +check "needs -O, like -l" has "[x] extra::dup 1.0.0 is already installed." +R yes_to syspkg -fO dup +check "-fO replaces it" line "extra::dup::1.1.0::explicit" + +hr "-u" +R yes_to syspkg -u +check "nothing newer: nothing to do" has "[✓] Nothing to do." +check "...exit 0" rc 0 +pk $E lib 2.1.0 extra +pk $B core 1.2.0 base +publish +R no_to syspkg -u +check "-u lists lib" has " * extra::lib 2.0.0 -> 2.1.0" +check "...and core" has " * base::core 1.1.0 -> 1.2.0" +check "...not app, which has nothing newer" lacks "extra::app " +R yes_to syspkg -u lib +check "-u lib upgrades lib" line "extra::lib::2.1.0::explicit" +check "...and only lib" line "base::core::1.1.0::auto" +R yes_to syspkg -u +check "-u upgrades the rest" line "base::core::1.2.0::auto" +check "...keeping core's dependency mark" line "base::core::1.2.0::auto" +check "...the old core is backed up" [ -f /glacier/sys/backup/base/core/core-1.1.0.gpkg ] +pk $E -d newdep:1.0.0 app 1.1.0 extra +pk $E newdep 1.0.0 extra +publish +R yes_to syspkg -u app +check "an upgrade's new dependency is added" line "extra::newdep::1.0.0::auto" +check "...with the upgrade" line "extra::app::1.1.0::explicit" +R syspkg -u nosuch +check "-u of a name not installed is refused" has "[x] nosuch is not installed." +conf "$BASE_E +$EXTRA_E" +R syspkg -u only +check "-u of a package whose repo isn't configured is refused" has "[x] community::only is not in any configured repository." +R yes_to syspkg -u +check "...and plain -u leaves it alone" line "community::only::1.0.0::explicit" +conf "$BASE_E +$EXTRA_E +$COMM_E" + +hr "gpkg -f / -u (user scope)" +adduser -D tester >/dev/null 2>&1 +U=$(id -u tester) +gstore -n "$U" >/dev/null +UB=/glacier/usr/$U +pk $E -d core:1.0.0 userapp 1.0.0 extra +publish +R su tester -c 'gpkg -f core' +check "gpkg never fetches from base" has "[x] core is not in any repository." +R su tester -c 'echo y | gpkg -f userapp' +check "gpkg -f installs into the user's scope" grep -q "^extra::userapp::1.0.0::explicit\$" $UB/index/current +check "...core, installed in the system, meets its dependency" sh -c "! grep -q core $UB/index/current" +check "...the user's cache is theirs, 0700" [ "$(stat -c '%u %a' $UB/cache $UB/cache/extra)" = "$U 700 +$U 700" ] +check "...and emptied" empty $UB/cache +check "...the user's indexes are theirs" [ "$(stat -c %u $UB/repos/extra.idx)" = "$U" ] +R su tester -c 'gpkg -f "%s%s%s%s%n"' +check "gpkg -f with %s%n as its operand" has "[x] %s%s%s%s%n is not in any repository." +R su tester -c 'gpkg -u "%s%s%s%s%n"' +check "gpkg -u with %s%n as its operand" has "[x] %s%s%s%s%n is not installed." +pk $E -d core:1.0.0 userapp 1.1.0 extra +publish +R su tester -c 'echo y | gpkg -u' +check "gpkg -u upgrades the user's package" grep -q "^extra::userapp::1.1.0::explicit\$" $UB/index/current +check "...the system's are untouched" line "extra::lib::2.1.0::explicit" +R su tester -c 'gpkg -f' +check "gpkg -f needs a name" has " -f PKG..." + +hr "syspkg -R DIR -f" +mkdir -p /mnt/img +syspkg -R /mnt/img -n >/dev/null +# -R uses the image's own keyring, as a package would ship it. +mkdir -p /mnt/img/etc/glacier && cp -a /etc/glacier/repos.conf /etc/glacier/keys /mnt/img/etc/glacier/ +R yes_to syspkg -R /mnt/img -f app +check "-R -f installs into the image" grep -q "^extra::app::1.1.0::explicit\$" /mnt/img/glacier/sys/index/current +check "...with its dependencies" grep -q "^extra::newdep::1.0.0::auto\$" /mnt/img/glacier/sys/index/current +check "...indexes and cache under the image" [ -f /mnt/img/glacier/sys/repos/extra.idx -a -d /mnt/img/glacier/sys/cache/extra ] +check "...the host's store is untouched" line "extra::app::1.1.0::explicit" + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/glacier_ffi.lua b/tests/glacier_ffi.lua new file mode 100644 index 0000000..bb68382 --- /dev/null +++ b/tests/glacier_ffi.lua @@ -0,0 +1,32 @@ +-- glacier_ffi.lua +-- +-- The test suite's handle on libglacier-ng. A thin wrapper over +-- lib/glacier_cdef.lua, the single source of truth for every ffi.cdef() +-- declaration. This file used to carry its own copy of all of them, and +-- had already drifted (it was missing GL_INSTALL_ERR_SCOPE) — the exact +-- duplication bug CLAUDE.md describes. Don't add declarations here; add +-- them to lib/glacier_cdef.lua. +-- +-- Usage: +-- local glacier = require("glacier_ffi") +-- local ctx = glacier.new_context() +-- glacier.lib.gl_init_live_context(ctx, glacier.SCOPE_USR, 1000) +-- +-- The combined .so is loaded by glacier_cdef.load(): LIBGLACIER_SO if +-- set, else /lib/glacier/libglacier-ng.so. + +-- lib/ lives one level up from tests/, wherever this is run from. +local here = (debug.getinfo(1, "S").source:match("^@(.*/)") or "./") +package.path = here .. "../?.lua;" .. package.path + +local ffi = require("ffi") +local cdef = require("lib/glacier_cdef") + +local M = {} +for k, v in pairs(cdef) do M[k] = v end + +M.ffi = ffi +M.C = ffi.C +M.lib = cdef.load() + +return M diff --git a/tests/installed_alpine.sh b/tests/installed_alpine.sh new file mode 100644 index 0000000..6ef393e --- /dev/null +++ b/tests/installed_alpine.sh @@ -0,0 +1,155 @@ +#!/bin/sh +# The installed layout (ROADMAP 1.4): syspkg, gpkg and gstore run from the +# store, as packaged by ~/Projects/everest/scripts/container.sh: +# usr/lib/glacier-ng/{syspkg,gpkg,gstore,lib/*.lua} +# usr/lib/glacier-ng/lib/glacier -> /usr/lib/glacier (absolute) +# usr/bin/X -> ../lib/glacier-ng/X +# etc/glacier/glacier.conf +# plus libglacier-ng's usr/lib/glacier/*.so. Both are installed into the +# container's own / by syspkg, then /app is moved away, so every later +# run can only work by loading from its realpath in the store: +# - each tool runs from any directory, as root and as a user; +# - syspkg installs and removes, gstore -n creates a user, a wheel user +# runs `doas gstore -n` with no password, and gpkg installs; +# - syspkg's and gstore's trust checks still hold in the store: a +# group-writable .lua there, or a non-root-owned store dir, is +# refused. +# Runs INSIDE the Dockerfile.alpine_root image: +# +# docker run --rm -v "$PWD/tests/installed_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } + +# R CMD...: run a shell command line, answering y. Sets $OUT and $RC. +R() { + OUT=$( (echo y | sh -c "$1"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed 's/^/ /' +} +# U CMD...: the same, as user glacier (uid 1000, in wheel). +U() { R "su glacier -c $(printf "'%s'" "$1")"; } +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } + +P=/srv/pkgs +mkdir -p $P +cp /app/tests/mkpkg /srv/mkpkg +chmod 755 /srv /srv/pkgs + +# seal DIR NAME VER: DIR/NAME-VER (files/ + manifest) -> $P/NAME-VER.gpkg +seal() { + printf 'PKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_DESC = "t";\nPKG_MAINT = "t@localhost";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "base";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' \ + "$2" "$3" > "$1/$2-$3/manifest.gpm.cfg" + tar czf "$P/$2-$3.gpkg" -C "$1" "$2-$3" + printf 'sha256:%s\n' "$(sha256sum "$P/$2-$3.gpkg" | cut -d' ' -f1)" > "$P/$2-$3.gpkg.sha256" + gsign -S -s /root/glacier-test.sec -m "$P/$2-$3.gpkg.sha256" >/dev/null + chmod 644 "$P/$2-$3.gpkg" "$P/$2-$3.gpkg.sha256" "$P/$2-$3.gpkg.sha256.sig" +} + +w=$(mktemp -d) +f=$w/libglacier-ng-4.0.0/files +mkdir -p $f/usr/lib/glacier +install -m 755 /app/lib/glacier/libglacier_*.so /app/lib/glacier/gsandbox $f/usr/lib/glacier/ +seal $w libglacier-ng 4.0.0 + +f=$w/glacier-ng-4.0.0/files +d=$f/usr/lib/glacier-ng +mkdir -p $d/lib $f/usr/bin $f/etc/glacier +(cd /app && install -m 755 syspkg gpkg gstore $d/ && + install -m 644 lib/cargs.lua lib/color.lua lib/glacier_cdef.lua lib/gpkg_common.lua lib/gpkg_build.lua lib/build-driver.sh $d/lib/ && + install -m 644 etc/glacier/glacier.conf $f/etc/glacier/) +ln -s /usr/lib/glacier $d/lib/glacier +for t in syspkg gpkg gstore; do ln -s ../lib/glacier-ng/$t $f/usr/bin/$t; done +seal $w glacier-ng 4.0.0 +rm -rf $w + +/srv/mkpkg -o $P demo 1.0.0 extra >/dev/null +/srv/mkpkg -o $P udemo 1.0.0 extra >/dev/null + +# The image's glacier.conf came from the Dockerfile: let the package own it. +rm /etc/glacier/glacier.conf +printf '%s\n' 'permit nopass :wheel as root cmd gstore args -n' \ + 'permit nopass :wheel as root cmd /usr/bin/gstore args -n' > /etc/doas.conf +chmod 0400 /etc/doas.conf + +hr "install glacier with /app's syspkg, then remove /app" +R "/app/syspkg -n && /app/syspkg -l $P/libglacier-ng-4.0.0.gpkg $P/glacier-ng-4.0.0.gpkg" +check "the install succeeds" rc 0 +check "it ends with no errors" has "Completed with no errors." +mv /app /app.gone +check "/usr/bin/syspkg resolves into the store" \ + sh -c 'case $(readlink -f /usr/bin/syspkg) in /glacier/sys/store/base/glacier-ng/glacier-ng-4.0.0/*) ;; *) exit 1 ;; esac' +check "glacier.conf is installed" grep -q KEEP_OLD /etc/glacier/glacier.conf + +hr "syspkg from the store" +R "cd / && /usr/bin/syspkg -h" +check "syspkg -h works from /" rc 0 +R "cd /tmp && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg -l (bare name, from /tmp) installs" rc 0 +check "...with no errors" has "Completed with no errors." +check "the installed program runs" sh -c '/glacier/sys/links/bin/demo | grep -q "demo 1.0.0 says hi"' +R "cd /srv && syspkg -x demo" +check "syspkg -x removes" rc 0 +check "...and its link is gone" sh -c '! [ -e /glacier/sys/links/bin/demo ]' + +hr "a user, through the store's gstore and gpkg" +U "cd / && doas -n gstore -n" +check "a wheel user's doas gstore -n needs no password" rc 0 +check "...and creates their directory" test -d /glacier/usr/1000 +U "cd /tmp && gpkg -l $P/udemo-1.0.0.gpkg" +check "gpkg -l (from /tmp) installs" rc 0 +check "...with no errors" has "Completed with no errors." +U "/glacier/usr/1000/links/bin/udemo" +check "the user's program runs" has "udemo 1.0.0 says hi" +U "cd / && gpkg -x udemo" +check "gpkg -x removes" rc 0 +R "cd /tmp && gstore -n 1001" +check "root's gstore -n UID works from the store" rc 0 + +hr "the trust checks hold in the store" +L=$(readlink -f /usr/lib/glacier-ng/lib/gpkg_common.lua) +chmod g+w "$L" +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg refuses a group-writable .lua in the store" rc 1 +check "...saying which" has "Refusing to run: $L is group- or world-writable." +chmod g-w "$L" +L=$(readlink -f /usr/lib/glacier-ng/lib/glacier_cdef.lua) +chmod g+w "$L" +R "cd / && gstore -n 1002" +check "gstore refuses a group-writable .lua it loads" has "Refusing to run: $L is group- or world-writable." +check "...and creates nothing" test ! -e /glacier/usr/1002 +chmod g-w "$L" +V=$(readlink -f /usr/bin/syspkg); V=${V%/usr/lib/glacier-ng/syspkg} +chown 1000 $V +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg refuses a store dir not owned by root" has "Refusing to run: $V is not owned by root." +check "...and installs nothing" test ! -e /glacier/sys/links/bin/demo +chown 0 $V +S=$(readlink -f /usr/lib/glacier/libglacier_log.so) +chmod o+w "$S" +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg refuses a world-writable .so behind lib/glacier" rc 1 +check "...saying so" has "is group- or world-writable." +chmod o-w "$S" +# The .so's are reached through lib/glacier -> /usr/lib/glacier -> links +# into libglacier-ng's store dir: that dir's ancestors must be checked +# too, not just those of the script's own realpath. +V=${S%/usr/lib/glacier/libglacier_log.so} +chown 1000 $V +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg refuses libglacier-ng's store dir not owned by root" has "Refusing to run: $V is not owned by root." +check "...and installs nothing" test ! -e /glacier/sys/links/bin/demo +R "cd / && gstore -n 1003" +check "gstore refuses it too" has "Refusing to run: $V is not owned by root." +check "...and creates nothing" test ! -e /glacier/usr/1003 +chown 0 $V +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "with everything restored, syspkg works again" rc 0 + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] && echo "ALL PASSED" +exit $FAILS diff --git a/tests/installed_alpine.sh.old b/tests/installed_alpine.sh.old new file mode 100644 index 0000000..3e37251 --- /dev/null +++ b/tests/installed_alpine.sh.old @@ -0,0 +1,155 @@ +#!/bin/sh +# The installed layout (ROADMAP 1.4): syspkg, gpkg and gstore run from the +# store, as packaged by ~/Projects/everest/scripts/container.sh: +# usr/lib/glacier-ng/{syspkg,gpkg,gstore,lib/*.lua} +# usr/lib/glacier-ng/lib/glacier -> /usr/lib/glacier (absolute) +# usr/bin/X -> ../lib/glacier-ng/X +# etc/glacier/glacier.conf +# plus libglacier-ng's usr/lib/glacier/*.so. Both are installed into the +# container's own / by syspkg, then /app is moved away, so every later +# run can only work by loading from its realpath in the store: +# - each tool runs from any directory, as root and as a user; +# - syspkg installs and removes, gstore -n creates a user, a wheel user +# runs `doas gstore -n` with no password, and gpkg installs; +# - syspkg's and gstore's trust checks still hold in the store: a +# group-writable .lua there, or a non-root-owned store dir, is +# refused. +# Runs INSIDE the Dockerfile.alpine_root image: +# +# docker run --rm -v "$PWD/tests/installed_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } + +# R CMD...: run a shell command line, answering y. Sets $OUT and $RC. +R() { + OUT=$( (echo y | sh -c "$1"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed 's/^/ /' +} +# U CMD...: the same, as user glacier (uid 1000, in wheel). +U() { R "su glacier -c $(printf "'%s'" "$1")"; } +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } + +P=/srv/pkgs +mkdir -p $P +cp /app/tests/mkpkg /srv/mkpkg +chmod 755 /srv /srv/pkgs + +# seal DIR NAME VER: DIR/NAME-VER (files/ + manifest) -> $P/NAME-VER.gpkg +seal() { + printf 'PKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_DESC = "t";\nPKG_MAINT = "t@localhost";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "base";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' \ + "$2" "$3" > "$1/$2-$3/manifest.gpm.cfg" + tar czf "$P/$2-$3.gpkg" -C "$1" "$2-$3" + printf 'sha256:%s\n' "$(sha256sum "$P/$2-$3.gpkg" | cut -d' ' -f1)" > "$P/$2-$3.gpkg.sha256" + gsign -S -s /root/glacier-test.sec -m "$P/$2-$3.gpkg.sha256" >/dev/null + chmod 644 "$P/$2-$3.gpkg" "$P/$2-$3.gpkg.sha256" "$P/$2-$3.gpkg.sha256.sig" +} + +w=$(mktemp -d) +f=$w/libglacier-ng-4.0.0/files +mkdir -p $f/usr/lib/glacier +install -m 755 /app/lib/glacier/libglacier_*.so $f/usr/lib/glacier/ +seal $w libglacier-ng 4.0.0 + +f=$w/glacier-ng-4.0.0/files +d=$f/usr/lib/glacier-ng +mkdir -p $d/lib $f/usr/bin $f/etc/glacier +(cd /app && install -m 755 syspkg gpkg gstore $d/ && + install -m 644 lib/cargs.lua lib/color.lua lib/glacier_cdef.lua lib/gpkg_common.lua $d/lib/ && + install -m 644 etc/glacier/glacier.conf $f/etc/glacier/) +ln -s /usr/lib/glacier $d/lib/glacier +for t in syspkg gpkg gstore; do ln -s ../lib/glacier-ng/$t $f/usr/bin/$t; done +seal $w glacier-ng 4.0.0 +rm -rf $w + +/srv/mkpkg -o $P demo 1.0.0 extra >/dev/null +/srv/mkpkg -o $P udemo 1.0.0 extra >/dev/null + +# The image's glacier.conf came from the Dockerfile: let the package own it. +rm /etc/glacier/glacier.conf +printf '%s\n' 'permit nopass :wheel as root cmd gstore args -n' \ + 'permit nopass :wheel as root cmd /usr/bin/gstore args -n' > /etc/doas.conf +chmod 0400 /etc/doas.conf + +hr "install glacier with /app's syspkg, then remove /app" +R "/app/syspkg -n && /app/syspkg -l $P/libglacier-ng-4.0.0.gpkg $P/glacier-ng-4.0.0.gpkg" +check "the install succeeds" rc 0 +check "it ends with no errors" has "Completed with no errors." +mv /app /app.gone +check "/usr/bin/syspkg resolves into the store" \ + sh -c 'case $(readlink -f /usr/bin/syspkg) in /glacier/sys/store/base/glacier-ng/glacier-ng-4.0.0/*) ;; *) exit 1 ;; esac' +check "glacier.conf is installed" grep -q KEEP_OLD /etc/glacier/glacier.conf + +hr "syspkg from the store" +R "cd / && /usr/bin/syspkg -h" +check "syspkg -h works from /" rc 0 +R "cd /tmp && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg -l (bare name, from /tmp) installs" rc 0 +check "...with no errors" has "Completed with no errors." +check "the installed program runs" sh -c '/glacier/sys/links/bin/demo | grep -q "demo 1.0.0 says hi"' +R "cd /srv && syspkg -x demo" +check "syspkg -x removes" rc 0 +check "...and its link is gone" sh -c '! [ -e /glacier/sys/links/bin/demo ]' + +hr "a user, through the store's gstore and gpkg" +U "cd / && doas -n gstore -n" +check "a wheel user's doas gstore -n needs no password" rc 0 +check "...and creates their directory" test -d /glacier/usr/1000 +U "cd /tmp && gpkg -l $P/udemo-1.0.0.gpkg" +check "gpkg -l (from /tmp) installs" rc 0 +check "...with no errors" has "Completed with no errors." +U "/glacier/usr/1000/links/bin/udemo" +check "the user's program runs" has "udemo 1.0.0 says hi" +U "cd / && gpkg -x udemo" +check "gpkg -x removes" rc 0 +R "cd /tmp && gstore -n 1001" +check "root's gstore -n UID works from the store" rc 0 + +hr "the trust checks hold in the store" +L=$(readlink -f /usr/lib/glacier-ng/lib/gpkg_common.lua) +chmod g+w "$L" +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg refuses a group-writable .lua in the store" rc 1 +check "...saying which" has "Refusing to run: $L is group- or world-writable." +chmod g-w "$L" +L=$(readlink -f /usr/lib/glacier-ng/lib/glacier_cdef.lua) +chmod g+w "$L" +R "cd / && gstore -n 1002" +check "gstore refuses a group-writable .lua it loads" has "Refusing to run: $L is group- or world-writable." +check "...and creates nothing" test ! -e /glacier/usr/1002 +chmod g-w "$L" +V=$(readlink -f /usr/bin/syspkg); V=${V%/usr/lib/glacier-ng/syspkg} +chown 1000 $V +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg refuses a store dir not owned by root" has "Refusing to run: $V is not owned by root." +check "...and installs nothing" test ! -e /glacier/sys/links/bin/demo +chown 0 $V +S=$(readlink -f /usr/lib/glacier/libglacier_log.so) +chmod o+w "$S" +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg refuses a world-writable .so behind lib/glacier" rc 1 +check "...saying so" has "is group- or world-writable." +chmod o-w "$S" +# The .so's are reached through lib/glacier -> /usr/lib/glacier -> links +# into libglacier-ng's store dir: that dir's ancestors must be checked +# too, not just those of the script's own realpath. +V=${S%/usr/lib/glacier/libglacier_log.so} +chown 1000 $V +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "syspkg refuses libglacier-ng's store dir not owned by root" has "Refusing to run: $V is not owned by root." +check "...and installs nothing" test ! -e /glacier/sys/links/bin/demo +R "cd / && gstore -n 1003" +check "gstore refuses it too" has "Refusing to run: $V is not owned by root." +check "...and creates nothing" test ! -e /glacier/usr/1003 +chown 0 $V +R "cd / && syspkg -l $P/demo-1.0.0.gpkg" +check "with everything restored, syspkg works again" rc 0 + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] && echo "ALL PASSED" +exit $FAILS diff --git a/tests/keyring_alpine.sh b/tests/keyring_alpine.sh new file mode 100644 index 0000000..960d592 --- /dev/null +++ b/tests/keyring_alpine.sh @@ -0,0 +1,226 @@ +#!/bin/sh +# The local base rule (REPO_DESIGN.txt sections 3 and 7): +# - syspkg -l of a package whose manifest says base needs +# FILE.sha256.sig, a signature of that sidecar by a key that +# /etc/glacier/repos.conf lists for base; extra stays sidecar-only; +# - the repo is the one the LIBRARY reads (a manifest comment can't +# make it look like extra); +# - a key trusted for another repo, an unlisted key, or a signature of +# other bytes is refused; the key is picked by keynum; +# - repos.conf is parsed strictly (unknown settings, http://, bad and +# duplicate names); it and the keys must be root-owned and not +# group/world-writable, ancestors included; a listed key that's +# missing stops the run; no repos.conf trusts nothing; +# - glacier-bootstrap carries the .sig to syspkg -R; gbuild -k signs. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/keyring_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +installed() { grep -q "^$1::$2::" /glacier/sys/index/current; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +P=/srv/pkgs +mkdir -p $P && chmod 755 /srv $P + +# Keys: `second` is also listed for base; `extrakey` is in the keyring +# but listed only for extra; `stranger` is in no keyring at all. +gsign -G -p $K/second.pub -s /root/second.sec -c second >/dev/null +gsign -G -p $K/extrakey.pub -s /root/extrakey.sec -c extrakey >/dev/null +gsign -G -p /root/stranger.pub -s /root/stranger.sec -c stranger >/dev/null +GOOD_CONF='repos = ( + { name = "base"; url = "https://pkg.example.org/base"; keys = [ "glacier-test", "second" ]; }, + { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; } +);' +good_conf() { echo "$GOOD_CONF" > $CONF; chmod 644 $CONF; } +good_conf + +# pk NAME REPO [KEY.sec]: $P/NAME-1.0.0.gpkg + sidecar, signed if a key is given +pk() { rm -f $P/$1-1.0.0.gpkg*; /app/tests/mkpkg -o $P ${3:+-k "$3"} "$1" 1.0.0 "$2" >/dev/null; } +inst() { R sh -c "echo y | syspkg -l $*"; } + +syspkg -n >/dev/null + +hr "signed and trusted" +pk okbase base $TEST_SEC +inst $P/okbase-1.0.0.gpkg +check "a base package signed by a key listed for base installs" installed base okbase +check "...cleanly" has "Completed with no errors." +pk okbase2 base /root/second.sec +inst $P/okbase2-1.0.0.gpkg +check "the second key listed for base works too (picked by keynum)" installed base okbase2 +pk plainextra extra +inst $P/plainextra-1.0.0.gpkg +check "an unsigned extra package installs (sidecar only)" installed extra plainextra + +hr "refused" +pk nosig base +inst $P/nosig-1.0.0.gpkg +check "an unsigned base package is refused" has "[x] base::nosig is not signed by a key trusted for base." +check "...exit 1" rc 1 +check "...before the prompt" lacks "Proceed" +check "...installing nothing" sh -c '! grep -q "::nosig::" /glacier/sys/index/current' +pk strangers base /root/stranger.sec +inst $P/strangers-1.0.0.gpkg +check "a key in no keyring is refused" has "[x] base::strangers is not signed by a key trusted for base." +pk extras base /root/extrakey.sec +inst $P/extras-1.0.0.gpkg +check "a key trusted only for extra is refused for base" has "[x] base::extras is not signed by a key trusted for base." +pk other base $TEST_SEC; pk swapped base +cp $P/other-1.0.0.gpkg.sha256.sig $P/swapped-1.0.0.gpkg.sha256.sig +inst $P/swapped-1.0.0.gpkg +check "a trusted signature of ANOTHER sidecar is refused" has "[x] base::swapped is not signed by a key trusted for base." +echo garbage > $P/nosig-1.0.0.gpkg.sha256.sig +inst $P/nosig-1.0.0.gpkg +check "a malformed .sig is refused the same way" has "[x] base::nosig is not signed by a key trusted for base." +inst $P/okbase-1.0.0.gpkg $P/nosig-1.0.0.gpkg $P/strangers-1.0.0.gpkg +both() { has "base::nosig is not" && has "base::strangers is not"; } +check "one unsigned package refuses the batch, each reported" both +check "...and nothing new is staged" lacks "staged from" + +# A comment the old pattern-matching manifest reader would have taken for +# the repo: libconfig (and so gl_install_pkg) says base. +w=$(mktemp -d); mkdir -p $w/sneaky-1.0.0/files/usr/bin +echo x > $w/sneaky-1.0.0/files/usr/bin/sneaky +printf '# PKG_REPO = "extra";\nPKG_NAME = "sneaky";\nPKG_VER = "1.0.0";\nPKG_DESC = "t";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "base";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' > $w/sneaky-1.0.0/manifest.gpm.cfg +tar czf $P/sneaky-1.0.0.gpkg -C $w sneaky-1.0.0; rm -rf $w +printf 'sha256:%s\n' "$(sha256sum $P/sneaky-1.0.0.gpkg | cut -d' ' -f1)" > $P/sneaky-1.0.0.gpkg.sha256 +inst $P/sneaky-1.0.0.gpkg +check "a manifest comment can't pass base off as extra" has "[x] base::sneaky is not signed by a key trusted for base." +check "...nothing linked into /usr" test ! -e /usr/bin/sneaky + +hr "repos.conf" +pk later base $TEST_SEC +rm $CONF +inst $P/later-1.0.0.gpkg +check "no repos.conf trusts no key" has "[x] base::later is not signed by a key trusted for base." +bad_conf() { # bad_conf DESCRIPTION CONTENT + printf '%s\n' "$2" > $CONF; chmod 644 $CONF + inst $P/later-1.0.0.gpkg + check "$1 is refused" has "[x] Malformed /etc/glacier/repos.conf." + check "...installing nothing" sh -c '! grep -q "::later::" /glacier/sys/index/current' +} +bad_conf "not libconfig" 'repos = ( {' +bad_conf "an http:// url" 'repos = ( { name = "base"; url = "http://x/base"; keys = [ "glacier-test" ]; } );' +bad_conf "an empty https:// url" 'repos = ( { name = "base"; url = "https://"; keys = [ "glacier-test" ]; } );' +bad_conf "an unknown entry setting" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; trust = "all"; } );' +bad_conf "an unknown top-level setting" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; } ); verify = false;' +bad_conf "a duplicate repo" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; }, { name = "base"; keys = [ ]; } );' +bad_conf "a key name with a path" 'repos = ( { name = "base"; keys = [ "../../root/stranger" ]; } );' +bad_conf "a repo name with a path" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; }, { name = "../x"; keys = [ ]; } );' +bad_conf "a missing keys list" 'repos = ( { name = "base"; } );' +bad_conf "keys as a string" 'repos = ( { name = "base"; keys = "glacier-test"; } );' +bad_conf "a malformed OTHER entry" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; }, { name = "extra"; url = "ftp://x"; keys = [ ]; } );' + +printf 'repos = ( { name = "base"; keys = [ "glacier-test" ]; } );\n' > $CONF +inst $P/later-1.0.0.gpkg +check "an entry without url works" installed base later +printf 'repos = ( { name = "base"; keys = [ "ghost" ]; } );\n' > $CONF +pk later2 base $TEST_SEC +inst $P/later2-1.0.0.gpkg +check "a listed key that doesn't exist stops the run" has "[x] Cannot read /etc/glacier/keys/ghost.pub." +echo "not a key" > $K/ghost.pub +inst $P/later2-1.0.0.gpkg +check "a listed key that isn't a key stops the run" has "[x] Malformed /etc/glacier/keys/ghost.pub." +rm $K/ghost.pub +printf 'repos = ( { name = "extra"; keys = [ "glacier-test" ]; } );\n' > $CONF +inst $P/later2-1.0.0.gpkg +check "a repos.conf without base trusts nothing for base" has "[x] base::later2 is not signed by a key trusted for base." + +hr "ownership" +good_conf +untrusted() { # untrusted DESCRIPTION PATH-AT-FAULT REFUSED-FILE + inst $P/later2-1.0.0.gpkg + check "$1" has "[x] Refusing $3: $2 is not root-owned, or is group/world-writable." + check "...installing nothing" sh -c '! grep -q "::later2::" /glacier/sys/index/current' +} +chmod 666 $CONF +untrusted "a world-writable repos.conf" $CONF $CONF +chmod 644 $CONF; chown glacier $CONF +untrusted "a repos.conf owned by a user" $CONF $CONF +chown root $CONF; chmod 777 /etc/glacier +untrusted "a world-writable /etc/glacier" /etc/glacier $CONF +chmod 755 /etc/glacier; chmod 775 $K +untrusted "a group-writable keys directory" $K $K/glacier-test.pub +chmod 755 $K; chown glacier $K/glacier-test.pub +untrusted "a key owned by a user" $K/glacier-test.pub $K/glacier-test.pub +chown root $K/glacier-test.pub +# A key that's a root-owned symlink into a user's directory: the REAL +# path's ancestors are checked too. +mkdir -p /home/glacier/k && cp $K/second.pub /home/glacier/k/ && chown glacier /home/glacier/k +mv $K/second.pub /root/second.pub.real; ln -s /home/glacier/k/second.pub $K/second.pub +untrusted "a key linked into a user's directory" /home/glacier/k $K/second.pub +rm $K/second.pub; mv /root/second.pub.real $K/second.pub +inst $P/later2-1.0.0.gpkg +check "restored, it installs" installed base later2 + +hr "glacier-bootstrap carries the signature" +mkdir -p /srv/img && chmod 755 /srv/img +pk bsbase base $TEST_SEC; pk bsextra extra +printf 'NAME=t\nPKG=bsbase 1.0.0\nPKG=bsextra 1.0.0\n' > /srv/t.template +R sh -c "echo y | glacier-bootstrap -d $P /srv/t.template /srv/img" +check "a signed base package bootstraps" rc 0 +check "...into the image" grep -q "^base::bsbase::" /srv/img/glacier/sys/index/current +# The signature covers the sidecar's exact bytes: one without a final +# newline must reach syspkg as it is, not rewritten. +mkdir -p /srv/img3 && chmod 755 /srv/img3 +pk bsnonl base +printf 'sha256:%s' "$(sha256sum $P/bsnonl-1.0.0.gpkg | cut -d' ' -f1)" > $P/bsnonl-1.0.0.gpkg.sha256 +gsign -S -s $TEST_SEC -m $P/bsnonl-1.0.0.gpkg.sha256 >/dev/null +printf 'NAME=t\nPKG=bsnonl 1.0.0\n' > /srv/t3.template +R sh -c "echo y | glacier-bootstrap -d $P /srv/t3.template /srv/img3" +check "a signed sidecar without a final newline bootstraps" grep -q "^base::bsnonl::" /srv/img3/glacier/sys/index/current +mkdir -p /srv/img2 && chmod 755 /srv/img2 +pk bsbase2 base +printf 'NAME=t\nPKG=bsbase2 1.0.0\n' > /srv/t2.template +R sh -c "echo y | glacier-bootstrap -d $P /srv/t2.template /srv/img2" +check "an unsigned one is refused by syspkg -R (exit 5)" rc 5 +check "...saying why" has "[x] base::bsbase2 is not signed by a key trusted for base." +check "...installing nothing" sh -c '! grep -q "bsbase2" /srv/img2/glacier/sys/index/current 2>/dev/null' + +hr "gbuild -k" +apk add --no-cache bash >/dev/null 2>&1 || { echo "apk failed"; exit 1; } +# Not /app on PATH: glacier-ng's checkout holds a host (glibc) gsha256sum. +gb() { env PATH=/usr/local/bin:/usr/bin:/bin /app/gbuild "$@"; } +mkdir -p /srv/gb/hello +printf 'all:\n\ttrue\ninstall:\n\tmkdir -p $(DESTDIR)/usr/bin && echo hi > $(DESTDIR)/usr/bin/hello\n' > /srv/gb/hello/Makefile +R gb -n hello -V 1.0.0 -d t -m t@e -g base -o /srv/gbout -k $TEST_SEC /srv/gb/hello +check "gbuild -k succeeds" rc 0 +check "...and its signature verifies the sidecar" gsign -V -p $K/glacier-test.pub -m /srv/gbout/hello-1.0.0.gpkg.sha256 +inst /srv/gbout/hello-1.0.0.gpkg +check "...which syspkg accepts for base" installed base hello +R gb -n hello -V 1.0.1 -d t -m t@e -g base -o /srv/gbout -k /root/missing.sec /srv/gb/hello +check "gbuild -k with an unreadable key fails" rc 1 +check "...before building anything" sh -c '! ls /srv/gbout | grep -q 1.0.1' +R gb -n hello -V 1.0.0 -d t -m t@e -g base -o /srv/gbout /srv/gb/hello +check "rebuilding without -k leaves no stale signature" test ! -e /srv/gbout/hello-1.0.0.gpkg.sha256.sig + + +hr "gbuild: hardlinks become files" +mkdir -p /srv/gb/hard +printf 'all:\n\ttrue\ninstall:\n\tmkdir -p $(DESTDIR)/usr/bin && echo hi > $(DESTDIR)/usr/bin/hard && ln $(DESTDIR)/usr/bin/hard $(DESTDIR)/usr/bin/hard2\n' > /srv/gb/hard/Makefile +R gb -n hard -V 1.0.0 -d t -m t@e -g extra -o /srv/gbout /srv/gb/hard +check "gbuild packs a hardlink" rc 0 +check "...as a plain file" sh -c '! tar -tvzf /srv/gbout/hard-1.0.0.gpkg | grep -q "^h"' +check "...both names in the package" sh -c 'tar -tzf /srv/gbout/hard-1.0.0.gpkg | grep -q "usr/bin/hard$" && tar -tzf /srv/gbout/hard-1.0.0.gpkg | grep -q "usr/bin/hard2$"' +inst /srv/gbout/hard-1.0.0.gpkg +check "...which installs" installed extra hard +check "...both files there" sh -c '[ "$(cat /glacier/sys/links/bin/hard2)" = hi ] && [ "$(cat /glacier/sys/links/bin/hard)" = hi ]' + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/keyring_alpine.sh.old b/tests/keyring_alpine.sh.old new file mode 100644 index 0000000..c8d529e --- /dev/null +++ b/tests/keyring_alpine.sh.old @@ -0,0 +1,214 @@ +#!/bin/sh +# The local base rule (REPO_DESIGN.txt sections 3 and 7): +# - syspkg -l of a package whose manifest says base needs +# FILE.sha256.sig, a signature of that sidecar by a key that +# /etc/glacier/repos.conf lists for base; extra stays sidecar-only; +# - the repo is the one the LIBRARY reads (a manifest comment can't +# make it look like extra); +# - a key trusted for another repo, an unlisted key, or a signature of +# other bytes is refused; the key is picked by keynum; +# - repos.conf is parsed strictly (unknown settings, http://, bad and +# duplicate names); it and the keys must be root-owned and not +# group/world-writable, ancestors included; a listed key that's +# missing stops the run; no repos.conf trusts nothing; +# - glacier-bootstrap carries the .sig to syspkg -R; gbuild -k signs. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/keyring_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +installed() { grep -q "^$1::$2::" /glacier/sys/index/current; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +P=/srv/pkgs +mkdir -p $P && chmod 755 /srv $P + +# Keys: `second` is also listed for base; `extrakey` is in the keyring +# but listed only for extra; `stranger` is in no keyring at all. +gsign -G -p $K/second.pub -s /root/second.sec -c second >/dev/null +gsign -G -p $K/extrakey.pub -s /root/extrakey.sec -c extrakey >/dev/null +gsign -G -p /root/stranger.pub -s /root/stranger.sec -c stranger >/dev/null +GOOD_CONF='repos = ( + { name = "base"; url = "https://pkg.example.org/base"; keys = [ "glacier-test", "second" ]; }, + { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; } +);' +good_conf() { echo "$GOOD_CONF" > $CONF; chmod 644 $CONF; } +good_conf + +# pk NAME REPO [KEY.sec]: $P/NAME-1.0.0.gpkg + sidecar, signed if a key is given +pk() { rm -f $P/$1-1.0.0.gpkg*; /app/tests/mkpkg -o $P ${3:+-k "$3"} "$1" 1.0.0 "$2" >/dev/null; } +inst() { R sh -c "echo y | syspkg -l $*"; } + +syspkg -n >/dev/null + +hr "signed and trusted" +pk okbase base $TEST_SEC +inst $P/okbase-1.0.0.gpkg +check "a base package signed by a key listed for base installs" installed base okbase +check "...cleanly" has "Completed with no errors." +pk okbase2 base /root/second.sec +inst $P/okbase2-1.0.0.gpkg +check "the second key listed for base works too (picked by keynum)" installed base okbase2 +pk plainextra extra +inst $P/plainextra-1.0.0.gpkg +check "an unsigned extra package installs (sidecar only)" installed extra plainextra + +hr "refused" +pk nosig base +inst $P/nosig-1.0.0.gpkg +check "an unsigned base package is refused" has "[x] base::nosig is not signed by a key trusted for base." +check "...exit 1" rc 1 +check "...before the prompt" lacks "Proceed" +check "...installing nothing" sh -c '! grep -q "::nosig::" /glacier/sys/index/current' +pk strangers base /root/stranger.sec +inst $P/strangers-1.0.0.gpkg +check "a key in no keyring is refused" has "[x] base::strangers is not signed by a key trusted for base." +pk extras base /root/extrakey.sec +inst $P/extras-1.0.0.gpkg +check "a key trusted only for extra is refused for base" has "[x] base::extras is not signed by a key trusted for base." +pk other base $TEST_SEC; pk swapped base +cp $P/other-1.0.0.gpkg.sha256.sig $P/swapped-1.0.0.gpkg.sha256.sig +inst $P/swapped-1.0.0.gpkg +check "a trusted signature of ANOTHER sidecar is refused" has "[x] base::swapped is not signed by a key trusted for base." +echo garbage > $P/nosig-1.0.0.gpkg.sha256.sig +inst $P/nosig-1.0.0.gpkg +check "a malformed .sig is refused the same way" has "[x] base::nosig is not signed by a key trusted for base." +inst $P/okbase-1.0.0.gpkg $P/nosig-1.0.0.gpkg $P/strangers-1.0.0.gpkg +both() { has "base::nosig is not" && has "base::strangers is not"; } +check "one unsigned package refuses the batch, each reported" both +check "...and nothing new is staged" lacks "staged from" + +# A comment the old pattern-matching manifest reader would have taken for +# the repo: libconfig (and so gl_install_pkg) says base. +w=$(mktemp -d); mkdir -p $w/sneaky-1.0.0/files/usr/bin +echo x > $w/sneaky-1.0.0/files/usr/bin/sneaky +printf '# PKG_REPO = "extra";\nPKG_NAME = "sneaky";\nPKG_VER = "1.0.0";\nPKG_DESC = "t";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "base";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' > $w/sneaky-1.0.0/manifest.gpm.cfg +tar czf $P/sneaky-1.0.0.gpkg -C $w sneaky-1.0.0; rm -rf $w +printf 'sha256:%s\n' "$(sha256sum $P/sneaky-1.0.0.gpkg | cut -d' ' -f1)" > $P/sneaky-1.0.0.gpkg.sha256 +inst $P/sneaky-1.0.0.gpkg +check "a manifest comment can't pass base off as extra" has "[x] base::sneaky is not signed by a key trusted for base." +check "...nothing linked into /usr" test ! -e /usr/bin/sneaky + +hr "repos.conf" +pk later base $TEST_SEC +rm $CONF +inst $P/later-1.0.0.gpkg +check "no repos.conf trusts no key" has "[x] base::later is not signed by a key trusted for base." +bad_conf() { # bad_conf DESCRIPTION CONTENT + printf '%s\n' "$2" > $CONF; chmod 644 $CONF + inst $P/later-1.0.0.gpkg + check "$1 is refused" has "[x] Malformed /etc/glacier/repos.conf." + check "...installing nothing" sh -c '! grep -q "::later::" /glacier/sys/index/current' +} +bad_conf "not libconfig" 'repos = ( {' +bad_conf "an http:// url" 'repos = ( { name = "base"; url = "http://x/base"; keys = [ "glacier-test" ]; } );' +bad_conf "an empty https:// url" 'repos = ( { name = "base"; url = "https://"; keys = [ "glacier-test" ]; } );' +bad_conf "an unknown entry setting" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; trust = "all"; } );' +bad_conf "an unknown top-level setting" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; } ); verify = false;' +bad_conf "a duplicate repo" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; }, { name = "base"; keys = [ ]; } );' +bad_conf "a key name with a path" 'repos = ( { name = "base"; keys = [ "../../root/stranger" ]; } );' +bad_conf "a repo name with a path" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; }, { name = "../x"; keys = [ ]; } );' +bad_conf "a missing keys list" 'repos = ( { name = "base"; } );' +bad_conf "keys as a string" 'repos = ( { name = "base"; keys = "glacier-test"; } );' +bad_conf "a malformed OTHER entry" 'repos = ( { name = "base"; keys = [ "glacier-test" ]; }, { name = "extra"; url = "ftp://x"; keys = [ ]; } );' + +printf 'repos = ( { name = "base"; keys = [ "glacier-test" ]; } );\n' > $CONF +inst $P/later-1.0.0.gpkg +check "an entry without url works" installed base later +printf 'repos = ( { name = "base"; keys = [ "ghost" ]; } );\n' > $CONF +pk later2 base $TEST_SEC +inst $P/later2-1.0.0.gpkg +check "a listed key that doesn't exist stops the run" has "[x] Cannot read /etc/glacier/keys/ghost.pub." +echo "not a key" > $K/ghost.pub +inst $P/later2-1.0.0.gpkg +check "a listed key that isn't a key stops the run" has "[x] Malformed /etc/glacier/keys/ghost.pub." +rm $K/ghost.pub +printf 'repos = ( { name = "extra"; keys = [ "glacier-test" ]; } );\n' > $CONF +inst $P/later2-1.0.0.gpkg +check "a repos.conf without base trusts nothing for base" has "[x] base::later2 is not signed by a key trusted for base." + +hr "ownership" +good_conf +untrusted() { # untrusted DESCRIPTION PATH-AT-FAULT REFUSED-FILE + inst $P/later2-1.0.0.gpkg + check "$1" has "[x] Refusing $3: $2 is not root-owned, or is group/world-writable." + check "...installing nothing" sh -c '! grep -q "::later2::" /glacier/sys/index/current' +} +chmod 666 $CONF +untrusted "a world-writable repos.conf" $CONF $CONF +chmod 644 $CONF; chown glacier $CONF +untrusted "a repos.conf owned by a user" $CONF $CONF +chown root $CONF; chmod 777 /etc/glacier +untrusted "a world-writable /etc/glacier" /etc/glacier $CONF +chmod 755 /etc/glacier; chmod 775 $K +untrusted "a group-writable keys directory" $K $K/glacier-test.pub +chmod 755 $K; chown glacier $K/glacier-test.pub +untrusted "a key owned by a user" $K/glacier-test.pub $K/glacier-test.pub +chown root $K/glacier-test.pub +# A key that's a root-owned symlink into a user's directory: the REAL +# path's ancestors are checked too. +mkdir -p /home/glacier/k && cp $K/second.pub /home/glacier/k/ && chown glacier /home/glacier/k +mv $K/second.pub /root/second.pub.real; ln -s /home/glacier/k/second.pub $K/second.pub +untrusted "a key linked into a user's directory" /home/glacier/k $K/second.pub +rm $K/second.pub; mv /root/second.pub.real $K/second.pub +inst $P/later2-1.0.0.gpkg +check "restored, it installs" installed base later2 + +hr "glacier-bootstrap carries the signature" +mkdir -p /srv/img && chmod 755 /srv/img +pk bsbase base $TEST_SEC; pk bsextra extra +printf 'NAME=t\nPKG=bsbase 1.0.0\nPKG=bsextra 1.0.0\n' > /srv/t.template +R sh -c "echo y | glacier-bootstrap -d $P /srv/t.template /srv/img" +check "a signed base package bootstraps" rc 0 +check "...into the image" grep -q "^base::bsbase::" /srv/img/glacier/sys/index/current +# The signature covers the sidecar's exact bytes: one without a final +# newline must reach syspkg as it is, not rewritten. +mkdir -p /srv/img3 && chmod 755 /srv/img3 +pk bsnonl base +printf 'sha256:%s' "$(sha256sum $P/bsnonl-1.0.0.gpkg | cut -d' ' -f1)" > $P/bsnonl-1.0.0.gpkg.sha256 +gsign -S -s $TEST_SEC -m $P/bsnonl-1.0.0.gpkg.sha256 >/dev/null +printf 'NAME=t\nPKG=bsnonl 1.0.0\n' > /srv/t3.template +R sh -c "echo y | glacier-bootstrap -d $P /srv/t3.template /srv/img3" +check "a signed sidecar without a final newline bootstraps" grep -q "^base::bsnonl::" /srv/img3/glacier/sys/index/current +mkdir -p /srv/img2 && chmod 755 /srv/img2 +pk bsbase2 base +printf 'NAME=t\nPKG=bsbase2 1.0.0\n' > /srv/t2.template +R sh -c "echo y | glacier-bootstrap -d $P /srv/t2.template /srv/img2" +check "an unsigned one is refused by syspkg -R (exit 5)" rc 5 +check "...saying why" has "[x] base::bsbase2 is not signed by a key trusted for base." +check "...installing nothing" sh -c '! grep -q "bsbase2" /srv/img2/glacier/sys/index/current 2>/dev/null' + +hr "gbuild -k" +apk add --no-cache bash >/dev/null 2>&1 || { echo "apk failed"; exit 1; } +# Not /app on PATH: glacier-ng's checkout holds a host (glibc) gsha256sum. +gb() { env PATH=/usr/local/bin:/usr/bin:/bin /app/gbuild "$@"; } +mkdir -p /srv/gb/hello +printf 'all:\n\ttrue\ninstall:\n\tmkdir -p $(DESTDIR)/usr/bin && echo hi > $(DESTDIR)/usr/bin/hello\n' > /srv/gb/hello/Makefile +R gb -n hello -V 1.0.0 -d t -m t@e -g base -o /srv/gbout -k $TEST_SEC /srv/gb/hello +check "gbuild -k succeeds" rc 0 +check "...and its signature verifies the sidecar" gsign -V -p $K/glacier-test.pub -m /srv/gbout/hello-1.0.0.gpkg.sha256 +inst /srv/gbout/hello-1.0.0.gpkg +check "...which syspkg accepts for base" installed base hello +R gb -n hello -V 1.0.1 -d t -m t@e -g base -o /srv/gbout -k /root/missing.sec /srv/gb/hello +check "gbuild -k with an unreadable key fails" rc 1 +check "...before building anything" sh -c '! ls /srv/gbout | grep -q 1.0.1' +R gb -n hello -V 1.0.0 -d t -m t@e -g base -o /srv/gbout /srv/gb/hello +check "rebuilding without -k leaves no stale signature" test ! -e /srv/gbout/hello-1.0.0.gpkg.sha256.sig + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/mkgrcp b/tests/mkgrcp new file mode 100755 index 0000000..4dc9c9b --- /dev/null +++ b/tests/mkgrcp @@ -0,0 +1,59 @@ +#!/bin/sh +# mkgrcp: pack recipe directories into recipe bundles (BUILD_DESIGN.txt +# section 4), for a NAME-src repository that grepo then indexes. +# +# mkgrcp [-o DIR] RECIPEDIR... +# +# -o DIR write DIR/NAME-VER.grcp (default: .) +# +# RECIPEDIR holds `recipe` and optionally `build` and patches/*.patch; +# NAME and VER are taken from the recipe's top-level `NAME = "..."` and +# `VER = "..."` lines (at the start of a line). Nothing else is packed. +# The bundle is checked by the library when grepo indexes it. +# +# Example: +# mkgrcp -o /srv/extra-src ~/Projects/everest/recipes/extra-src/*/ +# grepo -s KEY.sec -r extra-src /srv/extra-src + +usage() { echo "usage: mkgrcp [-o DIR] RECIPEDIR..." >&2; exit 1; } + +out=. +while getopts o:h opt; do + case $opt in + o) out=$OPTARG ;; + *) usage ;; + esac +done +shift $((OPTIND - 1)) +[ $# -ge 1 ] || usage +mkdir -p "$out" || exit 1 + +work=$(mktemp -d) || exit 1 +trap 'rm -rf "$work"' EXIT + +field() { sed -n "s/^$1[[:space:]]*=[[:space:]]*\"\([^\"]*\)\".*/\1/p" "$2" | head -1; } + +rc=0 +for r in "$@"; do + r=${r%/} + name=$(field NAME "$r/recipe") ver=$(field VER "$r/recipe") + if [ -z "$name" ] || [ -z "$ver" ]; then + echo "mkgrcp: $r/recipe: no NAME or VER line" >&2 + rc=1 + continue + fi + d=$work/$name-$ver + mkdir "$d" || exit 1 + cp "$r/recipe" "$d/" + [ -f "$r/build" ] && cp "$r/build" "$d/" + if [ -d "$r/patches" ]; then + mkdir "$d/patches" + cp "$r"/patches/*.patch "$d/patches/" 2>/dev/null + fi + chmod -R u=rwX,go=rX "$d" + b=$out/$name-$ver.grcp + tar czf "$b" -C "$work" "$name-$ver" || exit 1 + chmod 644 "$b" + echo "$b" +done +exit $rc diff --git a/tests/mkpkg b/tests/mkpkg new file mode 100755 index 0000000..727c807 --- /dev/null +++ b/tests/mkpkg @@ -0,0 +1,83 @@ +#!/bin/sh +# mkpkg: build a small demo .gpkg (plus its .sha256 sidecar) for trying +# out gpkg/syspkg by hand. The package ships one script, usr/bin/NAME, +# which prints "NAME VERSION says hi". +# +# mkpkg [-o DIR] [-k KEY.sec] [-d NAME:VER]... [-c NAME:VER]... NAME VERSION REPO +# +# -o DIR write DIR/NAME-VERSION.gpkg (default: current directory) +# -k KEY.sec sign the sidecar (NAME-VERSION.gpkg.sha256.sig) with gsign +# ($GSIGN_BIN, else gsign on PATH). syspkg requires this +# for base, by a key listed for base in +# /etc/glacier/repos.conf. The test images have one: +# -k /root/glacier-test.sec +# -d NAME:VER depend on NAME >= VER (repeatable) +# -c NAME:VER conflict with NAME (repeatable; the version is ignored) +# +# Examples: +# mkpkg -o /srv lib 2.0.0 extra +# mkpkg -o /srv -k /root/glacier-test.sec core 1.0.0 base +# mkpkg -o /srv -d lib:1.5.0 app 1.0.0 extra +# mkpkg -o /srv -c app:0.0.0 rival 1.0.0 extra +# +# Not a build tool: use gbuild for real packages. + +usage() { echo "usage: mkpkg [-o DIR] [-k KEY.sec] [-d NAME:VER]... [-c NAME:VER]... NAME VERSION REPO" >&2; exit 1; } + +out=. +key="" +deps="" +confs="" +while getopts o:k:d:c:h opt; do + case $opt in + o) out=$OPTARG ;; + k) key=$OPTARG ;; + d) deps="$deps $OPTARG" ;; + c) confs="$confs $OPTARG" ;; + *) usage ;; + esac +done +shift $((OPTIND - 1)) +[ $# -eq 3 ] || usage +name=$1 ver=$2 repo=$3 + +ident() { case $1 in ''|.|..|*[!A-Za-z0-9._-]*) return 1 ;; esac; } +semver() { echo "$1" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+$'; } +ident "$name" || { echo "mkpkg: bad name: $name" >&2; exit 1; } +ident "$repo" || { echo "mkpkg: bad repo: $repo" >&2; exit 1; } +semver "$ver" || { echo "mkpkg: version must be X.Y.Z: $ver" >&2; exit 1; } +for it in $deps $confs; do + case $it in *:*) ;; *) echo "mkpkg: expected NAME:VER, got $it" >&2; exit 1 ;; esac + ident "${it%%:*}" && semver "${it#*:}" || { echo "mkpkg: bad entry: $it" >&2; exit 1; } +done + +# libconfig list of { PKG_NAME; PKG_VER } groups +list() { + sep="" + for it in $1; do + printf '%s{ PKG_NAME = "%s"; PKG_VER = "%s"; }' "$sep" "${it%%:*}" "${it#*:}" + sep=", " + done +} + +mkdir -p "$out" || exit 1 +work=$(mktemp -d) || exit 1 +trap 'rm -rf "$work"' EXIT +dir=$work/$name-$ver + +mkdir -p "$dir/files/usr/bin" +printf '#!/bin/sh\necho "%s %s says hi"\n' "$name" "$ver" > "$dir/files/usr/bin/$name" +chmod 755 "$dir/files/usr/bin/$name" +printf 'PKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_DESC = "mkpkg demo package";\nPKG_MAINT = "mkpkg@localhost";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "%s";\nPKG_DEPS = (%s);\nPKG_CONFS = (%s);\n' \ + "$name" "$ver" "$repo" "$(list "$deps")" "$(list "$confs")" > "$dir/manifest.gpm.cfg" + +pkg=$out/$name-$ver.gpkg +tar czf "$pkg" -C "$work" "$name-$ver" || exit 1 +printf 'sha256:%s\n' "$(sha256sum "$pkg" | cut -d' ' -f1)" > "$pkg.sha256" +rm -f "$pkg.sha256.sig" +if [ -n "$key" ]; then + "${GSIGN_BIN:-gsign}" -S -s "$key" -m "$pkg.sha256" >/dev/null || exit 1 + chmod 644 "$pkg.sha256.sig" +fi +chmod 644 "$pkg" "$pkg.sha256" +echo "$pkg" diff --git a/tests/mkroot b/tests/mkroot new file mode 100755 index 0000000..fbfaa13 --- /dev/null +++ b/tests/mkroot @@ -0,0 +1,107 @@ +#!/bin/sh +# mkroot: pack files of THIS (Alpine) system into a .gpkg, for build +# tests (BUILD_DESIGN.txt section 6): a build layer needs real programs, +# and Everest has no toolchain packages yet. +# +# mkroot [-o DIR] [-p APK]... [-r APK]... [-f PATH]... NAME VERSION REPO +# +# -o DIR write DIR/NAME-VERSION.gpkg (+ .sha256; default: .) +# -p APK every file the installed Alpine package APK owns +# (apk info -L), with its symlinks +# -r APK the same for APK and everything it depends on +# -f PATH one file or symlink (absolute path) +# +# Paths are packed as the merged-/usr layout glacier uses: /bin, /sbin, +# /usr/sbin -> usr/bin, /lib -> usr/lib. For busybox, a symlink per +# applet is added (Alpine makes them at install time, not in the apk). +# +# Examples: +# mkroot -o /srv -p musl -p busybox testroot 1.0.0 extra +# mkroot -o /srv -p gcc -p binutils -p make toolchain 1.0.0 extra + +usage() { echo "usage: mkroot [-o DIR] [-p APK]... [-r APK]... [-f PATH]... NAME VERSION REPO" >&2; exit 1; } + +# The installed package owning a file, by name. +owner() { apk info -qW "$1" 2>/dev/null | head -1 | sed 's/-[0-9][^-]*-r[0-9]*$//'; } + +# APK and everything it depends on (installed packages only). +closure() { + todo=$1 done=" " + while [ -n "$todo" ]; do + set -- $todo; p=$1; shift; todo=$* + case "$done" in *" $p "*) continue ;; esac + done="$done$p " + for d in $(apk info -qR "$p" 2>/dev/null); do + d=${d%%[<>=~]*} + case $d in + so:*) + f=$(ls /lib/${d#so:} /usr/lib/${d#so:} 2>/dev/null | head -1) + [ -n "$f" ] && d=$(owner "$f") || continue ;; + *:*) continue ;; + esac + [ -n "$d" ] && todo="$todo $d" + done + done + echo $done +} + +out=. +apks="" +files="" +while getopts o:p:r:f:h opt; do + case $opt in + o) out=$OPTARG ;; + p) apks="$apks $OPTARG" ;; + r) apks="$apks $(closure "$OPTARG")" ;; + f) files="$files $OPTARG" ;; + *) usage ;; + esac +done +shift $((OPTIND - 1)) +[ $# -eq 3 ] || usage +name=$1 ver=$2 repo=$3 + +work=$(mktemp -d) || exit 1 +trap 'rm -rf "$work"' EXIT +dir=$work/$name-$ver +mkdir -p "$dir/files/usr/bin" "$dir/files/usr/lib" + +# The merged-/usr place of an absolute path. +dest() { + case $1 in + /bin/*|/sbin/*|/usr/sbin/*) echo "usr/bin/${1##*/}" ;; + /lib/*) echo "usr/lib/${1#/lib/}" ;; + *) echo "${1#/}" ;; + esac +} + +list=$work/list +: > "$list" +for p in $apks; do + apk info -qL "$p" 2>/dev/null | sed -n 's|^|/|p' >> "$list" || exit 1 +done +for f in $files; do echo "$f" >> "$list"; done + +while read -r f; do + [ -e "$f" ] || [ -L "$f" ] || continue + [ -d "$f" ] && [ ! -L "$f" ] && continue + d=$dir/files/$(dest "$f") + mkdir -p "${d%/*}" + cp -P "$f" "$d" 2>/dev/null || true +done < "$list" + +if [ -e "$dir/files/usr/bin/busybox" ]; then + for a in $(busybox --list); do + [ -e "$dir/files/usr/bin/$a" ] || ln -s busybox "$dir/files/usr/bin/$a" + done +fi + +printf 'PKG_NAME = "%s";\nPKG_VER = "%s";\nPKG_DESC = "mkroot test package";\nPKG_MAINT = "mkroot@localhost";\nPKG_COPYRIGHT = "various";\nPKG_REPO = "%s";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' \ + "$name" "$ver" "$repo" > "$dir/manifest.gpm.cfg" + +mkdir -p "$out" || exit 1 +pkg=$out/$name-$ver.gpkg +tar czf "$pkg" -C "$work" "$name-$ver" || exit 1 +printf 'sha256:%s\n' "$(sha256sum "$pkg" | cut -d' ' -f1)" > "$pkg.sha256" +chmod 644 "$pkg" "$pkg.sha256" +echo "$pkg" diff --git a/tests/overwrite_alpine.sh b/tests/overwrite_alpine.sh new file mode 100644 index 0000000..56f67c3 --- /dev/null +++ b/tests/overwrite_alpine.sh @@ -0,0 +1,126 @@ +#!/bin/sh +# -O/--overwrite tests for syspkg and gpkg. Runs inside a THROWAWAY alpine +# container as root — it displaces Alpine's own /usr/include and /usr/lib +# files, so never run it on a real system. +# +# Run it twice: once as-is (/glacier on the same filesystem as /usr, so +# displacing is a rename()), once with --tmpfs /glacier (different +# filesystem, so it exercises the copy+unlink EXDEV fallback): +# +# docker run --rm \ +# -v /home/lw/Projects/glacier-ng:/src:ro \ +# -v /home/lw/Projects/libglacier-ng:/libsrc:ro \ +# -v /home/lw/Projects/glacier-ng/tests/overwrite_alpine.sh:/t.sh:ro \ +# [--tmpfs /glacier:exec] alpine:latest sh /t.sh +# +# No gpkg/user-scope case: a user's links tree is swapped out wholesale on +# every commit, so nothing non-glacier can be sitting at a link +# destination when the post-commit relink runs. Only system-scope base +# packages, linking into /usr, can ever hit a conflict. +set -u +apk add --no-cache build-base luajit-dev libarchive-dev libconfig-dev linux-headers >/dev/null 2>&1 \ + || { echo "apk failed"; exit 1; } + +FAILS=0 +hr() { echo; echo "=== $* ==="; } +check() { # check DESCRIPTION COMMAND... + desc=$1; shift + if "$@"; then echo "PASS: $desc"; else echo "FAIL: $desc"; FAILS=$((FAILS + 1)); fi +} +# Strip the per-path "Refusing to overwrite" flood; print how many there were. +quiet() { "$@" 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | awk '/Refusing to overwrite non-glacier/ {n++; next} {print} END {if (n) print "(" n " x \"Refusing to overwrite non-glacier path\")"}'; } +# run CMD: like quiet, but keeps the output in $OUT and the exit status +# in $STATUS. +run() { + OUT=$(sh -c "$1; echo \"exit=\$?\"" 2>&1 | sed 's/\x1b\[[0-9;]*m//g') + STATUS=$(echo "$OUT" | sed -n 's/^exit=//p' | tail -1) + OUT=$(echo "$OUT" | grep -v '^exit=') + echo "$OUT" | awk '/Refusing to overwrite non-glacier/ {n++; next} {print} END {if (n) print "(" n " x \"Refusing to overwrite non-glacier path\")"}' +} +last_line() { echo "$OUT" | tail -1; } +sha() { sha256sum "$1" | cut -d' ' -f1; } +is_reg() { [ -f "$1" ] && [ ! -L "$1" ]; } +links_into_store() { case "$(readlink "$1")" in "$2"/*) return 0 ;; esac; return 1; } + +hr "0. build libglacier-ng against musl" +cp -a /libsrc /build && cd /build && make clean >/dev/null && make >/tmp/make.log 2>&1 \ + && echo "build ok" || { tail -30 /tmp/make.log; exit 1; } +cp -a /src /opt/glacier +mkdir -p /opt/glacier/lib/glacier +cp /build/build/lib/shared/libglacier_*.so /opt/glacier/lib/glacier/ +chown -R root:root /opt/glacier && chmod -R go-w /opt/glacier +# A throwaway key trusted for base (REPO_DESIGN.txt section 7), and the +# copies' sidecars signed with it. +mkdir -p /etc/glacier/keys +/build/build/bin/gsign -G -p /etc/glacier/keys/t.pub -s /root/t.sec -c t >/dev/null +printf 'repos = (\n\t{ name = "base"; keys = [ "t" ]; }\n);\n' > /etc/glacier/repos.conf +for s in /opt/glacier/*.gpkg.sha256 /opt/glacier/pkgs/*.gpkg.sha256; do + [ -e "$s" ] && /build/build/bin/gsign -S -s /root/t.sec -m "$s" >/dev/null +done +cd /opt/glacier +SP=/opt/glacier/syspkg +SYS_STORE=/glacier/sys/store +DISP=$SYS_STORE/.displaced + +echo "/usr fs: $(stat -f -c %i /usr 2>/dev/null) /glacier fs: $(mkdir -p /glacier; stat -f -c %i /glacier)" +$SP -n >/dev/null + +STDIO=/usr/include/stdio.h +LIBC=/usr/lib/libc.so # Alpine ships this as a symlink, not a file +ORIG_SHA=$(sha $STDIO) +ORIG_MODE=$(stat -c '%a %u %g' $STDIO) +ORIG_LIBC_TARGET=$(readlink $LIBC) + +hr "1. install base package without -O: originals untouched" +run "echo y | $SP -l pkgs/musl-1.2.5.gpkg" +check "stdio.h still Alpine's regular file" is_reg $STDIO +NREF=$(echo "$OUT" | grep -c 'Refusing to overwrite non-glacier') +check "refusals end in an error, not \"Completed\"" test "$(last_line)" = "[x] $NREF paths were not linked." +check "and exit status 1" test "$STATUS" = 1 +check "no displaced tree created" test ! -e $DISP + +hr "2. reinstall with -O: originals displaced, glacier symlinks in place" +run "echo y | $SP -O -l pkgs/musl-1.2.5.gpkg" +check "nothing refused: Completed with no errors" test "$(last_line)" = "[✓] Completed with no errors." +check "and exit status 0" test "$STATUS" = 0 +check "stdio.h is now a glacier symlink" links_into_store $STDIO $SYS_STORE +check "original stdio.h kept, content intact" test "$(sha $DISP$STDIO 2>/dev/null)" = "$ORIG_SHA" +check "original stdio.h mode/owner kept" test "$(stat -c '%a %u %g' $DISP$STDIO 2>/dev/null)" = "$ORIG_MODE" +check "libc.so (a foreign symlink) displaced as a symlink" test "$(readlink $DISP$LIBC 2>/dev/null)" = "$ORIG_LIBC_TARGET" +check "libc.so now a glacier symlink" links_into_store $LIBC $SYS_STORE +check "overwrite marker consumed" test -z "$(find $SYS_STORE -name .glacier-overwrite)" + +hr "3. unrelated transaction: displaced originals survive stage seeding" +quiet sh -c "echo y | $SP -l kilo-0.0.1.gpkg" +check "displaced stdio.h still present after another commit" test "$(sha $DISP$STDIO 2>/dev/null)" = "$ORIG_SHA" +check "stdio.h still a glacier symlink" links_into_store $STDIO $SYS_STORE + +hr "4. -O on a later install doesn't spread to other packages" +# Only /usr can hold a foreign file at relink time (the links trees are +# swapped out wholesale on every commit), so plant one at a path musl +# links to, then install a DIFFERENT package with -O: musl's path must +# stay refused, since musl itself wasn't installed with -O this time. +FOREIGN=/usr/include/libintl.h +rm -f $FOREIGN && echo foreign > $FOREIGN +run "echo y | $SP -O -l pkgs/sbase-0.0.1.gpkg" +check "foreign file at a musl path untouched" test "$(cat $FOREIGN)" = foreign +check "musl's standing conflict doesn't fail sbase's install" test "$STATUS" = 0 +check "and not displaced" test ! -e $DISP$FOREIGN +rm -f $FOREIGN + +hr "5. remove: originals restored" +quiet sh -c "echo y | $SP -x musl" +check "stdio.h restored as a regular file" is_reg $STDIO +check "restored stdio.h content matches" test "$(sha $STDIO)" = "$ORIG_SHA" +check "restored stdio.h mode/owner match" test "$(stat -c '%a %u %g' $STDIO)" = "$ORIG_MODE" +check "libc.so restored as Alpine's symlink" test "$(readlink $LIBC)" = "$ORIG_LIBC_TARGET" +check "no musl originals left in displaced tree" test -z "$(find $DISP/usr -type f -o -type l 2>/dev/null | grep -v sbase)" +check "Alpine toolchain still works" sh -c 'echo "int main(void){return 0;}" | cc -x c - -o /tmp/a.out && /tmp/a.out' + +hr "6. help / usage" +$SP -h | grep -- --overwrite +./gpkg -h | grep -- --overwrite + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/overwrite_alpine.sh.old b/tests/overwrite_alpine.sh.old new file mode 100644 index 0000000..e70d00d --- /dev/null +++ b/tests/overwrite_alpine.sh.old @@ -0,0 +1,125 @@ +#!/bin/sh +# -O/--overwrite tests for syspkg and gpkg. Runs inside a THROWAWAY alpine +# container as root — it displaces Alpine's own /usr/include and /usr/lib +# files, so never run it on a real system. +# +# Run it twice: once as-is (/glacier on the same filesystem as /usr, so +# displacing is a rename()), once with --tmpfs /glacier (different +# filesystem, so it exercises the copy+unlink EXDEV fallback): +# +# docker run --rm \ +# -v /home/lw/Projects/glacier-ng:/src:ro \ +# -v /home/lw/Projects/libglacier-ng:/libsrc:ro \ +# -v /home/lw/Projects/glacier-ng/tests/overwrite_alpine.sh:/t.sh:ro \ +# [--tmpfs /glacier:exec] alpine:latest sh /t.sh +# +# No gpkg/user-scope case: a user's links tree is swapped out wholesale on +# every commit, so nothing non-glacier can be sitting at a link +# destination when the post-commit relink runs. Only system-scope base +# packages, linking into /usr, can ever hit a conflict. +set -u +apk add --no-cache build-base luajit-dev libarchive-dev libconfig-dev linux-headers >/dev/null 2>&1 \ + || { echo "apk failed"; exit 1; } + +FAILS=0 +hr() { echo; echo "=== $* ==="; } +check() { # check DESCRIPTION COMMAND... + desc=$1; shift + if "$@"; then echo "PASS: $desc"; else echo "FAIL: $desc"; FAILS=$((FAILS + 1)); fi +} +# Strip the per-path "Refusing to overwrite" flood; print how many there were. +quiet() { "$@" 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | awk '/Refusing to overwrite non-glacier/ {n++; next} {print} END {if (n) print "(" n " x \"Refusing to overwrite non-glacier path\")"}'; } +# run CMD: like quiet, but keeps the output in $OUT and the exit status +# in $STATUS. +run() { + OUT=$(sh -c "$1; echo \"exit=\$?\"" 2>&1 | sed 's/\x1b\[[0-9;]*m//g') + STATUS=$(echo "$OUT" | sed -n 's/^exit=//p' | tail -1) + OUT=$(echo "$OUT" | grep -v '^exit=') + echo "$OUT" | awk '/Refusing to overwrite non-glacier/ {n++; next} {print} END {if (n) print "(" n " x \"Refusing to overwrite non-glacier path\")"}' +} +last_line() { echo "$OUT" | tail -1; } +sha() { sha256sum "$1" | cut -d' ' -f1; } +is_reg() { [ -f "$1" ] && [ ! -L "$1" ]; } +links_into_store() { case "$(readlink "$1")" in "$2"/*) return 0 ;; esac; return 1; } + +hr "0. build libglacier-ng against musl" +cp -a /libsrc /build && cd /build && make clean >/dev/null && make >/tmp/make.log 2>&1 \ + && echo "build ok" || { tail -30 /tmp/make.log; exit 1; } +cp -a /src /opt/glacier +cp /build/build/lib/shared/libglacier_*.so /opt/glacier/lib/glacier/ +chown -R root:root /opt/glacier && chmod -R go-w /opt/glacier +# A throwaway key trusted for base (REPO_DESIGN.txt section 7), and the +# copies' sidecars signed with it. +mkdir -p /etc/glacier/keys +/build/build/bin/gsign -G -p /etc/glacier/keys/t.pub -s /root/t.sec -c t >/dev/null +printf 'repos = (\n\t{ name = "base"; keys = [ "t" ]; }\n);\n' > /etc/glacier/repos.conf +for s in /opt/glacier/*.gpkg.sha256 /opt/glacier/pkgs/*.gpkg.sha256; do + [ -e "$s" ] && /build/build/bin/gsign -S -s /root/t.sec -m "$s" >/dev/null +done +cd /opt/glacier +SP=/opt/glacier/syspkg +SYS_STORE=/glacier/sys/store +DISP=$SYS_STORE/.displaced + +echo "/usr fs: $(stat -f -c %i /usr 2>/dev/null) /glacier fs: $(mkdir -p /glacier; stat -f -c %i /glacier)" +$SP -n >/dev/null + +STDIO=/usr/include/stdio.h +LIBC=/usr/lib/libc.so # Alpine ships this as a symlink, not a file +ORIG_SHA=$(sha $STDIO) +ORIG_MODE=$(stat -c '%a %u %g' $STDIO) +ORIG_LIBC_TARGET=$(readlink $LIBC) + +hr "1. install base package without -O: originals untouched" +run "echo y | $SP -l pkgs/musl-1.2.5.gpkg" +check "stdio.h still Alpine's regular file" is_reg $STDIO +NREF=$(echo "$OUT" | grep -c 'Refusing to overwrite non-glacier') +check "refusals end in an error, not \"Completed\"" test "$(last_line)" = "[x] $NREF paths were not linked." +check "and exit status 1" test "$STATUS" = 1 +check "no displaced tree created" test ! -e $DISP + +hr "2. reinstall with -O: originals displaced, glacier symlinks in place" +run "echo y | $SP -O -l pkgs/musl-1.2.5.gpkg" +check "nothing refused: Completed with no errors" test "$(last_line)" = "[✓] Completed with no errors." +check "and exit status 0" test "$STATUS" = 0 +check "stdio.h is now a glacier symlink" links_into_store $STDIO $SYS_STORE +check "original stdio.h kept, content intact" test "$(sha $DISP$STDIO 2>/dev/null)" = "$ORIG_SHA" +check "original stdio.h mode/owner kept" test "$(stat -c '%a %u %g' $DISP$STDIO 2>/dev/null)" = "$ORIG_MODE" +check "libc.so (a foreign symlink) displaced as a symlink" test "$(readlink $DISP$LIBC 2>/dev/null)" = "$ORIG_LIBC_TARGET" +check "libc.so now a glacier symlink" links_into_store $LIBC $SYS_STORE +check "overwrite marker consumed" test -z "$(find $SYS_STORE -name .glacier-overwrite)" + +hr "3. unrelated transaction: displaced originals survive stage seeding" +quiet sh -c "echo y | $SP -l kilo-0.0.1.gpkg" +check "displaced stdio.h still present after another commit" test "$(sha $DISP$STDIO 2>/dev/null)" = "$ORIG_SHA" +check "stdio.h still a glacier symlink" links_into_store $STDIO $SYS_STORE + +hr "4. -O on a later install doesn't spread to other packages" +# Only /usr can hold a foreign file at relink time (the links trees are +# swapped out wholesale on every commit), so plant one at a path musl +# links to, then install a DIFFERENT package with -O: musl's path must +# stay refused, since musl itself wasn't installed with -O this time. +FOREIGN=/usr/include/libintl.h +rm -f $FOREIGN && echo foreign > $FOREIGN +run "echo y | $SP -O -l pkgs/sbase-0.0.1.gpkg" +check "foreign file at a musl path untouched" test "$(cat $FOREIGN)" = foreign +check "musl's standing conflict doesn't fail sbase's install" test "$STATUS" = 0 +check "and not displaced" test ! -e $DISP$FOREIGN +rm -f $FOREIGN + +hr "5. remove: originals restored" +quiet sh -c "echo y | $SP -x musl" +check "stdio.h restored as a regular file" is_reg $STDIO +check "restored stdio.h content matches" test "$(sha $STDIO)" = "$ORIG_SHA" +check "restored stdio.h mode/owner match" test "$(stat -c '%a %u %g' $STDIO)" = "$ORIG_MODE" +check "libc.so restored as Alpine's symlink" test "$(readlink $LIBC)" = "$ORIG_LIBC_TARGET" +check "no musl originals left in displaced tree" test -z "$(find $DISP/usr -type f -o -type l 2>/dev/null | grep -v sbase)" +check "Alpine toolchain still works" sh -c 'echo "int main(void){return 0;}" | cc -x c - -o /tmp/a.out && /tmp/a.out' + +hr "6. help / usage" +$SP -h | grep -- --overwrite +./gpkg -h | grep -- --overwrite + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/recipe_alpine.sh b/tests/recipe_alpine.sh new file mode 100644 index 0000000..4c9a94e --- /dev/null +++ b/tests/recipe_alpine.sh @@ -0,0 +1,409 @@ +#!/bin/sh +# Recipe formats (BUILD_DESIGN.txt sections 3, 4 and 8; step 1): +# - gl_recipe_parse: the recipe's fields, strictly (unknown keys, +# missing required ones, bad names, versions, URLs, hashes, traits, +# IF conditions, arguments, @include and NUL are all refused); +# - gl_recipe_read: a bundle holds exactly NAME-VER/{recipe,build, +# patches/FILE}, regular files and directories only, the patches +# PATCHES lists, a build file for BUILD = "hooks", 16 MiB at most; +# - gl_index_parse: a REPO named X-src has BUILD_DEPS, TRAITS, IF and +# .grcp files; a binary index has none of them; +# - PKG_TRAITS in a manifest, read by gl_read_pkg_manifest; +# - grepo -r X-src indexes DIR's bundles, and syspkg -y accepts it. +# Runs INSIDE the Dockerfile.alpine_root image: +# +# docker run --rm -v "$PWD/tests/recipe_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +T=/tmp/rt +mkdir -p $T +SHA=sha256:$(printf '%064d' 0 | tr 0 a) + +# probe parse FILE | read BUNDLE | index REPO FILE | manifest GPKG +# prints "status=N" and the parsed fields. +cat > $T/probe.lua <<'EOF' +package.path = "/app/?.lua;" .. package.path +local ffi = require("ffi") +require("lib/glacier_cdef") +local pkg = ffi.load("/app/lib/glacier/libglacier_pkg.so") +local ist = ffi.load("/app/lib/glacier/libglacier_istoreutils.so") +local mode, a, b = arg[1], arg[2], arg[3] +local function slurp(p) local f = assert(io.open(p, "rb")); local s = f:read("*a"); f:close(); return s end +local function show(k, v) if v ~= nil then io.write(k, "=[", ffi.string(v), "]\n") end end +if mode == "parse" or mode == "read" then + local r = ffi.new("gl_recipe_t") + local st + if mode == "parse" then + -- parse FILE FIRST: FIRST is parsed before, in this process + if b then + local f = slurp(b) + pkg.gl_recipe_parse(f, #f, r) + end + local s = slurp(a) + st = pkg.gl_recipe_parse(s, #s, r) + else + st = ist.gl_recipe_read(a, r) + end + print("status=" .. tonumber(st)) + print("why=[" .. ffi.string(pkg.gl_recipe_error()) .. "]") + if st == 0 then + for _, k in ipairs({ "name", "ver", "repo", "desc", "maint", "copyright", + "sources", "patches", "build", "configure", "traits", "trait_args", + "deps", "build_deps", "confs" }) do + show(k, r[k]) + end + pkg.gl_recipe_free(r) + end +elseif mode == "index" then + local s = slurp(b) + local idx = ffi.new("gl_index_t") + local st = pkg.gl_index_parse(s, #s, a, idx) + print("status=" .. tonumber(st)) + if st == 0 then + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + show("file", p.file); show("deps", p.deps); show("confs", p.confs) + show("build_deps", p.build_deps); show("traits", p.traits) + end + pkg.gl_index_free(idx) + end +elseif mode == "manifest" then + local m = ffi.new("gl_pkg_t") + local st = ist.gl_read_pkg_manifest(a, m) + print("status=" .. tonumber(st)) + if st == 0 then + if m.pkg_traits == nil then print("traits=NULL") else show("traits", m.pkg_traits) end + ist.gl_free_pkg(m) + end +end +EOF +probe() { R luajit $T/probe.lua "$@"; } + +# A good recipe; variants are made from it with sed. +cat > $T/good < $T/minimal < $T/bad + probe parse $T/bad + check "refused: $1" has "status=3" + check "...because: $3" has "why=[$3" +} +bad "an unknown key" 's/^REPO = "extra";/REPO = "extra"; SOURCE = "x";/' 'unknown setting SOURCE]' +bad "a misspelt optional key" 's/^BUILD_DEPS/BUILDDEPS/' 'unknown setting BUILDDEPS]' +bad "no NAME" '/^NAME/d' 'NAME is missing]' +bad "no SOURCES" '/^SOURCES/,/^);/d' 'SOURCES is missing]' +bad "an empty SOURCES" '/^SOURCES/,/^);/c SOURCES = ();' 'SOURCES must be a non-empty list' +bad "no DESC" '/^DESC/d' 'DESC is missing]' +bad "an empty MAINT" 's/^MAINT = .*/MAINT = "";/' 'MAINT must be non-empty text without control characters]' +bad "a control character in DESC" 's/^DESC = .*/DESC = "a\\tb";/' 'DESC must be non-empty text' +bad "a name with a slash" 's/^NAME = .*/NAME = "a\/b";/' 'NAME must be a package name' +bad "NAME = .." 's/^NAME = .*/NAME = "..";/' 'NAME must be a package name' +bad "a two-part version" 's/^VER = .*/VER = "8.9";/' 'VER must be a version X.Y.Z' +bad "a version with a leading zero" 's/^VER = .*/VER = "8.09.0";/' 'VER must be a version X.Y.Z' +bad "a version with a tag" 's/^VER = .*/VER = "8.9.0-rc1";/' 'VER must be a version X.Y.Z' +bad "REPO naming a -src repository" 's/^REPO = .*/REPO = "extra-src";/' 'REPO must be the binary repository' +bad "an http:// source" 's|https://curl.se|http://curl.se|' 'SOURCES entry 1: URL must be https:// or file://' +bad "a source with no file name" 's|curl-8.9.0.tar.gz|curl/|' 'SOURCES entry 1: the URL must end in a file name' +bad "a source whose file name is .." 's|curl-8.9.0.tar.gz|..|' 'SOURCES entry 1: the URL must end in a file name' +bad "two sources with one file name" 's|extra-data.tar.gz|curl-8.9.0.tar.gz|' 'SOURCES entries 1 and 2 are both named curl-8.9.0.tar.gz]' +bad "a source without SHA256" "s|SHA256 = \"$SHA\"; },|},|" 'SOURCES entry 1 must have exactly URL and SHA256]' +bad "an uppercase hash" "/curl.se/s/$SHA/sha256:$(printf '%064d' 0 | tr 0 A)/" 'SOURCES entry 1: SHA256 must be "sha256:" followed by 64 lowercase hex digits]' +bad "a short hash" "/curl.se/s/$SHA/sha256:abc/" 'SOURCES entry 1: SHA256 must be' +bad "an unknown member in a source" 's|SHA256 = "\(sha256:[a-f]*\)"; },|SHA256 = "\1"; MIRROR = "x"; },|' 'SOURCES entry 1 must have exactly URL and SHA256]' +bad "a patch name with a slash" 's|01-a.patch|../a.patch|' 'PATCHES entry 1 must be a file name' +bad "a patch listed twice" 's|02-b.patch|01-a.patch|' 'PATCHES lists "01-a.patch" twice]' +bad "an unknown BUILD" 's/^BUILD = .*/BUILD = "scons";/' 'BUILD must be autotools, cmake, meson, make or hooks]' +bad "BUILD = \"\"" 's/^BUILD = .*/BUILD = "";/' 'BUILD must be autotools' +bad "a configure argument with a newline" 's|--disable-static|--a\\nb|' 'CONFIGURE entry 1 must be a non-empty string of printable ASCII' +bad "a configure argument with a tab" 's|--disable-static|--a\\tb|' 'CONFIGURE entry 1 must be' +bad "an empty configure argument" 's|"--disable-static"|""|' 'CONFIGURE entry 1 must be' +bad "an uppercase trait" 's/NAME = "ldap"/NAME = "LDAP"/' 'TRAITS entry 2: NAME must be 1-32 of a-z, 0-9 and _]' +bad "a trait name with a dash" 's/NAME = "ldap"/NAME = "no-ldap"/' 'TRAITS entry 2: NAME must be' +bad "a trait declared twice" 's/NAME = "ldap"/NAME = "ssl"/' 'TRAITS declares ssl twice]' +bad "a trait without DEFAULT" 's/ DEFAULT = false;//' 'TRAITS entry 2: DEFAULT must be true or false]' +bad "a DEFAULT that is not a boolean" 's/DEFAULT = false/DEFAULT = 0/' 'TRAITS entry 2: DEFAULT must be true or false]' +bad "an unknown member in a trait" 's/DEFAULT = false;/DEFAULT = false; USE = true;/' 'TRAITS entry 2 may only have NAME, DEFAULT, ON and OFF]' +bad "an IF naming no trait" 's/IF = "ssl"/IF = "tls"/' 'DEPS entry 2: IF "tls" names no trait in TRAITS]' +bad "an IF naming no trait, negated" 's/IF = "-ldap"/IF = "-tls"/' 'BUILD_DEPS entry 1: IF "-tls" names no trait' +bad "an IF that is not a string" 's/IF = "ssl"/IF = true/' 'DEPS entry 2: IF must be a string]' +bad "a dependency with an unsafe name" 's/"zlib"/"..\/zlib"/' 'DEPS entry 1: "../zlib" is not a valid package name]' +bad "a dependency without VER" 's/{ NAME = "zlib"; VER = "1.3.0"; }/{ NAME = "zlib"; }/' 'DEPS entry 1: VER is missing or not a string]' +bad "an unknown member in a dependency" 's/VER = "1.3.0"; }/VER = "1.3.0"; OPTIONAL = true; }/' 'DEPS entry 1 may only have NAME, VER and IF]' +# The included file is a valid part of a recipe, so only the @include +# refusal itself can stop it. +echo 'CONFS = ();' > $T/inc +bad "an @include line" "/^CONFS/d; 1i @include \"$T/inc\"" '@include is not allowed]' +bad "an indented @include line" "/^CONFS/d; 1i \\ @include \"$T/inc\"" '@include is not allowed]' +bad "a misspelt hash prefix" "/curl.se/s/$SHA/sha256i:$(printf '%064d' 0 | tr 0 a)/" 'SOURCES entry 1: SHA256 must be "sha256:" followed by 64 lowercase hex digits]' +bad "a libconfig syntax error" 's/^VER = "8.9.0";/VER = = "8.9.0";/' 'line 2: syntax error]' +bad "a missing REPO" '/^REPO/d' 'REPO is missing]' +bad "a non-string COPYRIGHT" 's/^COPYRIGHT = .*/COPYRIGHT = 1;/' 'COPYRIGHT must be non-empty text' +bad "PATCHES as a string" 's/^PATCHES = .*/PATCHES = "01-a.patch";/' 'PATCHES must be a list of strings]' +bad "an ON that is not a list" 's/ON = \[ "--with-openssl" \]/ON = "--with-openssl"/' 'TRAITS entry 1: ON must be a list of strings]' +bad "an empty OFF argument" 's/OFF = \[ "--without-ssl" \]/OFF = [ "" ]/' 'TRAITS entry 1: OFF entry 1 must be a non-empty string' +bad "DEPS as a string" 's/^DEPS = .*/DEPS = "zlib";/' 'DEPS must be a list of { NAME; VER; } groups]' +# Untrusted text quoted in the reason is printable ASCII only. +bad "an escape sequence in a dependency name" 's/"zlib"/"\\x1b[31mz"/' 'DEPS entry 1: "?[31mz" is not a valid package name]' +bad "SOURCES as a string" '/^SOURCES/,/^);/c SOURCES = "https://a/b.tar.gz";' 'SOURCES must be a non-empty list' +{ + sed '/^TRAITS/,/^);/d; /IF =/d; s/, { NAME = "libressl"; VER = "3.9.0"; IF = "ssl"; }//' $T/good | grep -v BUILD_DEPS + printf 'TRAITS = (' + i=0; sep="" + while [ $i -lt 33 ]; do printf '%s { NAME = "t%d"; DEFAULT = false; }' "$sep" $i; sep=","; i=$((i+1)); done + printf ' );\n' +} > $T/many +probe parse $T/many +check "refused: 33 traits" has "status=3" +check "...because: more than 32" has "why=[TRAITS has more than 32 traits]" +sed 's/ t32.*DEFAULT = false; }/ );/; s/, { NAME = "t32"; DEFAULT = false; }//' $T/many > $T/32 +probe parse $T/32 +check "32 traits parse" has "status=0" +printf 'NAME = "a\0b";\n' > $T/nul +probe parse $T/nul +check "refused: a NUL byte" has "status=3" +check "...because: a NUL byte" has "why=[the recipe contains a NUL byte]" +head -c $((1024*1024+1)) /dev/zero | tr '\0' ' ' > $T/huge +cat $T/minimal >> $T/huge +probe parse $T/huge +check "refused: more than 1 MiB" has "status=3" +check "...because: too large" has "why=[the recipe is larger than 1048576 bytes]" +probe parse $T/good $T/huge +check "a success after a failure leaves no reason" has "why=[]" + +hr "gl_recipe_read" +# mkb DIR -> bundle at $T/b.grcp, made from a tree in $T/tree/DIR +mkb() { (cd $T/tree && tar czf $T/b.grcp "$@"); } +fresh() { + rm -rf $T/tree && mkdir -p $T/tree/curl-8.9.0/patches + cp $T/good $T/tree/curl-8.9.0/recipe + echo a > $T/tree/curl-8.9.0/patches/01-a.patch + echo b > $T/tree/curl-8.9.0/patches/02-b.patch +} +fresh; mkb curl-8.9.0 +probe read $T/b.grcp +check "a good bundle reads" has "status=0" +check "...with no reason" has "why=[]" +check "...with its recipe" has "name=[curl]" +fresh; (cd $T/tree && tar czf $T/b.grcp curl-8.9.0/recipe curl-8.9.0/patches/01-a.patch curl-8.9.0/patches/02-b.patch) +probe read $T/b.grcp +check "no directory entries: still reads" has "status=0" +fresh; printf 'configure() { :; }\n' > $T/tree/curl-8.9.0/build; mkb curl-8.9.0 +probe read $T/b.grcp +check "a build file is allowed" has "status=0" +fresh; sed -i 's/^BUILD = .*/BUILD = "hooks";/' $T/tree/curl-8.9.0/recipe; mkb curl-8.9.0 +probe read $T/b.grcp +check "refused: BUILD = hooks without a build file" has "status=2" +check "...because: no build file" has 'why=[BUILD = "hooks" needs a build file]' +printf 'compile() { :; }\n' > $T/tree/curl-8.9.0/build; mkb curl-8.9.0 +probe read $T/b.grcp +check "BUILD = hooks with a build file reads" has "status=0" + +# badb DESCRIPTION WHY [STATUS] +badb() { + probe read $T/b.grcp + check "refused: $1" has "status=${3:-2}" + check "...because: $2" has "why=[$2" +} +fresh; rm $T/tree/curl-8.9.0/patches/02-b.patch; ln -s /etc/shadow $T/tree/curl-8.9.0/patches/02-b.patch; mkb curl-8.9.0 +badb "a symlink (as a listed patch)" 'curl-8.9.0/patches/02-b.patch is not a regular file or directory]' +fresh; ln $T/tree/curl-8.9.0/patches/01-a.patch $T/tree/curl-8.9.0/build; mkb curl-8.9.0 +badb "a hardlink" 'curl-8.9.0/build is not a regular file or directory]' +fresh; echo x > $T/tree/curl-8.9.0/README; mkb curl-8.9.0 +badb "an extra file at the top" 'curl-8.9.0/README is not allowed (only recipe, build and patches/FILE)]' +fresh; mkdir $T/tree/curl-8.9.0/files; mkb curl-8.9.0 +badb "an extra directory" 'curl-8.9.0/files/ is not allowed' +fresh; mkdir $T/tree/curl-8.9.0/patches/sub; mkb curl-8.9.0 +badb "a directory inside patches/" 'curl-8.9.0/patches/sub/ is not allowed' +fresh; echo c > $T/tree/curl-8.9.0/patches/03-c.patch; mkb curl-8.9.0 +badb "a patch PATCHES does not list" 'patches/03-c.patch is not in PATCHES]' +fresh; rm $T/tree/curl-8.9.0/patches/02-b.patch; mkb curl-8.9.0 +badb "a listed patch missing" 'PATCHES lists 02-b.patch, but there is no patches/02-b.patch]' +fresh; rm $T/tree/curl-8.9.0/recipe; mkb curl-8.9.0 +badb "no recipe" 'it has no recipe]' +fresh; mv $T/tree/curl-8.9.0 $T/tree/curl-9.0.0; mkb curl-9.0.0 +badb "a top directory that is not NAME-VER" 'its top directory is curl-9.0.0, but the recipe says curl-8.9.0]' +fresh; mkdir -p $T/tree/other; echo x > $T/tree/other/recipe; mkb curl-8.9.0 other +badb "two top directories" 'it has two top directories' +fresh; (cd $T/tree && tar czf $T/b.grcp curl-8.9.0 --transform 's|^curl-8.9.0/patches/02-b.patch|curl-8.9.0/../02-b.patch|') +badb "a .. entry" 'curl-8.9.0/../02-b.patch is not allowed' +fresh; (cd $T/tree && tar czf $T/b.grcp -P curl-8.9.0 --transform 's|^curl-8.9.0/patches/02-b.patch|/tmp/02-b.patch|') +badb "an absolute entry" '/tmp/02-b.patch is not under a NAME-VER directory]' +fresh; (cd $T/tree && tar czf $T/b.grcp curl-8.9.0 curl-8.9.0/patches/01-a.patch) +# tar stores the second copy as a hardlink to the first +badb "an entry twice" 'curl-8.9.0/patches/01-a.patch is not a regular file or directory]' +fresh; mkfifo $T/tree/curl-8.9.0/build; mkb curl-8.9.0 +badb "a fifo" 'curl-8.9.0/build is not a regular file or directory]' +fresh; head -c $((16*1024*1024)) /dev/zero > $T/tree/curl-8.9.0/patches/02-b.patch; mkb curl-8.9.0 +badb "more than 16 MiB in all" 'its files add up to more than 16777216 bytes]' +echo junk > $T/b.grcp +badb "junk" 'not a gzip tar' 1 +fresh; sed -i 's/^REPO = .*/REPO = "extra"; COLOR = "red";/' $T/tree/curl-8.9.0/recipe; mkb curl-8.9.0 +badb "a malformed recipe" 'unknown setting COLOR]' 3 + +hr "-src indexes" +cat > $T/src.idx < $T/bad.idx + probe index $2 $T/bad.idx + check "refused: $1" has "status=1" +} +badi "no BUILD_DEPS" extra-src 's/BUILD_DEPS = .*//' +badi "no TRAITS" extra-src 's/TRAITS = .*/}/' +badi "a .gpkg FILE" extra-src 's/curl-8.9.0.grcp/curl-8.9.0.gpkg/' +badi "an IF naming no trait" extra-src 's/IF = "ssl"/IF = "tls"/' +badi "ON in an index trait" extra-src 's/DEFAULT = true;/DEFAULT = true; ON = [ "x" ];/' +badi "REPO = -src alone" -src 's/"extra-src"/"-src"/' +# The same entry in a binary index: every recipe field is malformed. +sed 's/extra-src/extra/; s/grcp/gpkg/; s/, { NAME = "libressl"; VER = "3.9.0"; IF = "ssl"; }//; s/ IF = "-ldap";//' $T/src.idx > $T/bin.idx +probe index extra $T/bin.idx +check "refused: BUILD_DEPS and TRAITS in a binary index" has "status=1" +sed -i 's/BUILD_DEPS = .*//; s/TRAITS = .*/}/' $T/bin.idx +cp $T/bin.idx $T/good-bin.idx +sed -i 's/{ NAME = "zlib"; VER = "1.3.0"; }/{ NAME = "zlib"; VER = "1.3.0"; IF = "ssl"; }/' $T/bin.idx +probe index extra $T/bin.idx +check "refused: IF in a binary index" has "status=1" +probe index extra $T/good-bin.idx +check "...without them, it is a good binary index" has "status=0" +check "...whose build deps and traits are empty" sh -c 'echo "$0" | grep -q "^build_deps=\[\]" && echo "$0" | grep -q "^traits=\[\]"' "$OUT" + +hr "PKG_TRAITS" +mkman() { + rm -rf $T/m && mkdir -p $T/m/hi-1.0.0/files + printf 'PKG_NAME = "hi"; PKG_VER = "1.0.0"; PKG_REPO = "extra";\nPKG_DEPS = (); PKG_CONFS = ();\n%s\n' "$1" > $T/m/hi-1.0.0/manifest.gpm.cfg + tar czf $T/m.gpkg -C $T/m hi-1.0.0 +} +mkman 'PKG_TRAITS = [ "ssl", "-ldap" ];' +probe manifest $T/m.gpkg +check "PKG_TRAITS is read" sh -c 'echo "$0" | tr "\n" "|" | grep -qF "traits=[ssl|-ldap|]"' "$OUT" +mkman '' +probe manifest $T/m.gpkg +check "...and absent, NULL" has "traits=NULL" +mkman 'PKG_TRAITS = [ ];' +probe manifest $T/m.gpkg +check "...an empty list, empty" has "traits=[]" +for v in '[ "ssl", "-ssl" ]' '[ "SSL" ]' '[ "--ssl" ]' '[ "" ]' '"ssl"' '[ 1 ]'; do + mkman "PKG_TRAITS = $v;" + probe manifest $T/m.gpkg + check "refused: PKG_TRAITS = $v" has "status=2" +done + +hr "grepo -r X-src" +K=/etc/glacier/keys +D=/srv/extra-src +mkdir -p $D && chmod 755 /srv $D +gsign -G -p $K/srckey.pub -s /root/srckey.sec -c srckey >/dev/null +fresh; (cd $T/tree && tar czf $D/curl-8.9.0.grcp curl-8.9.0) +rm -rf $T/tree/hi-1.0.0 && mkdir -p $T/tree/hi-1.0.0 && cp $T/minimal $T/tree/hi-1.0.0/recipe +(cd $T/tree && tar czf $D/hi-1.0.0.grcp hi-1.0.0) +cp /dev/null $D/ignored.gpkg +R grepo -s /root/srckey.sec -r extra-src $D +check "grepo indexes a -src repository" rc 0 +check "...both bundles" has "2 packages" +probe index extra-src $D/repo.idx +check "...an index gl_index_parse accepts" has "status=0" +check "...with the recipe's relations and traits" sh -c 'echo "$0" | tr "\n" "|" | grep -qF "deps=[zlib 1.3.0|libressl 3.9.0 ssl|]|confs=[curl-old 0.0.0|]|build_deps=[perl 5.40.0 -ldap|]|traits=[ssl 1|ldap 0|]"' "$OUT" +check "...each bundle's hash" grep -qF "SHA256 = \"sha256:$(sha256sum $D/hi-1.0.0.grcp | cut -c1-64)\"" $D/repo.idx +mv $D/hi-1.0.0.grcp $D/hi-2.0.0.grcp +R grepo -s /root/srckey.sec -r extra-src $D +check "refused: a misnamed bundle" has "[x] $D/hi-2.0.0.grcp must be named hi-1.0.0.grcp, as its recipe says." +rm $D/hi-2.0.0.grcp +sed 's/REPO = "extra"/REPO = "community"/' $T/minimal > $T/tree/hi-1.0.0/recipe +(cd $T/tree && tar czf $D/hi-1.0.0.grcp hi-1.0.0) +R grepo -s /root/srckey.sec -r extra-src $D +check "refused: a recipe of another repository" has "[x] $D/hi-1.0.0.grcp builds community packages, not extra." +echo junk > $D/hi-1.0.0.grcp +R grepo -s /root/srckey.sec -r extra-src $D +check "refused: a bundle that can't be read" has "[x] $D/hi-1.0.0.grcp is not a readable recipe bundle: not a gzip tar" +sed 's/SHA256 = "sha256:/SHA256 = "sha256i:/' $T/minimal > $T/tree/hi-1.0.0/recipe +(cd $T/tree && tar czf $D/hi-1.0.0.grcp hi-1.0.0) +R grepo -s /root/srckey.sec -r extra-src $D +check "refused: a malformed recipe, saying why" has '[x] '"$D"'/hi-1.0.0.grcp is a bundle with a malformed recipe: SOURCES entry 1: SHA256 must be "sha256:" followed by 64 lowercase hex digits.' +cp $T/minimal $T/tree/hi-1.0.0/recipe; echo x > $T/tree/hi-1.0.0/notes +(cd $T/tree && tar czf $D/hi-1.0.0.grcp hi-1.0.0) +R grepo -s /root/srckey.sec -r extra-src $D +check "refused: an invalid bundle, saying why" has "[x] $D/hi-1.0.0.grcp is not a valid recipe bundle: hi-1.0.0/notes is not allowed (only recipe, build and patches/FILE)." +rm -rf $D/hi-1.0.0.grcp $T/tree/hi-1.0.0/notes +R grepo -s /root/srckey.sec -r extra-src $D + +hr "syspkg -y with a -src repository" +syspkg -n >/dev/null +printf 'repos = (\n\t{ name = "extra-src"; url = "file:///srv/extra-src"; keys = [ "srckey" ]; }\n);\n' > /etc/glacier/repos.conf +chmod 644 /etc/glacier/repos.conf +R syspkg -y +check "syspkg -y accepts a -src index" rc 0 +check "...and stores it" cmp $D/repo.idx /glacier/sys/repos/extra-src.idx + +echo +if [ $FAILS -eq 0 ]; then echo "ALL PASSED"; else echo "$FAILS FAILED"; fi +[ $FAILS -eq 0 ] diff --git a/tests/recipe_alpine.sh.old b/tests/recipe_alpine.sh.old new file mode 100644 index 0000000..e387947 --- /dev/null +++ b/tests/recipe_alpine.sh.old @@ -0,0 +1,370 @@ +#!/bin/sh +# Recipe formats (BUILD_DESIGN.txt sections 3, 4 and 8; step 1): +# - gl_recipe_parse: the recipe's fields, strictly (unknown keys, +# missing required ones, bad names, versions, URLs, hashes, traits, +# IF conditions, arguments, @include and NUL are all refused); +# - gl_recipe_read: a bundle holds exactly NAME-VER/{recipe,build, +# patches/FILE}, regular files and directories only, the patches +# PATCHES lists, a build file for BUILD = "hooks", 16 MiB at most; +# - gl_index_parse: a REPO named X-src has BUILD_DEPS, TRAITS, IF and +# .grcp files; a binary index has none of them; +# - PKG_TRAITS in a manifest, read by gl_read_pkg_manifest; +# - grepo -r X-src indexes DIR's bundles, and syspkg -y accepts it. +# Runs INSIDE the Dockerfile.alpine_root image: +# +# docker run --rm -v "$PWD/tests/recipe_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +T=/tmp/rt +mkdir -p $T +SHA=sha256:$(printf '%064d' 0 | tr 0 a) + +# probe parse FILE | read BUNDLE | index REPO FILE | manifest GPKG +# prints "status=N" and the parsed fields. +cat > $T/probe.lua <<'EOF' +package.path = "/app/?.lua;" .. package.path +local ffi = require("ffi") +require("lib/glacier_cdef") +local pkg = ffi.load("/app/lib/glacier/libglacier_pkg.so") +local ist = ffi.load("/app/lib/glacier/libglacier_istoreutils.so") +local mode, a, b = arg[1], arg[2], arg[3] +local function slurp(p) local f = assert(io.open(p, "rb")); local s = f:read("*a"); f:close(); return s end +local function show(k, v) if v ~= nil then io.write(k, "=[", ffi.string(v), "]\n") end end +if mode == "parse" or mode == "read" then + local r = ffi.new("gl_recipe_t") + local st + if mode == "parse" then + local s = slurp(a) + st = pkg.gl_recipe_parse(s, #s, r) + else + st = ist.gl_recipe_read(a, r) + end + print("status=" .. tonumber(st)) + if st == 0 then + for _, k in ipairs({ "name", "ver", "repo", "desc", "maint", "copyright", + "sources", "patches", "build", "configure", "traits", "trait_args", + "deps", "build_deps", "confs" }) do + show(k, r[k]) + end + pkg.gl_recipe_free(r) + end +elseif mode == "index" then + local s = slurp(b) + local idx = ffi.new("gl_index_t") + local st = pkg.gl_index_parse(s, #s, a, idx) + print("status=" .. tonumber(st)) + if st == 0 then + for k = 0, tonumber(idx.npkgs) - 1 do + local p = idx.pkgs[k] + show("file", p.file); show("deps", p.deps); show("confs", p.confs) + show("build_deps", p.build_deps); show("traits", p.traits) + end + pkg.gl_index_free(idx) + end +elseif mode == "manifest" then + local m = ffi.new("gl_pkg_t") + local st = ist.gl_read_pkg_manifest(a, m) + print("status=" .. tonumber(st)) + if st == 0 then + if m.pkg_traits == nil then print("traits=NULL") else show("traits", m.pkg_traits) end + ist.gl_free_pkg(m) + end +end +EOF +probe() { R luajit $T/probe.lua "$@"; } + +# A good recipe; variants are made from it with sed. +cat > $T/good < $T/minimal < $T/bad + probe parse $T/bad + check "refused: $1" has "status=3" +} +bad "an unknown key" 's/^REPO = "extra";/REPO = "extra"; SOURCE = "x";/' +bad "a misspelt optional key" 's/^BUILD_DEPS/BUILDDEPS/' +bad "no NAME" '/^NAME/d' +bad "no SOURCES" '/^SOURCES/,/^);/d' +bad "an empty SOURCES" '/^SOURCES/,/^);/c SOURCES = ();' +bad "no DESC" '/^DESC/d' +bad "an empty MAINT" 's/^MAINT = .*/MAINT = "";/' +bad "a control character in DESC" 's/^DESC = .*/DESC = "a\\tb";/' +bad "a name with a slash" 's/^NAME = .*/NAME = "a\/b";/' +bad "NAME = .." 's/^NAME = .*/NAME = "..";/' +bad "a two-part version" 's/^VER = .*/VER = "8.9";/' +bad "a version with a leading zero" 's/^VER = .*/VER = "8.09.0";/' +bad "a version with a tag" 's/^VER = .*/VER = "8.9.0-rc1";/' +bad "REPO naming a -src repository" 's/^REPO = .*/REPO = "extra-src";/' +bad "an http:// source" 's|https://curl.se|http://curl.se|' +bad "a source with no file name" 's|curl-8.9.0.tar.gz|curl/|' +bad "a source whose file name is .." 's|curl-8.9.0.tar.gz|..|' +bad "two sources with one file name" 's|extra-data.tar.gz|curl-8.9.0.tar.gz|' +bad "a source without SHA256" "s|SHA256 = \"$SHA\"; },|},|" +bad "an uppercase hash" "/curl.se/s/$SHA/sha256:$(printf '%064d' 0 | tr 0 A)/" +bad "a short hash" "/curl.se/s/$SHA/sha256:abc/" +bad "an unknown member in a source" 's|SHA256 = "\(sha256:[a-f]*\)"; },|SHA256 = "\1"; MIRROR = "x"; },|' +bad "a patch name with a slash" 's|01-a.patch|../a.patch|' +bad "a patch listed twice" 's|02-b.patch|01-a.patch|' +bad "an unknown BUILD" 's/^BUILD = .*/BUILD = "scons";/' +bad "BUILD = \"\"" 's/^BUILD = .*/BUILD = "";/' +bad "a configure argument with a newline" 's|--disable-static|--a\\nb|' +bad "a configure argument with a tab" 's|--disable-static|--a\\tb|' +bad "an empty configure argument" 's|"--disable-static"|""|' +bad "an uppercase trait" 's/NAME = "ldap"/NAME = "LDAP"/' +bad "a trait name with a dash" 's/NAME = "ldap"/NAME = "no-ldap"/' +bad "a trait declared twice" 's/NAME = "ldap"/NAME = "ssl"/' +bad "a trait without DEFAULT" 's/ DEFAULT = false;//' +bad "a DEFAULT that is not a boolean" 's/DEFAULT = false/DEFAULT = 0/' +bad "an unknown member in a trait" 's/DEFAULT = false;/DEFAULT = false; USE = true;/' +bad "an IF naming no trait" 's/IF = "ssl"/IF = "tls"/' +bad "an IF naming no trait, negated" 's/IF = "-ldap"/IF = "-tls"/' +bad "an IF that is not a string" 's/IF = "ssl"/IF = true/' +bad "a dependency with an unsafe name" 's/"zlib"/"..\/zlib"/' +bad "a dependency without VER" 's/{ NAME = "zlib"; VER = "1.3.0"; }/{ NAME = "zlib"; }/' +bad "an unknown member in a dependency" 's/VER = "1.3.0"; }/VER = "1.3.0"; OPTIONAL = true; }/' +# The included file is a valid part of a recipe, so only the @include +# refusal itself can stop it. +echo 'CONFS = ();' > $T/inc +bad "an @include line" "/^CONFS/d; 1i @include \"$T/inc\"" +bad "an indented @include line" "/^CONFS/d; 1i \\ @include \"$T/inc\"" +bad "SOURCES as a string" '/^SOURCES/,/^);/c SOURCES = "https://a/b.tar.gz";' +{ + sed '/^TRAITS/,/^);/d; /IF =/d; s/, { NAME = "libressl"; VER = "3.9.0"; IF = "ssl"; }//' $T/good | grep -v BUILD_DEPS + printf 'TRAITS = (' + i=0; sep="" + while [ $i -lt 33 ]; do printf '%s { NAME = "t%d"; DEFAULT = false; }' "$sep" $i; sep=","; i=$((i+1)); done + printf ' );\n' +} > $T/many +probe parse $T/many +check "refused: 33 traits" has "status=3" +sed 's/ t32.*DEFAULT = false; }/ );/; s/, { NAME = "t32"; DEFAULT = false; }//' $T/many > $T/32 +probe parse $T/32 +check "32 traits parse" has "status=0" +printf 'NAME = "a\0b";\n' > $T/nul +probe parse $T/nul +check "refused: a NUL byte" has "status=3" +head -c $((1024*1024+1)) /dev/zero | tr '\0' ' ' > $T/huge +cat $T/minimal >> $T/huge +probe parse $T/huge +check "refused: more than 1 MiB" has "status=3" + +hr "gl_recipe_read" +# mkb DIR -> bundle at $T/b.grcp, made from a tree in $T/tree/DIR +mkb() { (cd $T/tree && tar czf $T/b.grcp "$@"); } +fresh() { + rm -rf $T/tree && mkdir -p $T/tree/curl-8.9.0/patches + cp $T/good $T/tree/curl-8.9.0/recipe + echo a > $T/tree/curl-8.9.0/patches/01-a.patch + echo b > $T/tree/curl-8.9.0/patches/02-b.patch +} +fresh; mkb curl-8.9.0 +probe read $T/b.grcp +check "a good bundle reads" has "status=0" +check "...with its recipe" has "name=[curl]" +fresh; (cd $T/tree && tar czf $T/b.grcp curl-8.9.0/recipe curl-8.9.0/patches/01-a.patch curl-8.9.0/patches/02-b.patch) +probe read $T/b.grcp +check "no directory entries: still reads" has "status=0" +fresh; printf 'configure() { :; }\n' > $T/tree/curl-8.9.0/build; mkb curl-8.9.0 +probe read $T/b.grcp +check "a build file is allowed" has "status=0" +fresh; sed -i 's/^BUILD = .*/BUILD = "hooks";/' $T/tree/curl-8.9.0/recipe; mkb curl-8.9.0 +probe read $T/b.grcp +check "refused: BUILD = hooks without a build file" has "status=2" +printf 'compile() { :; }\n' > $T/tree/curl-8.9.0/build; mkb curl-8.9.0 +probe read $T/b.grcp +check "BUILD = hooks with a build file reads" has "status=0" + +badb() { probe read $T/b.grcp; check "refused: $1" has "status=${2:-2}"; } +fresh; rm $T/tree/curl-8.9.0/patches/02-b.patch; ln -s /etc/shadow $T/tree/curl-8.9.0/patches/02-b.patch; mkb curl-8.9.0 +badb "a symlink (as a listed patch)" +fresh; ln $T/tree/curl-8.9.0/patches/01-a.patch $T/tree/curl-8.9.0/build; mkb curl-8.9.0 +badb "a hardlink" +fresh; echo x > $T/tree/curl-8.9.0/README; mkb curl-8.9.0 +badb "an extra file at the top" +fresh; mkdir $T/tree/curl-8.9.0/files; mkb curl-8.9.0 +badb "an extra directory" +fresh; mkdir $T/tree/curl-8.9.0/patches/sub; mkb curl-8.9.0 +badb "a directory inside patches/" +fresh; echo c > $T/tree/curl-8.9.0/patches/03-c.patch; mkb curl-8.9.0 +badb "a patch PATCHES does not list" +fresh; rm $T/tree/curl-8.9.0/patches/02-b.patch; mkb curl-8.9.0 +badb "a listed patch missing" +fresh; rm $T/tree/curl-8.9.0/recipe; mkb curl-8.9.0 +badb "no recipe" +fresh; mv $T/tree/curl-8.9.0 $T/tree/curl-9.0.0; mkb curl-9.0.0 +badb "a top directory that is not NAME-VER" +fresh; mkdir -p $T/tree/other; echo x > $T/tree/other/recipe; mkb curl-8.9.0 other +badb "two top directories" +fresh; (cd $T/tree && tar czf $T/b.grcp curl-8.9.0 --transform 's|^curl-8.9.0/patches/02-b.patch|curl-8.9.0/../02-b.patch|') +badb "a .. entry" +fresh; (cd $T/tree && tar czf $T/b.grcp -P curl-8.9.0 --transform 's|^curl-8.9.0/patches/02-b.patch|/tmp/02-b.patch|') +badb "an absolute entry" +fresh; (cd $T/tree && tar czf $T/b.grcp curl-8.9.0 curl-8.9.0/patches/01-a.patch) +badb "an entry twice" +fresh; mkfifo $T/tree/curl-8.9.0/build; mkb curl-8.9.0 +badb "a fifo" +fresh; head -c $((16*1024*1024)) /dev/zero > $T/tree/curl-8.9.0/patches/02-b.patch; mkb curl-8.9.0 +badb "more than 16 MiB in all" +echo junk > $T/b.grcp +badb "junk" 1 +fresh; sed -i 's/^REPO = .*/REPO = "extra"; COLOR = "red";/' $T/tree/curl-8.9.0/recipe; mkb curl-8.9.0 +badb "a malformed recipe" 3 + +hr "-src indexes" +cat > $T/src.idx < $T/bad.idx + probe index $2 $T/bad.idx + check "refused: $1" has "status=1" +} +badi "no BUILD_DEPS" extra-src 's/BUILD_DEPS = .*//' +badi "no TRAITS" extra-src 's/TRAITS = .*/}/' +badi "a .gpkg FILE" extra-src 's/curl-8.9.0.grcp/curl-8.9.0.gpkg/' +badi "an IF naming no trait" extra-src 's/IF = "ssl"/IF = "tls"/' +badi "ON in an index trait" extra-src 's/DEFAULT = true;/DEFAULT = true; ON = [ "x" ];/' +badi "REPO = -src alone" -src 's/"extra-src"/"-src"/' +# The same entry in a binary index: every recipe field is malformed. +sed 's/extra-src/extra/; s/grcp/gpkg/; s/, { NAME = "libressl"; VER = "3.9.0"; IF = "ssl"; }//; s/ IF = "-ldap";//' $T/src.idx > $T/bin.idx +probe index extra $T/bin.idx +check "refused: BUILD_DEPS and TRAITS in a binary index" has "status=1" +sed -i 's/BUILD_DEPS = .*//; s/TRAITS = .*/}/' $T/bin.idx +cp $T/bin.idx $T/good-bin.idx +sed -i 's/{ NAME = "zlib"; VER = "1.3.0"; }/{ NAME = "zlib"; VER = "1.3.0"; IF = "ssl"; }/' $T/bin.idx +probe index extra $T/bin.idx +check "refused: IF in a binary index" has "status=1" +probe index extra $T/good-bin.idx +check "...without them, it is a good binary index" has "status=0" +check "...whose build deps and traits are empty" sh -c 'echo "$0" | grep -q "^build_deps=\[\]" && echo "$0" | grep -q "^traits=\[\]"' "$OUT" + +hr "PKG_TRAITS" +mkman() { + rm -rf $T/m && mkdir -p $T/m/hi-1.0.0/files + printf 'PKG_NAME = "hi"; PKG_VER = "1.0.0"; PKG_REPO = "extra";\nPKG_DEPS = (); PKG_CONFS = ();\n%s\n' "$1" > $T/m/hi-1.0.0/manifest.gpm.cfg + tar czf $T/m.gpkg -C $T/m hi-1.0.0 +} +mkman 'PKG_TRAITS = [ "ssl", "-ldap" ];' +probe manifest $T/m.gpkg +check "PKG_TRAITS is read" sh -c 'echo "$0" | tr "\n" "|" | grep -qF "traits=[ssl|-ldap|]"' "$OUT" +mkman '' +probe manifest $T/m.gpkg +check "...and absent, NULL" has "traits=NULL" +mkman 'PKG_TRAITS = [ ];' +probe manifest $T/m.gpkg +check "...an empty list, empty" has "traits=[]" +for v in '[ "ssl", "-ssl" ]' '[ "SSL" ]' '[ "--ssl" ]' '[ "" ]' '"ssl"' '[ 1 ]'; do + mkman "PKG_TRAITS = $v;" + probe manifest $T/m.gpkg + check "refused: PKG_TRAITS = $v" has "status=2" +done + +hr "grepo -r X-src" +K=/etc/glacier/keys +D=/srv/extra-src +mkdir -p $D && chmod 755 /srv $D +gsign -G -p $K/srckey.pub -s /root/srckey.sec -c srckey >/dev/null +fresh; (cd $T/tree && tar czf $D/curl-8.9.0.grcp curl-8.9.0) +rm -rf $T/tree/hi-1.0.0 && mkdir -p $T/tree/hi-1.0.0 && cp $T/minimal $T/tree/hi-1.0.0/recipe +(cd $T/tree && tar czf $D/hi-1.0.0.grcp hi-1.0.0) +cp /dev/null $D/ignored.gpkg +R grepo -s /root/srckey.sec -r extra-src $D +check "grepo indexes a -src repository" rc 0 +check "...both bundles" has "2 packages" +probe index extra-src $D/repo.idx +check "...an index gl_index_parse accepts" has "status=0" +check "...with the recipe's relations and traits" sh -c 'echo "$0" | tr "\n" "|" | grep -qF "deps=[zlib 1.3.0|libressl 3.9.0 ssl|]|confs=[curl-old 0.0.0|]|build_deps=[perl 5.40.0 -ldap|]|traits=[ssl 1|ldap 0|]"' "$OUT" +check "...each bundle's hash" grep -qF "SHA256 = \"sha256:$(sha256sum $D/hi-1.0.0.grcp | cut -c1-64)\"" $D/repo.idx +mv $D/hi-1.0.0.grcp $D/hi-2.0.0.grcp +R grepo -s /root/srckey.sec -r extra-src $D +check "refused: a misnamed bundle" has "[x] $D/hi-2.0.0.grcp must be named hi-1.0.0.grcp, as its recipe says." +rm $D/hi-2.0.0.grcp +sed 's/REPO = "extra"/REPO = "community"/' $T/minimal > $T/tree/hi-1.0.0/recipe +(cd $T/tree && tar czf $D/hi-1.0.0.grcp hi-1.0.0) +R grepo -s /root/srckey.sec -r extra-src $D +check "refused: a recipe of another repository" has "[x] $D/hi-1.0.0.grcp builds community packages, not extra." +echo junk > $D/hi-1.0.0.grcp +R grepo -s /root/srckey.sec -r extra-src $D +check "refused: a bundle that can't be read" has "[x] $D/hi-1.0.0.grcp is not a readable recipe bundle." +rm $D/hi-1.0.0.grcp +R grepo -s /root/srckey.sec -r extra-src $D + +hr "syspkg -y with a -src repository" +syspkg -n >/dev/null +printf 'repos = (\n\t{ name = "extra-src"; url = "file:///srv/extra-src"; keys = [ "srckey" ]; }\n);\n' > /etc/glacier/repos.conf +chmod 644 /etc/glacier/repos.conf +R syspkg -y +check "syspkg -y accepts a -src index" rc 0 +check "...and stores it" cmp $D/repo.idx /glacier/sys/repos/extra-src.idx + +echo +if [ $FAILS -eq 0 ]; then echo "ALL PASSED"; else echo "$FAILS FAILED"; fi +[ $FAILS -eq 0 ] diff --git a/tests/repo_alpine.sh b/tests/repo_alpine.sh new file mode 100644 index 0000000..c13f14a --- /dev/null +++ b/tests/repo_alpine.sh @@ -0,0 +1,322 @@ +#!/bin/sh +# Repository indexes (REPO_DESIGN.txt sections 4 and 5, step 3): +# - grepo writes DIR/repo.idx from DIR's packages and signs it; SERIAL +# is the date form YYYYMMDDNN, above the previous index's; -n, -e; +# packages of another repo, misnamed or non-regular are refused; +# - syspkg -y / gpkg -y fetch every repos.conf url's index (file:// +# here), check its signature with a key listed for THAT repo, parse +# it strictly, refuse a rollback, the same serial with other bytes, +# an expired index and another repo's index, and only then rename it +# into /repos; any failure keeps the accepted copy; +# - /repos gets the scope's owner and modes; it is refused if +# loosened or a symlink; -y holds the scope lock; -R stores under +# the install root, with the install root's own keyring. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/repo_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +B=/srv/base +E=/srv/extra +S=/glacier/sys/repos +mkdir -p $B $E && chmod 755 /srv $B $E + +gsign -G -p $K/extrakey.pub -s /root/extrakey.sec -c extrakey >/dev/null +gsign -G -p /root/stranger.pub -s /root/stranger.sec -c stranger >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; }' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; }' +pk() { /app/tests/mkpkg -o "$1" ${5:+-k "$5"} "$2" "$3" "$4" >/dev/null; } +field() { sed -n "s/^$1 = \\([0-9]*\\)L;\$/\\1/p" "$2"; } + +syspkg -n >/dev/null + +hr "grepo" +pk $B core 1.0.0 base $TEST_SEC +pk $B app 2.1.0 base $TEST_SEC +/app/tests/mkpkg -o $B -k $TEST_SEC -d core:1.0.0 -c rival:0.0.0 tool 1.2.3 base >/dev/null +R grepo -s $TEST_SEC -r base $B +check "grepo writes an index" rc 0 +check "...saying so" has "[✓] Wrote $B/repo.idx: 3 packages, serial $(date -u +%Y%m%d)01." +check "...signed: gsign verifies it with the test key" gsign -V -p $K/glacier-test.pub -m $B/repo.idx +check "...the first SERIAL is today's date form" [ "$(field SERIAL $B/repo.idx)" = "$(date -u +%Y%m%d)01" ] +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "...valid for 30 days by default" [ $((VU - NOW)) -gt $((30*86400 - 60)) -a $((VU - NOW)) -le $((30*86400)) ] +check "...packages sorted, with their sha256 and size" sh -c "grep -A1 'NAME = \"app\"' $B/repo.idx | grep -q \"SHA256 = \\\"sha256:$(sha256sum $B/app-2.1.0.gpkg | cut -c1-64)\\\"; SIZE = $(wc -c < $B/app-2.1.0.gpkg)L;\"" +check "...dependencies and conflicts from the manifest" grep -qF 'DEPS = ( { NAME = "core"; VER = "1.0.0"; } ); CONFS = ( { NAME = "rival"; VER = "0.0.0"; } );' $B/repo.idx +check "...no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +check "...the index is world-readable" [ "$(stat -c %a $B/repo.idx)" = 644 ] +R grepo -s $TEST_SEC -r base $B +check "a second run the same day takes the next serial" has "serial $(date -u +%Y%m%d)02." +R grepo -s $TEST_SEC -r base -n 5 $B +check "-n below the previous serial is refused" has "[x] SERIAL must be above $(date -u +%Y%m%d)02, the previous index's." +check "...exit 1, index unchanged" sh -c "[ $RC = 1 ] && grep -q '^SERIAL = $(date -u +%Y%m%d)02L;' $B/repo.idx" +R grepo -s $TEST_SEC -r base -n 2090010101 -e 1 $B +check "-n above it is used" grep -q '^SERIAL = 2090010101L;' $B/repo.idx +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "-e 1 makes it valid for one day" [ $((VU - NOW)) -gt $((86400 - 60)) -a $((VU - NOW)) -le 86400 ] +R grepo -s $TEST_SEC -r base -e 0 $B +check "-e 0 is refused" has "[x] DAYS must be a whole number from 1 to 3650." +R grepo -s $TEST_SEC -r base +check "no DIR prints the usage" has "usage: grepo [-hv] -s KEY.sec -r REPO [-n SERIAL] [-e DAYS] DIR" +R grepo -h +check "-h prints the help, exit 0" rc 0 +check "...listing every flag" has "{-e --expire} DAYS" +R grepo --version +check "--version prints the version" has "v4.0.0" +R gsign --help +check "gsign --help lists its modes" has "{-V --verify}" +R gsha256sum -h +check "gsha256sum -h prints its help" has "gsha256sum: Print a file's sha256" +R grepo -s /root/missing.sec -r base $B +check "an unreadable secret key is refused" has "[x] Secret key /root/missing.sec cannot be read." +R grepo -s $TEST_SEC -r 'ba/se' $B +check "an unsafe repo name is refused" has "[x] Repository name ba/se is not a safe name ([A-Za-z0-9._-])." +cp $B/repo.idx /srv/before.idx +pk $B stray 1.0.0 extra +R grepo -s $TEST_SEC -r base $B +check "a package of another repo is refused" has "[x] $B/stray-1.0.0.gpkg is a extra package, not base." +check "...and the index is left as it was" cmp -s $B/repo.idx /srv/before.idx +check "...with no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +rm $B/stray-1.0.0.gpkg* +cp $B/core-1.0.0.gpkg $B/renamed-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a package named unlike its manifest is refused" has "[x] $B/renamed-1.0.0.gpkg must be named core-1.0.0.gpkg, as its manifest says." +rm $B/renamed-1.0.0.gpkg +ln -s /srv/base/core-1.0.0.gpkg $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a symlinked package is refused" has "[x] Refusing $B/link-1.0.0.gpkg: not a regular file." +rm $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r extra $B +check "a DIR holding another repo's index is refused" has "[x] $B/repo.idx is the index of another repository." +mkdir -p /srv/empty +R grepo -s $TEST_SEC -r community /srv/empty +check "an empty DIR makes an empty index" has "[✓] Wrote /srv/empty/repo.idx: 0 packages" +R grepo -s $TEST_SEC -r base -n 2090010102 $B +check "grepo works again after those refusals" rc 0 + +hr "signify interop" +if apk add --no-cache signify >/dev/null 2>&1; then + check "signify verifies grepo's index" signify -V -q -p $K/glacier-test.pub -m $B/repo.idx -x $B/repo.idx.sig +else + echo "FAIL: apk add signify"; FAILS=$((FAILS+1)) +fi + +hr "syspkg -y: accepting" +rm -f $CONF +R syspkg -y +check "no repos.conf: nothing to refresh" has "[x] No remote repositories are configured." +check "...exit 1" rc 1 +conf ' { name = "base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "repos.conf without a url: the same" has "[x] No remote repositories are configured." +conf "$BASE_E" +R syspkg -y +check "an index signed by a key listed for base is accepted" has "[✓] All repositories synced successfully." +check "...nothing per repo without -V" lacks "Index for base" +check "...exit 0" rc 0 +check "...stored byte for byte" cmp -s $B/repo.idx $S/base.idx +check "...with its signature" cmp -s $B/repo.idx.sig $S/base.idx.sig +check "...in a root-owned 0755 repos dir" [ "$(stat -c '%u %a' $S)" = "0 755" ] +check "...as root-owned 0644 files" [ "$(stat -c '%u %a' $S/base.idx) $(stat -c '%u %a' $S/base.idx.sig)" = "0 644 0 644" ] +check "...no temporary files left" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +R syspkg -y +check "refreshing again: one sync line" has "[i] Syncing all repositories..." +check "...nothing per repo when up to date" lacks "Index for base" +check "...exit 0" rc 0 +R syspkg -yV +check "with -V: up to date, by repo" has "[i] Index for base is up to date: serial 2090010102." +check "...exit 0" rc 0 +grepo -s $TEST_SEC -r base -n 2090010103 $B >/dev/null +R syspkg --refresh -V +check "a newer index is accepted (--refresh)" has "[✓] All repositories synced successfully." +check "...with -V: its serial, by repo" has "[✓] Index for base: serial 2090010103, 3 packages." +check "...replacing the stored one" cmp -s $B/repo.idx $S/base.idx + +hr "syspkg -y: refusing" +cp $S/base.idx /srv/accepted.idx +# serve TEXT [KEY.sec]: publish TEXT as base's index, signed (test key +# by default; "-" for no signature). +serve() { + printf '%s\n' "$1" > $B/repo.idx + rm -f $B/repo.idx.sig + [ "${2:-}" = - ] || gsign -S -s "${2:-$TEST_SEC}" -m $B/repo.idx >/dev/null +} +kept() { cmp -s $S/base.idx /srv/accepted.idx; } +FUTURE=$(( $(date +%s) + 86400 )) +SHA="sha256:$(printf '%064d' 0)" +idx() { # idx SERIAL [VALID_UNTIL [PKGS [REPO]]] + printf 'REPO = "%s";\nSERIAL = %sL;\nVALID_UNTIL = %sL;\nPKGS = (%s);' \ + "${4:-base}" "$1" "${2:-$FUTURE}" "${3:-}" +} +PKG1="{ NAME = \"a\"; VER = \"1.0.0\"; FILE = \"a-1.0.0.gpkg\"; SHA256 = \"$SHA\"; SIZE = 1L; DEPS = (); CONFS = (); }" + +serve "$(idx 2090010102)" +R syspkg -y +check "an older serial is refused" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +check "...keeping the accepted index" kept +check "...and no temporary files" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +serve "$(idx 2090010103 "" "$PKG1")" +R syspkg -y +check "the same serial with other contents is refused" has "[x] Index for base has the serial of the one already accepted, but other contents." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 $(( $(date +%s) - 10 )))" +R syspkg -y +check "an expired index is refused" has "[x] Index for base has expired." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" - +R syspkg -y +check "no signature: refused as unfetchable" has "[x] Cannot fetch the index for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/stranger.sec +R syspkg -y +check "a key in no keyring is refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/extrakey.sec +conf "$BASE_E +,$EXTRA_E" +R syspkg -y +check "a key listed only for extra is refused for base" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +conf "$BASE_E" +serve "$(idx 2090010200)" +printf '# appended after signing\n' >> $B/repo.idx +R syspkg -y +check "bytes changed after signing are refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 "" "" extra)" +R syspkg -y +check "another repo's index (validly signed) is refused" has "[x] Index fetched for base is the index of another repository." +check "...keeping the accepted index" kept + +# Signed, but not a well-formed index: each one "Malformed index". +malformed() { + serve "$2" + R syspkg -y + check "malformed: $1" sh -c "echo \"\$0\" | grep -qF '[x] Malformed index for base.' && cmp -s $S/base.idx /srv/accepted.idx" "$OUT" +} +malformed "not libconfig" "this is not an index" +malformed "an unknown top-level setting" "$(idx 2090010200) EXTRA = 1;" +malformed "a missing setting" 'REPO = "base"; SERIAL = 2090010200L; PKGS = ();' +malformed "SERIAL 0" "$(idx 0)" +malformed "SERIAL a string" "$(idx '"2090010200"' | sed 's/"L;/";/')" +# An include that WOULD make a valid index: only the '@' rule stops it. +printf 'PKGS = ();\n' > /srv/inc.cfg +malformed "@include" "$(idx 2090010200 | grep -v '^PKGS') +@include \"/srv/inc.cfg\"" +malformed "an unknown package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/CONFS = ();/CONFS = (); X = 1;/')")" +malformed "a missing package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/SIZE = 1L; //')")" +malformed "FILE not NAME-VER.gpkg" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#a-1.0.0.gpkg#../x-1.0.0.gpkg#')")" +malformed "an unsafe NAME" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#NAME = "a"#NAME = "a/b"#; s#a-1.0.0.gpkg#a/b-1.0.0.gpkg#')")" +malformed "a version with a leading zero" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.00.0#g')")" +malformed "a version with a tag" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.0.0-rc1#g')")" +malformed "uppercase hex" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:A#')")" +malformed "a short hash" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:#')")" +malformed "a negative SIZE" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#SIZE = 1L#SIZE = -1L#')")" +malformed "the same NAME and VER twice" "$(idx 2090010200 "" "$PKG1, $PKG1")" +malformed "a dependency without VER" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#DEPS = ()#DEPS = ( { NAME = "b"; } )#')")" +serve "$(idx 2090010200 "" "$PKG1, $(echo "$PKG1" | sed 's#1\.0\.0#1.0.1#g')")" +R syspkg -yV +check "two versions of one package are fine" has "[✓] Index for base: serial 2090010200, 2 packages." +cp $S/base.idx /srv/accepted.idx + +hr "fetch failures and several repos" +grepo -s /root/extrakey.sec -r extra $E >/dev/null 2>&1 || true +pk $E ex 1.0.0 extra +grepo -s /root/extrakey.sec -r extra $E >/dev/null +conf ' { name = "base"; url = "file:///srv/nowhere"; keys = [ "glacier-test" ]; } +,'"$EXTRA_E" +R syspkg -yV +check "an unreachable repo fails" has "[x] Cannot fetch the index for base." +check "...the next repo is still refreshed" has "[✓] Index for extra: serial" +check "...not reported as all synced" lacks "All repositories synced" +check "...exit 1" rc 1 +check "...base's accepted index kept" kept +check "...extra's stored" cmp -s $E/repo.idx $S/extra.idx +conf ' { name = "base"; url = "http://example.org/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an http:// url is refused" has "[x] Malformed /etc/glacier/repos.conf." +conf ' { name = "base"; url = "https://127.0.0.1:1/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an https url that can't be reached fails in one line" has "[x] Cannot fetch the index for base." +check "...exit 1" rc 1 +conf "$BASE_E" + +hr "the repos directory and the lock" +cp $S/base.idx /srv/accepted.idx +printf 'garbage\n' > $S/base.idx +R syspkg -y +check "a corrupt accepted index is refused, not replaced" has "[x] Malformed $S/base.idx." +check "...exit 1" rc 1 +check "...left for the admin" grep -q garbage $S/base.idx +cp /srv/accepted.idx $S/base.idx +chmod 775 $S +R syspkg -y +check "a group-writable repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +chmod 755 $S +mv $S /srv/repos.real && ln -s /srv/repos.real $S +R syspkg -y +check "a symlinked repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +rm $S && mv /srv/repos.real $S +flock /glacier/sys/lock sleep 3 & +sleep 1 +R syspkg -y +check "-y waits for no one: a held lock refuses" has "[x] Another glacier transaction is already in progress for the system scope." +wait +R syspkg -y -l x +check "-y with -l is refused" has "[x] -n, -l, -f, -u, -x and -y are mutually exclusive." +R syspkg -y extra +check "-y takes no arguments" has "[x] Unexpected argument: extra" +adduser -D tester >/dev/null 2>&1 +R su tester -c 'syspkg -y' +check "syspkg -y as a user is refused" has "[x] Cannot open system index: Permission denied" + +hr "syspkg -R DIR -y" +mkdir -p /srv/img && chmod 755 /srv/img +syspkg -R /srv/img -n >/dev/null +cp $S/base.idx /srv/host.idx +grepo -s $TEST_SEC -r base -n 2090010300 $B >/dev/null +R syspkg -R /srv/img -y +check "-R reads the image's repos.conf, not the host's" has "[x] No remote repositories are configured." +# The image's own keyring, as a package would ship it. +mkdir -p /srv/img/etc/glacier && cp -a /etc/glacier/repos.conf /etc/glacier/keys /srv/img/etc/glacier/ +R syspkg -R /srv/img -y +check "-R stores the index under the install root" cmp -s $B/repo.idx /srv/img/glacier/sys/repos/base.idx +check "...leaving the host's alone" cmp -s $S/base.idx /srv/host.idx + +hr "gpkg -y" +U=$(id -u tester) +gstore -n "$U" >/dev/null +R su tester -c 'gpkg -y' +check "gpkg -y refreshes into the user's base" has "[✓] All repositories synced successfully." +check "...nothing per repo without -V" lacks "Index for base" +check "...owned by the user, 0700" [ "$(stat -c '%u %a' /glacier/usr/$U/repos)" = "$U 700" ] +check "...files 0600" [ "$(stat -c '%u %a' /glacier/usr/$U/repos/base.idx)" = "$U 600" ] +check "...byte for byte" cmp -s $B/repo.idx /glacier/usr/$U/repos/base.idx +serve "$(idx 2090010200)" +R su tester -c 'gpkg -y' +check "gpkg -y refuses a rollback too" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +R su tester -c 'gpkg -y base' +check "gpkg -y takes no arguments" has "[x] -y takes no arguments." + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/repo_alpine.sh.old b/tests/repo_alpine.sh.old new file mode 100644 index 0000000..1d42ae1 --- /dev/null +++ b/tests/repo_alpine.sh.old @@ -0,0 +1,301 @@ +#!/bin/sh +# Repository indexes (REPO_DESIGN.txt sections 4 and 5, step 3): +# - grepo writes DIR/repo.idx from DIR's packages and signs it; SERIAL +# is the date form YYYYMMDDNN, above the previous index's; -n, -e; +# packages of another repo, misnamed or non-regular are refused; +# - syspkg -y / gpkg -y fetch every repos.conf url's index (file:// +# here), check its signature with a key listed for THAT repo, parse +# it strictly, refuse a rollback, the same serial with other bytes, +# an expired index and another repo's index, and only then rename it +# into /repos; any failure keeps the accepted copy; +# - /repos gets the scope's owner and modes; it is refused if +# loosened or a symlink; -y holds the scope lock; -R stores under +# the install root, with the host's keyring. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/repo_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +B=/srv/base +E=/srv/extra +S=/glacier/sys/repos +mkdir -p $B $E && chmod 755 /srv $B $E + +gsign -G -p $K/extrakey.pub -s /root/extrakey.sec -c extrakey >/dev/null +gsign -G -p /root/stranger.pub -s /root/stranger.sec -c stranger >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; }' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; }' +pk() { /app/tests/mkpkg -o "$1" ${5:+-k "$5"} "$2" "$3" "$4" >/dev/null; } +field() { sed -n "s/^$1 = \\([0-9]*\\)L;\$/\\1/p" "$2"; } + +syspkg -n >/dev/null + +hr "grepo" +pk $B core 1.0.0 base $TEST_SEC +pk $B app 2.1.0 base $TEST_SEC +/app/tests/mkpkg -o $B -k $TEST_SEC -d core:1.0.0 -c rival:0.0.0 tool 1.2.3 base >/dev/null +R grepo -s $TEST_SEC -r base $B +check "grepo writes an index" rc 0 +check "...saying so" has "[✓] Wrote $B/repo.idx: 3 packages, serial $(date -u +%Y%m%d)01." +check "...signed: gsign verifies it with the test key" gsign -V -p $K/glacier-test.pub -m $B/repo.idx +check "...the first SERIAL is today's date form" [ "$(field SERIAL $B/repo.idx)" = "$(date -u +%Y%m%d)01" ] +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "...valid for 30 days by default" [ $((VU - NOW)) -gt $((30*86400 - 60)) -a $((VU - NOW)) -le $((30*86400)) ] +check "...packages sorted, with their sha256 and size" sh -c "grep -A1 'NAME = \"app\"' $B/repo.idx | grep -q \"SHA256 = \\\"sha256:$(sha256sum $B/app-2.1.0.gpkg | cut -c1-64)\\\"; SIZE = $(wc -c < $B/app-2.1.0.gpkg)L;\"" +check "...dependencies and conflicts from the manifest" grep -qF 'DEPS = ( { NAME = "core"; VER = "1.0.0"; } ); CONFS = ( { NAME = "rival"; VER = "0.0.0"; } );' $B/repo.idx +check "...no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +check "...the index is world-readable" [ "$(stat -c %a $B/repo.idx)" = 644 ] +R grepo -s $TEST_SEC -r base $B +check "a second run the same day takes the next serial" has "serial $(date -u +%Y%m%d)02." +R grepo -s $TEST_SEC -r base -n 5 $B +check "-n below the previous serial is refused" has "[x] SERIAL must be above $(date -u +%Y%m%d)02, the previous index's." +check "...exit 1, index unchanged" sh -c "[ $RC = 1 ] && grep -q '^SERIAL = $(date -u +%Y%m%d)02L;' $B/repo.idx" +R grepo -s $TEST_SEC -r base -n 2090010101 -e 1 $B +check "-n above it is used" grep -q '^SERIAL = 2090010101L;' $B/repo.idx +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "-e 1 makes it valid for one day" [ $((VU - NOW)) -gt $((86400 - 60)) -a $((VU - NOW)) -le 86400 ] +R grepo -s $TEST_SEC -r base -e 0 $B +check "-e 0 is refused" has "[x] DAYS must be a whole number from 1 to 3650." +R grepo -s $TEST_SEC -r base +check "no DIR prints the usage" has "usage: grepo -s KEY.sec -r REPO [-n SERIAL] [-e DAYS] DIR" +R grepo -s /root/missing.sec -r base $B +check "an unreadable secret key is refused" has "[x] Secret key /root/missing.sec cannot be read." +R grepo -s $TEST_SEC -r 'ba/se' $B +check "an unsafe repo name is refused" has "[x] Repository name ba/se is not a safe name ([A-Za-z0-9._-])." +cp $B/repo.idx /srv/before.idx +pk $B stray 1.0.0 extra +R grepo -s $TEST_SEC -r base $B +check "a package of another repo is refused" has "[x] $B/stray-1.0.0.gpkg is a extra package, not base." +check "...and the index is left as it was" cmp -s $B/repo.idx /srv/before.idx +check "...with no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +rm $B/stray-1.0.0.gpkg* +cp $B/core-1.0.0.gpkg $B/renamed-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a package named unlike its manifest is refused" has "[x] $B/renamed-1.0.0.gpkg must be named core-1.0.0.gpkg, as its manifest says." +rm $B/renamed-1.0.0.gpkg +ln -s /srv/base/core-1.0.0.gpkg $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a symlinked package is refused" has "[x] Refusing $B/link-1.0.0.gpkg: not a regular file." +rm $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r extra $B +check "a DIR holding another repo's index is refused" has "[x] $B/repo.idx is the index of another repository." +mkdir -p /srv/empty +R grepo -s $TEST_SEC -r community /srv/empty +check "an empty DIR makes an empty index" has "[✓] Wrote /srv/empty/repo.idx: 0 packages" +R grepo -s $TEST_SEC -r base -n 2090010102 $B +check "grepo works again after those refusals" rc 0 + +hr "signify interop" +if apk add --no-cache signify >/dev/null 2>&1; then + check "signify verifies grepo's index" signify -V -q -p $K/glacier-test.pub -m $B/repo.idx -x $B/repo.idx.sig +else + echo "FAIL: apk add signify"; FAILS=$((FAILS+1)) +fi + +hr "syspkg -y: accepting" +rm -f $CONF +R syspkg -y +check "no repos.conf: nothing to refresh" has "[x] No remote repositories are configured." +check "...exit 1" rc 1 +conf ' { name = "base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "repos.conf without a url: the same" has "[x] No remote repositories are configured." +conf "$BASE_E" +R syspkg -y +check "an index signed by a key listed for base is accepted" has "[✓] Index for base: serial 2090010102, 3 packages." +check "...exit 0" rc 0 +check "...stored byte for byte" cmp -s $B/repo.idx $S/base.idx +check "...with its signature" cmp -s $B/repo.idx.sig $S/base.idx.sig +check "...in a root-owned 0755 repos dir" [ "$(stat -c '%u %a' $S)" = "0 755" ] +check "...as root-owned 0644 files" [ "$(stat -c '%u %a' $S/base.idx) $(stat -c '%u %a' $S/base.idx.sig)" = "0 644 0 644" ] +check "...no temporary files left" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +R syspkg -y +check "refreshing again: up to date" has "[i] Index for base is up to date: serial 2090010102." +check "...exit 0" rc 0 +grepo -s $TEST_SEC -r base -n 2090010103 $B >/dev/null +R syspkg --refresh +check "a newer index is accepted (--refresh)" has "[✓] Index for base: serial 2090010103, 3 packages." +check "...replacing the stored one" cmp -s $B/repo.idx $S/base.idx + +hr "syspkg -y: refusing" +cp $S/base.idx /srv/accepted.idx +# serve TEXT [KEY.sec]: publish TEXT as base's index, signed (test key +# by default; "-" for no signature). +serve() { + printf '%s\n' "$1" > $B/repo.idx + rm -f $B/repo.idx.sig + [ "${2:-}" = - ] || gsign -S -s "${2:-$TEST_SEC}" -m $B/repo.idx >/dev/null +} +kept() { cmp -s $S/base.idx /srv/accepted.idx; } +FUTURE=$(( $(date +%s) + 86400 )) +SHA="sha256:$(printf '%064d' 0)" +idx() { # idx SERIAL [VALID_UNTIL [PKGS [REPO]]] + printf 'REPO = "%s";\nSERIAL = %sL;\nVALID_UNTIL = %sL;\nPKGS = (%s);' \ + "${4:-base}" "$1" "${2:-$FUTURE}" "${3:-}" +} +PKG1="{ NAME = \"a\"; VER = \"1.0.0\"; FILE = \"a-1.0.0.gpkg\"; SHA256 = \"$SHA\"; SIZE = 1L; DEPS = (); CONFS = (); }" + +serve "$(idx 2090010102)" +R syspkg -y +check "an older serial is refused" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +check "...keeping the accepted index" kept +check "...and no temporary files" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +serve "$(idx 2090010103 "" "$PKG1")" +R syspkg -y +check "the same serial with other contents is refused" has "[x] Index for base has the serial of the one already accepted, but other contents." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 $(( $(date +%s) - 10 )))" +R syspkg -y +check "an expired index is refused" has "[x] Index for base has expired." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" - +R syspkg -y +check "no signature: refused as unfetchable" has "[x] Cannot fetch the index for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/stranger.sec +R syspkg -y +check "a key in no keyring is refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/extrakey.sec +conf "$BASE_E +,$EXTRA_E" +R syspkg -y +check "a key listed only for extra is refused for base" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +conf "$BASE_E" +serve "$(idx 2090010200)" +printf '# appended after signing\n' >> $B/repo.idx +R syspkg -y +check "bytes changed after signing are refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 "" "" extra)" +R syspkg -y +check "another repo's index (validly signed) is refused" has "[x] Index fetched for base is the index of another repository." +check "...keeping the accepted index" kept + +# Signed, but not a well-formed index: each one "Malformed index". +malformed() { + serve "$2" + R syspkg -y + check "malformed: $1" sh -c "echo \"\$0\" | grep -qF '[x] Malformed index for base.' && cmp -s $S/base.idx /srv/accepted.idx" "$OUT" +} +malformed "not libconfig" "this is not an index" +malformed "an unknown top-level setting" "$(idx 2090010200) EXTRA = 1;" +malformed "a missing setting" 'REPO = "base"; SERIAL = 2090010200L; PKGS = ();' +malformed "SERIAL 0" "$(idx 0)" +malformed "SERIAL a string" "$(idx '"2090010200"' | sed 's/"L;/";/')" +# An include that WOULD make a valid index: only the '@' rule stops it. +printf 'PKGS = ();\n' > /srv/inc.cfg +malformed "@include" "$(idx 2090010200 | grep -v '^PKGS') +@include \"/srv/inc.cfg\"" +malformed "an unknown package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/CONFS = ();/CONFS = (); X = 1;/')")" +malformed "a missing package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/SIZE = 1L; //')")" +malformed "FILE not NAME-VER.gpkg" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#a-1.0.0.gpkg#../x-1.0.0.gpkg#')")" +malformed "an unsafe NAME" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#NAME = "a"#NAME = "a/b"#; s#a-1.0.0.gpkg#a/b-1.0.0.gpkg#')")" +malformed "a version with a leading zero" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.00.0#g')")" +malformed "a version with a tag" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.0.0-rc1#g')")" +malformed "uppercase hex" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:A#')")" +malformed "a short hash" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:#')")" +malformed "a negative SIZE" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#SIZE = 1L#SIZE = -1L#')")" +malformed "the same NAME and VER twice" "$(idx 2090010200 "" "$PKG1, $PKG1")" +malformed "a dependency without VER" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#DEPS = ()#DEPS = ( { NAME = "b"; } )#')")" +serve "$(idx 2090010200 "" "$PKG1, $(echo "$PKG1" | sed 's#1\.0\.0#1.0.1#g')")" +R syspkg -y +check "two versions of one package are fine" has "[✓] Index for base: serial 2090010200, 2 packages." +cp $S/base.idx /srv/accepted.idx + +hr "fetch failures and several repos" +grepo -s /root/extrakey.sec -r extra $E >/dev/null 2>&1 || true +pk $E ex 1.0.0 extra +grepo -s /root/extrakey.sec -r extra $E >/dev/null +conf ' { name = "base"; url = "file:///srv/nowhere"; keys = [ "glacier-test" ]; } +,'"$EXTRA_E" +R syspkg -y +check "an unreachable repo fails" has "[x] Cannot fetch the index for base." +check "...the next repo is still refreshed" has "[✓] Index for extra: serial" +check "...exit 1" rc 1 +check "...base's accepted index kept" kept +check "...extra's stored" cmp -s $E/repo.idx $S/extra.idx +conf ' { name = "base"; url = "http://example.org/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an http:// url is refused" has "[x] Malformed /etc/glacier/repos.conf." +conf ' { name = "base"; url = "https://127.0.0.1:1/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an https url that can't be reached fails in one line" has "[x] Cannot fetch the index for base." +check "...exit 1" rc 1 +conf "$BASE_E" + +hr "the repos directory and the lock" +cp $S/base.idx /srv/accepted.idx +printf 'garbage\n' > $S/base.idx +R syspkg -y +check "a corrupt accepted index is refused, not replaced" has "[x] Malformed $S/base.idx." +check "...exit 1" rc 1 +check "...left for the admin" grep -q garbage $S/base.idx +cp /srv/accepted.idx $S/base.idx +chmod 775 $S +R syspkg -y +check "a group-writable repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +chmod 755 $S +mv $S /srv/repos.real && ln -s /srv/repos.real $S +R syspkg -y +check "a symlinked repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +rm $S && mv /srv/repos.real $S +flock /glacier/sys/lock sleep 3 & +sleep 1 +R syspkg -y +check "-y waits for no one: a held lock refuses" has "[x] Another glacier transaction is already in progress for the system scope." +wait +R syspkg -y -l x +check "-y with -l is refused" has "[x] -n, -l, -x and -y are mutually exclusive." +R syspkg -y extra +check "-y takes no arguments" has "[x] Unexpected argument: extra" +adduser -D tester >/dev/null 2>&1 +R su tester -c 'syspkg -y' +check "syspkg -y as a user is refused" has "[x] Cannot open system index: Permission denied" + +hr "syspkg -R DIR -y" +mkdir -p /srv/img && chmod 755 /srv/img +syspkg -R /srv/img -n >/dev/null +cp $S/base.idx /srv/host.idx +grepo -s $TEST_SEC -r base -n 2090010300 $B >/dev/null +R syspkg -R /srv/img -y +check "-R stores the index under the install root" cmp -s $B/repo.idx /srv/img/glacier/sys/repos/base.idx +check "...leaving the host's alone" cmp -s $S/base.idx /srv/host.idx + +hr "gpkg -y" +U=$(id -u tester) +gstore -n "$U" >/dev/null +R su tester -c 'gpkg -y' +check "gpkg -y refreshes into the user's base" has "[✓] Index for base: serial 2090010300" +check "...owned by the user, 0700" [ "$(stat -c '%u %a' /glacier/usr/$U/repos)" = "$U 700" ] +check "...files 0600" [ "$(stat -c '%u %a' /glacier/usr/$U/repos/base.idx)" = "$U 600" ] +check "...byte for byte" cmp -s $B/repo.idx /glacier/usr/$U/repos/base.idx +serve "$(idx 2090010200)" +R su tester -c 'gpkg -y' +check "gpkg -y refuses a rollback too" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +R su tester -c 'gpkg -y base' +check "gpkg -y takes no arguments" has "[x] -y takes no arguments." + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/repo_alpine.sh.old2 b/tests/repo_alpine.sh.old2 new file mode 100644 index 0000000..7882da8 --- /dev/null +++ b/tests/repo_alpine.sh.old2 @@ -0,0 +1,301 @@ +#!/bin/sh +# Repository indexes (REPO_DESIGN.txt sections 4 and 5, step 3): +# - grepo writes DIR/repo.idx from DIR's packages and signs it; SERIAL +# is the date form YYYYMMDDNN, above the previous index's; -n, -e; +# packages of another repo, misnamed or non-regular are refused; +# - syspkg -y / gpkg -y fetch every repos.conf url's index (file:// +# here), check its signature with a key listed for THAT repo, parse +# it strictly, refuse a rollback, the same serial with other bytes, +# an expired index and another repo's index, and only then rename it +# into /repos; any failure keeps the accepted copy; +# - /repos gets the scope's owner and modes; it is refused if +# loosened or a symlink; -y holds the scope lock; -R stores under +# the install root, with the host's keyring. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/repo_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +B=/srv/base +E=/srv/extra +S=/glacier/sys/repos +mkdir -p $B $E && chmod 755 /srv $B $E + +gsign -G -p $K/extrakey.pub -s /root/extrakey.sec -c extrakey >/dev/null +gsign -G -p /root/stranger.pub -s /root/stranger.sec -c stranger >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; }' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; }' +pk() { /app/tests/mkpkg -o "$1" ${5:+-k "$5"} "$2" "$3" "$4" >/dev/null; } +field() { sed -n "s/^$1 = \\([0-9]*\\)L;\$/\\1/p" "$2"; } + +syspkg -n >/dev/null + +hr "grepo" +pk $B core 1.0.0 base $TEST_SEC +pk $B app 2.1.0 base $TEST_SEC +/app/tests/mkpkg -o $B -k $TEST_SEC -d core:1.0.0 -c rival:0.0.0 tool 1.2.3 base >/dev/null +R grepo -s $TEST_SEC -r base $B +check "grepo writes an index" rc 0 +check "...saying so" has "[✓] Wrote $B/repo.idx: 3 packages, serial $(date -u +%Y%m%d)01." +check "...signed: gsign verifies it with the test key" gsign -V -p $K/glacier-test.pub -m $B/repo.idx +check "...the first SERIAL is today's date form" [ "$(field SERIAL $B/repo.idx)" = "$(date -u +%Y%m%d)01" ] +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "...valid for 30 days by default" [ $((VU - NOW)) -gt $((30*86400 - 60)) -a $((VU - NOW)) -le $((30*86400)) ] +check "...packages sorted, with their sha256 and size" sh -c "grep -A1 'NAME = \"app\"' $B/repo.idx | grep -q \"SHA256 = \\\"sha256:$(sha256sum $B/app-2.1.0.gpkg | cut -c1-64)\\\"; SIZE = $(wc -c < $B/app-2.1.0.gpkg)L;\"" +check "...dependencies and conflicts from the manifest" grep -qF 'DEPS = ( { NAME = "core"; VER = "1.0.0"; } ); CONFS = ( { NAME = "rival"; VER = "0.0.0"; } );' $B/repo.idx +check "...no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +check "...the index is world-readable" [ "$(stat -c %a $B/repo.idx)" = 644 ] +R grepo -s $TEST_SEC -r base $B +check "a second run the same day takes the next serial" has "serial $(date -u +%Y%m%d)02." +R grepo -s $TEST_SEC -r base -n 5 $B +check "-n below the previous serial is refused" has "[x] SERIAL must be above $(date -u +%Y%m%d)02, the previous index's." +check "...exit 1, index unchanged" sh -c "[ $RC = 1 ] && grep -q '^SERIAL = $(date -u +%Y%m%d)02L;' $B/repo.idx" +R grepo -s $TEST_SEC -r base -n 2090010101 -e 1 $B +check "-n above it is used" grep -q '^SERIAL = 2090010101L;' $B/repo.idx +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "-e 1 makes it valid for one day" [ $((VU - NOW)) -gt $((86400 - 60)) -a $((VU - NOW)) -le 86400 ] +R grepo -s $TEST_SEC -r base -e 0 $B +check "-e 0 is refused" has "[x] DAYS must be a whole number from 1 to 3650." +R grepo -s $TEST_SEC -r base +check "no DIR prints the usage" has "usage: grepo -s KEY.sec -r REPO [-n SERIAL] [-e DAYS] DIR" +R grepo -s /root/missing.sec -r base $B +check "an unreadable secret key is refused" has "[x] Secret key /root/missing.sec cannot be read." +R grepo -s $TEST_SEC -r 'ba/se' $B +check "an unsafe repo name is refused" has "[x] Repository name ba/se is not a safe name ([A-Za-z0-9._-])." +cp $B/repo.idx /srv/before.idx +pk $B stray 1.0.0 extra +R grepo -s $TEST_SEC -r base $B +check "a package of another repo is refused" has "[x] $B/stray-1.0.0.gpkg is a extra package, not base." +check "...and the index is left as it was" cmp -s $B/repo.idx /srv/before.idx +check "...with no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +rm $B/stray-1.0.0.gpkg* +cp $B/core-1.0.0.gpkg $B/renamed-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a package named unlike its manifest is refused" has "[x] $B/renamed-1.0.0.gpkg must be named core-1.0.0.gpkg, as its manifest says." +rm $B/renamed-1.0.0.gpkg +ln -s /srv/base/core-1.0.0.gpkg $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a symlinked package is refused" has "[x] Refusing $B/link-1.0.0.gpkg: not a regular file." +rm $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r extra $B +check "a DIR holding another repo's index is refused" has "[x] $B/repo.idx is the index of another repository." +mkdir -p /srv/empty +R grepo -s $TEST_SEC -r community /srv/empty +check "an empty DIR makes an empty index" has "[✓] Wrote /srv/empty/repo.idx: 0 packages" +R grepo -s $TEST_SEC -r base -n 2090010102 $B +check "grepo works again after those refusals" rc 0 + +hr "signify interop" +if apk add --no-cache signify >/dev/null 2>&1; then + check "signify verifies grepo's index" signify -V -q -p $K/glacier-test.pub -m $B/repo.idx -x $B/repo.idx.sig +else + echo "FAIL: apk add signify"; FAILS=$((FAILS+1)) +fi + +hr "syspkg -y: accepting" +rm -f $CONF +R syspkg -y +check "no repos.conf: nothing to refresh" has "[x] No remote repositories are configured." +check "...exit 1" rc 1 +conf ' { name = "base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "repos.conf without a url: the same" has "[x] No remote repositories are configured." +conf "$BASE_E" +R syspkg -y +check "an index signed by a key listed for base is accepted" has "[✓] Index for base: serial 2090010102, 3 packages." +check "...exit 0" rc 0 +check "...stored byte for byte" cmp -s $B/repo.idx $S/base.idx +check "...with its signature" cmp -s $B/repo.idx.sig $S/base.idx.sig +check "...in a root-owned 0755 repos dir" [ "$(stat -c '%u %a' $S)" = "0 755" ] +check "...as root-owned 0644 files" [ "$(stat -c '%u %a' $S/base.idx) $(stat -c '%u %a' $S/base.idx.sig)" = "0 644 0 644" ] +check "...no temporary files left" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +R syspkg -y +check "refreshing again: up to date" has "[i] Index for base is up to date: serial 2090010102." +check "...exit 0" rc 0 +grepo -s $TEST_SEC -r base -n 2090010103 $B >/dev/null +R syspkg --refresh +check "a newer index is accepted (--refresh)" has "[✓] Index for base: serial 2090010103, 3 packages." +check "...replacing the stored one" cmp -s $B/repo.idx $S/base.idx + +hr "syspkg -y: refusing" +cp $S/base.idx /srv/accepted.idx +# serve TEXT [KEY.sec]: publish TEXT as base's index, signed (test key +# by default; "-" for no signature). +serve() { + printf '%s\n' "$1" > $B/repo.idx + rm -f $B/repo.idx.sig + [ "${2:-}" = - ] || gsign -S -s "${2:-$TEST_SEC}" -m $B/repo.idx >/dev/null +} +kept() { cmp -s $S/base.idx /srv/accepted.idx; } +FUTURE=$(( $(date +%s) + 86400 )) +SHA="sha256:$(printf '%064d' 0)" +idx() { # idx SERIAL [VALID_UNTIL [PKGS [REPO]]] + printf 'REPO = "%s";\nSERIAL = %sL;\nVALID_UNTIL = %sL;\nPKGS = (%s);' \ + "${4:-base}" "$1" "${2:-$FUTURE}" "${3:-}" +} +PKG1="{ NAME = \"a\"; VER = \"1.0.0\"; FILE = \"a-1.0.0.gpkg\"; SHA256 = \"$SHA\"; SIZE = 1L; DEPS = (); CONFS = (); }" + +serve "$(idx 2090010102)" +R syspkg -y +check "an older serial is refused" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +check "...keeping the accepted index" kept +check "...and no temporary files" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +serve "$(idx 2090010103 "" "$PKG1")" +R syspkg -y +check "the same serial with other contents is refused" has "[x] Index for base has the serial of the one already accepted, but other contents." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 $(( $(date +%s) - 10 )))" +R syspkg -y +check "an expired index is refused" has "[x] Index for base has expired." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" - +R syspkg -y +check "no signature: refused as unfetchable" has "[x] Cannot fetch the index for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/stranger.sec +R syspkg -y +check "a key in no keyring is refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/extrakey.sec +conf "$BASE_E +,$EXTRA_E" +R syspkg -y +check "a key listed only for extra is refused for base" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +conf "$BASE_E" +serve "$(idx 2090010200)" +printf '# appended after signing\n' >> $B/repo.idx +R syspkg -y +check "bytes changed after signing are refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 "" "" extra)" +R syspkg -y +check "another repo's index (validly signed) is refused" has "[x] Index fetched for base is the index of another repository." +check "...keeping the accepted index" kept + +# Signed, but not a well-formed index: each one "Malformed index". +malformed() { + serve "$2" + R syspkg -y + check "malformed: $1" sh -c "echo \"\$0\" | grep -qF '[x] Malformed index for base.' && cmp -s $S/base.idx /srv/accepted.idx" "$OUT" +} +malformed "not libconfig" "this is not an index" +malformed "an unknown top-level setting" "$(idx 2090010200) EXTRA = 1;" +malformed "a missing setting" 'REPO = "base"; SERIAL = 2090010200L; PKGS = ();' +malformed "SERIAL 0" "$(idx 0)" +malformed "SERIAL a string" "$(idx '"2090010200"' | sed 's/"L;/";/')" +# An include that WOULD make a valid index: only the '@' rule stops it. +printf 'PKGS = ();\n' > /srv/inc.cfg +malformed "@include" "$(idx 2090010200 | grep -v '^PKGS') +@include \"/srv/inc.cfg\"" +malformed "an unknown package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/CONFS = ();/CONFS = (); X = 1;/')")" +malformed "a missing package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/SIZE = 1L; //')")" +malformed "FILE not NAME-VER.gpkg" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#a-1.0.0.gpkg#../x-1.0.0.gpkg#')")" +malformed "an unsafe NAME" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#NAME = "a"#NAME = "a/b"#; s#a-1.0.0.gpkg#a/b-1.0.0.gpkg#')")" +malformed "a version with a leading zero" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.00.0#g')")" +malformed "a version with a tag" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.0.0-rc1#g')")" +malformed "uppercase hex" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:A#')")" +malformed "a short hash" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:#')")" +malformed "a negative SIZE" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#SIZE = 1L#SIZE = -1L#')")" +malformed "the same NAME and VER twice" "$(idx 2090010200 "" "$PKG1, $PKG1")" +malformed "a dependency without VER" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#DEPS = ()#DEPS = ( { NAME = "b"; } )#')")" +serve "$(idx 2090010200 "" "$PKG1, $(echo "$PKG1" | sed 's#1\.0\.0#1.0.1#g')")" +R syspkg -y +check "two versions of one package are fine" has "[✓] Index for base: serial 2090010200, 2 packages." +cp $S/base.idx /srv/accepted.idx + +hr "fetch failures and several repos" +grepo -s /root/extrakey.sec -r extra $E >/dev/null 2>&1 || true +pk $E ex 1.0.0 extra +grepo -s /root/extrakey.sec -r extra $E >/dev/null +conf ' { name = "base"; url = "file:///srv/nowhere"; keys = [ "glacier-test" ]; } +,'"$EXTRA_E" +R syspkg -y +check "an unreachable repo fails" has "[x] Cannot fetch the index for base." +check "...the next repo is still refreshed" has "[✓] Index for extra: serial" +check "...exit 1" rc 1 +check "...base's accepted index kept" kept +check "...extra's stored" cmp -s $E/repo.idx $S/extra.idx +conf ' { name = "base"; url = "http://example.org/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an http:// url is refused" has "[x] Malformed /etc/glacier/repos.conf." +conf ' { name = "base"; url = "https://127.0.0.1:1/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an https url that can't be reached fails in one line" has "[x] Cannot fetch the index for base." +check "...exit 1" rc 1 +conf "$BASE_E" + +hr "the repos directory and the lock" +cp $S/base.idx /srv/accepted.idx +printf 'garbage\n' > $S/base.idx +R syspkg -y +check "a corrupt accepted index is refused, not replaced" has "[x] Malformed $S/base.idx." +check "...exit 1" rc 1 +check "...left for the admin" grep -q garbage $S/base.idx +cp /srv/accepted.idx $S/base.idx +chmod 775 $S +R syspkg -y +check "a group-writable repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +chmod 755 $S +mv $S /srv/repos.real && ln -s /srv/repos.real $S +R syspkg -y +check "a symlinked repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +rm $S && mv /srv/repos.real $S +flock /glacier/sys/lock sleep 3 & +sleep 1 +R syspkg -y +check "-y waits for no one: a held lock refuses" has "[x] Another glacier transaction is already in progress for the system scope." +wait +R syspkg -y -l x +check "-y with -l is refused" has "[x] -n, -l, -f, -u, -x and -y are mutually exclusive." +R syspkg -y extra +check "-y takes no arguments" has "[x] Unexpected argument: extra" +adduser -D tester >/dev/null 2>&1 +R su tester -c 'syspkg -y' +check "syspkg -y as a user is refused" has "[x] Cannot open system index: Permission denied" + +hr "syspkg -R DIR -y" +mkdir -p /srv/img && chmod 755 /srv/img +syspkg -R /srv/img -n >/dev/null +cp $S/base.idx /srv/host.idx +grepo -s $TEST_SEC -r base -n 2090010300 $B >/dev/null +R syspkg -R /srv/img -y +check "-R stores the index under the install root" cmp -s $B/repo.idx /srv/img/glacier/sys/repos/base.idx +check "...leaving the host's alone" cmp -s $S/base.idx /srv/host.idx + +hr "gpkg -y" +U=$(id -u tester) +gstore -n "$U" >/dev/null +R su tester -c 'gpkg -y' +check "gpkg -y refreshes into the user's base" has "[✓] Index for base: serial 2090010300" +check "...owned by the user, 0700" [ "$(stat -c '%u %a' /glacier/usr/$U/repos)" = "$U 700" ] +check "...files 0600" [ "$(stat -c '%u %a' /glacier/usr/$U/repos/base.idx)" = "$U 600" ] +check "...byte for byte" cmp -s $B/repo.idx /glacier/usr/$U/repos/base.idx +serve "$(idx 2090010200)" +R su tester -c 'gpkg -y' +check "gpkg -y refuses a rollback too" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +R su tester -c 'gpkg -y base' +check "gpkg -y takes no arguments" has "[x] -y takes no arguments." + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/repo_alpine.sh.old3 b/tests/repo_alpine.sh.old3 new file mode 100644 index 0000000..e659c98 --- /dev/null +++ b/tests/repo_alpine.sh.old3 @@ -0,0 +1,305 @@ +#!/bin/sh +# Repository indexes (REPO_DESIGN.txt sections 4 and 5, step 3): +# - grepo writes DIR/repo.idx from DIR's packages and signs it; SERIAL +# is the date form YYYYMMDDNN, above the previous index's; -n, -e; +# packages of another repo, misnamed or non-regular are refused; +# - syspkg -y / gpkg -y fetch every repos.conf url's index (file:// +# here), check its signature with a key listed for THAT repo, parse +# it strictly, refuse a rollback, the same serial with other bytes, +# an expired index and another repo's index, and only then rename it +# into /repos; any failure keeps the accepted copy; +# - /repos gets the scope's owner and modes; it is refused if +# loosened or a symlink; -y holds the scope lock; -R stores under +# the install root, with the host's keyring. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/repo_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +B=/srv/base +E=/srv/extra +S=/glacier/sys/repos +mkdir -p $B $E && chmod 755 /srv $B $E + +gsign -G -p $K/extrakey.pub -s /root/extrakey.sec -c extrakey >/dev/null +gsign -G -p /root/stranger.pub -s /root/stranger.sec -c stranger >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; }' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; }' +pk() { /app/tests/mkpkg -o "$1" ${5:+-k "$5"} "$2" "$3" "$4" >/dev/null; } +field() { sed -n "s/^$1 = \\([0-9]*\\)L;\$/\\1/p" "$2"; } + +syspkg -n >/dev/null + +hr "grepo" +pk $B core 1.0.0 base $TEST_SEC +pk $B app 2.1.0 base $TEST_SEC +/app/tests/mkpkg -o $B -k $TEST_SEC -d core:1.0.0 -c rival:0.0.0 tool 1.2.3 base >/dev/null +R grepo -s $TEST_SEC -r base $B +check "grepo writes an index" rc 0 +check "...saying so" has "[✓] Wrote $B/repo.idx: 3 packages, serial $(date -u +%Y%m%d)01." +check "...signed: gsign verifies it with the test key" gsign -V -p $K/glacier-test.pub -m $B/repo.idx +check "...the first SERIAL is today's date form" [ "$(field SERIAL $B/repo.idx)" = "$(date -u +%Y%m%d)01" ] +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "...valid for 30 days by default" [ $((VU - NOW)) -gt $((30*86400 - 60)) -a $((VU - NOW)) -le $((30*86400)) ] +check "...packages sorted, with their sha256 and size" sh -c "grep -A1 'NAME = \"app\"' $B/repo.idx | grep -q \"SHA256 = \\\"sha256:$(sha256sum $B/app-2.1.0.gpkg | cut -c1-64)\\\"; SIZE = $(wc -c < $B/app-2.1.0.gpkg)L;\"" +check "...dependencies and conflicts from the manifest" grep -qF 'DEPS = ( { NAME = "core"; VER = "1.0.0"; } ); CONFS = ( { NAME = "rival"; VER = "0.0.0"; } );' $B/repo.idx +check "...no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +check "...the index is world-readable" [ "$(stat -c %a $B/repo.idx)" = 644 ] +R grepo -s $TEST_SEC -r base $B +check "a second run the same day takes the next serial" has "serial $(date -u +%Y%m%d)02." +R grepo -s $TEST_SEC -r base -n 5 $B +check "-n below the previous serial is refused" has "[x] SERIAL must be above $(date -u +%Y%m%d)02, the previous index's." +check "...exit 1, index unchanged" sh -c "[ $RC = 1 ] && grep -q '^SERIAL = $(date -u +%Y%m%d)02L;' $B/repo.idx" +R grepo -s $TEST_SEC -r base -n 2090010101 -e 1 $B +check "-n above it is used" grep -q '^SERIAL = 2090010101L;' $B/repo.idx +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "-e 1 makes it valid for one day" [ $((VU - NOW)) -gt $((86400 - 60)) -a $((VU - NOW)) -le 86400 ] +R grepo -s $TEST_SEC -r base -e 0 $B +check "-e 0 is refused" has "[x] DAYS must be a whole number from 1 to 3650." +R grepo -s $TEST_SEC -r base +check "no DIR prints the usage" has "usage: grepo -s KEY.sec -r REPO [-n SERIAL] [-e DAYS] DIR" +R grepo -s /root/missing.sec -r base $B +check "an unreadable secret key is refused" has "[x] Secret key /root/missing.sec cannot be read." +R grepo -s $TEST_SEC -r 'ba/se' $B +check "an unsafe repo name is refused" has "[x] Repository name ba/se is not a safe name ([A-Za-z0-9._-])." +cp $B/repo.idx /srv/before.idx +pk $B stray 1.0.0 extra +R grepo -s $TEST_SEC -r base $B +check "a package of another repo is refused" has "[x] $B/stray-1.0.0.gpkg is a extra package, not base." +check "...and the index is left as it was" cmp -s $B/repo.idx /srv/before.idx +check "...with no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +rm $B/stray-1.0.0.gpkg* +cp $B/core-1.0.0.gpkg $B/renamed-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a package named unlike its manifest is refused" has "[x] $B/renamed-1.0.0.gpkg must be named core-1.0.0.gpkg, as its manifest says." +rm $B/renamed-1.0.0.gpkg +ln -s /srv/base/core-1.0.0.gpkg $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a symlinked package is refused" has "[x] Refusing $B/link-1.0.0.gpkg: not a regular file." +rm $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r extra $B +check "a DIR holding another repo's index is refused" has "[x] $B/repo.idx is the index of another repository." +mkdir -p /srv/empty +R grepo -s $TEST_SEC -r community /srv/empty +check "an empty DIR makes an empty index" has "[✓] Wrote /srv/empty/repo.idx: 0 packages" +R grepo -s $TEST_SEC -r base -n 2090010102 $B +check "grepo works again after those refusals" rc 0 + +hr "signify interop" +if apk add --no-cache signify >/dev/null 2>&1; then + check "signify verifies grepo's index" signify -V -q -p $K/glacier-test.pub -m $B/repo.idx -x $B/repo.idx.sig +else + echo "FAIL: apk add signify"; FAILS=$((FAILS+1)) +fi + +hr "syspkg -y: accepting" +rm -f $CONF +R syspkg -y +check "no repos.conf: nothing to refresh" has "[x] No remote repositories are configured." +check "...exit 1" rc 1 +conf ' { name = "base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "repos.conf without a url: the same" has "[x] No remote repositories are configured." +conf "$BASE_E" +R syspkg -y +check "an index signed by a key listed for base is accepted" has "[✓] Index for base: serial 2090010102, 3 packages." +check "...exit 0" rc 0 +check "...stored byte for byte" cmp -s $B/repo.idx $S/base.idx +check "...with its signature" cmp -s $B/repo.idx.sig $S/base.idx.sig +check "...in a root-owned 0755 repos dir" [ "$(stat -c '%u %a' $S)" = "0 755" ] +check "...as root-owned 0644 files" [ "$(stat -c '%u %a' $S/base.idx) $(stat -c '%u %a' $S/base.idx.sig)" = "0 644 0 644" ] +check "...no temporary files left" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +R syspkg -y +check "refreshing again: one sync line" has "[i] Syncing all repositories..." +check "...nothing per repo when up to date" lacks "Index for base" +check "...exit 0" rc 0 +R syspkg -yV +check "with -V: up to date, by repo" has "[i] Index for base is up to date: serial 2090010102." +check "...exit 0" rc 0 +grepo -s $TEST_SEC -r base -n 2090010103 $B >/dev/null +R syspkg --refresh +check "a newer index is accepted (--refresh)" has "[✓] Index for base: serial 2090010103, 3 packages." +check "...replacing the stored one" cmp -s $B/repo.idx $S/base.idx + +hr "syspkg -y: refusing" +cp $S/base.idx /srv/accepted.idx +# serve TEXT [KEY.sec]: publish TEXT as base's index, signed (test key +# by default; "-" for no signature). +serve() { + printf '%s\n' "$1" > $B/repo.idx + rm -f $B/repo.idx.sig + [ "${2:-}" = - ] || gsign -S -s "${2:-$TEST_SEC}" -m $B/repo.idx >/dev/null +} +kept() { cmp -s $S/base.idx /srv/accepted.idx; } +FUTURE=$(( $(date +%s) + 86400 )) +SHA="sha256:$(printf '%064d' 0)" +idx() { # idx SERIAL [VALID_UNTIL [PKGS [REPO]]] + printf 'REPO = "%s";\nSERIAL = %sL;\nVALID_UNTIL = %sL;\nPKGS = (%s);' \ + "${4:-base}" "$1" "${2:-$FUTURE}" "${3:-}" +} +PKG1="{ NAME = \"a\"; VER = \"1.0.0\"; FILE = \"a-1.0.0.gpkg\"; SHA256 = \"$SHA\"; SIZE = 1L; DEPS = (); CONFS = (); }" + +serve "$(idx 2090010102)" +R syspkg -y +check "an older serial is refused" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +check "...keeping the accepted index" kept +check "...and no temporary files" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +serve "$(idx 2090010103 "" "$PKG1")" +R syspkg -y +check "the same serial with other contents is refused" has "[x] Index for base has the serial of the one already accepted, but other contents." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 $(( $(date +%s) - 10 )))" +R syspkg -y +check "an expired index is refused" has "[x] Index for base has expired." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" - +R syspkg -y +check "no signature: refused as unfetchable" has "[x] Cannot fetch the index for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/stranger.sec +R syspkg -y +check "a key in no keyring is refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/extrakey.sec +conf "$BASE_E +,$EXTRA_E" +R syspkg -y +check "a key listed only for extra is refused for base" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +conf "$BASE_E" +serve "$(idx 2090010200)" +printf '# appended after signing\n' >> $B/repo.idx +R syspkg -y +check "bytes changed after signing are refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 "" "" extra)" +R syspkg -y +check "another repo's index (validly signed) is refused" has "[x] Index fetched for base is the index of another repository." +check "...keeping the accepted index" kept + +# Signed, but not a well-formed index: each one "Malformed index". +malformed() { + serve "$2" + R syspkg -y + check "malformed: $1" sh -c "echo \"\$0\" | grep -qF '[x] Malformed index for base.' && cmp -s $S/base.idx /srv/accepted.idx" "$OUT" +} +malformed "not libconfig" "this is not an index" +malformed "an unknown top-level setting" "$(idx 2090010200) EXTRA = 1;" +malformed "a missing setting" 'REPO = "base"; SERIAL = 2090010200L; PKGS = ();' +malformed "SERIAL 0" "$(idx 0)" +malformed "SERIAL a string" "$(idx '"2090010200"' | sed 's/"L;/";/')" +# An include that WOULD make a valid index: only the '@' rule stops it. +printf 'PKGS = ();\n' > /srv/inc.cfg +malformed "@include" "$(idx 2090010200 | grep -v '^PKGS') +@include \"/srv/inc.cfg\"" +malformed "an unknown package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/CONFS = ();/CONFS = (); X = 1;/')")" +malformed "a missing package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/SIZE = 1L; //')")" +malformed "FILE not NAME-VER.gpkg" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#a-1.0.0.gpkg#../x-1.0.0.gpkg#')")" +malformed "an unsafe NAME" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#NAME = "a"#NAME = "a/b"#; s#a-1.0.0.gpkg#a/b-1.0.0.gpkg#')")" +malformed "a version with a leading zero" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.00.0#g')")" +malformed "a version with a tag" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.0.0-rc1#g')")" +malformed "uppercase hex" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:A#')")" +malformed "a short hash" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:#')")" +malformed "a negative SIZE" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#SIZE = 1L#SIZE = -1L#')")" +malformed "the same NAME and VER twice" "$(idx 2090010200 "" "$PKG1, $PKG1")" +malformed "a dependency without VER" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#DEPS = ()#DEPS = ( { NAME = "b"; } )#')")" +serve "$(idx 2090010200 "" "$PKG1, $(echo "$PKG1" | sed 's#1\.0\.0#1.0.1#g')")" +R syspkg -y +check "two versions of one package are fine" has "[✓] Index for base: serial 2090010200, 2 packages." +cp $S/base.idx /srv/accepted.idx + +hr "fetch failures and several repos" +grepo -s /root/extrakey.sec -r extra $E >/dev/null 2>&1 || true +pk $E ex 1.0.0 extra +grepo -s /root/extrakey.sec -r extra $E >/dev/null +conf ' { name = "base"; url = "file:///srv/nowhere"; keys = [ "glacier-test" ]; } +,'"$EXTRA_E" +R syspkg -y +check "an unreachable repo fails" has "[x] Cannot fetch the index for base." +check "...the next repo is still refreshed" has "[✓] Index for extra: serial" +check "...exit 1" rc 1 +check "...base's accepted index kept" kept +check "...extra's stored" cmp -s $E/repo.idx $S/extra.idx +conf ' { name = "base"; url = "http://example.org/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an http:// url is refused" has "[x] Malformed /etc/glacier/repos.conf." +conf ' { name = "base"; url = "https://127.0.0.1:1/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an https url that can't be reached fails in one line" has "[x] Cannot fetch the index for base." +check "...exit 1" rc 1 +conf "$BASE_E" + +hr "the repos directory and the lock" +cp $S/base.idx /srv/accepted.idx +printf 'garbage\n' > $S/base.idx +R syspkg -y +check "a corrupt accepted index is refused, not replaced" has "[x] Malformed $S/base.idx." +check "...exit 1" rc 1 +check "...left for the admin" grep -q garbage $S/base.idx +cp /srv/accepted.idx $S/base.idx +chmod 775 $S +R syspkg -y +check "a group-writable repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +chmod 755 $S +mv $S /srv/repos.real && ln -s /srv/repos.real $S +R syspkg -y +check "a symlinked repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +rm $S && mv /srv/repos.real $S +flock /glacier/sys/lock sleep 3 & +sleep 1 +R syspkg -y +check "-y waits for no one: a held lock refuses" has "[x] Another glacier transaction is already in progress for the system scope." +wait +R syspkg -y -l x +check "-y with -l is refused" has "[x] -n, -l, -f, -u, -x and -y are mutually exclusive." +R syspkg -y extra +check "-y takes no arguments" has "[x] Unexpected argument: extra" +adduser -D tester >/dev/null 2>&1 +R su tester -c 'syspkg -y' +check "syspkg -y as a user is refused" has "[x] Cannot open system index: Permission denied" + +hr "syspkg -R DIR -y" +mkdir -p /srv/img && chmod 755 /srv/img +syspkg -R /srv/img -n >/dev/null +cp $S/base.idx /srv/host.idx +grepo -s $TEST_SEC -r base -n 2090010300 $B >/dev/null +R syspkg -R /srv/img -y +check "-R stores the index under the install root" cmp -s $B/repo.idx /srv/img/glacier/sys/repos/base.idx +check "...leaving the host's alone" cmp -s $S/base.idx /srv/host.idx + +hr "gpkg -y" +U=$(id -u tester) +gstore -n "$U" >/dev/null +R su tester -c 'gpkg -y' +check "gpkg -y refreshes into the user's base" has "[✓] Index for base: serial 2090010300" +check "...owned by the user, 0700" [ "$(stat -c '%u %a' /glacier/usr/$U/repos)" = "$U 700" ] +check "...files 0600" [ "$(stat -c '%u %a' /glacier/usr/$U/repos/base.idx)" = "$U 600" ] +check "...byte for byte" cmp -s $B/repo.idx /glacier/usr/$U/repos/base.idx +serve "$(idx 2090010200)" +R su tester -c 'gpkg -y' +check "gpkg -y refuses a rollback too" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +R su tester -c 'gpkg -y base' +check "gpkg -y takes no arguments" has "[x] -y takes no arguments." + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/repo_alpine.sh.old4 b/tests/repo_alpine.sh.old4 new file mode 100644 index 0000000..d968c03 --- /dev/null +++ b/tests/repo_alpine.sh.old4 @@ -0,0 +1,309 @@ +#!/bin/sh +# Repository indexes (REPO_DESIGN.txt sections 4 and 5, step 3): +# - grepo writes DIR/repo.idx from DIR's packages and signs it; SERIAL +# is the date form YYYYMMDDNN, above the previous index's; -n, -e; +# packages of another repo, misnamed or non-regular are refused; +# - syspkg -y / gpkg -y fetch every repos.conf url's index (file:// +# here), check its signature with a key listed for THAT repo, parse +# it strictly, refuse a rollback, the same serial with other bytes, +# an expired index and another repo's index, and only then rename it +# into /repos; any failure keeps the accepted copy; +# - /repos gets the scope's owner and modes; it is refused if +# loosened or a symlink; -y holds the scope lock; -R stores under +# the install root, with the host's keyring. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/repo_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +B=/srv/base +E=/srv/extra +S=/glacier/sys/repos +mkdir -p $B $E && chmod 755 /srv $B $E + +gsign -G -p $K/extrakey.pub -s /root/extrakey.sec -c extrakey >/dev/null +gsign -G -p /root/stranger.pub -s /root/stranger.sec -c stranger >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; }' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; }' +pk() { /app/tests/mkpkg -o "$1" ${5:+-k "$5"} "$2" "$3" "$4" >/dev/null; } +field() { sed -n "s/^$1 = \\([0-9]*\\)L;\$/\\1/p" "$2"; } + +syspkg -n >/dev/null + +hr "grepo" +pk $B core 1.0.0 base $TEST_SEC +pk $B app 2.1.0 base $TEST_SEC +/app/tests/mkpkg -o $B -k $TEST_SEC -d core:1.0.0 -c rival:0.0.0 tool 1.2.3 base >/dev/null +R grepo -s $TEST_SEC -r base $B +check "grepo writes an index" rc 0 +check "...saying so" has "[✓] Wrote $B/repo.idx: 3 packages, serial $(date -u +%Y%m%d)01." +check "...signed: gsign verifies it with the test key" gsign -V -p $K/glacier-test.pub -m $B/repo.idx +check "...the first SERIAL is today's date form" [ "$(field SERIAL $B/repo.idx)" = "$(date -u +%Y%m%d)01" ] +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "...valid for 30 days by default" [ $((VU - NOW)) -gt $((30*86400 - 60)) -a $((VU - NOW)) -le $((30*86400)) ] +check "...packages sorted, with their sha256 and size" sh -c "grep -A1 'NAME = \"app\"' $B/repo.idx | grep -q \"SHA256 = \\\"sha256:$(sha256sum $B/app-2.1.0.gpkg | cut -c1-64)\\\"; SIZE = $(wc -c < $B/app-2.1.0.gpkg)L;\"" +check "...dependencies and conflicts from the manifest" grep -qF 'DEPS = ( { NAME = "core"; VER = "1.0.0"; } ); CONFS = ( { NAME = "rival"; VER = "0.0.0"; } );' $B/repo.idx +check "...no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +check "...the index is world-readable" [ "$(stat -c %a $B/repo.idx)" = 644 ] +R grepo -s $TEST_SEC -r base $B +check "a second run the same day takes the next serial" has "serial $(date -u +%Y%m%d)02." +R grepo -s $TEST_SEC -r base -n 5 $B +check "-n below the previous serial is refused" has "[x] SERIAL must be above $(date -u +%Y%m%d)02, the previous index's." +check "...exit 1, index unchanged" sh -c "[ $RC = 1 ] && grep -q '^SERIAL = $(date -u +%Y%m%d)02L;' $B/repo.idx" +R grepo -s $TEST_SEC -r base -n 2090010101 -e 1 $B +check "-n above it is used" grep -q '^SERIAL = 2090010101L;' $B/repo.idx +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "-e 1 makes it valid for one day" [ $((VU - NOW)) -gt $((86400 - 60)) -a $((VU - NOW)) -le 86400 ] +R grepo -s $TEST_SEC -r base -e 0 $B +check "-e 0 is refused" has "[x] DAYS must be a whole number from 1 to 3650." +R grepo -s $TEST_SEC -r base +check "no DIR prints the usage" has "usage: grepo -s KEY.sec -r REPO [-n SERIAL] [-e DAYS] DIR" +R grepo -s /root/missing.sec -r base $B +check "an unreadable secret key is refused" has "[x] Secret key /root/missing.sec cannot be read." +R grepo -s $TEST_SEC -r 'ba/se' $B +check "an unsafe repo name is refused" has "[x] Repository name ba/se is not a safe name ([A-Za-z0-9._-])." +cp $B/repo.idx /srv/before.idx +pk $B stray 1.0.0 extra +R grepo -s $TEST_SEC -r base $B +check "a package of another repo is refused" has "[x] $B/stray-1.0.0.gpkg is a extra package, not base." +check "...and the index is left as it was" cmp -s $B/repo.idx /srv/before.idx +check "...with no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +rm $B/stray-1.0.0.gpkg* +cp $B/core-1.0.0.gpkg $B/renamed-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a package named unlike its manifest is refused" has "[x] $B/renamed-1.0.0.gpkg must be named core-1.0.0.gpkg, as its manifest says." +rm $B/renamed-1.0.0.gpkg +ln -s /srv/base/core-1.0.0.gpkg $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a symlinked package is refused" has "[x] Refusing $B/link-1.0.0.gpkg: not a regular file." +rm $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r extra $B +check "a DIR holding another repo's index is refused" has "[x] $B/repo.idx is the index of another repository." +mkdir -p /srv/empty +R grepo -s $TEST_SEC -r community /srv/empty +check "an empty DIR makes an empty index" has "[✓] Wrote /srv/empty/repo.idx: 0 packages" +R grepo -s $TEST_SEC -r base -n 2090010102 $B +check "grepo works again after those refusals" rc 0 + +hr "signify interop" +if apk add --no-cache signify >/dev/null 2>&1; then + check "signify verifies grepo's index" signify -V -q -p $K/glacier-test.pub -m $B/repo.idx -x $B/repo.idx.sig +else + echo "FAIL: apk add signify"; FAILS=$((FAILS+1)) +fi + +hr "syspkg -y: accepting" +rm -f $CONF +R syspkg -y +check "no repos.conf: nothing to refresh" has "[x] No remote repositories are configured." +check "...exit 1" rc 1 +conf ' { name = "base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "repos.conf without a url: the same" has "[x] No remote repositories are configured." +conf "$BASE_E" +R syspkg -y +check "an index signed by a key listed for base is accepted" has "[✓] All repositories synced successfully." +check "...nothing per repo without -V" lacks "Index for base" +check "...exit 0" rc 0 +check "...stored byte for byte" cmp -s $B/repo.idx $S/base.idx +check "...with its signature" cmp -s $B/repo.idx.sig $S/base.idx.sig +check "...in a root-owned 0755 repos dir" [ "$(stat -c '%u %a' $S)" = "0 755" ] +check "...as root-owned 0644 files" [ "$(stat -c '%u %a' $S/base.idx) $(stat -c '%u %a' $S/base.idx.sig)" = "0 644 0 644" ] +check "...no temporary files left" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +R syspkg -y +check "refreshing again: one sync line" has "[i] Syncing all repositories..." +check "...nothing per repo when up to date" lacks "Index for base" +check "...exit 0" rc 0 +R syspkg -yV +check "with -V: up to date, by repo" has "[i] Index for base is up to date: serial 2090010102." +check "...exit 0" rc 0 +grepo -s $TEST_SEC -r base -n 2090010103 $B >/dev/null +R syspkg --refresh -V +check "a newer index is accepted (--refresh)" has "[✓] All repositories synced successfully." +check "...with -V: its serial, by repo" has "[✓] Index for base: serial 2090010103, 3 packages." +check "...replacing the stored one" cmp -s $B/repo.idx $S/base.idx + +hr "syspkg -y: refusing" +cp $S/base.idx /srv/accepted.idx +# serve TEXT [KEY.sec]: publish TEXT as base's index, signed (test key +# by default; "-" for no signature). +serve() { + printf '%s\n' "$1" > $B/repo.idx + rm -f $B/repo.idx.sig + [ "${2:-}" = - ] || gsign -S -s "${2:-$TEST_SEC}" -m $B/repo.idx >/dev/null +} +kept() { cmp -s $S/base.idx /srv/accepted.idx; } +FUTURE=$(( $(date +%s) + 86400 )) +SHA="sha256:$(printf '%064d' 0)" +idx() { # idx SERIAL [VALID_UNTIL [PKGS [REPO]]] + printf 'REPO = "%s";\nSERIAL = %sL;\nVALID_UNTIL = %sL;\nPKGS = (%s);' \ + "${4:-base}" "$1" "${2:-$FUTURE}" "${3:-}" +} +PKG1="{ NAME = \"a\"; VER = \"1.0.0\"; FILE = \"a-1.0.0.gpkg\"; SHA256 = \"$SHA\"; SIZE = 1L; DEPS = (); CONFS = (); }" + +serve "$(idx 2090010102)" +R syspkg -y +check "an older serial is refused" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +check "...keeping the accepted index" kept +check "...and no temporary files" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +serve "$(idx 2090010103 "" "$PKG1")" +R syspkg -y +check "the same serial with other contents is refused" has "[x] Index for base has the serial of the one already accepted, but other contents." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 $(( $(date +%s) - 10 )))" +R syspkg -y +check "an expired index is refused" has "[x] Index for base has expired." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" - +R syspkg -y +check "no signature: refused as unfetchable" has "[x] Cannot fetch the index for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/stranger.sec +R syspkg -y +check "a key in no keyring is refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/extrakey.sec +conf "$BASE_E +,$EXTRA_E" +R syspkg -y +check "a key listed only for extra is refused for base" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +conf "$BASE_E" +serve "$(idx 2090010200)" +printf '# appended after signing\n' >> $B/repo.idx +R syspkg -y +check "bytes changed after signing are refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 "" "" extra)" +R syspkg -y +check "another repo's index (validly signed) is refused" has "[x] Index fetched for base is the index of another repository." +check "...keeping the accepted index" kept + +# Signed, but not a well-formed index: each one "Malformed index". +malformed() { + serve "$2" + R syspkg -y + check "malformed: $1" sh -c "echo \"\$0\" | grep -qF '[x] Malformed index for base.' && cmp -s $S/base.idx /srv/accepted.idx" "$OUT" +} +malformed "not libconfig" "this is not an index" +malformed "an unknown top-level setting" "$(idx 2090010200) EXTRA = 1;" +malformed "a missing setting" 'REPO = "base"; SERIAL = 2090010200L; PKGS = ();' +malformed "SERIAL 0" "$(idx 0)" +malformed "SERIAL a string" "$(idx '"2090010200"' | sed 's/"L;/";/')" +# An include that WOULD make a valid index: only the '@' rule stops it. +printf 'PKGS = ();\n' > /srv/inc.cfg +malformed "@include" "$(idx 2090010200 | grep -v '^PKGS') +@include \"/srv/inc.cfg\"" +malformed "an unknown package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/CONFS = ();/CONFS = (); X = 1;/')")" +malformed "a missing package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/SIZE = 1L; //')")" +malformed "FILE not NAME-VER.gpkg" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#a-1.0.0.gpkg#../x-1.0.0.gpkg#')")" +malformed "an unsafe NAME" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#NAME = "a"#NAME = "a/b"#; s#a-1.0.0.gpkg#a/b-1.0.0.gpkg#')")" +malformed "a version with a leading zero" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.00.0#g')")" +malformed "a version with a tag" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.0.0-rc1#g')")" +malformed "uppercase hex" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:A#')")" +malformed "a short hash" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:#')")" +malformed "a negative SIZE" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#SIZE = 1L#SIZE = -1L#')")" +malformed "the same NAME and VER twice" "$(idx 2090010200 "" "$PKG1, $PKG1")" +malformed "a dependency without VER" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#DEPS = ()#DEPS = ( { NAME = "b"; } )#')")" +serve "$(idx 2090010200 "" "$PKG1, $(echo "$PKG1" | sed 's#1\.0\.0#1.0.1#g')")" +R syspkg -yV +check "two versions of one package are fine" has "[✓] Index for base: serial 2090010200, 2 packages." +cp $S/base.idx /srv/accepted.idx + +hr "fetch failures and several repos" +grepo -s /root/extrakey.sec -r extra $E >/dev/null 2>&1 || true +pk $E ex 1.0.0 extra +grepo -s /root/extrakey.sec -r extra $E >/dev/null +conf ' { name = "base"; url = "file:///srv/nowhere"; keys = [ "glacier-test" ]; } +,'"$EXTRA_E" +R syspkg -yV +check "an unreachable repo fails" has "[x] Cannot fetch the index for base." +check "...the next repo is still refreshed" has "[✓] Index for extra: serial" +check "...not reported as all synced" lacks "All repositories synced" +check "...exit 1" rc 1 +check "...base's accepted index kept" kept +check "...extra's stored" cmp -s $E/repo.idx $S/extra.idx +conf ' { name = "base"; url = "http://example.org/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an http:// url is refused" has "[x] Malformed /etc/glacier/repos.conf." +conf ' { name = "base"; url = "https://127.0.0.1:1/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an https url that can't be reached fails in one line" has "[x] Cannot fetch the index for base." +check "...exit 1" rc 1 +conf "$BASE_E" + +hr "the repos directory and the lock" +cp $S/base.idx /srv/accepted.idx +printf 'garbage\n' > $S/base.idx +R syspkg -y +check "a corrupt accepted index is refused, not replaced" has "[x] Malformed $S/base.idx." +check "...exit 1" rc 1 +check "...left for the admin" grep -q garbage $S/base.idx +cp /srv/accepted.idx $S/base.idx +chmod 775 $S +R syspkg -y +check "a group-writable repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +chmod 755 $S +mv $S /srv/repos.real && ln -s /srv/repos.real $S +R syspkg -y +check "a symlinked repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +rm $S && mv /srv/repos.real $S +flock /glacier/sys/lock sleep 3 & +sleep 1 +R syspkg -y +check "-y waits for no one: a held lock refuses" has "[x] Another glacier transaction is already in progress for the system scope." +wait +R syspkg -y -l x +check "-y with -l is refused" has "[x] -n, -l, -f, -u, -x and -y are mutually exclusive." +R syspkg -y extra +check "-y takes no arguments" has "[x] Unexpected argument: extra" +adduser -D tester >/dev/null 2>&1 +R su tester -c 'syspkg -y' +check "syspkg -y as a user is refused" has "[x] Cannot open system index: Permission denied" + +hr "syspkg -R DIR -y" +mkdir -p /srv/img && chmod 755 /srv/img +syspkg -R /srv/img -n >/dev/null +cp $S/base.idx /srv/host.idx +grepo -s $TEST_SEC -r base -n 2090010300 $B >/dev/null +R syspkg -R /srv/img -y +check "-R stores the index under the install root" cmp -s $B/repo.idx /srv/img/glacier/sys/repos/base.idx +check "...leaving the host's alone" cmp -s $S/base.idx /srv/host.idx + +hr "gpkg -y" +U=$(id -u tester) +gstore -n "$U" >/dev/null +R su tester -c 'gpkg -y' +check "gpkg -y refreshes into the user's base" has "[✓] All repositories synced successfully." +check "...nothing per repo without -V" lacks "Index for base" +check "...owned by the user, 0700" [ "$(stat -c '%u %a' /glacier/usr/$U/repos)" = "$U 700" ] +check "...files 0600" [ "$(stat -c '%u %a' /glacier/usr/$U/repos/base.idx)" = "$U 600" ] +check "...byte for byte" cmp -s $B/repo.idx /glacier/usr/$U/repos/base.idx +serve "$(idx 2090010200)" +R su tester -c 'gpkg -y' +check "gpkg -y refuses a rollback too" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +R su tester -c 'gpkg -y base' +check "gpkg -y takes no arguments" has "[x] -y takes no arguments." + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/repo_alpine.sh.old5 b/tests/repo_alpine.sh.old5 new file mode 100644 index 0000000..c9e44c0 --- /dev/null +++ b/tests/repo_alpine.sh.old5 @@ -0,0 +1,313 @@ +#!/bin/sh +# Repository indexes (REPO_DESIGN.txt sections 4 and 5, step 3): +# - grepo writes DIR/repo.idx from DIR's packages and signs it; SERIAL +# is the date form YYYYMMDDNN, above the previous index's; -n, -e; +# packages of another repo, misnamed or non-regular are refused; +# - syspkg -y / gpkg -y fetch every repos.conf url's index (file:// +# here), check its signature with a key listed for THAT repo, parse +# it strictly, refuse a rollback, the same serial with other bytes, +# an expired index and another repo's index, and only then rename it +# into /repos; any failure keeps the accepted copy; +# - /repos gets the scope's owner and modes; it is refused if +# loosened or a symlink; -y holds the scope lock; -R stores under +# the install root, with the install root's own keyring. +# Runs INSIDE the Dockerfile.alpine_root image (its test key, +# glacier-test, is listed for base): +# +# docker run --rm -v "$PWD/tests/repo_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +export PATH=/app:$PATH + +K=/etc/glacier/keys +CONF=/etc/glacier/repos.conf +TEST_SEC=/root/glacier-test.sec +B=/srv/base +E=/srv/extra +S=/glacier/sys/repos +mkdir -p $B $E && chmod 755 /srv $B $E + +gsign -G -p $K/extrakey.pub -s /root/extrakey.sec -c extrakey >/dev/null +gsign -G -p /root/stranger.pub -s /root/stranger.sec -c stranger >/dev/null +conf() { printf 'repos = (\n%s\n);\n' "$1" > $CONF; chmod 644 $CONF; } +BASE_E=' { name = "base"; url = "file:///srv/base"; keys = [ "glacier-test" ]; }' +EXTRA_E=' { name = "extra"; url = "file:///srv/extra"; keys = [ "extrakey" ]; }' +pk() { /app/tests/mkpkg -o "$1" ${5:+-k "$5"} "$2" "$3" "$4" >/dev/null; } +field() { sed -n "s/^$1 = \\([0-9]*\\)L;\$/\\1/p" "$2"; } + +syspkg -n >/dev/null + +hr "grepo" +pk $B core 1.0.0 base $TEST_SEC +pk $B app 2.1.0 base $TEST_SEC +/app/tests/mkpkg -o $B -k $TEST_SEC -d core:1.0.0 -c rival:0.0.0 tool 1.2.3 base >/dev/null +R grepo -s $TEST_SEC -r base $B +check "grepo writes an index" rc 0 +check "...saying so" has "[✓] Wrote $B/repo.idx: 3 packages, serial $(date -u +%Y%m%d)01." +check "...signed: gsign verifies it with the test key" gsign -V -p $K/glacier-test.pub -m $B/repo.idx +check "...the first SERIAL is today's date form" [ "$(field SERIAL $B/repo.idx)" = "$(date -u +%Y%m%d)01" ] +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "...valid for 30 days by default" [ $((VU - NOW)) -gt $((30*86400 - 60)) -a $((VU - NOW)) -le $((30*86400)) ] +check "...packages sorted, with their sha256 and size" sh -c "grep -A1 'NAME = \"app\"' $B/repo.idx | grep -q \"SHA256 = \\\"sha256:$(sha256sum $B/app-2.1.0.gpkg | cut -c1-64)\\\"; SIZE = $(wc -c < $B/app-2.1.0.gpkg)L;\"" +check "...dependencies and conflicts from the manifest" grep -qF 'DEPS = ( { NAME = "core"; VER = "1.0.0"; } ); CONFS = ( { NAME = "rival"; VER = "0.0.0"; } );' $B/repo.idx +check "...no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +check "...the index is world-readable" [ "$(stat -c %a $B/repo.idx)" = 644 ] +R grepo -s $TEST_SEC -r base $B +check "a second run the same day takes the next serial" has "serial $(date -u +%Y%m%d)02." +R grepo -s $TEST_SEC -r base -n 5 $B +check "-n below the previous serial is refused" has "[x] SERIAL must be above $(date -u +%Y%m%d)02, the previous index's." +check "...exit 1, index unchanged" sh -c "[ $RC = 1 ] && grep -q '^SERIAL = $(date -u +%Y%m%d)02L;' $B/repo.idx" +R grepo -s $TEST_SEC -r base -n 2090010101 -e 1 $B +check "-n above it is used" grep -q '^SERIAL = 2090010101L;' $B/repo.idx +VU=$(field VALID_UNTIL $B/repo.idx); NOW=$(date +%s) +check "-e 1 makes it valid for one day" [ $((VU - NOW)) -gt $((86400 - 60)) -a $((VU - NOW)) -le 86400 ] +R grepo -s $TEST_SEC -r base -e 0 $B +check "-e 0 is refused" has "[x] DAYS must be a whole number from 1 to 3650." +R grepo -s $TEST_SEC -r base +check "no DIR prints the usage" has "usage: grepo -s KEY.sec -r REPO [-n SERIAL] [-e DAYS] DIR" +R grepo -s /root/missing.sec -r base $B +check "an unreadable secret key is refused" has "[x] Secret key /root/missing.sec cannot be read." +R grepo -s $TEST_SEC -r 'ba/se' $B +check "an unsafe repo name is refused" has "[x] Repository name ba/se is not a safe name ([A-Za-z0-9._-])." +cp $B/repo.idx /srv/before.idx +pk $B stray 1.0.0 extra +R grepo -s $TEST_SEC -r base $B +check "a package of another repo is refused" has "[x] $B/stray-1.0.0.gpkg is a extra package, not base." +check "...and the index is left as it was" cmp -s $B/repo.idx /srv/before.idx +check "...with no temporary files left" [ "$(ls -A $B | grep -c '^\.')" = 0 ] +rm $B/stray-1.0.0.gpkg* +cp $B/core-1.0.0.gpkg $B/renamed-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a package named unlike its manifest is refused" has "[x] $B/renamed-1.0.0.gpkg must be named core-1.0.0.gpkg, as its manifest says." +rm $B/renamed-1.0.0.gpkg +ln -s /srv/base/core-1.0.0.gpkg $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r base $B +check "a symlinked package is refused" has "[x] Refusing $B/link-1.0.0.gpkg: not a regular file." +rm $B/link-1.0.0.gpkg +R grepo -s $TEST_SEC -r extra $B +check "a DIR holding another repo's index is refused" has "[x] $B/repo.idx is the index of another repository." +mkdir -p /srv/empty +R grepo -s $TEST_SEC -r community /srv/empty +check "an empty DIR makes an empty index" has "[✓] Wrote /srv/empty/repo.idx: 0 packages" +R grepo -s $TEST_SEC -r base -n 2090010102 $B +check "grepo works again after those refusals" rc 0 + +hr "signify interop" +if apk add --no-cache signify >/dev/null 2>&1; then + check "signify verifies grepo's index" signify -V -q -p $K/glacier-test.pub -m $B/repo.idx -x $B/repo.idx.sig +else + echo "FAIL: apk add signify"; FAILS=$((FAILS+1)) +fi + +hr "syspkg -y: accepting" +rm -f $CONF +R syspkg -y +check "no repos.conf: nothing to refresh" has "[x] No remote repositories are configured." +check "...exit 1" rc 1 +conf ' { name = "base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "repos.conf without a url: the same" has "[x] No remote repositories are configured." +conf "$BASE_E" +R syspkg -y +check "an index signed by a key listed for base is accepted" has "[✓] All repositories synced successfully." +check "...nothing per repo without -V" lacks "Index for base" +check "...exit 0" rc 0 +check "...stored byte for byte" cmp -s $B/repo.idx $S/base.idx +check "...with its signature" cmp -s $B/repo.idx.sig $S/base.idx.sig +check "...in a root-owned 0755 repos dir" [ "$(stat -c '%u %a' $S)" = "0 755" ] +check "...as root-owned 0644 files" [ "$(stat -c '%u %a' $S/base.idx) $(stat -c '%u %a' $S/base.idx.sig)" = "0 644 0 644" ] +check "...no temporary files left" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +R syspkg -y +check "refreshing again: one sync line" has "[i] Syncing all repositories..." +check "...nothing per repo when up to date" lacks "Index for base" +check "...exit 0" rc 0 +R syspkg -yV +check "with -V: up to date, by repo" has "[i] Index for base is up to date: serial 2090010102." +check "...exit 0" rc 0 +grepo -s $TEST_SEC -r base -n 2090010103 $B >/dev/null +R syspkg --refresh -V +check "a newer index is accepted (--refresh)" has "[✓] All repositories synced successfully." +check "...with -V: its serial, by repo" has "[✓] Index for base: serial 2090010103, 3 packages." +check "...replacing the stored one" cmp -s $B/repo.idx $S/base.idx + +hr "syspkg -y: refusing" +cp $S/base.idx /srv/accepted.idx +# serve TEXT [KEY.sec]: publish TEXT as base's index, signed (test key +# by default; "-" for no signature). +serve() { + printf '%s\n' "$1" > $B/repo.idx + rm -f $B/repo.idx.sig + [ "${2:-}" = - ] || gsign -S -s "${2:-$TEST_SEC}" -m $B/repo.idx >/dev/null +} +kept() { cmp -s $S/base.idx /srv/accepted.idx; } +FUTURE=$(( $(date +%s) + 86400 )) +SHA="sha256:$(printf '%064d' 0)" +idx() { # idx SERIAL [VALID_UNTIL [PKGS [REPO]]] + printf 'REPO = "%s";\nSERIAL = %sL;\nVALID_UNTIL = %sL;\nPKGS = (%s);' \ + "${4:-base}" "$1" "${2:-$FUTURE}" "${3:-}" +} +PKG1="{ NAME = \"a\"; VER = \"1.0.0\"; FILE = \"a-1.0.0.gpkg\"; SHA256 = \"$SHA\"; SIZE = 1L; DEPS = (); CONFS = (); }" + +serve "$(idx 2090010102)" +R syspkg -y +check "an older serial is refused" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +check "...keeping the accepted index" kept +check "...and no temporary files" [ "$(ls -A $S | tr '\n' ' ')" = "base.idx base.idx.sig " ] +serve "$(idx 2090010103 "" "$PKG1")" +R syspkg -y +check "the same serial with other contents is refused" has "[x] Index for base has the serial of the one already accepted, but other contents." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 $(( $(date +%s) - 10 )))" +R syspkg -y +check "an expired index is refused" has "[x] Index for base has expired." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" - +R syspkg -y +check "no signature: refused as unfetchable" has "[x] Cannot fetch the index for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/stranger.sec +R syspkg -y +check "a key in no keyring is refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200)" /root/extrakey.sec +conf "$BASE_E +,$EXTRA_E" +R syspkg -y +check "a key listed only for extra is refused for base" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +conf "$BASE_E" +serve "$(idx 2090010200)" +printf '# appended after signing\n' >> $B/repo.idx +R syspkg -y +check "bytes changed after signing are refused" has "[x] Index for base is not signed by a key trusted for base." +check "...keeping the accepted index" kept +serve "$(idx 2090010200 "" "" extra)" +R syspkg -y +check "another repo's index (validly signed) is refused" has "[x] Index fetched for base is the index of another repository." +check "...keeping the accepted index" kept + +# Signed, but not a well-formed index: each one "Malformed index". +malformed() { + serve "$2" + R syspkg -y + check "malformed: $1" sh -c "echo \"\$0\" | grep -qF '[x] Malformed index for base.' && cmp -s $S/base.idx /srv/accepted.idx" "$OUT" +} +malformed "not libconfig" "this is not an index" +malformed "an unknown top-level setting" "$(idx 2090010200) EXTRA = 1;" +malformed "a missing setting" 'REPO = "base"; SERIAL = 2090010200L; PKGS = ();' +malformed "SERIAL 0" "$(idx 0)" +malformed "SERIAL a string" "$(idx '"2090010200"' | sed 's/"L;/";/')" +# An include that WOULD make a valid index: only the '@' rule stops it. +printf 'PKGS = ();\n' > /srv/inc.cfg +malformed "@include" "$(idx 2090010200 | grep -v '^PKGS') +@include \"/srv/inc.cfg\"" +malformed "an unknown package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/CONFS = ();/CONFS = (); X = 1;/')")" +malformed "a missing package field" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's/SIZE = 1L; //')")" +malformed "FILE not NAME-VER.gpkg" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#a-1.0.0.gpkg#../x-1.0.0.gpkg#')")" +malformed "an unsafe NAME" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#NAME = "a"#NAME = "a/b"#; s#a-1.0.0.gpkg#a/b-1.0.0.gpkg#')")" +malformed "a version with a leading zero" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.00.0#g')")" +malformed "a version with a tag" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#1\.0\.0#1.0.0-rc1#g')")" +malformed "uppercase hex" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:A#')")" +malformed "a short hash" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#sha256:0#sha256:#')")" +malformed "a negative SIZE" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#SIZE = 1L#SIZE = -1L#')")" +malformed "the same NAME and VER twice" "$(idx 2090010200 "" "$PKG1, $PKG1")" +malformed "a dependency without VER" "$(idx 2090010200 "" "$(echo "$PKG1" | sed 's#DEPS = ()#DEPS = ( { NAME = "b"; } )#')")" +serve "$(idx 2090010200 "" "$PKG1, $(echo "$PKG1" | sed 's#1\.0\.0#1.0.1#g')")" +R syspkg -yV +check "two versions of one package are fine" has "[✓] Index for base: serial 2090010200, 2 packages." +cp $S/base.idx /srv/accepted.idx + +hr "fetch failures and several repos" +grepo -s /root/extrakey.sec -r extra $E >/dev/null 2>&1 || true +pk $E ex 1.0.0 extra +grepo -s /root/extrakey.sec -r extra $E >/dev/null +conf ' { name = "base"; url = "file:///srv/nowhere"; keys = [ "glacier-test" ]; } +,'"$EXTRA_E" +R syspkg -yV +check "an unreachable repo fails" has "[x] Cannot fetch the index for base." +check "...the next repo is still refreshed" has "[✓] Index for extra: serial" +check "...not reported as all synced" lacks "All repositories synced" +check "...exit 1" rc 1 +check "...base's accepted index kept" kept +check "...extra's stored" cmp -s $E/repo.idx $S/extra.idx +conf ' { name = "base"; url = "http://example.org/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an http:// url is refused" has "[x] Malformed /etc/glacier/repos.conf." +conf ' { name = "base"; url = "https://127.0.0.1:1/base"; keys = [ "glacier-test" ]; }' +R syspkg -y +check "an https url that can't be reached fails in one line" has "[x] Cannot fetch the index for base." +check "...exit 1" rc 1 +conf "$BASE_E" + +hr "the repos directory and the lock" +cp $S/base.idx /srv/accepted.idx +printf 'garbage\n' > $S/base.idx +R syspkg -y +check "a corrupt accepted index is refused, not replaced" has "[x] Malformed $S/base.idx." +check "...exit 1" rc 1 +check "...left for the admin" grep -q garbage $S/base.idx +cp /srv/accepted.idx $S/base.idx +chmod 775 $S +R syspkg -y +check "a group-writable repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +chmod 755 $S +mv $S /srv/repos.real && ln -s /srv/repos.real $S +R syspkg -y +check "a symlinked repos dir is refused" has "[x] Refusing $S: not a directory owned by UID 0 with mode 755." +rm $S && mv /srv/repos.real $S +flock /glacier/sys/lock sleep 3 & +sleep 1 +R syspkg -y +check "-y waits for no one: a held lock refuses" has "[x] Another glacier transaction is already in progress for the system scope." +wait +R syspkg -y -l x +check "-y with -l is refused" has "[x] -n, -l, -f, -u, -x and -y are mutually exclusive." +R syspkg -y extra +check "-y takes no arguments" has "[x] Unexpected argument: extra" +adduser -D tester >/dev/null 2>&1 +R su tester -c 'syspkg -y' +check "syspkg -y as a user is refused" has "[x] Cannot open system index: Permission denied" + +hr "syspkg -R DIR -y" +mkdir -p /srv/img && chmod 755 /srv/img +syspkg -R /srv/img -n >/dev/null +cp $S/base.idx /srv/host.idx +grepo -s $TEST_SEC -r base -n 2090010300 $B >/dev/null +R syspkg -R /srv/img -y +check "-R reads the image's repos.conf, not the host's" has "[x] No remote repositories are configured." +# The image's own keyring, as a package would ship it. +mkdir -p /srv/img/etc/glacier && cp -a /etc/glacier/repos.conf /etc/glacier/keys /srv/img/etc/glacier/ +R syspkg -R /srv/img -y +check "-R stores the index under the install root" cmp -s $B/repo.idx /srv/img/glacier/sys/repos/base.idx +check "...leaving the host's alone" cmp -s $S/base.idx /srv/host.idx + +hr "gpkg -y" +U=$(id -u tester) +gstore -n "$U" >/dev/null +R su tester -c 'gpkg -y' +check "gpkg -y refreshes into the user's base" has "[✓] All repositories synced successfully." +check "...nothing per repo without -V" lacks "Index for base" +check "...owned by the user, 0700" [ "$(stat -c '%u %a' /glacier/usr/$U/repos)" = "$U 700" ] +check "...files 0600" [ "$(stat -c '%u %a' /glacier/usr/$U/repos/base.idx)" = "$U 600" ] +check "...byte for byte" cmp -s $B/repo.idx /glacier/usr/$U/repos/base.idx +serve "$(idx 2090010200)" +R su tester -c 'gpkg -y' +check "gpkg -y refuses a rollback too" has "[x] Index for base is older than the one already accepted." +check "...exit 1" rc 1 +R su tester -c 'gpkg -y base' +check "gpkg -y takes no arguments" has "[x] -y takes no arguments." + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] diff --git a/tests/root_alpine.sh b/tests/root_alpine.sh new file mode 100644 index 0000000..b50a38e --- /dev/null +++ b/tests/root_alpine.sh @@ -0,0 +1,196 @@ +#!/bin/sh +# syspkg -R/--root DIR and --strict (ROADMAP 1.2), and file collisions +# between packages (ROADMAP 2.6): +# - the install root must be absolute, exist, and it and every +# directory above it must be root-owned, non-symlink directories that +# aren't group/world-writable; +# - -R builds a working system in DIR (chroot runs it) and leaves the +# host's /usr, /glacier and /etc byte-identical; +# - -R implies --strict: a path the link pass would refuse fails the +# whole transaction before the prompt (-O still displaces); +# - --strict on the host does the same; without it, the old behaviour +# (committed, "[x] N paths were not linked.", exit 1); +# - two packages shipping the same path are refused, in any scope, and +# the library refuses them at commit for callers that skip the CLI; +# Runs INSIDE the Dockerfile.alpine_root image: +# +# ./run_docker.sh Dockerfile.alpine_root # builds glacier-alpine_root +# docker run --rm -v "$PWD/tests/root_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +# run CMD: output (colour stripped) in $OUT, exit status in $STATUS +run() { + OUT=$(sh -c "$1; echo \"exit=\$?\"" 2>&1 | sed 's/\x1b\[[0-9;]*m//g') + STATUS=$(echo "$OUT" | sed -n 's/^exit=//p' | tail -1) + OUT=$(echo "$OUT" | grep -v '^exit=') + echo "$OUT" | sed 's/^/ /' +} +has() { echo "$OUT" | grep -qxF "$1"; } +hasnt() { ! echo "$OUT" | grep -qF "$1"; } +T=/mnt/img +S=/glacier/sys/store +SP="./syspkg" + +# pkg NAME REPO: /srv/src/NAME (laid out as files/...) -> /srv/NAME-1.0.0.gpkg + sidecar +pkg() { + w=$(mktemp -d); d=$w/$1-1.0.0 + mkdir -p $d; cp -a /srv/src/$1 $d/files + printf 'PKG_NAME = "%s";\nPKG_VER = "1.0.0";\nPKG_DESC = "t";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "%s";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' "$1" "$2" > $d/manifest.gpm.cfg + tar czf /srv/$1-1.0.0.gpkg -C $w $1-1.0.0 + printf 'sha256:%s\n' "$(sha256sum /srv/$1-1.0.0.gpkg | cut -d' ' -f1)" > /srv/$1-1.0.0.gpkg.sha256 + gsign -S -s /root/glacier-test.sec -m /srv/$1-1.0.0.gpkg.sha256 >/dev/null + chmod 644 /srv/$1-1.0.0.gpkg*; rm -rf $w +} +file() { mkdir -p "/srv/src/$1/$(dirname "$2")"; echo "$1" > "/srv/src/$1/$2"; } +mkdir -p /srv/src; chmod 755 /srv +# A bootable minimum: Alpine's loader + busybox, as base packages +mkdir -p /srv/src/alpmusl/usr/lib /srv/src/bb/usr/bin +cp /lib/ld-musl-x86_64.so.1 /srv/src/alpmusl/usr/lib/ +ln -s ld-musl-x86_64.so.1 /srv/src/alpmusl/usr/lib/libc.musl-x86_64.so.1 +cp /bin/busybox /srv/src/bb/usr/bin/busybox +pkg alpmusl base; pkg bb base +file tool usr/bin/tool; pkg tool extra +file clash usr/bin/clash; pkg clash base +file hclash usr/bin/hclash; pkg hclash base +file dupa usr/bin/dup; pkg dupa extra +file dupb usr/bin/dup; pkg dupb extra +file basedup usr/bin/dup; pkg basedup base # lands in /usr: no collision +file dird usr/share/thing/inside; pkg dird extra +file filed usr/share/thing; pkg filed extra +file ua usr/bin/udup; pkg ua extra +file ub usr/bin/udup; pkg ub extra + +cd /app +./syspkg -n >/dev/null 2>&1 # the host's own system +snap() { + find /usr /glacier /etc -xdev -printf '%p %y %m %U %G %s %T@ %l\n' 2>/dev/null | sort + find /usr /glacier /etc -xdev -type f -exec sha256sum {} + 2>/dev/null | sort +} +snap > /tmp/before + +echo "== 1. the install root is checked before anything happens" +run "su glacier -c 'cd /app && ./syspkg -R $T -n'" +check "non-root refused" has "[x] Cannot open system index: Permission denied" +mkdir -p /tmp/img +run "$SP -R /tmp/img -n" +check "under /tmp (world-writable)" has "[x] Refusing install root /tmp/img: /tmp is not root-owned, or is group/world-writable." +mkdir -p /mnt/userimg && chown glacier /mnt/userimg +run "$SP -R /mnt/userimg -n" +check "a user-owned root" has "[x] Refusing install root /mnt/userimg: /mnt/userimg is not root-owned, or is group/world-writable." +mkdir -p /mnt/real && ln -s /mnt/real /mnt/link +run "$SP -R /mnt/link -n" +check "a symlink" has "[x] Refusing install root /mnt/link: /mnt/link is a symlink." +run "$SP -R mnt/img -n" +check "a relative path" has "[x] Refusing install root mnt/img: not an absolute path without . or .. components." +run "$SP -R /mnt/../etc -n" +check "a .. component" has "[x] Refusing install root /mnt/../etc: not an absolute path without . or .. components." +run "$SP -R /mnt/nope -n" +check "a missing root" has "[x] Refusing install root /mnt/nope: /mnt/nope is missing." +check "nothing was created anywhere" test ! -e /tmp/img/glacier -a ! -e /mnt/userimg/glacier -a ! -e /mnt/real/glacier +run "$SP -R" +check "-R without a directory" has "[x] -R needs a directory." + +echo "== 2. -R DIR -n" +mkdir -p $T && chmod 755 $T +run "$SP -R $T -n" +check "created" has "[✓] Created system glacier directories:" +check "paths named under the root" has " * $T/glacier/sys/store" +check "merged-/usr tree in the root" test "$(readlink $T/bin)" = usr/bin +check "store is 755" test "$(stat -c %a $T$S)" = 755 +run "$SP -R $T -n" +check "a second -n refused" has "[x] Cannot create $T/glacier/sys: already exists" +run "$SP -R /mnt/real -l /srv/tool-1.0.0.gpkg" +check "-l before -n" has "[x] No system index found. Run ./syspkg -R /mnt/real -n first." + +echo "== 3. installing into the root (every flag form)" +run "echo y | $SP -R $T -l /srv/alpmusl-1.0.0.gpkg /srv/bb-1.0.0.gpkg" +check "-R DIR -l" test "$STATUS" = 0 +run "echo y | $SP -lR $T /srv/tool-1.0.0.gpkg" +check "-lR DIR" test "$STATUS" = 0 +run "echo y | $SP --root=$T -x tool" +check "--root=DIR -x" test "$STATUS" = 0 +run "echo y | $SP --root $T -l /srv/tool-1.0.0.gpkg" +check "--root DIR -l" test "$STATUS" = 0 +check "base links in T/usr say runtime paths" test "$(readlink $T/usr/bin/busybox)" = "$S/base/bb/bb-1.0.0/usr/bin/busybox" +check "extra links in T's sys links" test "$(readlink $T/glacier/sys/links/bin/tool)" = "$S/extra/tool/tool-1.0.0/usr/bin/tool" +check "chroot T runs busybox through T's loader" sh -c "chroot $T /usr/bin/busybox echo booted | grep -qx booted" +check "the image's index lists what it holds" grep -q "^extra::tool::1.0.0::explicit$" $T/glacier/sys/index/current + +echo "== 4. -R is strict: a refusal fails the transaction" +echo foreign > $T/usr/bin/clash +run "echo y | $SP -R $T -l /srv/clash-1.0.0.gpkg" +check "refused with the path" has "[x] Refusing to overwrite non-glacier path: $T/usr/bin/clash" +check "before the prompt" hasnt "Proceed?" +check "exit 1" test "$STATUS" = 1 +check "nothing installed" test ! -e $T$S/base/clash +check "the foreign file untouched" grep -qx foreign $T/usr/bin/clash +run "echo y | $SP -R $T -lO /srv/clash-1.0.0.gpkg" +check "-O displaces it instead" test "$STATUS" = 0 +check "original kept under its runtime path" grep -qx foreign $T$S/.displaced/usr/bin/clash + +echo "== 5. two packages shipping the same path" +run "echo y | $SP -R $T -l /srv/dupa-1.0.0.gpkg" +run "echo y | $SP -R $T -l /srv/dupb-1.0.0.gpkg" +check "refused, naming both and the path" has "[x] extra::dupb and extra::dupa both ship /glacier/sys/links/bin/dup." +check "before the prompt" hasnt "Proceed?" +check "dupb not installed" test ! -e $T$S/extra/dupb +run "echo y | $SP -R $T -x dupa" +run "echo y | $SP -R $T -l /srv/dupa-1.0.0.gpkg /srv/dupb-1.0.0.gpkg" +check "a colliding pair in one batch: reported once" test "$(echo "$OUT" | grep -c 'both ship')" = 1 +run "echo y | $SP -R $T -l /srv/dupa-1.0.0.gpkg /srv/basedup-1.0.0.gpkg" +check "same name in /usr and in sys links: no collision" test "$STATUS" = 0 +run "echo y | $SP -R $T -l /srv/dird-1.0.0.gpkg /srv/filed-1.0.0.gpkg" +check "a file where another package has a directory" has "[x] extra::dird and extra::filed both ship /glacier/sys/links/share/thing." + +snap > /tmp/after +check "everything under -R left the host's /usr, /glacier and /etc byte-identical" cmp -s /tmp/before /tmp/after +cmp -s /tmp/before /tmp/after || diff /tmp/before /tmp/after | head -10 + +echo "== 6. the host: --strict, and collisions without it" +echo foreign > /usr/bin/hclash +run "echo y | $SP --strict -l /srv/hclash-1.0.0.gpkg" +check "--strict refuses before the prompt" has "[x] Refusing to overwrite non-glacier path: /usr/bin/hclash" +check "nothing installed" test ! -e $S/base/hclash +run "echo y | $SP -l /srv/hclash-1.0.0.gpkg" +check "without --strict: committed, but an error" has "[x] 1 path was not linked." +check "exit 1" test "$STATUS" = 1 +run "echo y | $SP -l /srv/dupa-1.0.0.gpkg /srv/dupb-1.0.0.gpkg" +check "collisions refused without --strict too" has "[x] extra::dupa and extra::dupb both ship /glacier/sys/links/bin/dup." + +echo "== 7. the library refuses at commit (no CLI pre-check)" +cat > /tmp/lib.lua <<'EOF' +package.path = "/app/?.lua;" .. package.path +local ffi = require("ffi"); require("lib/glacier_cdef") +local istore = ffi.load("/app/lib/glacier/libglacier_istoreutils.so") +local txn = ffi.load("/app/lib/glacier/libglacier_transaction.so") +local ctx = ffi.new("gl_context_t") +assert(txn.gl_init_stage_context(ctx, ffi.C.GL_SCOPE_SYS, 0) == 0) +ctx.strict = arg[1] == "strict" and 1 or 0 +for i = 2, #arg do assert(istore.gl_install_pkg(ctx, arg[i]) == 0) end +local st = txn.gl_commit_transaction(ctx) +txn.gl_abort_transaction(ctx) +print(tonumber(st)) +EOF +echo y | $SP -x hclash >/dev/null 2>&1 +run "luajit /tmp/lib.lua strict /srv/hclash-1.0.0.gpkg" +check "strict context, foreign file: GL_TXN_ERR_DEPS" test "$(echo "$OUT" | tail -1)" = 9 +check "nothing committed" test ! -e $S/base/hclash +run "luajit /tmp/lib.lua loose /srv/dupa-1.0.0.gpkg /srv/dupb-1.0.0.gpkg" +check "a collision: GL_TXN_ERR_DEPS, strict or not" test "$(echo "$OUT" | tail -1)" = 9 +check "and said why" has "[x] extra::dupa and extra::dupb both ship /glacier/sys/links/bin/dup." + +echo "== 8. user scope: collisions refused, -R doesn't exist" +su glacier -c "doas /app/gstore -n" >/dev/null 2>&1 +run "su glacier -c 'cd /app && echo y | ./gpkg -l /srv/ua-1.0.0.gpkg /srv/ub-1.0.0.gpkg'" +check "two user packages shipping the same path" has "[x] extra::ua and extra::ub both ship /glacier/usr/1000/links/bin/udup." +run "su glacier -c 'cd /app && ./gpkg -R $T -l /srv/ua-1.0.0.gpkg'" +check "gpkg has no -R" has "[x] Unknown option: -R" + +echo "== 9. help" +run "$SP -h" +check "-R in the help" sh -c 'echo "$1" | grep -q -- "{-R --root} DIR"' _ "$OUT" +check "--strict in the help" sh -c 'echo "$1" | grep -q -- "{--strict}"' _ "$OUT" + +echo +[ $FAILS -eq 0 ] && echo "ALL PASSED" || echo "$FAILS FAILED" +exit $FAILS diff --git a/tests/run_all.lua b/tests/run_all.lua new file mode 100644 index 0000000..b42d33a --- /dev/null +++ b/tests/run_all.lua @@ -0,0 +1,41 @@ +-- run_all.lua +-- +-- Runs every test file as its own `luajit` process rather than +-- require()ing them all into one VM. This matters here specifically +-- because test_lock_crash_recovery.lua calls fork() — keeping each test +-- in its own process means a fork() gone wrong in one test can't corrupt +-- state for the others. +-- +-- Usage: +-- GLACIER_TEST_CONFIRM=yes LIBGLACIER_SO=./build/libglacier-ng.so \ +-- luajit run_all.lua + +local tests = { + "test_lock_contention.lua", + "test_lock_crash_recovery.lua", + "test_exdev.lua", + "test_relink_symlinks.lua", + "test_remove_live_pkg_via_stage.lua", + "test_package_symlinks.lua", + "test_fs_tree.lua", + "test_config_files.lua", + "test_index_abort.lua", + "test_live_remove_foreign.lua", + "test_abort_unlocked.lua", +} + +local failed = {} +for _, t in ipairs(tests) do + io.write("==== " .. t .. " ====\n") + local ok = os.execute("luajit " .. t) + local success = (ok == true) or (ok == 0) + if not success then failed[#failed + 1] = t end + io.write("\n") +end + +if #failed > 0 then + io.write("FAILED: " .. table.concat(failed, ", ") .. "\n") + os.exit(1) +end + +io.write("all test files passed\n") diff --git a/tests/sandbox_alpine.sh b/tests/sandbox_alpine.sh new file mode 100644 index 0000000..59561a6 --- /dev/null +++ b/tests/sandbox_alpine.sh @@ -0,0 +1,159 @@ +#!/bin/sh +# The build sandbox, gsandbox (BUILD_DESIGN.txt section 6; step 2): +# - -X extracts a package's files/ into a new layer, with the install +# rules (a hostile package is refused and leaves nothing); +# - -R runs /.glacier/in/driver as pid 1 of new namespaces, as uid 0 +# mapped to the caller: the layers (overlay, read-only below), no +# network, no host files, /.glacier/in read-only, /.glacier/out +# writable, no new privileges; its exit status comes back; +# - as root, -u is required and must not be uid 0; it drops to that +# user first; a user can't pass -u; +# - unsafe paths and layer names are refused. +# Needs user namespaces, overlayfs and /proc mounts inside Docker, and +# a work area that is not Docker's own overlay: +# +# docker run --rm --security-opt seccomp=unconfined \ +# --security-opt apparmor=unconfined --security-opt systempaths=unconfined \ +# --tmpfs /work:exec -v "$PWD/tests/sandbox_alpine.sh:/t.sh:ro" \ +# glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +SB=/app/lib/glacier/gsandbox +W=/work +GUID=$(id -u glacier) + +mkdir -p $W/pkgs $W/root && chmod 755 $W $W/pkgs +chown glacier:glacier $W/root +/app/tests/mkroot -o $W/pkgs -p musl -p busybox -f /etc/alpine-release testroot 1.0.0 extra >/dev/null +chmod 644 $W/pkgs/* + +# as glacier: run a command in the work area +asg() { su glacier -s /bin/sh -c "$*"; } + +hr "-X" +R asg "$SB -X -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/testroot" +check "a user extracts a layer" rc 0 +check "...its files, merged /usr" [ -x $W/root/testroot/usr/bin/busybox ] +check "...its symlinks" [ -L $W/root/testroot/usr/bin/sh ] +check "...owned by the user" [ "$(stat -c %u $W/root/testroot/usr/bin/busybox)" = "$GUID" ] +check "...no manifest or markers in the layer" [ ! -e $W/root/testroot/.glacier-manifest ] +R asg "$SB -X -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/testroot" +check "refused: a layer that exists" sh -c "[ $RC = 1 ]" +check "...saying so" has "[x] Cannot extract $W/pkgs/testroot-1.0.0.gpkg into $W/root/testroot." +check "...and leaving it alone" [ -x $W/root/testroot/usr/bin/busybox ] + +mkdir -p $W/evil/evil-1.0.0/files/usr/bin +echo x > $W/evil/evil-1.0.0/files/usr/bin/x +printf 'PKG_NAME = "evil"; PKG_VER = "1.0.0"; PKG_REPO = "extra";\n' > $W/evil/evil-1.0.0/manifest.gpm.cfg +tar czf $W/pkgs/evil-1.0.0.gpkg -C $W/evil evil-1.0.0 --transform 's|files/usr/bin/x|files/../../escape|' +chmod 644 $W/pkgs/evil-1.0.0.gpkg +R asg "$SB -X -p $W/pkgs/evil-1.0.0.gpkg -d $W/root/evil" +check "refused: a package with a .. entry" sh -c "[ $RC = 1 ]" +check "...nothing left behind" sh -c "[ ! -e $W/root/evil ] && [ ! -e $W/root/escape ] && [ ! -e $W/escape ]" +tar czf $W/pkgs/evil-1.0.0.gpkg -C $W/evil evil-1.0.0 --transform 's|files/usr/bin/x|files/.glacier-fresh|' +R asg "$SB -X -p $W/pkgs/evil-1.0.0.gpkg -d $W/root/evil" +check "refused: a reserved .glacier-* name" sh -c "[ $RC = 1 ] && [ ! -e $W/root/evil ]" + +hr "-R" +# run DRIVER-TEXT: a fresh work dir, in and out; the build as glacier +run() { + rm -rf $W/w $W/in $W/out + mkdir $W/w $W/in $W/out + printf '%s\n' "$1" > $W/in/driver + echo secret > $W/in/data + chown glacier:glacier $W/w $W/in $W/out $W/in/* + R asg "$SB -R -L $W/root -l testroot -w $W/w -i $W/in -o $W/out" +} +run 'echo "uid=$(id -u) gid=$(id -g) pid=$$ host=$(hostname)" +echo "nnp=$(grep NoNewPrivs /proc/self/status | tr -d "\t ")" +echo "init=$(tr "\0" " " < /proc/1/cmdline)" +echo "net=$(tail -n +3 /proc/net/dev | cut -d: -f1 | tr -d " " | tr "\n" ,)" +echo "root=$(ls -A / | tr "\n" ,)" +echo "in=$(cat /.glacier/in/data)" +touch /.glacier/in/new 2>/dev/null && echo in-writable +echo built > /.glacier/out/pkg +echo changed > /etc/alpine-release 2>/dev/null && echo "layer written through overlay" +ls /work /app /root/glacier-test.sec 2>/dev/null && echo host-visible +wget -q -T 2 -O- http://1.1.1.1 >/dev/null 2>&1 && echo network +echo "env=$(env | sort | tr "\n" ,)" +exit 7' +check "the driver runs" has "uid=0 gid=0 pid=1 host=glacier-build" +check "...its exit status comes back" rc 7 +check "...no new privileges" has "nnp=NoNewPrivs:1" +check "...pid 1 of its own pid namespace" has "init=/bin/sh /.glacier/in/driver " +check "...only a loopback" sh -c 'echo "$0" | grep -qx "net=lo,"' "$OUT" +check "...the skeleton and the layer, nothing of the host" has "root=.glacier,bin,build,dev,etc,lib,proc,sbin,tmp,usr," +check "...the input readable" has "in=secret" +check "...the input read-only" lacks "in-writable" +check "...the output written, owned by the user" sh -c "[ \"\$(cat $W/out/pkg)\" = built ] && [ \"\$(stat -c %u $W/out/pkg)\" = $GUID ]" +check "...writes to the root land in the upper layer" has "layer written through overlay" +check "...not in the layer" sh -c "cmp -s $W/root/testroot/etc/alpine-release /etc/alpine-release" +check "...but in WORK/upper" sh -c "[ \"\$(cat $W/w/upper/etc/alpine-release)\" = changed ]" +check "...no host files" lacks "host-visible" +check "...no network" lacks "network" +check "...a clean environment" has "env=FORCE_UNSAFE_CONFIGURE=1,HOME=/tmp,LC_ALL=C,PATH=/usr/bin:/bin,PWD=/,SHLVL=1,TERM=dumb,TZ=UTC," + +run 'true' +check "a driver that succeeds: 0" rc 0 +run 'echo "dev=$(ls /dev | tr "\n" ,)"; echo hi > /dev/null && echo devnull-ok; head -c 4 /dev/urandom | wc -c' +check "/dev has the six devices (tty if the host has it)" sh -c "echo \"\$0\" | grep -Eq 'dev=full,null,random,(tty,)?urandom,zero,'" "$OUT" +check "...usable" has "devnull-ok" +# A layer's directory removed and made again must come back empty: +# overlayfs marks it opaque, which in a user namespace needs userxattr. +run 'rm -rf /etc && mkdir /etc && echo "etc=$(ls -A /etc | tr "\n" ,)"' +check "a layer's directory remade in the root is empty" has "etc=" +check "...none of the layer's files show through" lacks "alpine-release" + +hr "as root" +run_root() { + rm -rf $W/w $W/in $W/out + mkdir $W/w $W/in $W/out + printf 'echo id=$(id -u); echo x > /.glacier/out/f\n' > $W/in/driver + chown glacier:glacier $W/w $W/in $W/out $W/in/driver + R $SB -R "$@" -L $W/root -l testroot -w $W/w -i $W/in -o $W/out +} +run_root +check "refused: root without -u" has "[x] Refusing to build as root: -u is required." +check "...exit 125" rc 125 +check "...nothing ran" [ ! -e $W/out/f ] +run_root -u root +check "refused: -u root" has "[x] Refusing to build as root: its uid or gid is 0." +run_root -u nobody-here +check "refused: an unknown user" has "[x] No user named nobody-here." +run_root -u glacier +check "-u glacier: the build runs" rc 0 +check "...as uid 0 inside" has "id=0" +check "...its output owned by glacier" [ "$(stat -c %u $W/out/f)" = "$GUID" ] +R $SB -X -u glacier -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/second +check "-X -u glacier as root: the layer is glacier's" sh -c "[ $RC = 0 ] && [ \"\$(stat -c %u $W/root/second/usr/bin/busybox)\" = $GUID ]" +R $SB -X -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/third +check "refused: -X as root without -u" sh -c "[ $RC = 1 ] && [ ! -e $W/root/third ]" +R asg "$SB -X -u glacier -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/fourth" +check "refused: -u from a user" has "[x] -u needs root." + +hr "paths" +rm -rf $W/w && mkdir $W/w && chown glacier $W/w +R asg "$SB -R -L $W/root -l ../root -w $W/w -i $W/in -o $W/out" +check "refused: a layer name with a slash" has "[x] Refusing layer name ../root." +R asg "$SB -R -L $W/root -l testroot -w $W/w,x -i $W/in -o $W/out" +check "refused: a work path with a comma" has "[x] Refusing a path that is not absolute or holds ',', ':' or '\\'." +R asg "$SB -R -L root -l testroot -w $W/w -i $W/in -o $W/out" +check "refused: a relative path" sh -c "[ $RC = 125 ]" +R asg "$SB -R -L $W/root -w $W/w -i $W/in" +check "a missing -o is a usage error" has "usage: gsandbox" +R $SB -h +check "-h prints the help" has "{-R --run}" + +echo +if [ $FAILS -eq 0 ]; then echo "ALL PASSED"; else echo "$FAILS FAILED"; fi +[ $FAILS -eq 0 ] diff --git a/tests/sandbox_alpine.sh.old b/tests/sandbox_alpine.sh.old new file mode 100644 index 0000000..d7afa67 --- /dev/null +++ b/tests/sandbox_alpine.sh.old @@ -0,0 +1,154 @@ +#!/bin/sh +# The build sandbox, gsandbox (BUILD_DESIGN.txt section 6; step 2): +# - -X extracts a package's files/ into a new layer, with the install +# rules (a hostile package is refused and leaves nothing); +# - -R runs /.glacier/in/driver as pid 1 of new namespaces, as uid 0 +# mapped to the caller: the layers (overlay, read-only below), no +# network, no host files, /.glacier/in read-only, /.glacier/out +# writable, no new privileges; its exit status comes back; +# - as root, -u is required and must not be uid 0; it drops to that +# user first; a user can't pass -u; +# - unsafe paths and layer names are refused. +# Needs user namespaces, overlayfs and /proc mounts inside Docker, and +# a work area that is not Docker's own overlay: +# +# docker run --rm --security-opt seccomp=unconfined \ +# --security-opt apparmor=unconfined --security-opt systempaths=unconfined \ +# --tmpfs /work:exec -v "$PWD/tests/sandbox_alpine.sh:/t.sh:ro" \ +# glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +lacks() { ! has "$1"; } +rc() { [ "$RC" = "$1" ]; } +hr() { echo; echo "== $*"; } +SB=/app/lib/glacier/gsandbox +W=/work +GUID=$(id -u glacier) + +mkdir -p $W/pkgs $W/root && chmod 755 $W $W/pkgs +chown glacier:glacier $W/root +/app/tests/mkroot -o $W/pkgs -p musl -p busybox -f /etc/alpine-release testroot 1.0.0 extra >/dev/null +chmod 644 $W/pkgs/* + +# as glacier: run a command in the work area +asg() { su glacier -s /bin/sh -c "$*"; } + +hr "-X" +R asg "$SB -X -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/testroot" +check "a user extracts a layer" rc 0 +check "...its files, merged /usr" [ -x $W/root/testroot/usr/bin/busybox ] +check "...its symlinks" [ -L $W/root/testroot/usr/bin/sh ] +check "...owned by the user" [ "$(stat -c %u $W/root/testroot/usr/bin/busybox)" = "$GUID" ] +check "...no manifest or markers in the layer" [ ! -e $W/root/testroot/.glacier-manifest ] +R asg "$SB -X -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/testroot" +check "refused: a layer that exists" sh -c "[ $RC = 1 ]" +check "...saying so" has "[x] Cannot extract $W/pkgs/testroot-1.0.0.gpkg into $W/root/testroot." +check "...and leaving it alone" [ -x $W/root/testroot/usr/bin/busybox ] + +mkdir -p $W/evil/evil-1.0.0/files/usr/bin +echo x > $W/evil/evil-1.0.0/files/usr/bin/x +printf 'PKG_NAME = "evil"; PKG_VER = "1.0.0"; PKG_REPO = "extra";\n' > $W/evil/evil-1.0.0/manifest.gpm.cfg +tar czf $W/pkgs/evil-1.0.0.gpkg -C $W/evil evil-1.0.0 --transform 's|files/usr/bin/x|files/../../escape|' +chmod 644 $W/pkgs/evil-1.0.0.gpkg +R asg "$SB -X -p $W/pkgs/evil-1.0.0.gpkg -d $W/root/evil" +check "refused: a package with a .. entry" sh -c "[ $RC = 1 ]" +check "...nothing left behind" sh -c "[ ! -e $W/root/evil ] && [ ! -e $W/root/escape ] && [ ! -e $W/escape ]" +tar czf $W/pkgs/evil-1.0.0.gpkg -C $W/evil evil-1.0.0 --transform 's|files/usr/bin/x|files/.glacier-fresh|' +R asg "$SB -X -p $W/pkgs/evil-1.0.0.gpkg -d $W/root/evil" +check "refused: a reserved .glacier-* name" sh -c "[ $RC = 1 ] && [ ! -e $W/root/evil ]" + +hr "-R" +# run DRIVER-TEXT: a fresh work dir, in and out; the build as glacier +run() { + rm -rf $W/w $W/in $W/out + mkdir $W/w $W/in $W/out + printf '%s\n' "$1" > $W/in/driver + echo secret > $W/in/data + chown glacier:glacier $W/w $W/in $W/out $W/in/* + R asg "$SB -R -L $W/root -l testroot -w $W/w -i $W/in -o $W/out" +} +run 'echo "uid=$(id -u) gid=$(id -g) pid=$$ host=$(hostname)" +echo "nnp=$(grep NoNewPrivs /proc/self/status | tr -d "\t ")" +echo "init=$(tr "\0" " " < /proc/1/cmdline)" +echo "net=$(tail -n +3 /proc/net/dev | cut -d: -f1 | tr -d " " | tr "\n" ,)" +echo "root=$(ls -A / | tr "\n" ,)" +echo "in=$(cat /.glacier/in/data)" +touch /.glacier/in/new 2>/dev/null && echo in-writable +echo built > /.glacier/out/pkg +echo changed > /etc/alpine-release 2>/dev/null && echo "layer written through overlay" +ls /work /app /root/glacier-test.sec 2>/dev/null && echo host-visible +wget -q -T 2 -O- http://1.1.1.1 >/dev/null 2>&1 && echo network +echo "env=$(env | sort | tr "\n" ,)" +exit 7' +check "the driver runs" has "uid=0 gid=0 pid=1 host=glacier-build" +check "...its exit status comes back" rc 7 +check "...no new privileges" has "nnp=NoNewPrivs:1" +check "...pid 1 of its own pid namespace" has "init=/bin/sh /.glacier/in/driver " +check "...only a loopback" sh -c 'echo "$0" | grep -qx "net=lo,"' "$OUT" +check "...the skeleton and the layer, nothing of the host" has "root=.glacier,bin,build,dev,etc,lib,proc,sbin,tmp,usr," +check "...the input readable" has "in=secret" +check "...the input read-only" lacks "in-writable" +check "...the output written, owned by the user" sh -c "[ \"\$(cat $W/out/pkg)\" = built ] && [ \"\$(stat -c %u $W/out/pkg)\" = $GUID ]" +check "...writes to the root land in the upper layer" has "layer written through overlay" +check "...not in the layer" sh -c "cmp -s $W/root/testroot/etc/alpine-release /etc/alpine-release" +check "...but in WORK/upper" sh -c "[ \"\$(cat $W/w/upper/etc/alpine-release)\" = changed ]" +check "...no host files" lacks "host-visible" +check "...no network" lacks "network" +check "...a clean environment" has "env=FORCE_UNSAFE_CONFIGURE=1,HOME=/tmp,LC_ALL=C,PATH=/usr/bin:/bin,PWD=/,SHLVL=1,TERM=dumb,TZ=UTC," + +run 'true' +check "a driver that succeeds: 0" rc 0 +run 'echo "dev=$(ls /dev | tr "\n" ,)"; echo hi > /dev/null && echo devnull-ok; head -c 4 /dev/urandom | wc -c' +check "/dev has the six devices (tty if the host has it)" sh -c "echo \"\$0\" | grep -Eq 'dev=full,null,random,(tty,)?urandom,zero,'" "$OUT" +check "...usable" has "devnull-ok" + +hr "as root" +run_root() { + rm -rf $W/w $W/in $W/out + mkdir $W/w $W/in $W/out + printf 'echo id=$(id -u); echo x > /.glacier/out/f\n' > $W/in/driver + chown glacier:glacier $W/w $W/in $W/out $W/in/driver + R $SB -R "$@" -L $W/root -l testroot -w $W/w -i $W/in -o $W/out +} +run_root +check "refused: root without -u" has "[x] Refusing to build as root: -u is required." +check "...exit 125" rc 125 +check "...nothing ran" [ ! -e $W/out/f ] +run_root -u root +check "refused: -u root" has "[x] Refusing to build as root: its uid or gid is 0." +run_root -u nobody-here +check "refused: an unknown user" has "[x] No user named nobody-here." +run_root -u glacier +check "-u glacier: the build runs" rc 0 +check "...as uid 0 inside" has "id=0" +check "...its output owned by glacier" [ "$(stat -c %u $W/out/f)" = "$GUID" ] +R $SB -X -u glacier -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/second +check "-X -u glacier as root: the layer is glacier's" sh -c "[ $RC = 0 ] && [ \"\$(stat -c %u $W/root/second/usr/bin/busybox)\" = $GUID ]" +R $SB -X -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/third +check "refused: -X as root without -u" sh -c "[ $RC = 1 ] && [ ! -e $W/root/third ]" +R asg "$SB -X -u glacier -p $W/pkgs/testroot-1.0.0.gpkg -d $W/root/fourth" +check "refused: -u from a user" has "[x] -u needs root." + +hr "paths" +rm -rf $W/w && mkdir $W/w && chown glacier $W/w +R asg "$SB -R -L $W/root -l ../root -w $W/w -i $W/in -o $W/out" +check "refused: a layer name with a slash" has "[x] Refusing layer name ../root." +R asg "$SB -R -L $W/root -l testroot -w $W/w,x -i $W/in -o $W/out" +check "refused: a work path with a comma" has "[x] Refusing a path that is not absolute or holds ',', ':' or '\\'." +R asg "$SB -R -L root -l testroot -w $W/w -i $W/in -o $W/out" +check "refused: a relative path" sh -c "[ $RC = 125 ]" +R asg "$SB -R -L $W/root -w $W/w -i $W/in" +check "a missing -o is a usage error" has "usage: gsandbox" +R $SB -h +check "-h prints the help" has "{-R --run}" + +echo +if [ $FAILS -eq 0 ]; then echo "ALL PASSED"; else echo "$FAILS FAILED"; fi +[ $FAILS -eq 0 ] diff --git a/tests/sign_alpine.sh b/tests/sign_alpine.sh new file mode 100644 index 0000000..a1430b9 --- /dev/null +++ b/tests/sign_alpine.sh @@ -0,0 +1,193 @@ +#!/bin/sh +# gsign / libglacier_verify's Ed25519 (REPO_DESIGN.txt section 2): +# - keypairs, signing and verifying round-trip; a changed message, a +# changed signature and another key's signature are each refused, +# with their own message; +# - interop with OpenBSD signify (Alpine's `signify`), both ways; +# - an encrypted secret key is refused as such; +# - malformed key and signature files are refused (comment line, +# extra or missing lines, non-canonical base64, wrong algorithm, +# wrong length, not a regular file), and so is a message over the +# size limit; +# - a new secret key is 0600 whatever the umask; existing keys are +# never overwritten; a signature is never written through a symlink. +# Runs in a throwaway alpine container: +# +# docker run --rm -v ~/Projects/libglacier-ng:/libsrc:ro \ +# -v ~/Projects/glacier-ng/tests/sign_alpine.sh:/t.sh:ro alpine:latest sh /t.sh +set -u +apk add --no-cache build-base libarchive-dev libconfig-dev linux-headers signify luajit >/dev/null 2>&1 \ + || { echo "apk failed"; exit 1; } +cp -a /libsrc /build && cd /build && make clean >/dev/null && make >/dev/null 2>&1 \ + || { echo "build failed"; exit 1; } +G=/build/build/bin/gsign + +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +R() { + OUT=$( ("$@"; echo "rc=$?") 2>&1 | nocolor) + RC=$(echo "$OUT" | sed -n 's/^rc=//p' | tail -1) + echo "$OUT" | sed '/^rc=/d; s/^/ /' +} +has() { echo "$OUT" | grep -qF -- "$1"; } +rc() { [ "$RC" = "$1" ]; } +mode() { stat -c %a "$1"; } +hr() { echo; echo "== $*"; } + +W=/w; mkdir -p $W && cd $W + +hr "keypairs" +R $G -G -p a.pub -s a.sec -c alice +check "gsign -G succeeds" rc 0 +check "the secret key is 0600" [ "$(mode a.sec)" = 600 ] +check "the public key is 0644" [ "$(mode a.pub)" = 644 ] +check "comments are signify's" sh -c 'head -1 a.pub | grep -qx "untrusted comment: alice public key" && head -1 a.sec | grep -qx "untrusted comment: alice secret key"' +(umask 000; $G -G -p u.pub -s u.sec >/dev/null 2>&1) +check "the secret key is 0600 under umask 000" [ "$(mode u.sec)" = 600 ] +(umask 077; $G -G -p v.pub -s v.sec >/dev/null 2>&1) +check "the public key is 0644 under umask 077 (users read system keys)" [ "$(mode v.pub)" = 644 ] +cp a.sec a.sec.bak +R $G -G -p new.pub -s a.sec +check "an existing secret key is never overwritten" rc 1 +check "...saying which" has "Secret key a.sec already exists." +check "...and it is unchanged" cmp -s a.sec a.sec.bak +check "...and no public key is left behind" [ ! -e new.pub ] +R $G -G -p a.pub -s new.sec +check "an existing public key is refused too" has "Public key a.pub already exists." +check "...leaving no secret key behind" [ ! -e new.sec ] +# The library refuses on its own, not only gsign's pre-check. +# `luajit -e CODE ARGS` would run ARGS' first word as a script: use a file. +cat > /gen.lua <<'LUA' +local ffi = require("ffi") +ffi.cdef[[int gl_sign_generate(const char *, const char *, const char *);]] +local v = ffi.load("/build/build/lib/shared/libglacier_verify.so") +io.write(tostring(v.gl_sign_generate(arg[1], arg[2], "lib")), "\n") +LUA +lib() { luajit /gen.lua "$@"; } +check "gl_sign_generate refuses an existing secret key (EXISTS)" [ "$(lib new2.pub a.sec)" = 8 ] +check "...leaving it unchanged" cmp -s a.sec a.sec.bak +check "...and writing no public key" [ ! -e new2.pub ] +ln -s /w/elsewhere.sec link.sec +check "gl_sign_generate refuses a symlink as the secret key" [ "$(lib new3.pub link.sec)" = 8 ] +check "...creating nothing through it" [ ! -e /w/elsewhere.sec ] +R $G -G -p b.pub -s b.sec -c "$(printf 'two\nlines')" +check "a multi-line comment is refused" rc 1 +check "...and creates nothing" [ ! -e b.pub ] && [ ! -e b.sec ] +$G -G -p b.pub -s b.sec -c bob >/dev/null + +hr "sign and verify" +echo "hello" > m +R $G -S -s a.sec -m m +check "gsign -S succeeds" rc 0 +check "the signature says which key verifies it" sh -c 'head -1 m.sig | grep -qx "untrusted comment: verify with a.pub"' +R $G -V -p a.pub -m m +check "gsign -V accepts it" rc 0 +check "...saying so" has "Signature verified: m." +cp m m2; echo "hello!" > m2; cp m.sig m2.sig +R $G -V -p a.pub -m m2 +check "a changed message is refused" rc 1 +check "...as not verifying" has "Signature does not verify: m2." +R $G -V -p b.pub -m m +check "another key's signature is refused" rc 1 +check "...as a different key" has "m was signed by a different key than b.pub." +# Flip one bit of the signature itself (byte 20 of the 74 decoded). +sed -n 2p m.sig | base64 -d > raw +printf "$(printf '\\%03o' $(( $(od -An -tu1 -j20 -N1 raw) ^ 1 )))" | dd of=raw bs=1 seek=20 conv=notrunc 2>/dev/null +{ head -1 m.sig; base64 -w0 raw; echo; } > m3.sig; cp m m3 +R $G -V -p a.pub -m m3 +check "a changed signature is refused" rc 1 +check "...as not verifying" has "Signature does not verify: m3." +R $G -V -p a.pub -m m -x m.sig +check "-x names the signature file" rc 0 +R $G -S -s a.sec -m m -x other.sig +check "-S -x writes there" [ -s other.sig ] + +hr "interop with signify" +R signify -V -p a.pub -m m -x m.sig +check "signify verifies gsign's signature" rc 0 +signify -G -n -p s.pub -s s.sec -c sig >/dev/null +echo "from signify" > sm +signify -S -s s.sec -m sm -x sm.sig +R $G -V -p s.pub -m sm -x sm.sig +check "gsign verifies signify's signature" rc 0 +R $G -S -s s.sec -m m -x ms.sig +check "gsign signs with signify's unencrypted key" rc 0 +R signify -V -p s.pub -m m -x ms.sig +check "...and signify verifies that" rc 0 +echo "x" > sm2; cp sm.sig sm2.sig +R $G -V -p s.pub -m sm2 +check "signify's signature over another message is refused" has "Signature does not verify: sm2." + +hr "encrypted secret keys" +# rounds (decoded bytes 4..7) = 42, as a passphrase-protected key has. +sed -n 2p s.sec | base64 -d > raw +printf '\000\000\000\052' | dd of=raw bs=1 seek=4 conv=notrunc 2>/dev/null +{ head -1 s.sec; base64 -w0 raw; echo; } > enc.sec +R $G -S -s enc.sec -m m -x enc.sig +check "an encrypted secret key is refused" rc 1 +check "...as encrypted" has "Secret key enc.sec is encrypted: sign with signify." +check "...writing nothing" [ ! -e enc.sig ] +# A corrupted secret key fails its checksum. +sed -n 2p a.sec | base64 -d > raw +printf 'X' | dd of=raw bs=1 seek=60 conv=notrunc 2>/dev/null +{ head -1 a.sec; base64 -w0 raw; echo; } > bad.sec +R $G -S -s bad.sec -m m -x bad.sig +check "a secret key failing its checksum is malformed" has "Secret key bad.sec is malformed." + +hr "malformed public keys and signatures" +L1=$(head -1 a.pub); L2=$(sed -n 2p a.pub) +S1=$(head -1 m.sig); S2=$(sed -n 2p m.sig) +bad_pub() { # NAME DESCRIPTION: a.pub variant in NAME must be refused + R $G -V -p "$1" -m m + check "$2" has "Public key $1 is malformed." +} +bad_sig() { + R $G -V -p a.pub -m m -x "$1" + check "$2" has "Signature $1 is malformed." +} +printf '%s\n' "$L2" > p1; bad_pub p1 "no comment line" +printf 'comment: x\n%s\n' "$L2" > p2; bad_pub p2 "a comment line without 'untrusted comment: '" +printf '%s\n%s' "$L1" "$L2" > p3; bad_pub p3 "no final newline" +printf '%s\n%sx' "$L1" "$L2" > p3b; bad_pub p3b "a final character other than a newline" +printf '%s\n%s\n\n' "$L1" "$L2" > p4; bad_pub p4 "an extra empty line" +printf '%s\n%s\nmore\n' "$L1" "$L2" > p5; bad_pub p5 "trailing data" +printf '%s\n%s\n' "$L1" "${L2%?}" > p6; bad_pub p6 "base64 one character short" +printf '%s\n%sA\n' "$L1" "$L2" > p7; bad_pub p7 "base64 one character long" +printf '%s\n%s\n' "$L1" "$(echo "$L2" | sed 's/^./*/')" > p8; bad_pub p8 "a character outside base64" +printf '%s\n%s\n' "$L1" "$S2" > p9; bad_pub p9 "a signature given as a public key" +sed -n 2p a.pub | base64 -d > raw; printf 'XX' | dd of=raw bs=1 conv=notrunc 2>/dev/null +printf '%s\n%s\n' "$L1" "$(base64 -w0 raw)" > p10; bad_pub p10 "an algorithm other than Ed" +printf '%s\n%s\n' "$L1" "$(echo "$L2" | sed 's/^\(.\{10\}\)/\1 /' | cut -c1-56)" > p11; bad_pub p11 "a space inside the base64" +printf '' > p12; bad_pub p12 "an empty file" +printf 'untrusted comment: %s\n%s\n' "$(head -c 1100 /dev/zero | tr '\0' x)" "$L2" > p13; bad_pub p13 "a comment over 1024 characters" +R $G -V -p /w -m m +check "a directory as the public key cannot be read" has "Public key /w cannot be read." +# Non-canonical base64: the signature's last data character (before +# its one '=') has two unused bits; set one. +A=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ +last=$(echo "$S2" | cut -c99) +i=$(awk -v a="$A" -v c="$last" 'BEGIN { print index(a, c) - 1 }') +nc=$(echo "$A" | cut -c$(( (i | 1) + 1 ))) +printf '%s\n%s%s=\n' "$S1" "$(echo "$S2" | cut -c1-98)" "$nc" > s1.sig +bad_sig s1.sig "non-canonical base64 (unused bits set)" +printf '%s\n%s\n' "$S1" "$(echo "$S2" | tr -d =)" > s2.sig; bad_sig s2.sig "missing padding" +printf '%s\n%s\n' "$S1" "$L2" > s3.sig; bad_sig s3.sig "a public key given as a signature" +R $G -V -p a.pub -m m -x missing.sig +check "a missing signature cannot be read" has "Signature missing.sig cannot be read." + +hr "limits and symlinks" +truncate -s 67108865 big +R $G -S -s a.sec -m big +check "a message over 64 MiB is refused" has "File big is too large." +ln -s /w/target.txt link.sig +R $G -S -s a.sec -m m -x link.sig +check "a signature is never written through a symlink" rc 1 +check "...the symlink's target is not created" [ ! -e /w/target.txt ] +R $G -V -p a.pub -m missing -x m.sig +check "a missing message cannot be read" has "File missing cannot be read." + +echo +echo "FAILURES: $FAILS" +[ $FAILS -eq 0 ] && echo "ALL PASSED" +exit $FAILS diff --git a/tests/sys_perms_alpine.sh b/tests/sys_perms_alpine.sh new file mode 100644 index 0000000..b8e67f5 --- /dev/null +++ b/tests/sys_perms_alpine.sh @@ -0,0 +1,71 @@ +#!/bin/sh +# System scope is world-readable, like /usr (gl_scope_dir_mode): every +# user must be able to run what syspkg installs, through /usr or +# /glacier/sys/links, and read the system index. User scope stays 0700. +# syspkg runs under umask 077 here, so a mode that only comes from +# mkdir()'s argument (and not an explicit chmod) fails. Runs INSIDE the +# Dockerfile.alpine_root image: +# +# ./run_docker.sh Dockerfile.alpine_root # builds glacier-alpine_root +# docker run --rm -v "$PWD/tests/sys_perms_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +mode() { [ "$(stat -c %a "$1")" = "$2" ]; } +U() { su glacier -c "$1" >/dev/null 2>&1; } + +# mkpkg NAME REPO -> /srv/NAME-1.0.0.gpkg (+ sidecar). The archive lists +# only files, no directory entries, so every parent of usr/bin/NAME is +# created implicitly at extraction. +mkpkg() { + w=$(mktemp -d); d=$w/$1-1.0.0 + mkdir -p $d/files/usr/bin + printf '#!/bin/sh\necho %s-ok\n' "$1" > $d/files/usr/bin/$1; chmod 755 $d/files/usr/bin/$1 + printf 'PKG_NAME = "%s";\nPKG_VER = "1.0.0";\nPKG_DESC = "t";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "%s";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' "$1" "$2" > $d/manifest.gpm.cfg + tar czf /srv/$1-1.0.0.gpkg -C $w $1-1.0.0/manifest.gpm.cfg $1-1.0.0/files/usr/bin/$1 + printf 'sha256:%s\n' "$(sha256sum /srv/$1-1.0.0.gpkg | cut -d' ' -f1)" > /srv/$1-1.0.0.gpkg.sha256 + gsign -S -s /root/glacier-test.sec -m /srv/$1-1.0.0.gpkg.sha256 >/dev/null + chmod 644 /srv/$1-1.0.0.gpkg /srv/$1-1.0.0.gpkg.sha256 /srv/$1-1.0.0.gpkg.sha256.sig + rm -rf $w +} +mkdir -p /srv; chmod 755 /srv +mkpkg pbase base; mkpkg pextra extra; mkpkg puser extra + +cd /app +(umask 077; ./syspkg -n >/dev/null 2>&1) +(umask 077; echo y | ./syspkg -l /srv/pbase-1.0.0.gpkg /srv/pextra-1.0.0.gpkg >/dev/null 2>&1) + +echo "== system scope, installed under umask 077" +for d in /glacier/sys/index /glacier/sys/store /glacier/sys/links \ + /glacier/sys/store/base /glacier/sys/store/base/pbase \ + /glacier/sys/store/base/pbase/pbase-1.0.0 \ + /glacier/sys/store/base/pbase/pbase-1.0.0/usr \ + /glacier/sys/store/base/pbase/pbase-1.0.0/usr/bin \ + /glacier/sys/links/bin; do + check "$d is 755" mode $d 755 +done +check "system index file is 644" mode "$(readlink -f /glacier/sys/index/current)" 644 +check "user runs a base package through /usr" U "/usr/bin/pbase | grep -q pbase-ok" +check "user runs an extra package through sys links" U "/glacier/sys/links/bin/pextra | grep -q pextra-ok" +check "user reads the system index" U "grep -q base::pbase /glacier/sys/index/current" + +echo "== a later transaction (seeded stage) keeps the modes" +(umask 077; echo y | ./syspkg -x pextra >/dev/null 2>&1) +check "store still 755 after removal" mode /glacier/sys/store 755 +check "store/base still 755 after removal" mode /glacier/sys/store/base 755 +check "index file still 644 after removal" mode "$(readlink -f /glacier/sys/index/current)" 644 +check "user still runs the base package" U "/usr/bin/pbase | grep -q pbase-ok" + +echo "== user scope stays private" +U "doas /app/gstore -n" +U "cd /app && echo y | ./gpkg -l /srv/puser-1.0.0.gpkg" +B=/glacier/usr/1000 +check "user package installed" test -d $B/store/extra/puser +for d in $B/index $B/store $B/links $B/store/extra $B/store/extra/puser \ + $B/store/extra/puser/puser-1.0.0 $B/store/extra/puser/puser-1.0.0/usr; do + check "$d is 700" mode $d 700 +done +check "user index file is 600" mode "$(readlink -f $B/index/current)" 600 + +echo +[ $FAILS -eq 0 ] && echo "ALL PASSED" || echo "$FAILS FAILED" +exit $FAILS diff --git a/tests/syspkg_alpine.sh b/tests/syspkg_alpine.sh new file mode 100755 index 0000000..ef9162d --- /dev/null +++ b/tests/syspkg_alpine.sh @@ -0,0 +1,112 @@ +#!/bin/sh +# syspkg root-path tests. Runs inside a THROWAWAY alpine container as root — +# it installs into /glacier/sys and links base packages into /usr, so never +# run it on a real system. +# +# Builds libglacier-ng from source in-container (the host's glibc .so's +# won't load on musl), copies glacier-ng into a root-owned /opt/glacier, +# then exercises syspkg's privilege checks and install/remove paths. +# +# Usage, from anywhere: +# docker run --rm \ +# -v /home/lw/Projects/glacier-ng:/src:ro \ +# -v /home/lw/Projects/libglacier-ng:/libsrc:ro \ +# -v /home/lw/Projects/glacier-ng/tests/syspkg_alpine.sh:/t.sh:ro \ +# alpine:latest sh /t.sh +set -u +# Deps per Dockerfile.alpine, minus debugging tools, plus linux-headers +# (needed for ; Dockerfile.alpine is missing it). +apk add --no-cache build-base luajit-dev libarchive-dev libconfig-dev linux-headers doas >/dev/null 2>&1 \ + || { echo "apk failed"; exit 1; } + +hr() { echo; echo "=== $* ==="; } + +# Symlinks under $1 pointing into the system store. busybox find has no +# -lname, so resolve each link by hand. +glacier_links() { + find "$1" -type l 2>/dev/null | while read -r l; do + case "$(readlink "$l")" in /glacier/sys/store/*) echo "$l -> $(readlink "$l")" ;; esac + done +} + +hr "0. build libglacier-ng against musl" +cp -a /libsrc /build && cd /build && make clean >/dev/null && make >/tmp/make.log 2>&1 \ + && echo "build ok" || { tail -30 /tmp/make.log; exit 1; } + +cp -a /src /opt/glacier +mkdir -p /opt/glacier/lib/glacier +cp /build/build/lib/shared/libglacier_*.so /opt/glacier/lib/glacier/ +chown -R root:root /opt/glacier +chmod -R go-w /opt/glacier +# A throwaway key trusted for base (REPO_DESIGN.txt section 7), and the +# copies' sidecars signed with it. +mkdir -p /etc/glacier/keys +/build/build/bin/gsign -G -p /etc/glacier/keys/t.pub -s /root/t.sec -c t >/dev/null +printf 'repos = (\n\t{ name = "base"; keys = [ "t" ]; }\n);\n' > /etc/glacier/repos.conf +for s in /opt/glacier/*.gpkg.sha256 /opt/glacier/pkgs/*.gpkg.sha256; do + [ -e "$s" ] && /build/build/bin/gsign -S -s /root/t.sec -m "$s" >/dev/null +done +SP=/opt/glacier/syspkg + +adduser -D -u 1000 tester +echo "permit nopass tester as root cmd $SP" > /etc/doas.conf +chmod 0400 /etc/doas.conf + +hr "1. non-root user: -h/-v allowed, operations refused" +su tester -c "$SP -v"; echo "exit=$? (expect 0)" +su tester -c "$SP -n"; echo "exit=$? (expect 1)" + +hr "2. help" +$SP -h; echo "exit=$?" + +hr "3. copy owned by a normal user is refused even as root" +cp -a /opt/glacier /home/tester/glacier && chown -R tester /home/tester/glacier +/home/tester/glacier/syspkg -v; echo "exit=$?" + +hr "4. hostile lib/ in CWD is ignored (via restricted doas rule)" +mkdir -p /tmp/evil/lib && echo 'print("EVIL CODE RAN") os.exit(9)' > /tmp/evil/lib/cargs.lua +chown -R tester /tmp/evil +su tester -c "cd /tmp/evil && doas $SP -v"; echo "exit=$?" + +hr "5. LUA_INIT / LUA_PATH are ignored (as root directly, no doas env reset)" +LUA_INIT='print("EVIL LUA_INIT")' LUA_PATH='/tmp/evil/?.lua' $SP -v; echo "exit=$?" + +hr "6. install before -n" +cd /opt/glacier +echo y | $SP -l kilo-0.0.1.gpkg; echo "exit=$?" + +hr "7. -n with no /glacier at all" +$SP -n -V; echo "exit=$?" + +hr "7b. -n with /glacier/sys pre-created (dirs but no index: completes)" +rm -rf /glacier && mkdir -p /glacier/sys +$SP -n -V; echo "exit=$?" +$SP -n; echo "re-run exit=$? (expect 1: already exists)" +echo "-- index survived the refused re-run:"; cat /glacier/sys/index/current +ls -la /glacier/sys + +hr "8. install extra-repo package" +echo y | $SP -l kilo-0.0.1.gpkg; echo "exit=$?" +find /glacier/sys -maxdepth 4 | sort +echo "-- links:"; glacier_links /glacier/sys/links +echo "-- index:"; cat /glacier/sys/index/* 2>/dev/null + +hr "9. install base-repo package (should link into /usr)" +echo y | $SP -l pkgs/musl-1.2.5.gpkg; echo "exit=$?" +glacier_links /usr | head +echo "-- index:"; cat /glacier/sys/index/* 2>/dev/null + +hr "10. remove both" +echo y | $SP -x kilo; echo "exit=$?" +echo y | $SP -x musl; echo "exit=$?" +echo "-- leftover glacier symlinks in /usr: $(glacier_links /usr | wc -l)" +echo "-- leftover glacier symlinks in /glacier/sys/links: $(glacier_links /glacier/sys/links | wc -l)" +echo "-- index:"; cat /glacier/sys/index/* 2>/dev/null + +hr "11. remove something not installed" +echo y | $SP -x nosuchpkg; echo "exit=$?" + +hr "12. arg handling" +$SP -n -l x; echo "exit=$?" +$SP --bogus; echo "exit=$?" +$SP -l; echo "exit=$?" diff --git a/tests/syspkg_alpine.sh.old b/tests/syspkg_alpine.sh.old new file mode 100755 index 0000000..408cc25 --- /dev/null +++ b/tests/syspkg_alpine.sh.old @@ -0,0 +1,111 @@ +#!/bin/sh +# syspkg root-path tests. Runs inside a THROWAWAY alpine container as root — +# it installs into /glacier/sys and links base packages into /usr, so never +# run it on a real system. +# +# Builds libglacier-ng from source in-container (the host's glibc .so's +# won't load on musl), copies glacier-ng into a root-owned /opt/glacier, +# then exercises syspkg's privilege checks and install/remove paths. +# +# Usage, from anywhere: +# docker run --rm \ +# -v /home/lw/Projects/glacier-ng:/src:ro \ +# -v /home/lw/Projects/libglacier-ng:/libsrc:ro \ +# -v /home/lw/Projects/glacier-ng/tests/syspkg_alpine.sh:/t.sh:ro \ +# alpine:latest sh /t.sh +set -u +# Deps per Dockerfile.alpine, minus debugging tools, plus linux-headers +# (needed for ; Dockerfile.alpine is missing it). +apk add --no-cache build-base luajit-dev libarchive-dev libconfig-dev linux-headers doas >/dev/null 2>&1 \ + || { echo "apk failed"; exit 1; } + +hr() { echo; echo "=== $* ==="; } + +# Symlinks under $1 pointing into the system store. busybox find has no +# -lname, so resolve each link by hand. +glacier_links() { + find "$1" -type l 2>/dev/null | while read -r l; do + case "$(readlink "$l")" in /glacier/sys/store/*) echo "$l -> $(readlink "$l")" ;; esac + done +} + +hr "0. build libglacier-ng against musl" +cp -a /libsrc /build && cd /build && make clean >/dev/null && make >/tmp/make.log 2>&1 \ + && echo "build ok" || { tail -30 /tmp/make.log; exit 1; } + +cp -a /src /opt/glacier +cp /build/build/lib/shared/libglacier_*.so /opt/glacier/lib/glacier/ +chown -R root:root /opt/glacier +chmod -R go-w /opt/glacier +# A throwaway key trusted for base (REPO_DESIGN.txt section 7), and the +# copies' sidecars signed with it. +mkdir -p /etc/glacier/keys +/build/build/bin/gsign -G -p /etc/glacier/keys/t.pub -s /root/t.sec -c t >/dev/null +printf 'repos = (\n\t{ name = "base"; keys = [ "t" ]; }\n);\n' > /etc/glacier/repos.conf +for s in /opt/glacier/*.gpkg.sha256 /opt/glacier/pkgs/*.gpkg.sha256; do + [ -e "$s" ] && /build/build/bin/gsign -S -s /root/t.sec -m "$s" >/dev/null +done +SP=/opt/glacier/syspkg + +adduser -D -u 1000 tester +echo "permit nopass tester as root cmd $SP" > /etc/doas.conf +chmod 0400 /etc/doas.conf + +hr "1. non-root user: -h/-v allowed, operations refused" +su tester -c "$SP -v"; echo "exit=$? (expect 0)" +su tester -c "$SP -n"; echo "exit=$? (expect 1)" + +hr "2. help" +$SP -h; echo "exit=$?" + +hr "3. copy owned by a normal user is refused even as root" +cp -a /opt/glacier /home/tester/glacier && chown -R tester /home/tester/glacier +/home/tester/glacier/syspkg -v; echo "exit=$?" + +hr "4. hostile lib/ in CWD is ignored (via restricted doas rule)" +mkdir -p /tmp/evil/lib && echo 'print("EVIL CODE RAN") os.exit(9)' > /tmp/evil/lib/cargs.lua +chown -R tester /tmp/evil +su tester -c "cd /tmp/evil && doas $SP -v"; echo "exit=$?" + +hr "5. LUA_INIT / LUA_PATH are ignored (as root directly, no doas env reset)" +LUA_INIT='print("EVIL LUA_INIT")' LUA_PATH='/tmp/evil/?.lua' $SP -v; echo "exit=$?" + +hr "6. install before -n" +cd /opt/glacier +echo y | $SP -l kilo-0.0.1.gpkg; echo "exit=$?" + +hr "7. -n with no /glacier at all" +$SP -n -V; echo "exit=$?" + +hr "7b. -n with /glacier/sys pre-created (dirs but no index: completes)" +rm -rf /glacier && mkdir -p /glacier/sys +$SP -n -V; echo "exit=$?" +$SP -n; echo "re-run exit=$? (expect 1: already exists)" +echo "-- index survived the refused re-run:"; cat /glacier/sys/index/current +ls -la /glacier/sys + +hr "8. install extra-repo package" +echo y | $SP -l kilo-0.0.1.gpkg; echo "exit=$?" +find /glacier/sys -maxdepth 4 | sort +echo "-- links:"; glacier_links /glacier/sys/links +echo "-- index:"; cat /glacier/sys/index/* 2>/dev/null + +hr "9. install base-repo package (should link into /usr)" +echo y | $SP -l pkgs/musl-1.2.5.gpkg; echo "exit=$?" +glacier_links /usr | head +echo "-- index:"; cat /glacier/sys/index/* 2>/dev/null + +hr "10. remove both" +echo y | $SP -x kilo; echo "exit=$?" +echo y | $SP -x musl; echo "exit=$?" +echo "-- leftover glacier symlinks in /usr: $(glacier_links /usr | wc -l)" +echo "-- leftover glacier symlinks in /glacier/sys/links: $(glacier_links /glacier/sys/links | wc -l)" +echo "-- index:"; cat /glacier/sys/index/* 2>/dev/null + +hr "11. remove something not installed" +echo y | $SP -x nosuchpkg; echo "exit=$?" + +hr "12. arg handling" +$SP -n -l x; echo "exit=$?" +$SP --bogus; echo "exit=$?" +$SP -l; echo "exit=$?" diff --git a/tests/sysroot_alpine.sh b/tests/sysroot_alpine.sh new file mode 100644 index 0000000..c83631d --- /dev/null +++ b/tests/sysroot_alpine.sh @@ -0,0 +1,174 @@ +#!/bin/sh +# Install root / sysroot (ROADMAP 1.1, IMAGE_DESIGN section 3): building +# a system into T=/mnt/img through the library's *_at contexts. +# - the host's /usr, /glacier and /etc stay byte-identical (the +# non-negotiable assertion); +# - links in T say RUNTIME paths (/glacier/sys/store/...), and T boots: +# chroot T runs a linked binary through T's own loader; +# - stale-link pruning judges T's links against T's store, not the +# host's: links survive although the host lacks the package, and are +# pruned although the host has it; +# - -O's .displaced originals are keyed by runtime path and restored; +# - /etc config lands in T/etc; dependencies are checked against T; +# - user scope refuses an install root. +# syspkg --root is ROADMAP 1.2, so this drives the library over FFI. +# Runs INSIDE the Dockerfile.alpine_root image: +# +# ./run_docker.sh Dockerfile.alpine_root # builds glacier-alpine_root +# docker run --rm -v "$PWD/tests/sysroot_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +T=/mnt/img +S=/glacier/sys/store + +# mkpkg NAME REPO [DEPS] -> /srv/NAME-1.0.0.gpkg; files come from +# /srv/src/NAME (already laid out as files/...) +mkpkg() { + w=$(mktemp -d); d=$w/$1-1.0.0 + mkdir -p $d; cp -a /srv/src/$1 $d/files + deps=""; sep="" + for it in $3; do deps="$deps$sep{ PKG_NAME = \"${it%%:*}\"; PKG_VER = \"${it#*:}\"; }"; sep=", "; done + printf 'PKG_NAME = "%s";\nPKG_VER = "1.0.0";\nPKG_DESC = "t";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "%s";\nPKG_DEPS = (%s);\nPKG_CONFS = ();\n' "$1" "$2" "$deps" > $d/manifest.gpm.cfg + tar czf /srv/$1-1.0.0.gpkg -C $w $1-1.0.0 + rm -rf $w +} +mkdir -p /srv/src +# alpmusl: Alpine's own loader/libc, so T can run Alpine's busybox +mkdir -p /srv/src/alpmusl/usr/lib +cp /lib/ld-musl-x86_64.so.1 /srv/src/alpmusl/usr/lib/ +ln -s ld-musl-x86_64.so.1 /srv/src/alpmusl/usr/lib/libc.musl-x86_64.so.1 +# imgbase: a binary, a relative and an ABSOLUTE package symlink, config +mkdir -p /srv/src/imgbase/usr/bin /srv/src/imgbase/usr/lib /srv/src/imgbase/etc +cp /bin/busybox /srv/src/imgbase/usr/bin/busybox +echo lib > /srv/src/imgbase/usr/lib/libimg.so.1.0 +ln -s libimg.so.1.0 /srv/src/imgbase/usr/lib/libimg.so.1 +ln -s /usr/lib/libimg.so.1.0 /srv/src/imgbase/usr/lib/libimg-abs.so +echo "image config" > /srv/src/imgbase/etc/imgbase.conf +# imgextra: extra repo, depends on imgbase (which the HOST doesn't have) +mkdir -p /srv/src/imgextra/usr/bin; echo extra > /srv/src/imgextra/usr/bin/imgextra +# shared: installed on the host AND in the image +mkdir -p /srv/src/shared/usr/share/shared; echo shared > /srv/src/shared/usr/share/shared/data +# displacer: replaces a foreign file in T with -O +mkdir -p /srv/src/displacer/usr/bin; echo pkg > /srv/src/displacer/usr/bin/displaceme +mkpkg alpmusl base; mkpkg imgbase base; mkpkg imgextra extra "imgbase:1.0.0" +mkdir -p /srv/src/noop/usr/share/noop; echo noop > /srv/src/noop/usr/share/noop/data +mkpkg shared base; mkpkg displacer base; mkpkg noop extra + +# Driver: img.lua ROOT ACTION ARGS. Prints the status as a number. +cat > /tmp/img.lua <<'EOF' +package.path = "/app/?.lua;" .. package.path +local ffi = require("ffi"); require("lib/glacier_cdef") +local istore = ffi.load("/app/lib/glacier/libglacier_istoreutils.so") +local txn = ffi.load("/app/lib/glacier/libglacier_transaction.so") +local root, action = arg[1], arg[2] +if action == "init" then + print(tonumber(istore.gl_init_sys_at(root, false))) +elseif action == "install" or action == "install-O" or action == "remove" then + local ctx = ffi.new("gl_context_t") + local st = txn.gl_init_stage_context_at(ctx, ffi.C.GL_SCOPE_SYS, 0, root) + if st ~= 0 then print("stage " .. tonumber(st)); os.exit(1) end + ctx.overwrite = action == "install-O" and 1 or 0 + for i = 3, #arg do + local r + if action == "remove" then + local repo, name = arg[i]:match("^(.-)::(.*)$") + r = istore.gl_remove_pkg(ctx, name, repo) + else + r = istore.gl_install_pkg(ctx, arg[i]) + end + if r ~= 0 then print("op " .. tonumber(r)); txn.gl_abort_transaction(ctx); os.exit(1) end + end + local c = txn.gl_commit_transaction(ctx) + if c ~= 0 then txn.gl_abort_transaction(ctx) end + print(tonumber(c)) +elseif action == "usr-live" then + local ctx = ffi.new("gl_context_t") + print(tonumber(txn.gl_init_live_context_at(ctx, ffi.C.GL_SCOPE_USR, 1000, root))) +elseif action == "usr-stage" then + local ctx = ffi.new("gl_context_t") + print(tonumber(txn.gl_init_stage_context_at(ctx, ffi.C.GL_SCOPE_USR, 1000, root))) +elseif action == "sys-live" then + local ctx = ffi.new("gl_context_t") + print(tonumber(txn.gl_init_live_context_at(ctx, ffi.C.GL_SCOPE_SYS, 0, root))) +end +EOF +img() { luajit /tmp/img.lua "$@" 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | tail -1; } +imgout() { luajit /tmp/img.lua "$@" 2>&1 | sed 's/\x1b\[[0-9;]*m//g'; } + +# --- the host: its own glacier system, with `shared` installed +cd /app && ./syspkg -n >/dev/null 2>&1 +printf 'sha256:%s\n' "$(sha256sum /srv/shared-1.0.0.gpkg | cut -d' ' -f1)" > /srv/shared-1.0.0.gpkg.sha256 +gsign -S -s /root/glacier-test.sec -m /srv/shared-1.0.0.gpkg.sha256 >/dev/null +echo y | ./syspkg -l /srv/shared-1.0.0.gpkg >/dev/null 2>&1 +check "host has shared installed" test -L /usr/share/shared/data +# uid 1000 gets a real base, so a user-scope refusal below can only come +# from the install root. +./gstore -n 1000 >/dev/null 2>&1 + +snap() { + find /usr /glacier /etc -xdev -printf '%p %y %m %U %G %s %T@ %l\n' 2>/dev/null | sort + find /usr /glacier /etc -xdev -type f -exec sha256sum {} + 2>/dev/null | sort +} +snap > /tmp/before + +# --- the image +mkdir -p $T; chmod 755 $T +mkdir -p $T/usr/bin; echo foreign > $T/usr/bin/displaceme + +echo "== build" +check "gl_init_sys_at T" test "$(img $T init)" = 0 +check "T has the merged-/usr tree" test "$(readlink $T/bin)" = usr/bin +check "T has its system index" test -L $T/glacier/sys/index/current +check "install alpmusl + imgbase + shared into T" test "$(img $T install /srv/alpmusl-1.0.0.gpkg /srv/imgbase-1.0.0.gpkg /srv/shared-1.0.0.gpkg)" = 0 + +echo "== links say runtime paths" +check "T/usr/bin/busybox -> runtime store path" \ + test "$(readlink $T/usr/bin/busybox)" = "$S/base/imgbase/imgbase-1.0.0/usr/bin/busybox" +check "the absolute package symlink is kept verbatim" \ + test "$(readlink $T$S/base/imgbase/imgbase-1.0.0/usr/lib/libimg-abs.so)" = /usr/lib/libimg.so.1.0 +check "no link anywhere in T mentions T" sh -c "! find $T -type l -exec readlink {} \; | grep -q '^$T'" +check "chroot T runs busybox through T's own loader" sh -c "chroot $T /usr/bin/busybox echo booted | grep -qx booted" +check "chroot T resolves the absolute package symlink" sh -c "chroot $T /usr/bin/busybox cat /usr/lib/libimg-abs.so | grep -qx lib" + +echo "== /etc" +check "config copied into T/etc" sh -c "grep -qx 'image config' $T/etc/imgbase.conf" +check "not into the host's /etc" test ! -e /etc/imgbase.conf + +echo "== dependencies are checked against T" +check "imgextra (needs imgbase, which only T has) installs" test "$(img $T install /srv/imgextra-1.0.0.gpkg)" = 0 +check "imgextra linked in T's sys links" test -L $T/glacier/sys/links/bin/imgextra +OUT=$(imgout $T remove base::imgbase) +check "removing imgbase from T is refused for T's dependent" sh -c 'echo "$1" | grep -qxF "[x] Removing base::imgbase breaks extra::imgextra."' _ "$OUT" +check "imgbase still in T" test -d $T$S/base/imgbase + +echo "== pruning judges T's links against T's store" +check "imgbase's links survived the second commit (host lacks imgbase)" test -L $T/usr/bin/busybox +check "remove shared from T" test "$(img $T remove base::shared)" = 0 +check "T's shared link pruned (although the host has shared)" sh -c "! test -e $T/usr/share/shared/data -o -L $T/usr/share/shared/data" + +echo "== -O: displaced originals keyed by runtime path" +check "install-O displacer into T" test "$(img $T install-O /srv/displacer-1.0.0.gpkg)" = 0 +check "original kept under the runtime key" sh -c "grep -qx foreign $T$S/.displaced/usr/bin/displaceme" +check "no T-prefixed key" test ! -e "$T$S/.displaced$T" +check "an unrelated later commit to T" test "$(img $T install /srv/noop-1.0.0.gpkg)" = 0 +check "the displacing link survived it (host lacks displacer)" \ + test "$(readlink $T/usr/bin/displaceme)" = "$S/base/displacer/displacer-1.0.0/usr/bin/displaceme" +check "the original is still kept aside" sh -c "grep -qx foreign $T$S/.displaced/usr/bin/displaceme" +check "remove displacer from T" test "$(img $T remove base::displacer)" = 0 +check "original restored in T" sh -c "grep -qx foreign $T/usr/bin/displaceme" + +echo "== user scope refuses an install root" +check "live context: refused" test "$(img $T usr-live)" = -1 +check "stage context: refused (GL_TXN_ERR_PERM)" test "$(img $T usr-stage)" = 3 +check "relative install root refused" test "$(img mnt/img sys-live)" = -1 +check "install root with .. refused" test "$(img /mnt/../etc sys-live)" = -1 +check "/ is the running system" test "$(img / sys-live)" = 0 + +echo "== the host" +snap > /tmp/after +check "host /usr, /glacier and /etc are byte-identical" cmp -s /tmp/before /tmp/after +cmp -s /tmp/before /tmp/after || diff /tmp/before /tmp/after | head -20 + +echo +[ $FAILS -eq 0 ] && echo "ALL PASSED" || echo "$FAILS FAILED" +exit $FAILS diff --git a/tests/test_abort_unlocked.lua b/tests/test_abort_unlocked.lua new file mode 100644 index 0000000..9ff9bf6 --- /dev/null +++ b/tests/test_abort_unlocked.lua @@ -0,0 +1,36 @@ +-- test_abort_unlocked.lua +-- +-- gl_abort_transaction only removes the stage of the context holding the +-- scope's lock. A context whose gl_init_stage_context lost the race (or +-- never began) used to wipe the stage anyway, i.e. the running +-- transaction of whoever DID hold the lock. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +h.reset_glacier_root() + +local uid = 1001 +io.write("== test_abort_unlocked (uid " .. uid .. ") ==\n") + +glacier.lib.gl_init_user(uid, false) + +local ctx1 = glacier.new_context() +local st1 = glacier.lib.gl_init_stage_context(ctx1, glacier.SCOPE_USR, uid) +h.check(tonumber(st1) == 0, "first stage context acquires the lock: " .. glacier.txn_name(st1)) + +local stage = "/glacier/usr/" .. uid .. "/stage" +h.check(h.exists(stage .. "/index"), "the first context's stage exists") + +local ctx2 = glacier.new_context() +local st2 = glacier.lib.gl_init_stage_context(ctx2, glacier.SCOPE_USR, uid) +h.check(tonumber(st2) == 1, "second context is refused the lock: " .. glacier.txn_name(st2)) + +local ab = glacier.lib.gl_abort_transaction(ctx2) +h.check(tonumber(ab) == 7, "aborting without the lock is GL_TXN_ERR_NO_TXN: " .. glacier.txn_name(ab)) +h.check(h.exists(stage .. "/index"), "...and leaves the lock holder's stage alone") + +glacier.lib.gl_abort_transaction(ctx1) +h.check(not h.exists(stage), "the lock holder's own abort removes it") + +h.summary() diff --git a/tests/test_config_files.lua b/tests/test_config_files.lua new file mode 100644 index 0000000..592924a --- /dev/null +++ b/tests/test_config_files.lua @@ -0,0 +1,139 @@ +-- test_config_files.lua +-- +-- /etc handling (decision GLACIER_BOOTSTRAP.txt 9c: option 1, copy on +-- install, .new on conflict). A system-scope package's etc/ is COPIED +-- into /etc, never linked; an admin-modified, admin-deleted or +-- not-glacier-installed file is never overwritten; package changes to +-- such a file are offered as FILE.new, once. +-- +-- Uses the real /etc of the (throwaway) test container, confined to +-- /etc/glacier-cfgtest. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +h.reset_glacier_root() +io.write("== test_config_files ==\n") + +local D = "/etc/glacier-cfgtest" +h.sh("rm -rf " .. D) +h.check(tonumber(glacier.lib.gl_init_sys(false)) == 0, "gl_init_sys") + +local function read(path) + local f = io.open(path, "r") + if not f then return nil end + local c = f:read("*a") + f:close() + return c +end +local function write(path, c) + local f = assert(io.open(path, "w")) + f:write(c) + f:close() +end +local function is_symlink(path) + local ok = os.execute("test -L " .. h.quote(path)) + return ok == true or ok == 0 +end +local function readlink(path) + local p = io.popen("readlink " .. h.quote(path) .. " 2>/dev/null") + local s = p:read("*l") + p:close() + return s +end + +-- One system-scope transaction: remove `remove` (list of {name, repo}), +-- then install `pkgs`. +local function sys_txn(pkgs, remove) + local ctx = glacier.new_context() + local st = glacier.lib.gl_init_stage_context(ctx, glacier.SCOPE_SYS, 0) + if tonumber(st) ~= 0 then return "stage:" .. glacier.txn_name(st) end + for _, r in ipairs(remove or {}) do + local rr = glacier.lib.gl_remove_pkg(ctx, r[1], r[2]) + if tonumber(rr) ~= 0 then + glacier.lib.gl_abort_transaction(ctx) + return "remove:" .. glacier.remove_name(rr) + end + end + for _, p in ipairs(pkgs or {}) do + local r = glacier.lib.gl_install_pkg(ctx, p) + if tonumber(r) ~= 0 then + glacier.lib.gl_abort_transaction(ctx) + return glacier.install_name(r) + end + end + return glacier.txn_name(glacier.lib.gl_commit_transaction(ctx)) +end + +local function cfgpkg(ver, files, symlinks) + local f = {} + for k, v in pairs(files) do f["etc/glacier-cfgtest/" .. k] = v end + local l = {} + for k, v in pairs(symlinks or {}) do l["etc/glacier-cfgtest/" .. k] = v end + return h.build_fixture_pkg{ name = "cfgpkg", ver = ver, repo = "extra", files = f, symlinks = l } +end + +-- --------------------------------------------------------------------- +io.write("-- first install\n") +h.sh("mkdir -p " .. D) +write(D .. "/c.conf", "admin c\n") -- already there, not glacier's + +local v1 = cfgpkg("1.0.0", + { ["a.conf"] = "a1\n", ["b.conf"] = "b1\n", ["c.conf"] = "c1\n", ["d.conf"] = "d1\n" }, + { ["link.conf"] = "a.conf" }) +h.check(sys_txn({ v1 }) == "GL_TXN_OK", "install cfgpkg 1.0.0") + +h.check(read(D .. "/a.conf") == "a1\n" and not is_symlink(D .. "/a.conf"), + "a.conf COPIED into /etc (a regular file, not a link into the store)") +h.check(read(D .. "/b.conf") == "b1\n", "b.conf installed") +h.check(readlink(D .. "/link.conf") == "a.conf", "a config symlink is copied as a symlink") +h.check(read(D .. "/c.conf") == "admin c\n", "pre-existing c.conf (not glacier's) untouched") +h.check(read(D .. "/c.conf.new") == "c1\n", "package's c.conf offered as c.conf.new") +h.check(not h.exists("/usr/etc") and not h.exists("/glacier/sys/links/etc"), + "nothing linked under /usr/etc or the links tree") + +-- --------------------------------------------------------------------- +io.write("-- admin edits / deletes, then an unrelated commit\n") +write(D .. "/a.conf", "a-admin\n") +os.remove(D .. "/d.conf") +local other = h.build_fixture_pkg{ name = "cfgother", ver = "1.0.0", repo = "extra" } +h.check(sys_txn({ other }) == "GL_TXN_OK", "unrelated transaction") +h.check(read(D .. "/a.conf") == "a-admin\n", "edited a.conf left alone") +h.check(not h.exists(D .. "/a.conf.new"), "no .new for an edit when the package didn't change") +h.check(not h.exists(D .. "/d.conf"), "deleted d.conf stays deleted") + +-- --------------------------------------------------------------------- +io.write("-- upgrade to 2.0.0\n") +local v2 = cfgpkg("2.0.0", + { ["a.conf"] = "a2\n", ["b.conf"] = "b2\n", ["c.conf"] = "c1\n", ["d.conf"] = "d2\n" }, + { ["link.conf"] = "a.conf" }) +h.check(sys_txn({ v2 }, { { "cfgpkg", "extra" } }) == "GL_TXN_OK", "upgrade (remove 1.0.0 + install 2.0.0)") + +h.check(read(D .. "/a.conf") == "a-admin\n", "edited a.conf kept") +h.check(read(D .. "/a.conf.new") == "a2\n", "package's new a.conf offered as a.conf.new") +h.check(read(D .. "/b.conf") == "b2\n" and not h.exists(D .. "/b.conf.new"), + "untouched b.conf upgraded in place, no .new") +h.check(read(D .. "/c.conf") == "admin c\n", "foreign c.conf still untouched") +h.check(not h.exists(D .. "/d.conf"), "deleted d.conf not resurrected by the upgrade") + +-- --------------------------------------------------------------------- +io.write("-- an offer is made once\n") +os.remove(D .. "/a.conf.new") +os.remove(D .. "/c.conf.new") +local other2 = h.build_fixture_pkg{ name = "cfgother2", ver = "1.0.0", repo = "extra" } +h.check(sys_txn({ other2 }) == "GL_TXN_OK", "another unrelated transaction") +h.check(not h.exists(D .. "/a.conf.new") and not h.exists(D .. "/c.conf.new"), + "dismissed .new files are not recreated") + +-- --------------------------------------------------------------------- +io.write("-- removal\n") +h.check(sys_txn({}, { { "cfgpkg", "extra" } }) == "GL_TXN_OK", "remove cfgpkg") +h.check(not h.exists(D .. "/b.conf"), "unmodified b.conf removed with its package") +h.check(not is_symlink(D .. "/link.conf"), "unmodified config symlink removed") +h.check(read(D .. "/a.conf") == "a-admin\n", "edited a.conf kept after removal") +h.check(read(D .. "/c.conf") == "admin c\n", "foreign c.conf kept after removal") +h.check(not h.exists("/glacier/sys/store/.etc-state/glacier-cfgtest/b.conf"), + "records for the removed package are gone") + +h.sh("rm -rf " .. D) +h.summary() diff --git a/tests/test_exdev.lua b/tests/test_exdev.lua new file mode 100644 index 0000000..8447013 --- /dev/null +++ b/tests/test_exdev.lua @@ -0,0 +1,68 @@ +-- test_exdev.lua +-- +-- Verifies gl_commit_transaction detects and rejects a cross-filesystem +-- commit instead of failing partway through the rename sequence. Rather +-- than trust that the check is "probably fine", this actually mounts a +-- tmpfs over /glacier/usr//stage so the filesystem mismatch is real, not +-- simulated. +-- +-- Requires CAP_SYS_ADMIN (root) to call mount()/umount2() — expected to +-- be running as root inside the test container. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +h.reset_glacier_root() + +local uid = 1002 +io.write("== test_exdev (uid " .. uid .. ") ==\n") + +if tonumber(glacier.C.geteuid()) ~= 0 then + io.write(" SKIP - not running as root, can't mount(); " .. + "run this test as root inside the container\n") + os.exit(0) +end + +glacier.lib.gl_init_user(uid, false) + +local stage = "/glacier/usr/" .. uid .. "/stage" +h.sh("mkdir -p " .. stage) +local mnt_rc = glacier.C.mount("tmpfs", stage, "tmpfs", 0, "size=16m") +if tonumber(mnt_rc) ~= 0 then + local why = glacier.strerror() + io.write(" SKIP - mount() failed: " .. why .. "\n") + io.write(" This is very likely the container's seccomp profile blocking " .. + "the mount syscall, not a bug under test.\n" .. + " Re-run the container with --cap-add=SYS_ADMIN (or --privileged) " .. + "to actually exercise this test.\n") + os.exit(0) +end +h.check(true, "tmpfs mounted on " .. stage) + +local ctx = glacier.new_context() +local st = glacier.lib.gl_init_stage_context(ctx, glacier.SCOPE_USR, uid) + +-- Two places can catch it, both correct: stage seeding hardlinks live +-- into the stage and link() fails EXDEV (init returns GL_TXN_ERR_XDEV), +-- or — if live had nothing to seed — commit's own same-fs check does. +-- What must never happen is a different error, or a partial commit. +if tonumber(st) == 0 then + local commit = glacier.lib.gl_commit_transaction(ctx) + h.check(tonumber(commit) == 8, -- GL_TXN_ERR_XDEV + "commit across filesystems is rejected with GL_TXN_ERR_XDEV: got " .. + glacier.txn_name(commit)) + glacier.lib.gl_abort_transaction(ctx) +else + h.check(tonumber(st) == 8, -- GL_TXN_ERR_XDEV + "stage on a different fs is rejected at init with GL_TXN_ERR_XDEV: got " .. + glacier.txn_name(st)) +end + +h.check(not h.exists("/glacier/usr/" .. uid .. "/store/core"), + "live store was NOT mutated by the rejected transaction") +h.check(h.exists("/glacier/usr/" .. uid .. "/index/current"), + "live index still intact") + +glacier.C.umount2(stage, 0) + +h.summary() diff --git a/tests/test_fs_tree.lua b/tests/test_fs_tree.lua new file mode 100644 index 0000000..06c2ff9 --- /dev/null +++ b/tests/test_fs_tree.lua @@ -0,0 +1,83 @@ +-- test_fs_tree.lua +-- +-- gl_create_fs_tree: the top-level merged-/usr tree `syspkg -n` lays +-- down (decision GLACIER_BOOTSTRAP.txt 9d). Run against throwaway roots, +-- never "/": it must create exactly what's missing, with the right +-- types and modes, and leave anything already present untouched. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +io.write("== test_fs_tree ==\n") + +local function mkroot() + local p = io.popen("mktemp -d /tmp/fstree.XXXXXX") + local d = p:read("*l") + p:close() + return d +end + +local function stat(path) -- " " via busybox/coreutils stat + local p = io.popen("stat -c '%F %a' " .. h.quote(path) .. " 2>/dev/null") + local s = p:read("*l") + p:close() + return s +end + +local function readlink(path) + local p = io.popen("readlink " .. h.quote(path) .. " 2>/dev/null") + local s = p:read("*l") + p:close() + return s +end + +-- 1. Empty root: everything created, right type and mode. +local r = mkroot() +h.check(tonumber(glacier.lib.gl_create_fs_tree(r, false)) == 0, "create tree in an empty root") + +local dirs = { + ["/usr"] = "755", ["/usr/bin"] = "755", ["/usr/lib"] = "755", + ["/etc"] = "755", ["/dev"] = "755", ["/proc"] = "555", ["/sys"] = "555", + ["/run"] = "755", ["/tmp"] = "1777", ["/var"] = "755", ["/var/tmp"] = "1777", + ["/root"] = "700", ["/home"] = "755", +} +for d, mode in pairs(dirs) do + h.check(stat(r .. d) == "directory " .. mode, d .. " is a directory, mode " .. mode) +end + +local links = { ["/bin"] = "usr/bin", ["/sbin"] = "usr/bin", ["/lib"] = "usr/lib", ["/usr/sbin"] = "bin" } +for l, target in pairs(links) do + h.check(readlink(r .. l) == target, l .. " -> " .. target .. " (relative)") +end + +-- Relative links resolve INSIDE the root, which is what makes them work +-- both under a prefix (syspkg --root) and once chrooted/booted: +-- musl's PT_INTERP /lib/ld-musl-*.so.1 -> /usr/lib/ld-musl-*.so.1. +h.sh("echo loader > " .. h.quote(r .. "/usr/lib/ld-test.so.1")) +h.check(h.exists(r .. "/lib/ld-test.so.1"), "/lib/x resolves to /usr/lib/x within the root") +h.sh("echo tool > " .. h.quote(r .. "/usr/bin/tool")) +h.check(h.exists(r .. "/sbin/tool") and h.exists(r .. "/usr/sbin/tool"), + "/sbin/x and /usr/sbin/x resolve to /usr/bin/x") + +-- 2. Re-running is a no-op. +h.check(tonumber(glacier.lib.gl_create_fs_tree(r, false)) == 0, "second run succeeds") +h.check(stat(r .. "/tmp") == "directory 1777" and readlink(r .. "/bin") == "usr/bin", + "second run changed nothing") + +-- 3. Existing entries of the "wrong" type are left exactly as they are. +local r2 = mkroot() +h.sh("mkdir " .. h.quote(r2 .. "/bin") .. " && echo keep > " .. h.quote(r2 .. "/bin/existing")) +h.sh("echo i-am-a-file > " .. h.quote(r2 .. "/tmp")) +h.sh("ln -s /elsewhere " .. h.quote(r2 .. "/lib")) +h.check(tonumber(glacier.lib.gl_create_fs_tree(r2 .. "/", false)) == 0, + "create tree over a partly-populated root (trailing slash on root)") +h.check(stat(r2 .. "/bin") == "directory 755" or (stat(r2 .. "/bin") or ""):match("^directory"), + "existing real /bin directory NOT replaced by a symlink") +h.check(h.exists(r2 .. "/bin/existing"), "its contents untouched") +h.check((stat(r2 .. "/tmp") or ""):match("^regular") ~= nil, "existing /tmp file left alone") +h.check(readlink(r2 .. "/lib") == "/elsewhere", "existing foreign /lib symlink left alone") +h.check(readlink(r2 .. "/sbin") == "usr/bin" and stat(r2 .. "/var/tmp") == "directory 1777", + "the missing entries were still created") + +h.sh("rm -rf " .. h.quote(r) .. " " .. h.quote(r2)) +h.summary() diff --git a/tests/test_helpers.lua b/tests/test_helpers.lua new file mode 100644 index 0000000..d6ad43a --- /dev/null +++ b/tests/test_helpers.lua @@ -0,0 +1,139 @@ +-- test_helpers.lua +-- Shared helpers for the libglacier-ng Lua test suite. These operate on +-- the real filesystem (/glacier) and real subprocesses — there is no +-- mocking here, by design, since the whole point of these tests is to +-- exercise real rename()/flock()/mount() behavior. + +local M = {} + +function M.quote(s) + return "'" .. s:gsub("'", "'\\''") .. "'" +end + +function M.sh(cmd) + local ok = os.execute(cmd) + local success = (ok == true) or (ok == 0) + if not success then + error(string.format("command failed (%s): %s", tostring(ok), cmd), 2) + end +end + +function M.exists(path) + local ok = os.execute("test -e " .. M.quote(path)) + return ok == true or ok == 0 +end + +-- Wipes and recreates a bare /glacier tree so each test file starts +-- clean. DESTRUCTIVE. Guarded behind an explicit env var so nobody runs +-- this against a real system by accident. +function M.reset_glacier_root() + assert(os.getenv("GLACIER_TEST_CONFIRM") == "yes", + "refusing to rm -rf /glacier: set GLACIER_TEST_CONFIRM=yes " .. + "to confirm this is running in a throwaway test container") + M.sh("rm -rf /glacier") + -- gl_init_user creates /glacier/usr itself, and gl_init_sys the + -- system tree; this just gives both the root-owned, 0755 parents + -- the per-uid layout's safety check expects (see common.h). + M.sh("mkdir -p /glacier/usr /glacier/sys/index /glacier/sys/store /glacier/sys/links") + M.sh("chmod 755 /glacier /glacier/usr /glacier/sys") +end + +-- Builds a minimal but real .gpkg (gzip tar with a libconfig manifest +-- and a files/ payload) that gl_install_pkg can actually parse and +-- extract. Returns (path_to_gpkg, workdir). +function M.build_fixture_pkg(opts) + opts = opts or {} + local name = opts.name or "testpkg" + local ver = opts.ver or "1.0.0" + local repo = opts.repo or "core" + local payload = opts.payload or ("hello from " .. name .. "\n") + + local work = os.tmpname() + M.sh("rm -f " .. M.quote(work)) + M.sh("mkdir -p " .. M.quote(work)) + + local pkgdir = string.format("%s/%s-%s", work, name, ver) + M.sh("mkdir -p " .. M.quote(pkgdir .. "/files/usr/bin")) + + local manifest = assert(io.open(pkgdir .. "/manifest.gpm.cfg", "w")) + manifest:write(string.format( + 'PKG_NAME = "%s";\n' .. + 'PKG_VER = "%s";\n' .. + 'PKG_DESC = "Fixture package for tests";\n' .. + 'PKG_MAINT = "test@example.com";\n' .. + 'PKG_COPYRIGHT = "2026 Test";\n' .. + 'PKG_REPO = "%s";\n', + name, ver, repo)) + manifest:close() + + local bin = assert(io.open(pkgdir .. "/files/usr/bin/" .. name, "w")) + bin:write(payload) + bin:close() + + -- opts.files = { ["usr/lib/libx.so"] = "content", ... } + -- opts.symlinks = { ["usr/bin/alias"] = "target", ... } + -- Both relative to files/. + local function place(root, files, symlinks) + for rel, content in pairs(files or {}) do + local path = root .. "/" .. rel + M.sh("mkdir -p " .. M.quote(path:match("^(.*)/"))) + local f = assert(io.open(path, "w")) + f:write(content) + f:close() + end + for rel, target in pairs(symlinks or {}) do + local path = root .. "/" .. rel + M.sh("mkdir -p " .. M.quote(path:match("^(.*)/"))) + M.sh("ln -s " .. M.quote(target) .. " " .. M.quote(path)) + end + end + place(pkgdir .. "/files", opts.files, opts.symlinks) + + local out_path = opts.out or (work .. "/" .. name .. ".gpkg") + local tar_path = work .. "/" .. name .. ".tar" + M.sh(string.format("tar cf %s -C %s %s-%s", + M.quote(tar_path), M.quote(work), name, ver)) + + -- opts.append = { { files = {...}, symlinks = {...} }, ... } + -- Each batch is APPENDED to the archive as extra entries under the + -- same files/ prefix, from a separate tree — the only way to get + -- an archive no real filesystem could produce, e.g. a symlink `x` + -- followed by a file `x/y`. Needs GNU tar (--append). + for i, batch in ipairs(opts.append or {}) do + local alt = string.format("%s/append%d", work, i) + local alt_pkg = string.format("%s/%s-%s", alt, name, ver) + place(alt_pkg .. "/files", batch.files, batch.symlinks) + -- Leaf entries only (no directory entries), so e.g. `x/y` + -- arrives with NO real directory `x` in front of it. + local list = alt .. ".list" + M.sh(string.format( + "cd %s && find %s-%s/files ! -type d > %s && " .. + "tar rf %s --no-recursion -C %s -T %s", + M.quote(alt), name, ver, M.quote(list), + M.quote(tar_path), M.quote(alt), M.quote(list))) + end + + M.sh(string.format("gzip -c %s > %s", M.quote(tar_path), M.quote(out_path))) + + return out_path, work +end + +local pass, fail = 0, 0 + +function M.check(cond, msg) + if cond then + pass = pass + 1 + io.write(" ok - " .. msg .. "\n") + else + fail = fail + 1 + io.write(" FAIL - " .. msg .. "\n") + end + return cond +end + +function M.summary() + io.write(string.format("\n%d passed, %d failed\n", pass, fail)) + os.exit(fail == 0 and 0 or 1) +end + +return M diff --git a/tests/test_index_abort.lua b/tests/test_index_abort.lua new file mode 100644 index 0000000..9c7645a --- /dev/null +++ b/tests/test_index_abort.lua @@ -0,0 +1,68 @@ +-- test_index_abort.lua +-- +-- An aborted transaction must leave the live index exactly as it was +-- (CLAUDE.md bug 25). Index files are named to the second, and stage +-- seeding HARDLINKS live's into the stage, so a staged install in the +-- same second as the last commit produces an index file with the same +-- name as live's, sharing its inode. gl_rebuild_index used to +-- fopen(name, "w") it, rewriting the live index in place. +-- +-- The collision depends on timing, so this repeats commit + staged +-- install until the stage's new index really does share a name with +-- live's, then checks live after the abort. Without a collision there's +-- nothing to test, and that is reported as a failure rather than a pass. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +h.reset_glacier_root() + +local uid = 1004 +io.write("== test_index_abort (uid " .. uid .. ") ==\n") +glacier.lib.gl_init_user(uid, false) + +local function read(path) + local f = io.open(path, "r") + if not f then return nil end + local s = f:read("*a") + f:close() + return s +end + +local index_dir = "/glacier/usr/" .. uid .. "/index" +local stage_index = "/glacier/usr/" .. uid .. "/stage/index" + +local collided = false +for i = 1, 20 do + -- A commit, so live gets a fresh index file named for this second. + local path = h.build_fixture_pkg{ name = "base" .. i, ver = "1.0.0", repo = "core" } + local c = glacier.new_context() + assert(tonumber(glacier.lib.gl_init_stage_context(c, glacier.SCOPE_USR, uid)) == 0) + assert(tonumber(glacier.lib.gl_install_pkg(c, path)) == 0) + assert(tonumber(glacier.lib.gl_commit_transaction(c)) == 0) + + local p = io.popen("readlink " .. h.quote(index_dir .. "/current")) + local live_name = p:read("*l"); p:close() + local before = read(index_dir .. "/" .. live_name) + + -- Straight away: a staged install, then abort. + local extra = h.build_fixture_pkg{ name = "aborted" .. i, ver = "1.0.0", repo = "core" } + local s = glacier.new_context() + assert(tonumber(glacier.lib.gl_init_stage_context(s, glacier.SCOPE_USR, uid)) == 0) + assert(tonumber(glacier.lib.gl_install_pkg(s, extra)) == 0) + p = io.popen("readlink " .. h.quote(stage_index .. "/current")) + local stage_name = p:read("*l"); p:close() + glacier.lib.gl_abort_transaction(s) + + if stage_name == live_name then + collided = true + h.check(read(index_dir .. "/" .. live_name) == before, + "live index unchanged after an aborted same-second transaction (attempt " .. i .. ")") + h.check(not (read(index_dir .. "/current") or ""):find("aborted" .. i, 1, true), + "live index doesn't list the aborted package") + break + end +end + +h.check(collided, "a same-second index name collision happened (needed for this test)") +h.summary() diff --git a/tests/test_live_remove_foreign.lua b/tests/test_live_remove_foreign.lua new file mode 100644 index 0000000..92d0f99 --- /dev/null +++ b/tests/test_live_remove_foreign.lua @@ -0,0 +1,53 @@ +-- test_live_remove_foreign.lua +-- +-- Removing a package through a LIVE context must only remove glacier's +-- own links (CLAUDE.md bug 26). gl_unlink_pkg used to unlink() the link +-- destination of every regular file in the package without checking +-- is_glacier_symlink, so a file the package was REFUSED to overwrite (a +-- foreign file already at its destination) was deleted on removal, and +-- the package's symlinks were left dangling. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +h.reset_glacier_root() +io.write("== test_live_remove_foreign ==\n") +h.sh("rm -rf /glacier/sys") +h.check(tonumber(glacier.lib.gl_init_sys(false)) == 0, "gl_init_sys") + +-- A foreign file where the package wants to link, plus a package symlink +-- (store entry) so the symlink half of removal is covered too. +h.sh("mkdir -p /usr/share/livefgn && echo foreign > /usr/share/livefgn/data") +local pkg = h.build_fixture_pkg{ name = "livefgn", ver = "1.0.0", repo = "base" } +local work = os.tmpname() +h.sh("rm -f " .. work .. " && mkdir -p " .. work) +h.sh("cd " .. work .. " && tar xzf " .. h.quote(pkg)) +h.sh("mkdir -p " .. work .. "/livefgn-1.0.0/files/usr/share/livefgn") +h.sh("echo pkg > " .. work .. "/livefgn-1.0.0/files/usr/share/livefgn/data") +h.sh("echo own > " .. work .. "/livefgn-1.0.0/files/usr/share/livefgn/own") +h.sh("ln -s own " .. work .. "/livefgn-1.0.0/files/usr/share/livefgn/own-link") +h.sh("cd " .. work .. " && tar czf " .. h.quote(pkg) .. " livefgn-1.0.0") + +local live = glacier.new_context() +glacier.lib.gl_init_live_context(live, glacier.SCOPE_SYS, 0) +local st = glacier.lib.gl_install_pkg(live, pkg) +h.check(tonumber(st) == 0, "live install: " .. glacier.install_name(st)) +h.check(h.exists("/usr/share/livefgn/own"), "the package's own file is linked") +h.check(h.exists("/usr/share/livefgn/own-link"), "the package's own symlink is linked") + +local rm = glacier.lib.gl_remove_pkg(live, "livefgn", "base") +h.check(tonumber(rm) == 0, "live remove: " .. glacier.remove_name(rm)) + +local f = io.open("/usr/share/livefgn/data", "r") +local content = f and f:read("*l") +if f then f:close() end +h.check(content == "foreign", "the foreign file the package never replaced is still there") +local function lexists(p) + local ok = os.execute("test -e " .. h.quote(p) .. " -o -L " .. h.quote(p)) + return ok == true or ok == 0 +end +h.check(not lexists("/usr/share/livefgn/own"), "the package's link is gone") +h.check(not lexists("/usr/share/livefgn/own-link"), "the package's symlink's link is gone") + +h.sh("rm -rf /usr/share/livefgn") +h.summary() diff --git a/tests/test_lock_contention.lua b/tests/test_lock_contention.lua new file mode 100644 index 0000000..291c5a5 --- /dev/null +++ b/tests/test_lock_contention.lua @@ -0,0 +1,39 @@ +-- test_lock_contention.lua +-- +-- Confirms flock() alone is still enough to reject a second concurrent +-- stage transaction for the same uid/scope. This matters because the +-- fix for stale locks (dropping O_EXCL) could easily have accidentally +-- weakened real contention too — this test makes sure it didn't. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +h.reset_glacier_root() + +local uid = 1001 +io.write("== test_lock_contention (uid " .. uid .. ") ==\n") + +glacier.lib.gl_init_user(uid, false) + +local ctx1 = glacier.new_context() +local st1 = glacier.lib.gl_init_stage_context(ctx1, glacier.SCOPE_USR, uid) +h.check(tonumber(st1) == 0, + "first stage context acquires the lock: " .. glacier.txn_name(st1)) + +local ctx2 = glacier.new_context() +local st2 = glacier.lib.gl_init_stage_context(ctx2, glacier.SCOPE_USR, uid) +h.check(tonumber(st2) == 1, -- GL_TXN_ERR_LOCK + "second concurrent stage context is rejected: got " .. glacier.txn_name(st2)) + +-- ctx2 failed to acquire, so it holds no lock — only abort ctx1. +glacier.lib.gl_abort_transaction(ctx1) + +local ctx3 = glacier.new_context() +local st3 = glacier.lib.gl_init_stage_context(ctx3, glacier.SCOPE_USR, uid) +h.check(tonumber(st3) == 0, + "lock is available again after a clean abort: " .. glacier.txn_name(st3)) +if tonumber(st3) == 0 then + glacier.lib.gl_abort_transaction(ctx3) +end + +h.summary() diff --git a/tests/test_lock_crash_recovery.lua b/tests/test_lock_crash_recovery.lua new file mode 100644 index 0000000..c3d0545 --- /dev/null +++ b/tests/test_lock_crash_recovery.lua @@ -0,0 +1,59 @@ +-- test_lock_crash_recovery.lua +-- +-- This is the actual regression test for the O_EXCL fix. The old +-- gl_begin_transaction used open(O_CREAT|O_EXCL), so a crashed holder +-- left a lock file on disk that permanently blocked every future +-- transaction for that uid/scope until someone manually rm'd it. The +-- fix relies on flock() being tied to the open file description, which +-- the kernel releases automatically when the holding process dies — +-- including via SIGKILL, which gives the process no chance to run any +-- cleanup code at all. +-- +-- fork() duplicates the whole LuaJIT VM. To keep this safe, the child +-- does the absolute minimum (one FFI call, then _exit) and touches no +-- further Lua state before exiting. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") +local ffi = glacier.ffi + +h.reset_glacier_root() + +local uid = 1000 +io.write("== test_lock_crash_recovery (uid " .. uid .. ") ==\n") + +glacier.lib.gl_init_user(uid, false) + +local child = glacier.C.fork() +if child == 0 then + -- CHILD: acquire the lock, then simulate a wedged/crashed + -- process by sleeping. No cleanup, no unlock — the parent will + -- SIGKILL this before it ever gets a chance to. + local ctx = glacier.new_context() + local st = glacier.lib.gl_init_stage_context(ctx, glacier.SCOPE_USR, uid) + if tonumber(st) ~= 0 then + glacier.C._exit(1) + end + glacier.C.sleep(30) + glacier.C._exit(0) +end + +-- PARENT: give the child a moment to actually acquire the lock before +-- killing it. +glacier.C.sleep(1) + +glacier.C.kill(child, 9) -- SIGKILL — no handlers, no cleanup, ever +local status = ffi.new("int[1]") +glacier.C.waitpid(child, status, 0) + +local ctx2 = glacier.new_context() +local st2 = glacier.lib.gl_init_stage_context(ctx2, glacier.SCOPE_USR, uid) +h.check(tonumber(st2) == 0, + "stage context acquired immediately after the holder was SIGKILLed: " .. + glacier.txn_name(st2)) + +if tonumber(st2) == 0 then + glacier.lib.gl_abort_transaction(ctx2) +end + +h.summary() diff --git a/tests/test_package_symlinks.lua b/tests/test_package_symlinks.lua new file mode 100644 index 0000000..ef4a2a5 --- /dev/null +++ b/tests/test_package_symlinks.lua @@ -0,0 +1,241 @@ +-- test_package_symlinks.lua +-- +-- Symlinks shipped inside packages: they used to be silently dropped at +-- extraction (only dirs and regular files were handled), which meant +-- e.g. musl's loader lib/ld-musl-x86_64.so.1 -> /usr/lib/libc.so was +-- never installed. Now they're extracted verbatim and linked like files. +-- +-- The security half: an archive must never be able to write THROUGH a +-- symlink it ships (`x -> /victim`, then `x/pwn`). Symlinks are created +-- only after all regular content, and any entry whose parent is a +-- symlink is refused. Linking must likewise never descend through +-- another package's symlink into that package's store directory. +-- +-- Needs GNU tar (the hostile archives are built with --append). + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +h.reset_glacier_root() + +local uid = 1004 +io.write("== test_package_symlinks (uid " .. uid .. ") ==\n") +glacier.lib.gl_init_user(uid, false) + +local base = "/glacier/usr/" .. uid +local store, links = base .. "/store", base .. "/links" + +local function readlink(path) + local p = io.popen("readlink " .. h.quote(path) .. " 2>/dev/null") + local out = p:read("*l") + p:close() + return out +end + +local function is_symlink(path) + local ok = os.execute("test -L " .. h.quote(path)) + return ok == true or ok == 0 +end + +local function read_file(path) + local f = io.open(path, "r") + if not f then return nil end + local c = f:read("*a") + f:close() + return c +end + +-- Install `pkgs` (list of .gpkg paths) as one staged transaction. +-- Returns the first non-OK install status, or the commit status. +local function install(pkgs) + local ctx = glacier.new_context() + local st = glacier.lib.gl_init_stage_context(ctx, glacier.SCOPE_USR, uid) + if tonumber(st) ~= 0 then return "stage:" .. glacier.txn_name(st) end + for _, p in ipairs(pkgs) do + local r = glacier.lib.gl_install_pkg(ctx, p) + if tonumber(r) ~= 0 then + glacier.lib.gl_abort_transaction(ctx) + return glacier.install_name(r) + end + end + local c = glacier.lib.gl_commit_transaction(ctx) + if tonumber(c) ~= 0 then glacier.lib.gl_abort_transaction(ctx) end + return glacier.txn_name(c) +end + +-- --------------------------------------------------------------------- +io.write("-- legitimate symlinks are installed and linked\n") + +local good = h.build_fixture_pkg{ + name = "symok", ver = "1.0.0", repo = "core", + files = { + ["usr/lib/libsymok.so.1.0.0"] = "the library\n", + }, + symlinks = { + ["usr/lib/libsymok.so.1"] = "libsymok.so.1.0.0", -- relative (soname) + ["lib/ld-symok.so.1"] = "/usr/lib/libsymok.so.1", -- absolute (loader-style) + ["usr/share/symok-lib"] = "../lib", -- directory symlink + ["usr/bin/symok-dangling"] = "/nonexistent/on/purpose", -- dangles by design + }, +} + +h.check(install{ good } == "GL_TXN_OK", "install package carrying symlinks") + +local ver_dir = store .. "/core/symok/symok-1.0.0" +h.check(readlink(ver_dir .. "/usr/lib/libsymok.so.1") == "libsymok.so.1.0.0", + "relative symlink extracted verbatim into the store") +h.check(readlink(ver_dir .. "/lib/ld-symok.so.1") == "/usr/lib/libsymok.so.1", + "absolute symlink extracted verbatim (target means the RUNTIME path)") +h.check(readlink(ver_dir .. "/usr/share/symok-lib") == "../lib", + "directory symlink extracted verbatim") + +h.check(readlink(links .. "/lib/libsymok.so.1") == ver_dir .. "/usr/lib/libsymok.so.1", + "links tree points at the store symlink") +h.check(read_file(links .. "/lib/libsymok.so.1") == "the library\n", + "reading through links -> store symlink -> real file works") +h.check(is_symlink(links .. "/lib/ld-symok.so.1"), + "loader-style symlink outside usr/ is linked too (lib/ld-* -> links/lib/)") +h.check(is_symlink(links .. "/bin/symok-dangling"), + "a package's intentionally dangling symlink is linked") + +-- Another commit runs a full prune + relink; the dangling one must not +-- be mistaken for stale (its STORE entry still exists). +local other = h.build_fixture_pkg{ name = "unrelated", ver = "1.0.0", repo = "core" } +h.check(install{ other } == "GL_TXN_OK", "unrelated second transaction") +h.check(is_symlink(links .. "/bin/symok-dangling"), + "dangling package symlink survives the next commit's prune") +h.check(read_file(links .. "/lib/libsymok.so.1") == "the library\n", + "soname link still resolves after the next commit") + +-- --------------------------------------------------------------------- +io.write("-- hostile archives are refused, victim untouched\n") + +local function fresh_victim(dir) + h.sh("rm -rf " .. h.quote(dir) .. " && mkdir -p " .. h.quote(dir)) +end + +-- A: symlink x -> victim, then a FILE x/pwn (no directory entry for x). +fresh_victim("/tmp/victimA") +local evilA = h.build_fixture_pkg{ + name = "evila", ver = "1.0.0", repo = "core", + symlinks = { ["x"] = "/tmp/victimA" }, + append = { { files = { ["x/pwn"] = "owned\n" } } }, +} +h.check(install{ evilA } ~= "GL_TXN_OK", "A: symlink then file-through-it is refused") +h.check(not h.exists("/tmp/victimA/pwn"), "A: nothing written through the symlink") + +-- B: symlink x -> victim, then a SYMLINK x/evil. Both are deferred, so +-- this exercises the parent-is-a-symlink check on the deferred pass. +fresh_victim("/tmp/victimB") +local evilB = h.build_fixture_pkg{ + name = "evilb", ver = "1.0.0", repo = "core", + append = { + { symlinks = { ["x"] = "/tmp/victimB" } }, + { symlinks = { ["x/evil"] = "whatever" } }, + }, +} +h.check(install{ evilB } ~= "GL_TXN_OK", "B: symlink then symlink-through-it is refused") +h.check(not is_symlink("/tmp/victimB/evil") and not h.exists("/tmp/victimB/evil"), + "B: nothing created through the symlink") + +-- C: a symlink and a directory at the same path. +local evilC = h.build_fixture_pkg{ + name = "evilc", ver = "1.0.0", repo = "core", + files = { ["usr/share/both/f"] = "x\n" }, + append = { { symlinks = { ["usr/share/both"] = "/tmp" } } }, +} +h.check(install{ evilC } ~= "GL_TXN_OK", "C: symlink colliding with a directory is refused") + +h.check(not h.exists(store .. "/core/evila") and not h.exists(store .. "/core/evilb") + and not h.exists(store .. "/core/evilc"), + "refused packages left nothing in the live store") + +-- A refused package must not leave a half-extracted version dir behind: +-- in a LIVE context (no stage to throw away) that used to make every +-- later attempt report GL_INSTALL_ERR_ALREADY_INSTALLED. +local live = glacier.new_context() +glacier.lib.gl_init_live_context(live, glacier.SCOPE_USR, uid) +local r1 = glacier.lib.gl_install_pkg(live, evilA) +local r2 = glacier.lib.gl_install_pkg(live, evilA) +h.check(glacier.install_name(r1) == "GL_INSTALL_ERR_EXTRACT" + and glacier.install_name(r2) == "GL_INSTALL_ERR_EXTRACT", + "live context: refused twice for the same reason, not 'already installed' the 2nd time (" + .. glacier.install_name(r2) .. ")") +h.check(not h.exists(store .. "/core/evila/evila-1.0.0"), + "live context: no half-extracted version dir left in the store") + +-- --------------------------------------------------------------------- +io.write("-- linking never descends through another package's symlink\n") + +local pkgA = h.build_fixture_pkg{ + name = "dira", ver = "1.0.0", repo = "core", + files = { ["usr/lib/a.so"] = "a\n" }, + symlinks = { ["usr/lib64"] = "lib" }, +} +local pkgB = h.build_fixture_pkg{ + name = "dirb", ver = "1.0.0", repo = "core", + files = { ["usr/lib64/b.so"] = "b\n" }, +} +-- Since ROADMAP 2.6 the pair is a file collision (A ships lib64 as a +-- symlink, B as a directory) and is refused before anything is linked. +h.check(install{ pkgA, pkgB } == "GL_TXN_ERR_DEPS", + "A (lib64 -> lib) and B (lib64/b.so) together: refused as a collision") +h.check(install{ pkgA } == "GL_TXN_OK", "A alone installs") + +-- The link pass's own defence still matters for a store that got that +-- way without the check (one from before it, say): put B into the live +-- store by hand and relink. +local b_dir = store .. "/core/dirb/dirb-1.0.0" +h.sh("mkdir -p " .. h.quote(b_dir) .. " && tar xzf " .. h.quote(pkgB) .. + " --strip-components=2 -C " .. h.quote(b_dir) .. " dirb-1.0.0/files") +local relive = glacier.new_context() +glacier.lib.gl_init_live_context(relive, glacier.SCOPE_USR, uid) +glacier.lib.gl_relink_store(relive) +local a_store_lib = store .. "/core/dira/dira-1.0.0/usr/lib" +h.check(not h.exists(a_store_lib .. "/b.so") and not is_symlink(a_store_lib .. "/b.so"), + "B's file was NOT created inside A's store directory") +h.check(read_file(a_store_lib .. "/a.so") == "a\n", "A's own content untouched") + +-- --------------------------------------------------------------------- +io.write("-- system scope: a dangling package symlink that displaced a file stays put\n") + +-- Only /usr keeps links across commits (user/sys links trees are swapped +-- wholesale), so this is where a wrong prune is visible: pruning a +-- dangling-by-design link would also restore the original it displaced, +-- and the relink would then be refused by that original. +local victim = "/usr/bin/glacier-fixture-dangle" +h.sh("printf 'original\\n' > " .. victim) +h.check(tonumber(glacier.lib.gl_init_sys(false)) == 0, "gl_init_sys") + +local function sys_install(pkgs, overwrite) + local ctx = glacier.new_context() + local st = glacier.lib.gl_init_stage_context(ctx, glacier.SCOPE_SYS, 0) + if tonumber(st) ~= 0 then return "stage:" .. glacier.txn_name(st) end + ctx.overwrite = overwrite and 1 or 0 + for _, p in ipairs(pkgs) do + local r = glacier.lib.gl_install_pkg(ctx, p) + if tonumber(r) ~= 0 then + glacier.lib.gl_abort_transaction(ctx) + return glacier.install_name(r) + end + end + local c = glacier.lib.gl_commit_transaction(ctx) + if tonumber(c) ~= 0 then glacier.lib.gl_abort_transaction(ctx) end + return glacier.txn_name(c) +end + +local dangler = h.build_fixture_pkg{ + name = "dangler", ver = "1.0.0", repo = "base", + symlinks = { ["usr/bin/glacier-fixture-dangle"] = "/nonexistent/on/purpose" }, +} +h.check(sys_install({ dangler }, true) == "GL_TXN_OK", "install base pkg with -O over an existing file") +h.check(is_symlink(victim), "dangling package symlink displaced the original") + +local filler = h.build_fixture_pkg{ name = "sysfiller", ver = "1.0.0", repo = "extra" } +h.check(sys_install({ filler }, false) == "GL_TXN_OK", "unrelated system transaction") +h.check(is_symlink(victim), + "after the next commit it is still the package's symlink (not pruned + original restored)") + +h.sh("rm -f " .. victim) + +h.summary() diff --git a/tests/test_relink_symlinks.lua b/tests/test_relink_symlinks.lua new file mode 100644 index 0000000..4c823ff --- /dev/null +++ b/tests/test_relink_symlinks.lua @@ -0,0 +1,69 @@ +-- test_relink_symlinks.lua +-- +-- This is the regression test for the symlink-staleness bug: gl_link_pkg +-- used to run during a staged gl_install_pkg, embedding ctx->store_path +-- (the STAGE path) as the symlink target — which goes stale the instant +-- gl_commit_transaction renames the store into its live location. +-- +-- The fix is two-part: +-- 1. gl_install_pkg only calls gl_link_pkg for a GL_CTX_LIVE context. +-- 2. gl_commit_transaction calls gl_relink_store(&live_ctx) after +-- promotion, regenerating the links tree from the (now real, +-- final) live store paths. +-- +-- This test checks the raw (non-canonicalized) symlink target text +-- directly, since that's exactly what the original bug got wrong. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +h.reset_glacier_root() + +local uid = 1000 +local pkg_name = "relinktest" +io.write("== test_relink_symlinks (uid " .. uid .. ") ==\n") + +glacier.lib.gl_init_user(uid, false) + +local stage = glacier.new_context() +local st = glacier.lib.gl_init_stage_context(stage, glacier.SCOPE_USR, uid) +if not h.check(tonumber(st) == 0, "gl_init_stage_context: " .. glacier.txn_name(st)) then + h.summary() +end + +local pkgpath = h.build_fixture_pkg{ name = pkg_name, ver = "1.0.0", repo = "core" } + +local inst = glacier.lib.gl_install_pkg(stage, pkgpath) +h.check(tonumber(inst) == 0, + "gl_install_pkg (staged): " .. glacier.install_name(inst)) + +-- Before commit: the live links tree must not have been touched at all, +-- since gl_link_pkg should have been skipped entirely for this stage ctx. +h.check(not h.exists("/glacier/usr/" .. uid .. "/links/bin/" .. pkg_name), + "no premature symlink exists in the live links tree before commit") + +local commit = glacier.lib.gl_commit_transaction(stage) +h.check(tonumber(commit) == 0, "gl_commit_transaction: " .. glacier.txn_name(commit)) + +local link_path = "/glacier/usr/" .. uid .. "/links/bin/" .. pkg_name +h.check(h.exists(link_path), "symlink exists post-commit at " .. link_path) + +local rl = io.popen("readlink " .. h.quote(link_path)) +local raw_target = rl and rl:read("*l") +if rl then rl:close() end + +h.check(raw_target ~= nil and raw_target:find("/glacier/usr/" .. uid .. "/store/", 1, true) == 1, + "raw symlink target embeds the LIVE store path: " .. tostring(raw_target)) +h.check(raw_target ~= nil and not raw_target:find("/glacier/usr/" .. uid .. "/stage/", 1, true), + "raw symlink target does NOT embed the stage path") + +local f = io.open(link_path, "r") +h.check(f ~= nil, "symlink target is actually readable through the link") +if f then + local data = f:read("*a") + f:close() + h.check(data == "hello from " .. pkg_name .. "\n", + "file content read through the symlink matches the fixture payload") +end + +h.summary() diff --git a/tests/test_remove_live_pkg_via_stage.lua b/tests/test_remove_live_pkg_via_stage.lua new file mode 100644 index 0000000..6cd64fa --- /dev/null +++ b/tests/test_remove_live_pkg_via_stage.lua @@ -0,0 +1,66 @@ +-- test_remove_live_pkg_via_stage.lua +-- +-- CAVEAT: this exercises hardlink-seeding of the stage store from live +-- at gl_init_stage_context time — described in chat as a hardlink_tree() +-- helper called from gl_init_stage_context, but that code was only ever +-- given as a snippet, never confirmed applied to your actual +-- transaction.c. If it isn't wired up yet, this test will fail in an +-- informative way (see the two checks below) rather than silently pass. +-- +-- What this actually verifies: gl_commit_transaction promotes stage to +-- live via a *whole-directory* rename, not a merge. So if a staged +-- transaction only stages the one thing it's changing (here: removing +-- "removeme"), and the stage store isn't first seeded with everything +-- else that's live ("keepme"), then committing that transaction would +-- silently delete every live package the transaction never touched. +-- That's the failure mode this test is designed to catch. + +local glacier = require("glacier_ffi") +local h = require("test_helpers") + +h.reset_glacier_root() + +local uid = 1003 +io.write("== test_remove_live_pkg_via_stage (uid " .. uid .. ") ==\n") + +glacier.lib.gl_init_user(uid, false) + +local live = glacier.new_context() +glacier.lib.gl_init_live_context(live, glacier.SCOPE_USR, uid) + +local pkgA_path = h.build_fixture_pkg{ name = "keepme", ver = "1.0.0", repo = "core" } +local pkgB_path = h.build_fixture_pkg{ name = "removeme", ver = "1.0.0", repo = "core" } + +local instA = glacier.lib.gl_install_pkg(live, pkgA_path) +h.check(tonumber(instA) == 0, "install keepme live: " .. glacier.install_name(instA)) + +local instB = glacier.lib.gl_install_pkg(live, pkgB_path) +h.check(tonumber(instB) == 0, "install removeme live: " .. glacier.install_name(instB)) + +local stage = glacier.new_context() +local st = glacier.lib.gl_init_stage_context(stage, glacier.SCOPE_USR, uid) +if not h.check(tonumber(st) == 0, "stage context for removal txn: " .. glacier.txn_name(st)) then + h.summary() +end + +local rm = glacier.lib.gl_remove_pkg(stage, "removeme", "core") +h.check(tonumber(rm) == 0, + "gl_remove_pkg (staged, targeting a LIVE package): " .. glacier.remove_name(rm) .. + " -- GL_REMOVE_ERR_NOT_FOUND here almost certainly means the stage " .. + "store was never seeded from live; hardlink-seeding isn't wired up yet") + +local commit = glacier.lib.gl_commit_transaction(stage) +h.check(tonumber(commit) == 0, "commit: " .. glacier.txn_name(commit)) + +h.check(not h.exists("/glacier/usr/" .. uid .. "/store/core/removeme"), + "removeme is gone from the live store") + +-- This is the assertion that actually matters: keepme was never staged +-- or touched by this transaction at all, so its survival is the direct +-- signal of whether copy-on-write seeding happened. +h.check(h.exists("/glacier/usr/" .. uid .. "/store/core/keepme"), + "keepme (untouched by this transaction) SURVIVED the commit -- " .. + "if this fails, the whole-directory-swap wiped every live package " .. + "the transaction didn't explicitly stage") + +h.summary() diff --git a/tests/upgrade_alpine.sh b/tests/upgrade_alpine.sh new file mode 100644 index 0000000..44c4d09 --- /dev/null +++ b/tests/upgrade_alpine.sh @@ -0,0 +1,109 @@ +#!/bin/sh +# Replacing an installed version (ROADMAP 2.1): plain -l refuses, -lO +# replaces, KEEP_OLD (glacier.conf, no default) governs compressed +# backups of the replaced version. Runs INSIDE the Dockerfile.alpine_root +# image: +# +# ./run_docker.sh Dockerfile.alpine_root # builds glacier-alpine_root +# docker run --rm -v "$PWD/tests/upgrade_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +apk add --no-cache tar >/dev/null 2>&1 # GNU tar, for the hostile 3.0.0 below +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +has() { echo "$OUT" | grep -q "$1"; } +CONF=/etc/glacier/glacier.conf + +# A package "upg" at VERSION, with a file, a soname symlink and a manifest +# description that only the real (saved) manifest carries. +mkpkg() { # mkpkg VERSION -> /srv/upg-VERSION.gpkg (+ sidecar) + w=$(mktemp -d); d=$w/upg-$1 + mkdir -p $d/files/usr/bin $d/files/usr/lib + printf '#!/bin/sh\necho upg %s\n' "$1" > $d/files/usr/bin/upg; chmod 755 $d/files/usr/bin/upg + echo "lib $1" > $d/files/usr/lib/libupg.so.1.0; ln -s libupg.so.1.0 $d/files/usr/lib/libupg.so.1 + printf 'PKG_NAME = "upg";\nPKG_VER = "%s";\nPKG_DESC = "real manifest %s";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "extra";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' "$1" "$1" > $d/manifest.gpm.cfg + tar czf /srv/upg-$1.gpkg -C $w upg-$1 + printf 'sha256:%s\n' "$(sha256sum /srv/upg-$1.gpkg | cut -d' ' -f1)" > /srv/upg-$1.gpkg.sha256 + rm -rf $w +} +mkdir -p /srv; mkpkg 1.0.0; mkpkg 2.0.0 +# 3.0.0: valid manifest and hash, but an entry escaping files/ via "..": +# refused at extraction, i.e. AFTER the backup has been written and the +# old version removed from the stage. Exercises the abort path for real. +w=$(mktemp -d); mkdir -p $w/upg-3.0.0/files/usr/bin +printf 'PKG_NAME = "upg";\nPKG_VER = "3.0.0";\nPKG_DESC = "x";\nPKG_MAINT = "t@e";\nPKG_COPYRIGHT = "MIT";\nPKG_REPO = "extra";\nPKG_DEPS = ();\nPKG_CONFS = ();\n' > $w/upg-3.0.0/manifest.gpm.cfg +echo evil > $w/evil +tar cf $w/p.tar -C $w upg-3.0.0 +tar rf $w/p.tar -C $w --transform 's|^evil|upg-3.0.0/files/../../evil|' evil +gzip -c $w/p.tar > /srv/upg-3.0.0.gpkg +printf 'sha256:%s\n' "$(sha256sum /srv/upg-3.0.0.gpkg | cut -d' ' -f1)" > /srv/upg-3.0.0.gpkg.sha256 +rm -rf $w +S=/glacier/sys/store/extra/upg; B=/glacier/sys/backup/extra/upg +cd /app && ./syspkg -n >/dev/null +echo y | ./syspkg -l /srv/upg-1.0.0.gpkg >/dev/null 2>&1 +check "1.0.0 installed" test -d $S/upg-1.0.0 +check "manifest saved beside the installed files" test -f $S/upg-1.0.0/.glacier-manifest + +echo "=== plain -l of another version: refused, no hint, no prompt" +OUT=$(echo y | ./syspkg -l /srv/upg-2.0.0.gpkg 2>&1 | nocolor); echo "$OUT" +check "refused with the installed version named" has "extra::upg 1.0.0 is already installed." +check "nothing else said (no prompt, no -lO hint)" test "$(echo "$OUT" | wc -l)" -eq 1 +check "still 1.0.0" test -d $S/upg-1.0.0 -a ! -d $S/upg-2.0.0 + +echo "=== KEEP_OLD problems are refused before the prompt" +cp $CONF /tmp/conf.bak +rm $CONF +OUT=$(echo y | ./syspkg -lO /srv/upg-2.0.0.gpkg 2>&1 | nocolor); echo "$OUT" +check "no glacier.conf" has "Cannot read /etc/glacier/glacier.conf." +echo '// nothing here' > $CONF +OUT=$(echo y | ./syspkg -lO /srv/upg-2.0.0.gpkg 2>&1 | nocolor); echo "$OUT" +check "KEEP_OLD absent" has "KEEP_OLD is not set" +echo 'KEEP_OLD = -1;' > $CONF +OUT=$(echo y | ./syspkg -lO /srv/upg-2.0.0.gpkg 2>&1 | nocolor); echo "$OUT" +check "KEEP_OLD negative" has "must be a whole number" +check "none of those reached the prompt or changed anything" sh -c "! echo '$OUT' | grep -q Proceed && test -d $S/upg-1.0.0" +OUT=$(echo y | ./syspkg -lO /srv/upg-1.0.0.gpkg 2>&1 | nocolor) +check "same-version reinstall doesn't need KEEP_OLD" has "Completed with no errors" +cp /tmp/conf.bak $CONF + +echo "=== -lO replaces, KEEP_OLD = 1 backs up" +OUT=$(echo y | ./syspkg -lO /srv/upg-2.0.0.gpkg 2>&1 | nocolor); echo "$OUT" +check "summary shows 1.0.0 -> 2.0.0" has "1.0.0 -> 2.0.0" +check "only 2.0.0 in the store" test -d $S/upg-2.0.0 -a ! -d $S/upg-1.0.0 +check "links point at 2.0.0" sh -c "readlink /glacier/sys/links/bin/upg | grep -q upg-2.0.0" +check "backup + sidecar written" test -f $B/upg-1.0.0.gpkg -a -f $B/upg-1.0.0.gpkg.sha256 +check "sidecar matches" sh -c "test -f $B/upg-1.0.0.gpkg && test \"\$(cut -c8- $B/upg-1.0.0.gpkg.sha256)\" = \"\$(sha256sum $B/upg-1.0.0.gpkg | cut -d' ' -f1)\"" +check "backup carries the REAL manifest" sh -c "tar xzOf $B/upg-1.0.0.gpkg upg-1.0.0/manifest.gpm.cfg | grep -q 'real manifest 1.0.0'" +check "backup keeps the symlink" sh -c "tar tvzf $B/upg-1.0.0.gpkg | grep -q 'libupg.so.1 -> libupg.so.1.0'" +check "backup has no glacier markers" sh -c "tar tzf $B/upg-1.0.0.gpkg >/tmp/l && ! grep -q glacier- /tmp/l" +check "no .part left" sh -c "test -d $B && ! ls $B | grep -q part" + +echo "=== a backup is an installable package (restore path)" +OUT=$(echo y | ./syspkg -lO $B/upg-1.0.0.gpkg 2>&1 | nocolor); echo "$OUT" | tail -2 +check "restored 1.0.0 from its backup" test -d $S/upg-1.0.0 -a ! -d $S/upg-2.0.0 +check "KEEP_OLD = 1: only the newest backup kept (2.0.0)" test -f $B/upg-2.0.0.gpkg -a ! -f $B/upg-1.0.0.gpkg + +echo "=== a failed replacement leaves no backup and changes nothing" +rm -f $B/* +OUT=$(echo y | ./syspkg -lO /srv/upg-3.0.0.gpkg 2>&1 | nocolor); echo "$OUT" | tail -2 +check "it got past the backup step (extraction refused)" has "Refusing unsafe archive entry" +check "still 1.0.0" test -d $S/upg-1.0.0 -a ! -d $S/upg-3.0.0 +check "no backup of 1.0.0 created by the failed attempt" test ! -f $B/upg-1.0.0.gpkg +check "no .part left" sh -c "test -d $B && ! ls $B | grep -q part" + +echo "=== KEEP_OLD = 0: replace without a backup" +rm -f $B/* +echo 'KEEP_OLD = 0;' > $CONF +echo y | ./syspkg -lO /srv/upg-2.0.0.gpkg >/dev/null 2>&1 +check "replaced" test -d $S/upg-2.0.0 +check "no backup of 1.0.0" test ! -f $B/upg-1.0.0.gpkg +cp /tmp/conf.bak $CONF + +echo "=== gpkg (user scope) does the same" +su glacier -c "doas /app/gstore -n" >/dev/null 2>&1 +chmod 644 /srv/*.gpkg /srv/*.sha256 +su glacier -c "cd /app && echo y | ./gpkg -l /srv/upg-1.0.0.gpkg" >/dev/null 2>&1 +OUT=$(su glacier -c "cd /app && echo y | ./gpkg -lO /srv/upg-2.0.0.gpkg" 2>&1 | nocolor); echo "$OUT" | tail -2 +check "user backup in the user's own dir" test -f /glacier/usr/1000/backup/extra/upg/upg-1.0.0.gpkg +check "owned by the user" test "$(stat -c %u /glacier/usr/1000/backup/extra/upg/upg-1.0.0.gpkg)" = 1000 + +echo; echo "FAILURES: $FAILS"; [ $FAILS -eq 0 ] diff --git a/tests/user_layout_alpine.sh b/tests/user_layout_alpine.sh new file mode 100644 index 0000000..d6eba23 --- /dev/null +++ b/tests/user_layout_alpine.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# Per-user layout + doas self-service tests: /glacier/usr/ ownership, +# `doas gstore -n` for yourself only, root `gstore -n UID`, refusal of +# squatted / loosened / symlinked bases, and syspkg alongside. Runs INSIDE +# the Dockerfile.alpine_root image (needs its glacier user + doas rule): +# +# ./run_docker.sh Dockerfile.alpine_root # builds glacier-alpine_root +# docker run --rm -v "$PWD/tests/user_layout_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +cd /app +# Only the pinned rule: the image also lets glacier run anything as root. +echo "permit nopass :wheel as root cmd /app/gstore args -n" > /etc/doas.conf +U() { su glacier -c "cd /app && $1" 2>&1 | sed 's/\x1b\[[0-9;]*m//g'; } +R() { sh -c "$1" 2>&1 | sed 's/\x1b\[[0-9;]*m//g'; } +hr() { echo; echo "=== $*"; } + +hr "1. user before setup: gpkg points at doas gstore -n" +U "echo y | ./gpkg -l kilo-0.0.1.gpkg" +hr "2. user without doas: refused with hint" +U "./gstore -n" +hr "3. user via doas: creates OWN dir (uid derived)" +U "doas /app/gstore -n" +ls -la /glacier /glacier/usr /glacier/usr/1000 +hr "4. user via doas naming another uid: doas refuses" +U "doas /app/gstore -n 1001" +hr "5. user via doas again: already exists" +U "doas /app/gstore -n" +hr "6. user installs + removes (no root involved)" +U "echo y | ./gpkg -l kilo-0.0.1.gpkg" +ls -la /glacier/usr/1000/links/bin/ +U ". /etc/profile.d/glacier.sh; command -v kilo" +U "echo y | ./gpkg -x kilo" | tail -2 +ls -A /glacier/usr/1000 +hr "7. root creates for another uid; that user can then install" +adduser -D -u 1001 alice >/dev/null +R "/app/gstore -n 1001" +su alice -c "cd /app && echo y | ./gpkg -l kilo-0.0.1.gpkg" 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | tail -1 +hr "8. users can't see into each other's dirs" +U "ls /glacier/usr/1001" +hr "9. squatted base (wrong owner) is refused" +chown -R 1000 /glacier/usr/1001 +su alice -c "cd /app && echo y | ./gpkg -l kilo-0.0.1.gpkg" 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | tail -1 +hr "10. root cleans it up and re-creates" +R "/app/gstore -x 1001 && /app/gstore -n 1001" | tail -2 +hr "11. loosened /glacier/usr is refused by gpkg and gstore" +chmod 777 /glacier/usr +U "echo y | ./gpkg -l kilo-0.0.1.gpkg" | tail -1 +adduser -D -u 1002 bob >/dev/null +R "/app/gstore -n 1002" +chmod 755 /glacier/usr +hr "12. symlink in place of a base: delete refuses to follow it" +mkdir -p /tmp/victim && touch /tmp/victim/keep && ln -s /tmp/victim /glacier/usr/1003 +R "/app/gstore -x 1003"; ls /tmp/victim +rm /glacier/usr/1003 +hr "13. syspkg still works; lock now in /glacier/sys" +R "./syspkg -n && echo y | ./syspkg -l kilo-0.0.1.gpkg" | tail -1 +ls -A /glacier/sys; ls -A /glacier/usr +hr "14. help" +R "./gstore -h" | sed -n 2p +R "./gstore -h" | grep -- "--new" diff --git a/tests/user_layout_alpine.sh.old b/tests/user_layout_alpine.sh.old new file mode 100644 index 0000000..d13526a --- /dev/null +++ b/tests/user_layout_alpine.sh.old @@ -0,0 +1,57 @@ +#!/bin/sh +# Per-user layout + doas self-service tests: /glacier/usr/ ownership, +# `doas gstore -n` for yourself only, root `gstore -n UID`, refusal of +# squatted / loosened / symlinked bases, and syspkg alongside. Runs INSIDE +# the Dockerfile.alpine_root image (needs its glacier user + doas rule): +# +# ./run_docker.sh Dockerfile.alpine_root # builds glacier-alpine_root +# docker run --rm -v "$PWD/tests/user_layout_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +cd /app +U() { su glacier -c "cd /app && $1" 2>&1 | sed 's/\x1b\[[0-9;]*m//g'; } +R() { sh -c "$1" 2>&1 | sed 's/\x1b\[[0-9;]*m//g'; } +hr() { echo; echo "=== $*"; } + +hr "1. user before setup: gpkg points at doas gstore -n" +U "echo y | ./gpkg -l kilo-0.0.1.gpkg" +hr "2. user without doas: refused with hint" +U "./gstore -n" +hr "3. user via doas: creates OWN dir (uid derived)" +U "doas /app/gstore -n" +ls -la /glacier /glacier/usr /glacier/usr/1000 +hr "4. user via doas naming another uid: doas refuses" +U "doas /app/gstore -n 1001" +hr "5. user via doas again: already exists" +U "doas /app/gstore -n" +hr "6. user installs + removes (no root involved)" +U "echo y | ./gpkg -l kilo-0.0.1.gpkg" +ls -la /glacier/usr/1000/links/bin/ +U ". /etc/profile.d/glacier.sh; command -v kilo" +U "echo y | ./gpkg -x kilo" | tail -2 +ls -A /glacier/usr/1000 +hr "7. root creates for another uid; that user can then install" +adduser -D -u 1001 alice >/dev/null +R "/app/gstore -n 1001" +su alice -c "cd /app && echo y | ./gpkg -l kilo-0.0.1.gpkg" 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | tail -1 +hr "8. users can't see into each other's dirs" +U "ls /glacier/usr/1001" +hr "9. squatted base (wrong owner) is refused" +chown -R 1000 /glacier/usr/1001 +su alice -c "cd /app && echo y | ./gpkg -l kilo-0.0.1.gpkg" 2>&1 | sed 's/\x1b\[[0-9;]*m//g' | tail -1 +hr "10. root cleans it up and re-creates" +R "/app/gstore -x 1001 && /app/gstore -n 1001" | tail -2 +hr "11. loosened /glacier/usr is refused by gpkg and gstore" +chmod 777 /glacier/usr +U "echo y | ./gpkg -l kilo-0.0.1.gpkg" | tail -1 +adduser -D -u 1002 bob >/dev/null +R "/app/gstore -n 1002" +chmod 755 /glacier/usr +hr "12. symlink in place of a base: delete refuses to follow it" +mkdir -p /tmp/victim && touch /tmp/victim/keep && ln -s /tmp/victim /glacier/usr/1003 +R "/app/gstore -x 1003"; ls /tmp/victim +rm /glacier/usr/1003 +hr "13. syspkg still works; lock now in /glacier/sys" +R "./syspkg -n && echo y | ./syspkg -l kilo-0.0.1.gpkg" | tail -1 +ls -A /glacier/sys; ls -A /glacier/usr +hr "14. help" +R "./gstore -h" | sed -n 2p +R "./gstore -h" | grep -- "--new" diff --git a/tests/verify_alpine.sh b/tests/verify_alpine.sh new file mode 100644 index 0000000..8a7f220 --- /dev/null +++ b/tests/verify_alpine.sh @@ -0,0 +1,70 @@ +#!/bin/sh +# Install-time integrity verification (SECURITY_DESIGN.txt section 4): +# missing sidecar == mismatch == refused, for syspkg and gpkg alike; +# packages are verified and installed from a private copy, which is +# always cleaned up. Runs INSIDE the Dockerfile.alpine_root image: +# +# ./run_docker.sh Dockerfile.alpine_root # builds glacier-alpine_root +# docker run --rm -v "$PWD/tests/verify_alpine.sh:/t.sh:ro" glacier-alpine_root sh /t.sh +FAILS=0 +check() { d=$1; shift; if "$@"; then echo "PASS: $d"; else echo "FAIL: $d"; FAILS=$((FAILS+1)); fi; } +nocolor() { sed 's/\x1b\[[0-9;]*m//g'; } +sidecar() { printf 'sha256:%s\n' "$(sha256sum "$1" | cut -d' ' -f1)" > "$1.sha256"; gsign -S -s /root/glacier-test.sec -m "$1.sha256" >/dev/null; } +no_leftovers() { [ -z "$(ls -d /tmp/gpkg-verify.* 2>/dev/null)" ]; } + +W=/srv/pkgs; mkdir -p $W; cp /app/pkgs/*.gpkg /app/kilo-0.0.1.gpkg $W/ 2>/dev/null; chmod 755 /srv $W; chmod 644 $W/* +cd /app && ./syspkg -n >/dev/null + +echo "=== 1. no sidecar: refused before the prompt" +out=$(echo y | ./syspkg -l $W/kilo-0.0.1.gpkg 2>&1 | nocolor); echo "$out" +check "refused, says no sidecar" sh -c "echo '$out' | grep -q 'Refusing $W/kilo-0.0.1.gpkg: no sidecar'" +check "never reached the prompt" sh -c "! echo '$out' | grep -q Proceed" +check "nothing installed" test ! -e /glacier/sys/store/extra/kilo +check "no private copies left" no_leftovers + +echo "=== 2. valid sidecar: installs" +sidecar $W/kilo-0.0.1.gpkg +echo y | ./syspkg -l $W/kilo-0.0.1.gpkg 2>&1 | nocolor | tail -2 +check "installed" test -d /glacier/sys/store/extra/kilo +check "message names the ORIGINAL path" sh -c "echo y | ./syspkg -l $W/kilo-0.0.1.gpkg 2>&1 | grep -q 'staged from $W/kilo-0.0.1.gpkg'" +check "no private copies left" no_leftovers + +echo "=== 3. tampered package, stale sidecar: refused" +cp $W/musl-1.2.5.gpkg $W/musl-t.gpkg; sidecar $W/musl-t.gpkg; printf 'x' >> $W/musl-t.gpkg +out=$(echo y | ./syspkg -l $W/musl-t.gpkg 2>&1 | nocolor); echo "$out" +check "refused as hash mismatch" sh -c "echo '$out' | grep -q 'hash mismatch'" +check "musl not installed" test ! -e /glacier/sys/store/base/musl + +echo "=== 4. malformed sidecar: refused" +cp $W/sbase-0.0.1.gpkg $W/sbase-m.gpkg; sha256sum $W/sbase-m.gpkg > $W/sbase-m.gpkg.sha256 # coreutils format, not sha256: +out=$(echo y | ./syspkg -l $W/sbase-m.gpkg 2>&1 | nocolor); echo "$out" +check "refused as malformed" sh -c "echo '$out' | grep -q 'malformed sidecar'" + +echo "=== 5. one bad package refuses the whole batch" +sidecar $W/sbase-0.0.1.gpkg +out=$(echo y | ./syspkg -l $W/sbase-0.0.1.gpkg $W/musl-1.2.5.gpkg 2>&1 | nocolor); echo "$out" +check "batch refused (musl has no sidecar)" sh -c "echo '$out' | grep -q 'Refusing $W/musl-1.2.5.gpkg'" +check "sbase NOT installed either" test ! -e /glacier/sys/store/core/sbase + +echo "=== 6. declining the prompt still cleans up" +echo n | ./syspkg -l $W/sbase-0.0.1.gpkg >/dev/null 2>&1 +check "no private copies left after 'n'" no_leftovers + +echo "=== 7. swapping the original after verification changes nothing" +# Install reads only the private copy: corrupt the original while syspkg +# waits at the prompt, then answer y. The verified bytes get installed. +sidecar $W/musl-1.2.5.gpkg +( sleep 1; printf 'garbage' > $W/musl-1.2.5.gpkg; sleep 1; echo y ) | ./syspkg -l $W/musl-1.2.5.gpkg 2>&1 | nocolor | tail -1 +check "musl installed from the verified copy" test -e /glacier/sys/store/base/musl/musl-1.2.5/usr/lib/libc.so + +echo "=== 8. gpkg (user scope) enforces the same" +cp /app/kilo-0.0.1.gpkg /srv/userkilo.gpkg; chmod 644 /srv/userkilo.gpkg +su glacier -c "doas /app/gstore -n" >/dev/null 2>&1 +out=$(su glacier -c "cd /app && echo y | ./gpkg -l /srv/userkilo.gpkg" 2>&1 | nocolor); echo "$out" +check "gpkg refuses without sidecar" sh -c "echo '$out' | grep -q 'no sidecar'" +sidecar /srv/userkilo.gpkg +su glacier -c "cd /app && echo y | ./gpkg -l /srv/userkilo.gpkg" 2>&1 | nocolor | tail -1 +check "gpkg installs with sidecar" test -e /glacier/usr/1000/store/extra/kilo -o -n "$(su glacier -c 'ls /glacier/usr/1000/store/extra 2>/dev/null')" +check "no private copies left" no_leftovers + +echo; echo "FAILURES: $FAILS"; [ $FAILS -eq 0 ] diff --git a/tree/glacier/index/1000/12-05-25@1400 b/tree/glacier/index/1000/12-05-25@1400 new file mode 100644 index 0000000..5239a4e --- /dev/null +++ b/tree/glacier/index/1000/12-05-25@1400 @@ -0,0 +1,16 @@ +# +# Glacier Package Index +# + +uid = 1000 +listed = 9 + +base::musl-1.2.5 +base::systemd-258.2 +base::busybox-1.36.1 +base::linux-6.17.9-everest +base::gcc-15.2 +base::binutils-2.45 +base::vim-9.1.1577 +world::foo-1.0.0 +galaxy::bar-2.5.3 diff --git a/tree/glacier/index/1000/current b/tree/glacier/index/1000/current new file mode 120000 index 0000000..2cd19e8 --- /dev/null +++ b/tree/glacier/index/1000/current @@ -0,0 +1 @@ +12-05-25@1400 \ No newline at end of file diff --git a/tree/glacier/store/1000/base/binutils-2.45 b/tree/glacier/store/1000/base/binutils-2.45 new file mode 100644 index 0000000..e69de29 diff --git a/tree/glacier/store/1000/base/busybox-1.36.1 b/tree/glacier/store/1000/base/busybox-1.36.1 new file mode 100644 index 0000000..e69de29 diff --git a/tree/glacier/store/1000/base/gcc-15.2 b/tree/glacier/store/1000/base/gcc-15.2 new file mode 100644 index 0000000..e69de29 diff --git a/tree/glacier/store/1000/base/linux-6.17.9-everest b/tree/glacier/store/1000/base/linux-6.17.9-everest new file mode 100644 index 0000000..e69de29 diff --git a/tree/glacier/store/1000/base/musl-1.2.5 b/tree/glacier/store/1000/base/musl-1.2.5 new file mode 100644 index 0000000..e69de29 diff --git a/tree/glacier/store/1000/base/systemd-258.2 b/tree/glacier/store/1000/base/systemd-258.2 new file mode 100644 index 0000000..e69de29 diff --git a/tree/glacier/store/1000/base/vim-9.1.1577 b/tree/glacier/store/1000/base/vim-9.1.1577 new file mode 100644 index 0000000..e69de29 diff --git a/tree/glacier/store/1000/galaxy/bar-2.5.3 b/tree/glacier/store/1000/galaxy/bar-2.5.3 new file mode 100644 index 0000000..e69de29 diff --git a/tree/glacier/store/1000/world/foo-1.0.0 b/tree/glacier/store/1000/world/foo-1.0.0 new file mode 100644 index 0000000..e69de29