glacier-ng 4.0.0

This commit is contained in:
lw-everestlinux committed 2026-10-29 09:15:34 -04:00
commit 0cf4829fa5
159 files changed
+33717

No files matched your search

+160
View File
@@ -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"
+131
View File
@@ -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"
+155
View File
@@ -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"
+17
View File
@@ -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
+24
View File
@@ -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
+424
View File
@@ -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. <project_root>/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
+367
View File
@@ -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. <project_root>/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
+368
View File
@@ -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. <project_root>/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
+423
View File
@@ -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. <project_root>/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
+695
View File
@@ -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 (<base>, 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
-- ---------------------------------------------------------------------
-- <base>/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 <base>/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 <base>/build/layers by the
-- builder: NAME-VER-<first 8 of its hash>.
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 <base>/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). <base>/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
-- <base>/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
+593
View File
@@ -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 (<base>, 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
-- ---------------------------------------------------------------------
-- <base>/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 <base>/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 <base>/build/layers by the
-- builder: NAME-VER-<first 8 of its hash>.
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 <base>/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
+602
View File
@@ -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 (<base>, 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
-- ---------------------------------------------------------------------
-- <base>/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 <base>/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 <base>/build/layers by the
-- builder: NAME-VER-<first 8 of its hash>.
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 <base>/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
+685
View File
@@ -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 (<base>, 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
-- ---------------------------------------------------------------------
-- <base>/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 <base>/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 <base>/build/layers by the
-- builder: NAME-VER-<first 8 of its hash>.
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 <base>/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). <base>/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
-- <base>/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
+686
View File
@@ -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 (<base>, 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
-- ---------------------------------------------------------------------
-- <base>/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 <base>/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 <base>/build/layers by the
-- builder: NAME-VER-<first 8 of its hash>.
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 <base>/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). <base>/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
-- <base>/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
+694
View File
@@ -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 (<base>, 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
-- ---------------------------------------------------------------------
-- <base>/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 <base>/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 <base>/build/layers by the
-- builder: NAME-VER-<first 8 of its hash>.
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 <base>/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). <base>/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
-- <base>/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
+1745
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff