glacier-ng 4.0.0
This commit is contained in:
commit
0cf4829fa5
159 files changed
+33717
No files matched your search
Executable
+791
@@ -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] <SOURCE_DIR>\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] <SOURCE_DIR>"
|
||||
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:
|
||||
# <pkgname>-<ver>/
|
||||
# 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 <pkgname>-<ver>/
|
||||
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
|
||||
Executable
+642
@@ -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)
|
||||
@@ -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/<uid> 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
|
||||
Executable
+354
@@ -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/<uid>, 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
|
||||
Executable
+385
@@ -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
|
||||
Reference in new issue
Block a user