Compare commits

..
10 Commits
Author SHA1 Message Date
lw-everestlinux 6b378aee29 Merge pull request 'libglacier-ng 4.0.0-rc' (#2) from dev into main
Reviewed-on: #2
2026-10-29 09:13:56 -04:00
lw-everestlinux fb02622b5b staging 4.0.0-rc 2026-10-29 09:10:02 -04:00
lw-everestlinux ae54f74070 10/14 2026-10-14 00:50:56 -04:00
lw-everestlinux ee4bcc3b77 10/4 2026-10-05 14:47:58 -04:00
lw-everestlinuxandClaude Sonnet 5 c432274936 Refuse base-repo installs under GL_SCOPE_USR at the library level
gl_install_pkg now returns GL_INSTALL_ERR_SCOPE for
scope == GL_SCOPE_USR && repo == "base", checked immediately after
manifest parse and before any store path construction or filesystem
mutation. Per SECURITY_DESIGN.txt section 8: enforced in the library
rather than a CLI, since the split-.so architecture lets third-party
tools call gl_install_pkg directly.

Also drops src/istoreutils.c.rej, .c.back, .h.back — stale leftovers
from the uid -> gl_context_t migration patch; that migration is fully
present in the current tree, so these were dead weight.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-18 11:20:59 -04:00
lw-everestlinux 7b22e3746a 7/19 2026-07-19 17:49:23 -04:00
lw-everestlinux 0d8859b063 Working progress as of May 18th 2026-05-18 18:43:30 -04:00
lw-everestlinux 6819fe7c69 3/18: Functional package installation backend 2026-03-18 09:57:09 -04:00
lw-everestlinux e79c96a987 Working as of 12/11 2025-12-11 14:50:41 -05:00
lw-everestlinux e591b71143 10/29 added basic package processing 2025-10-29 09:01:29 -04:00
56 changed files with 14798 additions and 418 deletions

No files matched your search

+16
View File
@@ -0,0 +1,16 @@
BasedOnStyle: LLVM
BreakBeforeBraces: Custom
BraceWrapping:
AfterFunction: true
AfterControlStatement: false
AfterEnum: true
AfterStruct: true
AfterUnion: true
AfterClass: true
AlwaysBreakAfterReturnType: All
IndentWidth: 8
TabWidth: 8
UseTab: Always
+2
View File
@@ -0,0 +1,2 @@
# Build outputs (make; make libglacier-ng)
/build/
+1329
View File
File diff suppressed because it is too large. Load diff
+94 -8
View File
@@ -1,8 +1,31 @@
include config.mk include config.mk
all: prepare log log_test rt make_conf .PHONY: all prepare log log_test pkg transaction istoreutils install clean static libglacier.a install_static libglacier-ng sha256 gsha256sum libglacier_verify gsign grepo gsandbox
all: prepare log log_test pkg transaction istoreutils sha256 libglacier_verify gsha256sum gsign grepo gsandbox
@echo "libglacier-ng has finished building" @echo "libglacier-ng has finished building"
static: prepare log_static pkg_static istoreutils_static libglacier.a
log_static:
$(CC) $(CFLAGS) -c src/log.c -o build/lib/tmp/log.o
pkg_static:
$(CC) $(CFLAGS) -c src/pkg.c -o build/lib/tmp/pkg.o
istoreutils_static: pkg_static
$(CC) $(CFLAGS) -c src/istoreutils.c -o build/lib/tmp/istoreutils.o
$(CC) $(CFLAGS) -c src/deps.c -o build/lib/tmp/deps.o
$(CC) $(CFLAGS) -c src/recipe.c -o build/lib/tmp/recipe.o
libglacier.a:
ar rcs build/lib/libglacier.a \
build/lib/tmp/log.o \
build/lib/tmp/pkg.o \
build/lib/tmp/istoreutils.o \
build/lib/tmp/deps.o \
build/lib/tmp/recipe.o
prepare: prepare:
mkdir -p build mkdir -p build
mkdir -p build/lib mkdir -p build/lib
@@ -10,22 +33,85 @@ prepare:
mkdir -p build/lib/tmp mkdir -p build/lib/tmp
mkdir -p build/lib/shared mkdir -p build/lib/shared
mkdir -p build/include/glacier mkdir -p build/include/glacier
mkdir -p build/bin
log: log:
$(CC) $(CFLAGS) src/log.c -c -o build/lib/tmp/log.o $(CC) $(CFLAGS) src/log.c -c -o build/lib/tmp/log.o
cp src/log.h build/include/glacier/log.h cp src/log.h build/include/glacier/log.h
log_test: log_test:
$(CC) $(CFLAGS) -shared -fPIC src/log.c -o build/lib/shared/lg_log.so $(CC) $(CFLAGS) -shared -fPIC src/log.c -o build/lib/shared/libglacier_log.so
rt: sha256:
$(CC) $(CFLAGS) src/runtime.c -c -o build/lib/tmp/runtime.o $(CC) $(CFLAGS) src/sha256.c -c -o build/lib/tmp/sha256.o
make_conf: # Monocypher, vendored unmodified (src/monocypher/README): Ed25519 for
$(CC) $(CFLAGS) src/make_conf.c -c -o build/lib/tmp/make_conf.o # sign.c.
MONOCYPHER = src/monocypher/monocypher.c src/monocypher/monocypher-ed25519.c
install_test_dir: libglacier_verify:
install build/lib/shared/lg_log.so $(TEST_DIR) $(CC) $(CFLAGS) -shared -fPIC src/sha256.c src/sign.c $(MONOCYPHER) \
-o build/lib/shared/libglacier_verify.so
gsha256sum: prepare
$(CC) $(CFLAGS) src/gsha256sum.c src/sha256.c -o build/bin/gsha256sum
gsign: prepare
$(CC) $(CFLAGS) src/gsign.c src/sign.c src/log.c $(MONOCYPHER) -o build/bin/gsign
# grepo reads packages (manifest, hash) and signs the index: built
# from source like gsign, so it needs no rpath to the shared objects.
grepo: prepare
$(CC) $(CFLAGS) src/grepo.c src/sign.c src/sha256.c src/log.c src/pkg.c \
src/istoreutils.c src/deps.c src/recipe.c src/transaction.c $(MONOCYPHER) \
-larchive -lconfig -o build/bin/grepo
# gsandbox runs builds (BUILD_DESIGN.txt section 6). Not a maintainer
# tool: gpkg/syspkg run it, so it is installed beside the libraries.
gsandbox: prepare
$(CC) $(CFLAGS) src/gsandbox.c src/log.c src/pkg.c src/istoreutils.c \
src/deps.c src/recipe.c src/transaction.c \
-larchive -lconfig -o build/bin/gsandbox
transaction: log istoreutils
$(CC) $(CFLAGS) -shared -fPIC src/transaction.c \
-Lbuild/lib/shared -lglacier_istoreutils -lglacier_log \
-Wl,-rpath,'$$ORIGIN' \
-o build/lib/shared/libglacier_transaction.so
istoreutils: pkg
$(CC) $(CFLAGS) -shared -fPIC src/istoreutils.c src/deps.c src/recipe.c \
-Lbuild/lib/shared -lglacier_log -lglacier_pkg -larchive \
-Wl,-rpath,'$$ORIGIN' \
-o build/lib/shared/libglacier_istoreutils.so
pkg:
$(CC) $(CFLAGS) -shared -fPIC src/pkg.c \
-Lbuild/lib/shared -lglacier_log -lconfig \
-Wl,-rpath,'$$ORIGIN' \
-o build/lib/shared/libglacier_pkg.so
libglacier-ng: prepare
$(CC) $(CFLAGS) -shared -fPIC \
src/log.c src/pkg.c src/transaction.c src/istoreutils.c src/deps.c \
src/recipe.c -larchive -lconfig \
-o build/lib/shared/libglacier-ng.so
install:
mkdir -p $(PREFIX)/lib/glacier/
install build/lib/shared/libglacier_log.so $(PREFIX)/lib/glacier/ -m 755
install build/lib/shared/libglacier_istoreutils.so $(PREFIX)/lib/glacier/ -m 755
install build/lib/shared/libglacier_transaction.so $(PREFIX)/lib/glacier/ -m 755
install build/lib/shared/libglacier_pkg.so $(PREFIX)/lib/glacier -m 755
install build/lib/shared/libglacier_verify.so $(PREFIX)/lib/glacier -m 755
install build/bin/gsha256sum $(PREFIX)/bin/ -m 755
install build/bin/gsign $(PREFIX)/bin/ -m 755
install build/bin/grepo $(PREFIX)/bin/ -m 755
install build/bin/gsandbox $(PREFIX)/lib/glacier/ -m 755
install_static:
mkdir -p $(PREFIX)/lib/glacier
install build/lib/libglacier.a $(PREFIX)/lib/glacier/ -m 644
clean: clean:
rm -rf build rm -rf build
+51
View File
@@ -0,0 +1,51 @@
+ libglacier-ng
Backend APIs for the Glacier package manager
+ Modularity
Libglacier-ng is, by default, incredibly modular. The default featureset is very
minimal, but modules are available for installtion. These modules allow for features
such as HTML reports, remote package deployment, and more. Keep in mind that the
more features you have installed, the larger the attack surface is. The default
featureset should be sufficient for 99% of users.
+ Installation
Libglacier-ng is provided by default as multiple shared object files (.so).
Static compilation at this time is not possible because glacier-ng, which is primarily
written in Lua, requires shared objects.
Libglacier-ng depends on the following libraries:
~ libconfig
Once these dependencies are installed, clone this repository:
+---------------------------------------------------------------------+
| $ git clone https://git.everestlinux.org/EverestLinux/libglacier-ng |
+---------------------------------------------------------------------+
Enter the directory and make any desired modifications to config.mk:
+----------------------------------------------+
| $ cd libglacier |
| $ EDITOR="/bin/vim" # or your desired editor |
| $ ${EDITOR} config.mk |
+----------------------------------------------+
Build and install the library:
+-----------------+
| $ make $(nproc) |
| # make install |
+-----------------+
+ Documentation
Online documentation can be accessed at https://www.everestlinux.org/docs/libglacier
Offline documentationn can be accessed with the following command:
+--------------------+
| $ man 3 libglacier |
+--------------------+
-40
View File
@@ -1,40 +0,0 @@
#ifndef LOG_H_
#define LOG_H_
#define _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#define _XOPEN_SOURCE 700
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <syslog.h>
#include <time.h>
#include "color.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef enum
{
LG_INFO,
LG_WARN,
LG_ERR,
LG_SUCCESS
}
loglevel_t;
int supports_utf8(void);
const char *p2s(int priority);
void lg_printf(loglevel_t loglevel, const char *fmt, ...);
void lg_syslog(int priority, const char *fmt, ...);
void lg_log(bool use_syslog, FILE *logfile, int priority, const char *fmt, ...);
#ifdef __cplusplus
}
#endif
#endif /* LOG_H_ */
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+3 -2
View File
@@ -2,6 +2,7 @@
# config.mk # config.mk
# #
CFLAGS = -std=c11 -pedantic -O2 -flto -Wall -Wextra -Wshadow -Wformat=2 -Wconversion -Wpedantic -Werror PREFIX ?= /usr
CFLAGS = -std=c11 -pedantic -O2 -Wall -Wextra -Wshadow -Wformat=2 -Wconversion -Wpedantic -Werror -Wno-format-truncation
TEST_DIR = /home/lw/Projects/glacier-ng/lib
+4
View File
@@ -0,0 +1,4 @@
+ Glacier Packaging Format
Every Glacier package should contain the following files:
* pkg_meta.gpm (Glacier Package Manifest metadata file)
+17
View File
@@ -0,0 +1,17 @@
#
# bar
#
PKG_NAME = "bar";
PKG_VER = 1.0.0;
PKG_DESC = "example pkg";
PKG_MAINT = "liamwaldron@everestlinux.org";
PKG_COPYRIGHT = "GPL3";
PKG_DEPS = (
{ PKG_NAME = "foo"; PKG_VER = 1.1.1; };
);
PKG_CONFS = (
{};
);
+10
View File
@@ -0,0 +1,10 @@
#
# pkg_meta.gpm
#
PACKAGE_NAME = "pkg"
PACKAGE_VER = 1.0.0
PACKAGE_DESC = ""
PACKAGE_MAINT = ""
PACKAGE_LICENSE = "";
PACKAGE_ARCH = "";
+249
View File
@@ -0,0 +1,249 @@
#ifndef COMMON_H_
#define COMMON_H_
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
/*
* On-disk layout. Each scope keeps everything it ever creates, renames
* or locks under ONE base directory it owns:
*
* /glacier/usr/<uid>/{index,store,links,stage,old,lock} owned by uid, 0700
* /glacier/sys/{index,store,links,stage,old,lock} root
*
* /glacier/usr itself is root-owned and not group/world-writable, so a
* user can never create (or squat) another uid's base; root creates
* each one (gl_init_user, via `gstore -n` directly or through doas).
* Every transaction step — stage, old/, lock, the commit renames — then
* happens inside a directory the acting user owns, which is what lets
* an unprivileged user run their own transactions at all.
*/
#define GL_USR_ROOT "/glacier/usr"
/* In a package's version dir: "installed as a dependency, not by name".
* Dot-prefixed like the other store markers, so seeding carries it and
* linking skips it; the index's 4th field is derived from it. */
#define GL_AUTO_MARKER ".glacier-auto"
/* <ver>/.glacier-src: built from this recipe repository (gl_set_pkg_src). */
#define GL_SRC_MARKER ".glacier-src"
/* The other files glacier keeps in a version dir (see gl_install_pkg):
* the package's saved manifest, and the one-shot markers for the next
* link pass (this transaction installed it; it may displace, -O). A
* package may not ship any top-level name starting with GL_MARKER_PREFIX:
* these are glacier's, and one shipped as a symlink would redirect
* glacier's own writes. */
#define GL_MARKER_PREFIX ".glacier-"
#define GL_MANIFEST_COPY ".glacier-manifest"
#define GL_FRESH_MARKER ".glacier-fresh"
#define GL_OVERWRITE_MARKER ".glacier-overwrite"
#define GL_SYS_ROOT "/glacier/sys"
static inline void
gl_usr_base(uid_t uid, char *out, size_t outsz)
{
snprintf(out, outsz, GL_USR_ROOT "/%u", (unsigned)uid);
}
typedef enum {
GL_USR_BASE_OK = 0,
GL_USR_BASE_MISSING, /* no /glacier/usr/<uid> yet: run gstore -n */
GL_USR_BASE_UNSAFE_ROOT, /* /glacier/usr not root-owned, or group/world-writable */
GL_USR_BASE_UNSAFE /* not a real dir, not owned by uid, or not 0700-ish */
} gl_usr_base_status_t;
/* Refuse to operate on a user base we didn't hand out. lstat(), never
* stat(): a symlink in place of /glacier/usr/<uid> is exactly what a
* squatter would plant. Backstop for the layout invariant above, so a
* hand-loosened /glacier/usr can't silently turn into one user writing
* another's store. */
static inline gl_usr_base_status_t
gl_usr_base_check(uid_t uid)
{
struct stat st;
if (lstat(GL_USR_ROOT, &st) != 0) { return GL_USR_BASE_MISSING; }
if (!S_ISDIR(st.st_mode) || st.st_uid != 0 ||
(st.st_mode & (S_IWGRP | S_IWOTH)) != 0) {
return GL_USR_BASE_UNSAFE_ROOT;
}
char base[PATH_MAX];
gl_usr_base(uid, base, sizeof(base));
if (lstat(base, &st) != 0) { return GL_USR_BASE_MISSING; }
if (!S_ISDIR(st.st_mode) || st.st_uid != uid ||
(st.st_mode & (S_IRWXG | S_IRWXO)) != 0) {
return GL_USR_BASE_UNSAFE;
}
return GL_USR_BASE_OK;
}
/* An install root (gl_context_t.sysroot) in canonical form: NULL, "" and
* "/" mean the running system and give ""; anything else must be an
* absolute path with no "." or ".." components, and loses its trailing
* slashes. Room is left for the paths built under it. Returns -1 if
* it's refused. */
static inline int
gl_normalize_sysroot(const char *in, char *out, size_t outsz)
{
out[0] = '\0';
if (!in || in[0] == '\0') { return 0; }
if (in[0] != '/') { return -1; }
size_t len = strlen(in);
while (len > 0 && in[len - 1] == '/') { len--; }
if (len == 0) { return 0; } /* "/" or "//" */
if (len + 256 > outsz || len + 256 > PATH_MAX) { return -1; }
for (size_t i = 0; i < len; ) {
size_t j = i + 1; /* in[i] == '/' */
while (j < len && in[j] != '/') { j++; }
size_t clen = j - i - 1;
const char *comp = in + i + 1;
if (clen == 0 || (clen == 1 && comp[0] == '.') ||
(clen == 2 && comp[0] == '.' && comp[1] == '.')) {
return -1;
}
i = j;
}
memcpy(out, in, len);
out[len] = '\0';
return 0;
}
/* Is a (normalized, non-empty) install root safe for root to write into?
* It and every directory above it must be a real directory (not a
* symlink), owned by root, and not group/world-writable: otherwise a
* user could swap part of the tree for a symlink to the host's /usr
* between two syscalls (IMAGE_DESIGN section 4). Returns 0 if trusted;
* otherwise -1, with the offending path in `bad` and `why` set to
* "a symlink", "not a directory", or "not root-owned, or is
* group/world-writable". */
static inline int
gl_sysroot_check_one(const char *path, char *bad, size_t badsz, const char **why)
{
struct stat st;
if (lstat(path, &st) != 0) {
*why = "missing";
} else if (S_ISLNK(st.st_mode)) {
*why = "a symlink";
} else if (!S_ISDIR(st.st_mode)) {
*why = "not a directory";
} else if (st.st_uid != 0 || (st.st_mode & 022) != 0) {
*why = "not root-owned, or is group/world-writable";
} else {
return 0;
}
snprintf(bad, badsz, "%s", path);
return -1;
}
static inline int
gl_sysroot_trusted(const char *root, char *bad, size_t badsz, const char **why)
{
if (gl_sysroot_check_one("/", bad, badsz, why) != 0) { return -1; }
char prefix[PATH_MAX];
snprintf(prefix, sizeof(prefix), "%s", root);
/* each ancestor, shortest first, then root itself */
for (char *p = prefix + 1; *p; p++) {
if (*p != '/') { continue; }
*p = '\0';
int rc = gl_sysroot_check_one(prefix, bad, badsz, why);
*p = '/';
if (rc != 0) { return -1; }
}
return gl_sysroot_check_one(prefix, bad, badsz, why);
}
/* mkdir -p. Every directory this creates gets exactly `mode`, whatever
* the caller's umask: a system store made under umask 077 would otherwise
* be unreachable for every user but root. Directories that already exist
* are left alone. */
static inline int
gl_mkdir_exact(const char *path, mode_t mode)
{
if (mkdir(path, mode) == 0) {
return chmod(path, mode);
}
return errno == EEXIST ? 0 : -1;
}
static inline int
gl_mkdirp(const char *path, mode_t mode)
{
char tmp[PATH_MAX];
strncpy(tmp, path, sizeof(tmp));
tmp[sizeof(tmp) - 1] = '\0';
for (char *p = tmp + 1; *p; p++) {
if (*p == '/') {
*p = '\0';
if (gl_mkdir_exact(tmp, mode) != 0) {
return -1;
}
*p = '/';
}
}
return gl_mkdir_exact(tmp, mode);
}
/* Empties the directory open at `fd` (and closes it). Every step is
* relative to a descriptor opened with O_NOFOLLOW, so nothing is ever
* resolved through a symlink: an entry swapped for a symlink mid-walk
* (root deleting a tree a user can write to, gstore -x) is unlinked
* itself, never followed into its target. */
static inline void
gl_empty_dir_fd(int fd)
{
DIR *dir = fdopendir(fd);
if (!dir) {
close(fd);
return;
}
struct dirent *ent;
while ((ent = readdir(dir))) {
/* Only . and ..: dotfiles are content too (a package's own,
* the store's .displaced tree). */
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {
continue;
}
int sub = openat(dirfd(dir), ent->d_name,
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (sub >= 0) {
gl_empty_dir_fd(sub);
unlinkat(dirfd(dir), ent->d_name, AT_REMOVEDIR);
} else {
unlinkat(dirfd(dir), ent->d_name, 0);
}
}
closedir(dir);
}
/* rm -r of a directory. `path` itself must be a directory, not a
* symlink to one (refused, -1). */
static inline int
gl_rmdir_recursive(const char *path)
{
int fd = open(path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0) { return -1; }
gl_empty_dir_fd(fd);
return rmdir(path);
}
#endif
-22
View File
@@ -1,22 +0,0 @@
#define _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#define _XOPEN_SOURCE 700
#include "color.h"
#include <archive.h>
#include <archive_entry.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
static int
extract_tar(const char *tarfile, const char *dest)
{
struct archive *a = archive_read_new();
struct archive *ext = archive_write_disk_new();
}
+727
View File
@@ -0,0 +1,727 @@
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#include <archive.h>
#include <archive_entry.h>
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include "common.h"
#include "deps.h"
#include "istoreutils.h"
#include "log.h"
#include "pkg.h"
/* Where one entry of a package lands once linked: its RUNTIME path (what
* a message names and what two packages are compared by). */
struct dest {
char *path;
bool dir;
};
/* One installed (or about to be installed) package. repo/name/dirname
* come from the store layout (store/<repo>/<name>/<name>-<ver>), or from
* the manifest for a package that isn't installed yet. deps/confs come
* from the manifest; a version dir without one (installed before
* manifests were saved) has none. */
struct rec {
char repo[NAME_MAX + 1];
char name[NAME_MAX + 1];
char dirname[NAME_MAX + 1];
semver_t ver;
gl_pkg_t pkg;
bool touched; /* added or replaced by this transaction */
bool gone; /* removed or replaced: not in the result */
/* For the file checks: where its files come from (a version dir in
* a store, or a .gpkg not installed yet), whether its link pass is
* this transaction's (fresh: it reports refusals), whether that
* pass may displace foreign files (-O), and, once computed, where
* every entry lands. */
char src[PATH_MAX];
bool from_archive;
bool fresh;
bool overwrite;
struct dest *dests;
size_t ndests;
bool dests_loaded;
};
/* What the file checks need to know about the transaction's context. */
struct env {
gl_ctx_scope_t scope;
uid_t uid;
const char *sysroot;
int strict;
char store_rt[PATH_MAX]; /* live store, runtime path: link targets */
char store_at[PATH_MAX]; /* the store being checked, install path */
};
struct set {
struct rec *v;
size_t n;
};
/* A package the transaction removes outright (not replaced). */
struct removed {
char repo[NAME_MAX + 1];
char name[NAME_MAX + 1];
};
static void
set_free(struct set *s)
{
for (size_t i = 0; i < s->n; i++) {
gl_free_pkg(&s->v[i].pkg);
gl_free_semver(&s->v[i].ver);
for (size_t k = 0; k < s->v[i].ndests; k++) { free(s->v[i].dests[k].path); }
free(s->v[i].dests);
}
free(s->v);
s->v = NULL;
s->n = 0;
}
static struct rec *
set_add(struct set *s)
{
struct rec *grown = realloc(s->v, (s->n + 1) * sizeof(*s->v));
if (!grown) { return NULL; }
s->v = grown;
memset(&s->v[s->n], 0, sizeof(*s->v));
return &s->v[s->n++];
}
static int
semver_cmp(const semver_t *a, const semver_t *b)
{
if (a->maj != b->maj) { return a->maj < b->maj ? -1 : 1; }
if (a->min != b->min) { return a->min < b->min ? -1 : 1; }
if (a->pat != b->pat) { return a->pat < b->pat ? -1 : 1; }
return 0;
}
/* Every installed package in `store`. A missing store is empty (nothing
* installed); any other failure to read it is an error, unless `lenient`
* (the system store as seen from user scope: unreadable means "nothing
* there to depend on", and the check then says what's missing). */
static int
load_store(const char *store, struct set *s, bool lenient)
{
DIR *sd = opendir(store);
if (!sd) {
return (errno == ENOENT || lenient) ? 0 : -1;
}
int rc = 0;
struct dirent *re;
while (rc == 0 && (re = readdir(sd))) {
if (re->d_name[0] == '.') { continue; }
char repo_path[PATH_MAX];
snprintf(repo_path, sizeof(repo_path), "%s/%s", store, re->d_name);
DIR *rd = opendir(repo_path);
if (!rd) { continue; } /* not a directory */
struct dirent *ne;
while (rc == 0 && (ne = readdir(rd))) {
if (ne->d_name[0] == '.') { continue; }
char name_path[PATH_MAX];
snprintf(name_path, sizeof(name_path), "%s/%s", repo_path, ne->d_name);
DIR *nd = opendir(name_path);
if (!nd) { continue; }
struct dirent *ve;
while ((ve = readdir(nd))) {
if (ve->d_name[0] == '.') { continue; }
struct rec *r = set_add(s);
if (!r) { rc = -1; break; }
snprintf(r->repo, sizeof(r->repo), "%s", re->d_name);
snprintf(r->name, sizeof(r->name), "%s", ne->d_name);
snprintf(r->dirname, sizeof(r->dirname), "%s", ve->d_name);
snprintf(r->src, sizeof(r->src), "%s/%s", name_path, ve->d_name);
char manifest[PATH_MAX];
snprintf(manifest, sizeof(manifest), "%s/%s/" GL_MANIFEST_COPY,
name_path, ve->d_name);
if (gl_gpm2gpkg(manifest, &r->pkg) != 0) {
gl_free_pkg(&r->pkg);
memset(&r->pkg, 0, sizeof(r->pkg));
}
/* The version is the dir name minus "<name>-". */
size_t prefix = strlen(ne->d_name) + 1;
r->ver = gl_parse_semver(strlen(ve->d_name) > prefix
? ve->d_name + prefix : NULL);
break; /* one version per package */
}
closedir(nd);
}
closedir(rd);
}
closedir(sd);
return rc;
}
static const struct rec *
find_live(const struct set *s, const char *repo, const char *name)
{
for (size_t i = 0; i < s->n; i++) {
if (!s->v[i].gone && strcmp(s->v[i].repo, repo) == 0 &&
strcmp(s->v[i].name, name) == 0) {
return &s->v[i];
}
}
return NULL;
}
/* Is there a package named `name` (any repo) in the result or, from user
* scope, the system? With `min`, it must also be at least that version. */
static bool
provided(const struct set *res, const struct set *sys, const char *name,
const semver_t *min)
{
const struct set *sets[] = { res, sys };
for (int k = 0; k < 2; k++) {
for (size_t i = 0; i < sets[k]->n; i++) {
const struct rec *r = &sets[k]->v[i];
if (r->gone || strcmp(r->name, name) != 0) { continue; }
if (!min || semver_cmp(&r->ver, min) >= 0) { return true; }
}
}
return false;
}
static bool
lists_conflict(const struct rec *r, const char *name)
{
if (!r->pkg.pkg_conflicts) { return false; }
for (const conf_t *c = r->pkg.pkg_conflicts; c->conf_name; c++) {
if (strcmp(c->conf_name, name) == 0) { return true; }
}
return false;
}
/* Does the transaction touch packages named `name`: add or replace one,
* or remove one outright? */
static bool
name_touched(const struct set *res, const struct removed *rm, size_t nrm,
const char *name)
{
for (size_t i = 0; i < res->n; i++) {
if (res->v[i].touched && strcmp(res->v[i].name, name) == 0) { return true; }
}
for (size_t i = 0; i < nrm; i++) {
if (strcmp(rm[i].name, name) == 0) { return true; }
}
return false;
}
static void
fmt_ver(const semver_t *v, char *out, size_t outsz)
{
snprintf(out, outsz, "%d.%d.%d", v->maj, v->min, v->pat);
}
/*
* File checks (ROADMAP 2.6 and 1.2's --strict).
*
* Every entry of a package lands somewhere once linked; dest_of mirrors
* gl_link_pkg exactly: entries under a dot-prefixed name are never
* linked, a leading usr/ is stripped, base-repo packages in system scope
* land in /usr and everything else in the scope's links tree, and in
* system scope the top-level etc/ is copied into /etc.
*/
static bool
has_dot_component(const char *rel)
{
for (const char *c = rel; c; c = strchr(c, '/')) {
if (*c == '/') { c++; }
if (*c == '.') { return true; }
if (!*c) { break; }
}
return false;
}
static int
dest_of(const struct env *e, const char *repo, const char *rel, char *out, size_t outsz)
{
if (e->scope == GL_SCOPE_SYS &&
(strcmp(rel, "etc") == 0 || strncmp(rel, "etc/", 4) == 0)) {
return snprintf(out, outsz, "/%s", rel) >= (int)outsz ? -1 : 0;
}
if (strncmp(rel, "usr/", 4) == 0) { rel += 4; }
char base[PATH_MAX];
if (e->scope == GL_SCOPE_SYS) {
snprintf(base, sizeof(base), "%s", strcmp(repo, "base") == 0
? "/usr" : GL_SYS_ROOT "/links");
} else {
char ub[PATH_MAX];
gl_usr_base(e->uid, ub, sizeof(ub));
snprintf(base, sizeof(base), "%s/links", ub);
}
return snprintf(out, outsz, "%s/%s", base, rel) >= (int)outsz ? -1 : 0;
}
static int
add_dest(struct rec *r, const char *path, bool dir)
{
for (size_t k = 0; k < r->ndests; k++) {
if (strcmp(r->dests[k].path, path) == 0) {
if (!dir) { r->dests[k].dir = false; }
return 0;
}
}
struct dest *grown = realloc(r->dests, (r->ndests + 1) * sizeof(*grown));
if (!grown) { return -1; }
r->dests = grown;
r->dests[r->ndests].path = strdup(path);
if (!r->dests[r->ndests].path) { return -1; }
r->dests[r->ndests].dir = dir;
r->ndests++;
return 0;
}
/* `rel` (and, for an archive entry, its parents, which tar needn't list) */
static int
add_rel(const struct env *e, struct rec *r, const char *rel, bool dir, bool parents)
{
if (rel[0] == '\0' || has_dot_component(rel)) { return 0; }
char d[PATH_MAX];
if (parents) {
char buf[PATH_MAX];
snprintf(buf, sizeof(buf), "%s", rel);
for (char *p = buf; (p = strchr(p, '/')); p++) {
*p = '\0';
if (dest_of(e, r->repo, buf, d, sizeof(d)) != 0 || add_dest(r, d, true) != 0) {
return -1;
}
*p = '/';
}
}
if (dest_of(e, r->repo, rel, d, sizeof(d)) != 0) { return -1; }
return add_dest(r, d, dir);
}
static int
walk_store_dir(const struct env *e, struct rec *r, const char *dir, size_t strip)
{
DIR *d = opendir(dir);
if (!d) { return 0; }
int rc = 0;
struct dirent *ent;
while (rc == 0 && (ent = readdir(d))) {
if (ent->d_name[0] == '.') { continue; }
char full[PATH_MAX];
snprintf(full, sizeof(full), "%s/%s", dir, ent->d_name);
struct stat st;
if (lstat(full, &st) != 0) { continue; }
const char *rel = full + strip;
if (S_ISDIR(st.st_mode)) {
rc = add_rel(e, r, rel, true, false);
if (rc == 0) { rc = walk_store_dir(e, r, full, strip); }
} else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
rc = add_rel(e, r, rel, false, false);
}
}
closedir(d);
return rc;
}
static int
walk_archive(const struct env *e, struct rec *r)
{
char prefix[PATH_MAX];
snprintf(prefix, sizeof(prefix), "%s-%d.%d.%d/files/", r->name,
r->pkg.pkg_ver.maj, r->pkg.pkg_ver.min, r->pkg.pkg_ver.pat);
size_t plen = strlen(prefix);
struct archive *a = archive_read_new();
archive_read_support_filter_gzip(a);
archive_read_support_format_tar(a);
if (archive_read_open_filename(a, r->src, 10240) != ARCHIVE_OK) {
archive_read_free(a);
return -1;
}
int rc = 0;
struct archive_entry *entry;
while (rc == 0 && archive_read_next_header(a, &entry) == ARCHIVE_OK) {
const char *path = archive_entry_pathname(entry);
if (strncmp(path, prefix, plen) == 0) {
char rel[PATH_MAX];
snprintf(rel, sizeof(rel), "%s", path + plen);
size_t len = strlen(rel);
while (len > 0 && rel[len - 1] == '/') { rel[--len] = '\0'; }
mode_t type = archive_entry_filetype(entry);
if (type == AE_IFDIR) {
rc = add_rel(e, r, rel, true, true);
} else if (type == AE_IFREG || type == AE_IFLNK) {
rc = add_rel(e, r, rel, false, true);
}
}
archive_read_data_skip(a);
}
archive_read_free(a);
return rc;
}
static int
load_dests(const struct env *e, struct rec *r)
{
if (r->dests_loaded) { return 0; }
r->dests_loaded = true;
if (r->from_archive) { return walk_archive(e, r); }
return walk_store_dir(e, r, r->src, strlen(r->src) + 1);
}
struct item {
const char *path;
bool dir;
size_t rec;
};
static int
item_cmp(const void *a, const void *b)
{
const struct item *x = a, *y = b;
int c = strcmp(x->path, y->path);
if (c != 0) { return c; }
return x->rec < y->rec ? -1 : x->rec > y->rec;
}
/* Two packages shipping the same path (ROADMAP 2.6): whichever linked
* last used to win silently. Refused when either package is part of
* this transaction; at least one of the two entries must be a file or
* symlink (sharing a directory is normal). */
static int
check_collisions(const struct env *e, struct set *res)
{
size_t n = 0;
for (size_t i = 0; i < res->n; i++) {
if (res->v[i].gone) { continue; }
if (load_dests(e, &res->v[i]) != 0) { return -1; }
n += res->v[i].ndests;
}
if (n == 0) { return 0; }
struct item *items = malloc(n * sizeof(*items));
if (!items) { return -1; }
size_t k = 0;
for (size_t i = 0; i < res->n; i++) {
if (res->v[i].gone) { continue; }
for (size_t j = 0; j < res->v[i].ndests; j++) {
items[k++] = (struct item){ res->v[i].dests[j].path, res->v[i].dests[j].dir, i };
}
}
qsort(items, n, sizeof(*items), item_cmp);
int problems = 0;
for (size_t start = 0; start < n; ) {
size_t end = start + 1;
while (end < n && strcmp(items[end].path, items[start].path) == 0) { end++; }
for (size_t a = start; a < end; a++) {
const struct rec *ra = &res->v[items[a].rec];
if (!ra->touched && !ra->fresh) { continue; }
for (size_t b = start; b < end; b++) {
if (b == a || (items[a].dir && items[b].dir)) { continue; }
const struct rec *rb = &res->v[items[b].rec];
/* two of this transaction's packages: report once */
if ((rb->touched || rb->fresh) && b < a) { continue; }
lg_printf(2, "%s::%s and %s::%s both ship %s.",
ra->repo, ra->name, rb->repo, rb->name, items[a].path);
problems++;
}
}
start = end;
}
free(items);
return problems;
}
/* --strict: what the post-commit link pass would refuse, refused now
* instead, before anything is committed. Same rules as gl_link_pkg, for
* this transaction's packages only (the ones whose refusals it reports).
* User scope never has a foreign file in its links tree (rebuilt on
* every commit), and config in /etc is offered as .new, never refused. */
static int
check_links(const struct env *e, struct set *res)
{
if (!e->strict || e->scope != GL_SCOPE_SYS) { return 0; }
char store_prefix[PATH_MAX];
snprintf(store_prefix, sizeof(store_prefix), "%s/", e->store_rt);
size_t splen = strlen(store_prefix);
int problems = 0;
for (size_t i = 0; i < res->n; i++) {
struct rec *r = &res->v[i];
if (r->gone || !(r->touched || r->fresh)) { continue; }
if (load_dests(e, r) != 0) { return -1; }
for (size_t k = 0; k < r->ndests; k++) {
const struct dest *d = &r->dests[k];
if (strcmp(d->path, "/etc") == 0 || strncmp(d->path, "/etc/", 5) == 0) { continue; }
char at[PATH_MAX];
snprintf(at, sizeof(at), "%s%s", e->sysroot, d->path);
struct stat st;
if (lstat(at, &st) != 0) {
if (errno == ENOTDIR) {
lg_printf(2, "Refusing to overwrite non-glacier path: %s", at);
problems++;
}
continue;
}
bool ours = false;
if (S_ISLNK(st.st_mode)) {
char target[PATH_MAX];
ssize_t tn = readlink(at, target, sizeof(target) - 1);
ours = tn >= 0 && (size_t)tn >= splen &&
strncmp(target, store_prefix, splen) == 0;
}
if (d->dir) {
/* a foreign symlink here (usr/sbin -> bin) is followed,
* like gl_link_pkg does; one of glacier's isn't */
if (S_ISDIR(st.st_mode) || (S_ISLNK(st.st_mode) && !ours)) { continue; }
if (ours) {
lg_printf(2, "Refusing to merge directory %s into another package's symlink", at);
} else {
lg_printf(2, "Refusing to overwrite non-glacier path: %s", at);
}
problems++;
continue;
}
if (ours) { continue; }
if (r->overwrite && (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) {
char kept[PATH_MAX];
snprintf(kept, sizeof(kept), "%s/.displaced%s", e->store_at, d->path);
struct stat kst;
if (lstat(kept, &kst) != 0) { continue; } /* -O moves it aside */
}
lg_printf(2, "Refusing to overwrite non-glacier path: %s", at);
problems++;
}
}
return problems;
}
/* The checks themselves, on the result of a transaction. */
static int
check(const struct env *e, struct set *res, const struct set *sys,
const struct removed *rm, size_t nrm)
{
int problems = 0;
char ver[64];
for (size_t i = 0; i < res->n; i++) {
const struct rec *p = &res->v[i];
if (p->gone) { continue; }
const dep_t *deps = p->pkg.pkg_dependencies;
for (const dep_t *d = deps; d && d->dep_name; d++) {
/* An added package: all its deps. An untouched one:
* only deps on something this transaction changes. */
if (!p->touched && !name_touched(res, rm, nrm, d->dep_name)) { continue; }
if (provided(res, sys, d->dep_name, &d->dep_ver)) { continue; }
const struct removed *gone = NULL;
for (size_t k = 0; !p->touched && k < nrm; k++) {
if (strcmp(rm[k].name, d->dep_name) == 0) { gone = &rm[k]; break; }
}
if (gone && !provided(res, sys, d->dep_name, NULL)) {
lg_printf(2, "Removing %s::%s breaks %s::%s.",
gone->repo, gone->name, p->repo, p->name);
} else {
fmt_ver(&d->dep_ver, ver, sizeof(ver));
lg_printf(2, "%s::%s requires %s >= %s, which is not installed.",
p->repo, p->name, d->dep_name, ver);
}
problems++;
}
if (!p->touched) { continue; }
for (size_t j = 0; j < res->n; j++) {
const struct rec *q = &res->v[j];
if (j == i || q->gone) { continue; }
/* Two added packages: report the pair once. */
if (q->touched && j < i) { continue; }
if (lists_conflict(p, q->name) || lists_conflict(q, p->name)) {
lg_printf(2, "%s::%s conflicts with %s::%s.",
p->repo, p->name, q->repo, q->name);
problems++;
}
}
}
int files = check_collisions(e, res);
if (files < 0) { return -1; }
problems += files;
files = check_links(e, res);
if (files < 0) { return -1; }
return problems + files;
}
/* The runtime path of the live store for a context's scope and root. */
static void
env_init(struct env *e, const gl_context_t *ctx, const char *store_at)
{
e->scope = ctx->scope;
e->uid = ctx->uid;
e->sysroot = ctx->sysroot;
e->strict = ctx->strict;
if (ctx->scope == GL_SCOPE_USR) {
char ub[PATH_MAX];
gl_usr_base(ctx->uid, ub, sizeof(ub));
snprintf(e->store_rt, sizeof(e->store_rt), "%s/store", ub);
} else {
snprintf(e->store_rt, sizeof(e->store_rt), "%s/store", GL_SYS_ROOT);
}
snprintf(e->store_at, sizeof(e->store_at), "%s", store_at);
}
/* The system store, which a user-scope transaction's deps may rely on.
* Always the running system's: user scope never has an install root. */
static int
load_sys(gl_ctx_scope_t scope, struct set *sys)
{
if (scope != GL_SCOPE_USR) { return 0; }
return load_store(GL_SYS_ROOT "/store", sys, true);
}
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)
{
if (!live) { return -1; }
struct set res = { NULL, 0 }, sys = { NULL, 0 };
struct removed *rm = calloc(n_remove + 1, sizeof(*rm));
size_t nrm = 0;
int rc = -1;
if (!rm || load_store(live->store_path, &res, false) != 0 ||
load_sys(live->scope, &sys) != 0) {
goto out;
}
for (size_t i = 0; i < n_remove; i++) {
const char *sep = strstr(remove_ids[i], "::");
if (!sep) { goto out; }
char repo[NAME_MAX + 1];
snprintf(repo, sizeof(repo), "%.*s", (int)(sep - remove_ids[i]), remove_ids[i]);
struct rec *r = (struct rec *)find_live(&res, repo, sep + 2);
if (!r) { continue; } /* not installed: nothing to break */
r->gone = true;
snprintf(rm[nrm].repo, sizeof(rm[nrm].repo), "%s", r->repo);
snprintf(rm[nrm].name, sizeof(rm[nrm].name), "%s", r->name);
nrm++;
}
for (size_t i = 0; i < n_add; i++) {
gl_pkg_t pkg = {0};
if (gl_read_pkg_manifest(add_paths[i], &pkg) != GL_INSTALL_OK) { goto out; }
/* Same repo::name installed: this replaces it. */
struct rec *old = (struct rec *)find_live(&res, pkg.pkg_repo, pkg.pkg_name);
if (old) { old->gone = true; }
struct rec *r = set_add(&res);
if (!r) { gl_free_pkg(&pkg); goto out; }
snprintf(r->repo, sizeof(r->repo), "%s", pkg.pkg_repo);
snprintf(r->name, sizeof(r->name), "%s", pkg.pkg_name);
r->ver = (semver_t){ pkg.pkg_ver.maj, pkg.pkg_ver.min, pkg.pkg_ver.pat, NULL };
r->pkg = pkg;
r->touched = true;
r->fresh = true;
r->overwrite = live->overwrite != 0;
r->from_archive = true;
snprintf(r->src, sizeof(r->src), "%s", add_paths[i]);
}
struct env e;
env_init(&e, live, live->store_path);
rc = check(&e, &res, &sys, rm, nrm);
out:
set_free(&res);
set_free(&sys);
free(rm);
return rc;
}
int
gl_check_txn(const gl_context_t *stage)
{
if (!stage || stage->mode != GL_CTX_STAGE) { return -1; }
char base[PATH_MAX], live_store[PATH_MAX];
if (stage->scope == GL_SCOPE_USR) {
gl_usr_base(stage->uid, base, sizeof(base));
} else {
snprintf(base, sizeof(base), "%s%s", stage->sysroot, GL_SYS_ROOT);
}
snprintf(live_store, sizeof(live_store), "%s/store", base);
struct set res = { NULL, 0 }, live = { NULL, 0 }, sys = { NULL, 0 };
struct removed *rm = NULL;
size_t nrm = 0;
int rc = -1;
if (load_store(stage->store_path, &res, false) != 0 ||
load_store(live_store, &live, false) != 0 ||
load_sys(stage->scope, &sys) != 0) {
goto out;
}
rm = calloc(live.n + 1, sizeof(*rm));
if (!rm) { goto out; }
/* Touched: in the stage, but not as this exact version in live.
* Fresh: installed by this transaction (a reinstall of the same
* version is fresh but not touched); its link pass is this one's. */
for (size_t i = 0; i < res.n; i++) {
struct rec *r = &res.v[i];
const struct rec *l = find_live(&live, r->repo, r->name);
r->touched = !l || strcmp(l->dirname, r->dirname) != 0;
char marker[PATH_MAX];
struct stat mst;
snprintf(marker, sizeof(marker), "%s/" GL_FRESH_MARKER, r->src);
r->fresh = lstat(marker, &mst) == 0;
snprintf(marker, sizeof(marker), "%s/" GL_OVERWRITE_MARKER, r->src);
r->overwrite = lstat(marker, &mst) == 0;
}
/* Removed: in live, and no longer in the stage under that repo::name. */
for (size_t i = 0; i < live.n; i++) {
if (find_live(&res, live.v[i].repo, live.v[i].name)) { continue; }
snprintf(rm[nrm].repo, sizeof(rm[nrm].repo), "%s", live.v[i].repo);
snprintf(rm[nrm].name, sizeof(rm[nrm].name), "%s", live.v[i].name);
nrm++;
}
struct env e;
env_init(&e, stage, stage->store_path);
rc = check(&e, &res, &sys, rm, nrm);
out:
set_free(&res);
set_free(&live);
set_free(&sys);
free(rm);
return rc;
}
+55
View File
@@ -0,0 +1,55 @@
#ifndef DEPS_H_
#define DEPS_H_
#include <stddef.h>
#include "transaction.h"
/*
* Dependency and conflict checks (ROADMAP 2.3). Built into
* libglacier_istoreutils.so.
*
* Rules:
* - A PKG_DEPS entry {name, ver} is met by any installed package of
* that name (any repo) at version >= ver.
* - In user scope, a dependency may also be met by a system package.
* System scope never looks at user scopes.
* - PKG_CONFS is matched by name, both ways (either package listing
* the other is a conflict); its version is ignored. Only packages in
* the same scope conflict.
* - Only what a transaction CHANGES is checked: the packages it adds
* (deps and conflicts), and the installed packages that depend on
* something it removes or replaces. A store that was already
* inconsistent doesn't block unrelated work.
* - Two packages may not ship the same path (ROADMAP 2.6), compared by
* where each entry lands once linked; sharing a directory is fine.
* Checked whenever either package is part of the transaction.
* - With ctx->strict (syspkg --strict, implied by -R), anything the
* post-commit link pass would refuse (a foreign file in the way, a
* directory over another package's symlink) is refused up front,
* unless -O will move it aside. System scope only: a user's links
* tree is rebuilt on every commit.
* - Every problem is reported with lg_printf, one line each:
* extra::foo requires bar >= 1.2.0, which is not installed.
* Removing base::musl breaks extra::foo.
* extra::foo conflicts with extra::bar.
* extra::foo and extra::bar both ship /glacier/sys/links/bin/x.
* Refusing to overwrite non-glacier path: /usr/bin/x
*
* Both return the number of problems (0 = fine), or -1 if a store or a
* manifest couldn't be read.
*/
/* Before a transaction: `live` is a live context; add_paths are .gpkg
* files to install (a package already installed under the same
* repo::name is replaced); remove_ids are "repo::name" strings. */
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);
/* At commit: compares the stage against live. gl_commit_transaction
* calls this itself and refuses with GL_TXN_ERR_DEPS, so a caller that
* skips gl_check_plan is still held to the rules. */
int gl_check_txn(const gl_context_t *stage);
#endif
-23
View File
@@ -1,23 +0,0 @@
[2025-09-16 17:54:10] [INFO] Glacier started with PID 12345
[2025-09-16 20:09:54] [6] Glacier started with PID 12345
[2025-09-16 20:13:34] [-173481940] Glacier started with PID 12345
[2025-09-16 20:13:36] [-1935986644] Glacier started with PID 12345
[2025-09-16 20:15:21] [INFO] Glacier started with PID 12345
[2025-09-16 20:17:18] [INFO] Glacier started with PID 12345
[2025-09-16 20:17:18] [ERR] Failed to install package glibc
[2025-09-16 20:19:42] [INFO] Glacier started with PID 12345
[2025-09-16 20:19:42] [ERR] Failed to install package glibc
[2025-09-17 08:39:22] [INFO] Glacier started with PID 12345
[2025-09-17 08:39:22] [ERR] Failed to install package glibc
[2025-09-17 11:33:39] [INFO] Glacier started with PID 12345
[2025-09-17 11:33:39] [ERR] Failed to install package glibc
[2025-09-17 11:33:40] [INFO] Glacier started with PID 12345
[2025-09-17 11:33:40] [ERR] Failed to install package glibc
[2025-09-18 14:21:45] [INFO] Glacier started with PID 12345
[2025-09-18 14:21:45] [ERR] Failed to install package glibc
[2025-09-18 20:37:44] [INFO] Glacier started with PID 12345
[2025-09-18 20:37:44] [ERR] Failed to install package glibc
[2025-09-22 23:24:51] [INFO] Glacier started with PID 12345
[2025-09-22 23:24:51] [ERR] Failed to install package glibc
[2025-09-22 23:24:51] [INFO] Glacier started with PID 12345
[2025-09-22 23:24:51] [ERR] Failed to install package glibc
-70
View File
@@ -1,70 +0,0 @@
local gpkg = {}
function gpkg.parse_manifest(buffer)
local pkg = {
PKG_NAME = nil,
PKG_DESC = nil,
PKG_MAJOR = 0,
PKG_MINOR = 0,
PKG_PAATCH = 0,
PKG_MAINT = nil,
PKG_LICENSE = nil,
PKG_ARCH = nil,
PKG_DEPS = {},
PKG_CONFLICTS = {},
}
for line in buffer:gmatch("[^\r\n]+") do
line = line:match("^%s*(.-)%s*$+");
if line -= "" and not line:match("^#") then
local key, val = line:match("([^=]+)=(.*)");
if key and val then
key = key:match("^%s*(.-)%s*$");
val = val:match("^%s*(.-)%s*$");
if key == "PKG_NAME" then pkg.PKG_NAME = val
elseif key == "PKG_DESC" then pkg.PKG_DESC = val
elseif key == "PKG_MAJOR" then pkg.PKG_MAJOR = tonumber(val) or 0
elseif key == "PKG_MINOR" then pkg.PKG_MINOR = tonumber(val) or 0
elseif key == "PKG_PATCH" then pkg.PKG_PATCH = tonumber(val) or 0
elseif key == "PKG_MAINT" then pkg.PKG_MAINT = val
elseif key == "PKG_LICENSE" then pkg.PKG_LICENSE = val
elseif key == "PKG_ARCH" then pkg.PKG_ARCH = val
elseif key == "PKG_DEPS" then
pkg.PKG_DEPS = {}
for dep in val:gmatch("[^,%s]+") do
table.insert(pkg.PKG_DEPS, dep)
end
elseif key == "PKG_CONFLICTS" then
pkg.PKG_CONFLICTS = {}
for c in val:gmatch("[^,%s]+") do
table.insert(pkg.PKG_CONFLICTS, c)
end
end
end
end
end
return pkg
end
function gpkg.serialize(pkg)
local out = {}
local function line(k, v) table.insert(out, string.format("%s=%s", k, v or "")) end
line("PKG_NAME", pkg.PKG_NAME or "")
line("PKG_DESC", pkg.PKG_DESC or "")
line("PKG_MAJOR", pkg.PKG_MAJOR or 0)
line("PKG_MINOR", pkg.PKG_MINOR or 0)
line("PKG_PATCH", pkg.PKG_PATCH or 0)
line("PKG_MAINT", pkg.PKG_MAINT or "")
line("PKG_LICENSE", pkg.PKG_LICENSE or "")
line("PKG_ARCH", pkg.PKG_ARCH or "")
line("PKG_DEPS", table.concat(pkg.PKG_DEPS or {}, ","))
line("PKG_CONFLICTS", table.concat(pkg.PKG_CONFLICTS or {}, ","))
return table.concat(out, "\n") .. "\n"
end
return gpkg
+480
View File
@@ -0,0 +1,480 @@
/*
* grepo: write and sign a repository index (REPO_DESIGN.txt section 4).
* A maintainer tool, like gsign.
*
* grepo -s KEY.sec -r REPO [-n SERIAL] [-e DAYS] DIR
*
* Reads every NAME-VER.gpkg in DIR (its manifest, sha256 and size) and
* writes DIR/repo.idx plus DIR/repo.idx.sig, signed with KEY.sec. Each
* package's manifest must say REPO, and its file name must be
* NAME-VER.gpkg as the manifest names it. The server is then any static
* file host serving DIR.
*
* A REPO named X-src is a recipe repository (BUILD_DESIGN.txt section
* 3): DIR holds recipe bundles, NAME-VER.grcp, each read with
* gl_recipe_read; the recipe's REPO must be X.
*
* SERIAL (decided 2026-10-06) is the date form YYYYMMDDNN: the larger
* of the previous DIR/repo.idx's SERIAL + 1 and today (UTC) * 100 + 1.
* -n sets it explicitly; it must still be above the previous one, or
* clients would refuse the index. VALID_UNTIL is now + DAYS days
* (default 30; decision 10c).
*
* Exit 0 on success, 1 otherwise.
*/
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <inttypes.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include "istoreutils.h"
#include "log.h"
#include "pkg.h"
#include "recipe.h"
#include "sha256.h"
#include "sign.h"
#define DEFAULT_DAYS 30
#define MAX_DAYS 3650
#define USAGE "usage: grepo [-hv] -s KEY.sec -r REPO [-n SERIAL] [-e DAYS] DIR\n"
static const struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ "seckey", required_argument, NULL, 's' },
{ "repo", required_argument, NULL, 'r' },
{ "serial", required_argument, NULL, 'n' },
{ "expire", required_argument, NULL, 'e' },
{ NULL, 0, NULL, 0 }
};
static void
usage(void)
{
fprintf(stderr, USAGE);
}
static void
help(void)
{
printf("grepo: Write and sign a repository index\n");
printf(USAGE);
printf("\n");
printf("%-25s %s\n", "{-h --help}", "Show this message");
printf("%-25s %s\n", "{-v --version}", "Show the current version");
printf("%-25s %s\n", "{-s --seckey} KEY.sec", "Sign the index with this secret key");
printf("%-25s %s\n", "{-r --repo} REPO", "Repository the packages in DIR belong to");
printf("%-25s %s\n", "{-n --serial} SERIAL", "Index serial (default: YYYYMMDDNN)");
printf("%-25s Days until the index expires (default: %d)\n", "{-e --expire} DAYS", DEFAULT_DAYS);
printf("\n");
printf("This program is free software.\n");
printf("See the GNU GPL version 3 for details.\n");
}
static int
by_name(const void *a, const void *b)
{
return strcmp(*(char *const *)a, *(char *const *)b);
}
/* sha256 ("sha256:<hex>") and size of a regular file, read once. */
static int
hash_file(const char *path, char sha[72], int64_t *size)
{
int fd = open(path, O_RDONLY | O_NOFOLLOW);
if (fd < 0)
return -1;
gl_sha256_ctx_t h;
gl_sha256_init(&h);
uint8_t buf[65536];
ssize_t n;
int64_t total = 0;
while ((n = read(fd, buf, sizeof buf)) > 0) {
gl_sha256_update(&h, buf, (size_t)n);
total += n;
}
close(fd);
if (n < 0)
return -1;
uint8_t digest[32];
char hex[65];
gl_sha256_final(&h, digest);
gl_sha256_to_hex(digest, hex);
snprintf(sha, 72, "sha256:%s", hex);
*size = total;
return 0;
}
/* Reads a whole file (an index: at most GL_SIGN_MAX_MSG). NULL if it
* doesn't exist (errno ENOENT) or can't be read. */
static char *
slurp(const char *path, size_t *len)
{
FILE *f = fopen(path, "rb");
if (!f)
return NULL;
char *buf = malloc(GL_SIGN_MAX_MSG + 1);
size_t n = buf ? fread(buf, 1, GL_SIGN_MAX_MSG + 1, f) : 0;
int bad = !buf || ferror(f) || n > GL_SIGN_MAX_MSG;
fclose(f);
if (bad) {
free(buf);
errno = EIO;
return NULL;
}
*len = n;
return buf;
}
/* One DEPS/CONFS element. 0 having said why if the name is unsafe. */
static int
relation(FILE *f, const char *path, const char *what, const char *name,
const semver_t *v, int first)
{
if (!gl_valid_pkg_ident(name)) {
lg_printf(LG_ERR, "%s has a %s that is not a safe name.", path, what);
return 0;
}
fprintf(f, "%s { NAME = \"%s\"; VER = \"%d.%d.%d\"; }", first ? "" : ",",
name, v->maj, v->min, v->pat);
return 1;
}
/* Whether REPO is a recipe repository, "X-src" (X not empty). */
static int
is_src(const char *repo)
{
size_t l = strlen(repo);
return l > 4 && strcmp(repo + l - 4, "-src") == 0;
}
/* gl_recipe_t relation lines ("NAME VER[ IF]\n") as an index list. */
static void
relation_lines(FILE *f, const char *key, const char *lines)
{
fprintf(f, "\n\t %s = (", key);
const char *sep = "";
for (const char *p = lines; *p; p = strchr(p, '\n') + 1) {
/* One line: "NAME VER" or "NAME VER IF", never more. */
char line[512];
snprintf(line, sizeof line, "%.*s", (int)(strchr(p, '\n') - p), p);
char *ver = strchr(line, ' ');
*ver++ = '\0';
char *cond = strchr(ver, ' ');
if (cond)
*cond++ = '\0';
fprintf(f, "%s { NAME = \"%s\"; VER = \"%s\";", sep, line, ver);
if (cond)
fprintf(f, " IF = \"%s\";", cond);
fprintf(f, " }");
sep = ",";
}
fprintf(f, "%s);", *sep ? " " : "");
}
/* One recipe bundle's PKGS entry (REPO is X-src). */
static int
write_src_entry(FILE *f, const char *path, const char *file, const char *repo)
{
gl_recipe_t r;
gl_recipe_status_t st = gl_recipe_read(path, &r);
if (st != GL_RECIPE_OK) {
lg_printf(LG_ERR, "%s is %s: %s.", path,
st == GL_RECIPE_ERR_READ ? "not a readable recipe bundle" :
st == GL_RECIPE_ERR_BUNDLE ? "not a valid recipe bundle" :
"a bundle with a malformed recipe", gl_recipe_error());
return -1;
}
int rc = -1;
char want[PATH_MAX];
snprintf(want, sizeof want, "%s-%s.grcp", r.name, r.ver);
if (strlen(r.repo) != strlen(repo) - 4 || strncmp(r.repo, repo, strlen(r.repo)) != 0) {
lg_printf(LG_ERR, "%s builds %s packages, not %.*s.", path, r.repo,
(int)(strlen(repo) - 4), repo);
goto out;
}
if (strcmp(file, want) != 0) {
lg_printf(LG_ERR, "%s must be named %s, as its recipe says.", path, want);
goto out;
}
char sha[72];
int64_t size;
if (hash_file(path, sha, &size) != 0) {
lg_printf(LG_ERR, "Cannot read %s.", path);
goto out;
}
fprintf(f, "\t{ NAME = \"%s\"; VER = \"%s\"; FILE = \"%s\";\n"
"\t SHA256 = \"%s\"; SIZE = %" PRId64 "L;", r.name, r.ver, file, sha, size);
relation_lines(f, "DEPS", r.deps);
relation_lines(f, "CONFS", r.confs);
relation_lines(f, "BUILD_DEPS", r.build_deps);
fprintf(f, "\n\t TRAITS = (");
const char *sep = "";
for (const char *p = r.traits; *p; p = strchr(p, '\n') + 1) {
size_t l = (size_t)(strchr(p, ' ') - p);
fprintf(f, "%s { NAME = \"%.*s\"; DEFAULT = %s; }", sep, (int)l, p,
p[l + 1] == '1' ? "true" : "false");
sep = ",";
}
fprintf(f, "%s); }", *sep ? " " : "");
rc = 0;
out:
gl_recipe_free(&r);
return rc;
}
/* One package's PKGS entry, appended to f. 0, or -1 having said why. */
static int
write_entry(FILE *f, const char *dir, const char *file, const char *repo)
{
char path[PATH_MAX];
snprintf(path, sizeof path, "%s/%s", dir, file);
struct stat st;
if (lstat(path, &st) != 0 || !S_ISREG(st.st_mode)) {
lg_printf(LG_ERR, "Refusing %s: not a regular file.", path);
return -1;
}
if (is_src(repo))
return write_src_entry(f, path, file, repo);
gl_pkg_t pkg = {0};
if (gl_read_pkg_manifest(path, &pkg) != 0) {
lg_printf(LG_ERR, "Cannot read the manifest of %s.", path);
return -1;
}
int rc = -1;
char ver[64], want[PATH_MAX];
snprintf(ver, sizeof ver, "%d.%d.%d", pkg.pkg_ver.maj, pkg.pkg_ver.min,
pkg.pkg_ver.pat);
snprintf(want, sizeof want, "%s-%s.gpkg", pkg.pkg_name, ver);
if (strcmp(pkg.pkg_repo, repo) != 0) {
lg_printf(LG_ERR, "%s is a %s package, not %s.", path, pkg.pkg_repo, repo);
goto out;
}
if (strcmp(file, want) != 0) {
lg_printf(LG_ERR, "%s must be named %s, as its manifest says.", path, want);
goto out;
}
char sha[72];
int64_t size;
if (hash_file(path, sha, &size) != 0) {
lg_printf(LG_ERR, "Cannot read %s.", path);
goto out;
}
fprintf(f, "\t{ NAME = \"%s\"; VER = \"%s\"; FILE = \"%s\";\n"
"\t SHA256 = \"%s\"; SIZE = %" PRId64 "L;\n\t DEPS = (",
pkg.pkg_name, ver, file, sha, size);
int first = 1;
for (dep_t *d = pkg.pkg_dependencies; d && d->dep_name; d++) {
if (!relation(f, path, "dependency", d->dep_name, &d->dep_ver, first))
goto out;
first = 0;
}
fprintf(f, "%s); CONFS = (", first ? "" : " ");
first = 1;
for (conf_t *k = pkg.pkg_conflicts; k && k->conf_name; k++) {
if (!relation(f, path, "conflict", k->conf_name, &k->conf_ver, first))
goto out;
first = 0;
}
fprintf(f, "%s); }", first ? "" : " ");
rc = 0;
out:
gl_free_pkg(&pkg);
return rc;
}
int
main(int argc, char *argv[])
{
const char *sec = NULL, *repo = NULL;
int64_t serial = 0;
long days = DEFAULT_DAYS;
int c;
while ((c = getopt_long(argc, argv, "hvs:r:n:e:", longopts, NULL)) != -1) {
char *end;
switch (c) {
case 'h':
help();
return 0;
case 'v':
printf("v4.0.0\n");
return 0;
case 's': sec = optarg; break;
case 'r': repo = optarg; break;
case 'n':
errno = 0;
serial = strtoll(optarg, &end, 10);
if (errno || *end || end == optarg || serial <= 0) {
lg_printf(LG_ERR, "SERIAL must be a whole number above 0.");
return 1;
}
break;
case 'e':
errno = 0;
days = strtol(optarg, &end, 10);
if (errno || *end || end == optarg || days < 1 || days > MAX_DAYS) {
lg_printf(LG_ERR, "DAYS must be a whole number from 1 to %d.", MAX_DAYS);
return 1;
}
break;
default:
usage();
return 1;
}
}
if (!sec || !repo || optind != argc - 1) {
usage();
return 1;
}
const char *dir = argv[optind];
if (!gl_valid_pkg_ident(repo)) {
lg_printf(LG_ERR, "Repository name %s is not a safe name ([A-Za-z0-9._-]).", repo);
return 1;
}
int st = gl_sign_check_seckey(sec);
if (st != GL_SIGN_OK) {
lg_printf(LG_ERR, "Secret key %s %s.", sec,
st == GL_SIGN_ERR_ENCRYPTED ? "is encrypted: sign with signify" :
st == GL_SIGN_ERR_FORMAT ? "is malformed" : "cannot be read");
return 1;
}
char idx_path[PATH_MAX], sig_path[PATH_MAX];
if ((size_t)snprintf(idx_path, sizeof idx_path, "%s/repo.idx", dir) >= sizeof idx_path ||
(size_t)snprintf(sig_path, sizeof sig_path, "%s/repo.idx.sig", dir) >= sizeof sig_path) {
lg_printf(LG_ERR, "Path too long: %s", dir);
return 1;
}
/* The previous index, for its SERIAL. The maintainer's own file:
* parsed, not verified, but it must be a well-formed index for
* this repo (a mixed-up DIR is better caught here). */
int64_t prev = 0;
size_t plen;
char *ptext = slurp(idx_path, &plen);
if (!ptext && errno != ENOENT) {
lg_printf(LG_ERR, "Cannot read %s.", idx_path);
return 1;
}
if (ptext) {
gl_index_t old;
gl_index_status_t ist = gl_index_parse(ptext, plen, repo, &old);
free(ptext);
if (ist == GL_INDEX_ERR_REPO) {
lg_printf(LG_ERR, "%s is the index of another repository.", idx_path);
return 1;
}
if (ist != GL_INDEX_OK) {
lg_printf(LG_ERR, "Malformed %s.", idx_path);
return 1;
}
prev = old.serial;
gl_index_free(&old);
}
time_t now = time(NULL);
if (serial == 0) {
struct tm tm;
gmtime_r(&now, &tm);
int64_t today = ((int64_t)(tm.tm_year + 1900) * 10000 +
(tm.tm_mon + 1) * 100 + tm.tm_mday) * 100 + 1;
serial = prev + 1 > today ? prev + 1 : today;
} else if (serial <= prev) {
lg_printf(LG_ERR, "SERIAL must be above %" PRId64 ", the previous index's.", prev);
return 1;
}
DIR *d = opendir(dir);
if (!d) {
lg_printf(LG_ERR, "Cannot open %s: %s", dir, strerror(errno));
return 1;
}
char **names = NULL;
size_t n = 0;
struct dirent *de;
while ((de = readdir(d))) {
size_t l = strlen(de->d_name);
if (de->d_name[0] == '.' || l < 6 ||
strcmp(de->d_name + l - 5, is_src(repo) ? ".grcp" : ".gpkg") != 0)
continue;
char **grown = realloc(names, (n + 1) * sizeof *names);
if (!grown || !(grown[n] = strdup(de->d_name))) {
lg_printf(LG_ERR, "Out of memory.");
return 1;
}
names = grown;
n++;
}
closedir(d);
qsort(names, n, sizeof *names, by_name);
/* Written beside the result, then renamed over it: never in place. */
char tmp_idx[PATH_MAX], tmp_sig[PATH_MAX];
snprintf(tmp_idx, sizeof tmp_idx, "%s/.repo.idx.XXXXXX", dir);
int fd = mkstemp(tmp_idx);
FILE *f = fd < 0 ? NULL : fdopen(fd, "w");
if (!f) {
lg_printf(LG_ERR, "Cannot write in %s: %s", dir, strerror(errno));
return 1;
}
snprintf(tmp_sig, sizeof tmp_sig, "%s.sig", tmp_idx);
fprintf(f, "# Repository index written by grepo. Signed: repo.idx.sig.\n"
"REPO = \"%s\";\nSERIAL = %" PRId64 "L;\nVALID_UNTIL = %" PRId64 "L;\n"
"PKGS = (\n", repo, serial, (int64_t)now + (int64_t)days * 86400);
int rc = 0;
for (size_t i = 0; i < n && rc == 0; i++) {
if (i)
fprintf(f, ",\n");
rc = write_entry(f, dir, names[i], repo);
}
fprintf(f, "%s);\n", n ? "\n" : "");
if (fchmod(fd, 0644) != 0 || fflush(f) != 0 || fsync(fd) != 0)
rc = rc ? rc : (lg_printf(LG_ERR, "Cannot write %s.", tmp_idx), -1);
if (fclose(f) != 0 && rc == 0) {
lg_printf(LG_ERR, "Cannot write %s.", tmp_idx);
rc = -1;
}
for (size_t i = 0; i < n; i++)
free(names[i]);
free(names);
if (rc == 0 && (st = gl_sign_file(sec, tmp_idx, tmp_sig)) != GL_SIGN_OK) {
lg_printf(LG_ERR, "Cannot sign %s.", tmp_idx);
rc = -1;
}
/* The signature first: a client that fetches between the renames
* gets a new .sig with the old index, which fails to verify and is
* refused, never an index accepted under the wrong signature. */
if (rc == 0 && (rename(tmp_sig, sig_path) != 0 || rename(tmp_idx, idx_path) != 0)) {
lg_printf(LG_ERR, "Cannot replace %s: %s", idx_path, strerror(errno));
rc = -1;
}
if (rc != 0) {
unlink(tmp_idx);
unlink(tmp_sig);
return 1;
}
lg_printf(LG_SUCCESS, "Wrote %s: %zu %s, serial %" PRId64 ".", idx_path, n,
n == 1 ? "package" : "packages", serial);
return 0;
}
+435
View File
@@ -0,0 +1,435 @@
/*
* gsandbox: the build sandbox (BUILD_DESIGN.txt section 6). Run by
* gpkg/syspkg, not by hand; installed beside the libraries.
*
* gsandbox -X [-u USER] -p GPKG -d LAYER
* gsandbox -R [-u USER] -L DIR [-l NAME]... -w WORK -i IN -o OUT
*
* Run as root, -u is required: gsandbox drops to USER (supplementary
* groups, gid, uid) before anything else and refuses a USER whose uid
* is 0. Run as anyone else, there is no -u: it acts as its caller.
*
* -X extracts GPKG's files/ tree into LAYER (created; it must not
* exist), with the rules of an install (gl_extract_files).
*
* -R runs a build. In new user, mount, network, pid, ipc and uts
* namespaces, with the caller mapped to uid/gid 0: an overlay whose
* lower layers are DIR/NAME for each -l (the first on top) over a
* skeleton made in WORK, with WORK/upper as its writable layer; /dev's
* null, zero, full, random, urandom and tty bound in; a fresh /proc;
* IN read-only at /.glacier/in and OUT writable at /.glacier/out; then
* pivot_root into it, no new privileges, a clean environment, and
* /bin/sh /.glacier/in/driver as pid 1. The network namespace has only
* a loopback, down. Everything the build writes outside OUT lands in
* WORK/upper, which the caller deletes.
*
* Exit: -X 0 or 1; -R the driver's status (128 + signal if killed), or
* 125 if the sandbox could not be set up (having said why).
*/
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <grp.h>
#include <limits.h>
#include <pwd.h>
#include <sched.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "istoreutils.h"
#include "log.h"
#include "pkg.h"
#define SETUP_FAILED 125
#define MAX_LAYERS 256
#define USAGE \
"usage: gsandbox [-hv]\n" \
" gsandbox -X [-u USER] -p GPKG -d LAYER\n" \
" gsandbox -R [-u USER] -L DIR [-l NAME]... -w WORK -i IN -o OUT\n"
static const struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ "extract", no_argument, NULL, 'X' },
{ "run", no_argument, NULL, 'R' },
{ "user", required_argument, NULL, 'u' },
{ "package", required_argument, NULL, 'p' },
{ "dest", required_argument, NULL, 'd' },
{ "layers", required_argument, NULL, 'L' },
{ "layer", required_argument, NULL, 'l' },
{ "work", required_argument, NULL, 'w' },
{ "in", required_argument, NULL, 'i' },
{ "out", required_argument, NULL, 'o' },
{ NULL, 0, NULL, 0 }
};
static void
usage(void)
{
fprintf(stderr, USAGE);
}
static void
help(void)
{
printf("gsandbox: Run Glacier package builds in a sandbox\n");
printf(USAGE);
printf("\n");
printf("%-25s %s\n", "{-h --help}", "Show this message");
printf("%-25s %s\n", "{-v --version}", "Show the current version");
printf("%-25s %s\n", "{-X --extract}", "Extract a package into a build layer");
printf("%-25s %s\n", "{-R --run}", "Run a build");
printf("%-25s %s\n", "{-u --user} USER", "Build as USER (required as root)");
printf("%-25s %s\n", "{-p --package} GPKG", "Package to extract");
printf("%-25s %s\n", "{-d --dest} LAYER", "Layer directory to create");
printf("%-25s %s\n", "{-L --layers} DIR", "Directory holding the layers");
printf("%-25s %s\n", "{-l --layer} NAME", "Add a layer, first on top");
printf("%-25s %s\n", "{-w --work} WORK", "Work directory");
printf("%-25s %s\n", "{-i --in} IN", "Build input, read-only");
printf("%-25s %s\n", "{-o --out} OUT", "Build output");
printf("\n");
printf("This program is free software.\n");
printf("See the GNU GPL version 3 for details.\n");
}
/* As root: become USER for good. Elsewhere: USER must not be given. */
static int
drop_privileges(const char *user)
{
if (geteuid() != 0) {
if (user) {
lg_printf(LG_ERR, "-u needs root.");
return -1;
}
return 0;
}
if (!user) {
lg_printf(LG_ERR, "Refusing to build as root: -u is required.");
return -1;
}
struct passwd *pw = getpwnam(user);
if (!pw) {
lg_printf(LG_ERR, "No user named %s.", user);
return -1;
}
if (pw->pw_uid == 0 || pw->pw_gid == 0) {
lg_printf(LG_ERR, "Refusing to build as %s: its uid or gid is 0.", user);
return -1;
}
if (setgroups(0, NULL) != 0 || setgid(pw->pw_gid) != 0 ||
setuid(pw->pw_uid) != 0) {
lg_printf(LG_ERR, "Cannot become %s: %s", user, strerror(errno));
return -1;
}
if (setuid(0) == 0 || geteuid() == 0 || getegid() == 0) {
lg_printf(LG_ERR, "Cannot drop root.");
return -1;
}
/* Changing uid made the process non-dumpable, which leaves
* /proc/self owned by root: it could not write its own uid_map.
* Nothing of root's is left in it to protect. */
if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) != 0) {
lg_printf(LG_ERR, "Cannot drop root.");
return -1;
}
return 0;
}
static int
write_file(const char *path, const char *text)
{
int fd = open(path, O_WRONLY | O_CLOEXEC);
if (fd < 0)
return -1;
ssize_t n = write(fd, text, strlen(text));
int rc = (n == (ssize_t)strlen(text)) ? 0 : -1;
close(fd);
return rc;
}
static int
make_file(const char *path, const char *text, mode_t mode)
{
int fd = open(path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, mode);
if (fd < 0)
return -1;
ssize_t n = write(fd, text, strlen(text));
int rc = (n == (ssize_t)strlen(text) && fchmod(fd, mode) == 0) ? 0 : -1;
close(fd);
return rc;
}
/* The lowest layer: the merged-/usr links gl_create_fs_tree makes, the
* mount points, a root user and the build directory. */
static int
make_skeleton(const char *skel)
{
static const char *const dirs[] = { "", "usr", "usr/bin", "usr/lib",
"etc", "dev", "proc", "tmp", "build", ".glacier", ".glacier/in",
".glacier/out", NULL };
static const char *const links[][2] = { { "bin", "usr/bin" },
{ "sbin", "usr/bin" }, { "lib", "usr/lib" }, { "usr/sbin", "bin" } };
char p[PATH_MAX];
for (size_t i = 0; dirs[i]; i++) {
snprintf(p, sizeof p, "%s/%s", skel, dirs[i]);
if (mkdir(p, 0755) != 0 || chmod(p, 0755) != 0)
return -1;
}
snprintf(p, sizeof p, "%s/tmp", skel);
if (chmod(p, 01777) != 0)
return -1;
for (size_t i = 0; i < sizeof links / sizeof *links; i++) {
snprintf(p, sizeof p, "%s/%s", skel, links[i][0]);
if (symlink(links[i][1], p) != 0)
return -1;
}
snprintf(p, sizeof p, "%s/etc/passwd", skel);
if (make_file(p, "root:x:0:0:root:/tmp:/bin/sh\n", 0644) != 0)
return -1;
snprintf(p, sizeof p, "%s/etc/group", skel);
return make_file(p, "root:x:0:\n", 0644);
}
/* A path that can go into overlayfs's option string as is. */
static bool
plain_path(const char *s)
{
return *s == '/' && !strpbrk(s, ",:\\") && strlen(s) < 1024;
}
static int
bind_dir(const char *src, const char *dst, bool ro)
{
if (mount(src, dst, NULL, MS_BIND | MS_REC, NULL) != 0)
return -1;
unsigned long fl = MS_BIND | MS_REMOUNT | MS_NOSUID | MS_NODEV | (ro ? MS_RDONLY : 0);
return mount(NULL, dst, NULL, fl, NULL);
}
#define FAIL(...) do { lg_printf(LG_ERR, __VA_ARGS__); _exit(SETUP_FAILED); } while (0)
/* Pid 1 of the new namespaces: mount the root, enter it, run the driver. */
static void
child(const char *ldir, char **layers, size_t nlayers, const char *work,
const char *in, const char *out)
{
char skel[PATH_MAX], upper[PATH_MAX], ovl[PATH_MAX], root[PATH_MAX];
snprintf(skel, sizeof skel, "%s/skel", work);
snprintf(upper, sizeof upper, "%s/upper", work);
snprintf(ovl, sizeof ovl, "%s/ovl", work);
snprintf(root, sizeof root, "%s/root", work);
if (mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL) != 0)
FAIL("Cannot make the mounts private: %s", strerror(errno));
/* Layer names relative to DIR keep the option string short. */
if (chdir(ldir) != 0)
FAIL("Cannot enter %s: %s", ldir, strerror(errno));
size_t cap = 3 * PATH_MAX + 64, used = 0;
for (size_t i = 0; i < nlayers; i++)
cap += strlen(layers[i]) + 1;
char *opts = malloc(cap);
if (!opts)
FAIL("Out of memory.");
used += (size_t)snprintf(opts, cap, "lowerdir=");
for (size_t i = 0; i < nlayers; i++)
used += (size_t)snprintf(opts + used, cap - used, "%s:", layers[i]);
/* userxattr: inside a user namespace overlayfs can't set its
* trusted.* xattrs, so without it a directory removed and made
* again in the build root would show the layer's old contents
* (no opaque marker). Kernels before 5.11 don't know the option. */
used += (size_t)snprintf(opts + used, cap - used,
"%s,upperdir=%s,workdir=%s", skel, upper, ovl);
snprintf(opts + used, cap - used, ",userxattr");
if (mount("overlay", root, "overlay", MS_NOSUID | MS_NODEV, opts) != 0) {
opts[used] = '\0';
if (errno != EINVAL ||
mount("overlay", root, "overlay", MS_NOSUID | MS_NODEV, opts) != 0)
FAIL("Cannot mount the build root: %s", strerror(errno));
}
free(opts);
static const char *const devs[] = { "null", "zero", "full", "random",
"urandom", "tty", NULL };
char p[PATH_MAX], h[PATH_MAX];
for (size_t i = 0; devs[i]; i++) {
snprintf(h, sizeof h, "/dev/%s", devs[i]);
if (access(h, F_OK) != 0)
continue;
snprintf(p, sizeof p, "%s/dev/%s", root, devs[i]);
int fd = open(p, O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0666);
if (fd < 0)
FAIL("Cannot create %s: %s", p, strerror(errno));
close(fd);
if (mount(h, p, NULL, MS_BIND, NULL) != 0)
FAIL("Cannot bind %s: %s", h, strerror(errno));
}
snprintf(p, sizeof p, "%s/proc", root);
if (mount("proc", p, "proc", MS_NOSUID | MS_NODEV | MS_NOEXEC, NULL) != 0)
FAIL("Cannot mount /proc: %s", strerror(errno));
snprintf(p, sizeof p, "%s/.glacier/in", root);
if (bind_dir(in, p, true) != 0)
FAIL("Cannot bind %s: %s", in, strerror(errno));
snprintf(p, sizeof p, "%s/.glacier/out", root);
if (bind_dir(out, p, false) != 0)
FAIL("Cannot bind %s: %s", out, strerror(errno));
if (chdir(root) != 0 || syscall(SYS_pivot_root, ".", ".") != 0 ||
umount2(".", MNT_DETACH) != 0 || chdir("/") != 0)
FAIL("Cannot enter the build root: %s", strerror(errno));
if (sethostname("glacier-build", 13) != 0 ||
prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0)
FAIL("Cannot set up the build: %s", strerror(errno));
for (int fd = 3; fd < 1024; fd++)
close(fd);
char *const argv[] = { "/bin/sh", "/.glacier/in/driver", NULL };
char *const envp[] = { "PATH=/usr/bin:/bin", "HOME=/tmp", "LC_ALL=C",
"TZ=UTC", "TERM=dumb", "FORCE_UNSAFE_CONFIGURE=1", NULL };
execve(argv[0], argv, envp);
FAIL("Cannot run the build driver: %s", strerror(errno));
}
static int
run(const char *ldir, char **layers, size_t nlayers, const char *work,
const char *in, const char *out)
{
if (!plain_path(work) || !plain_path(ldir) || !plain_path(in) || !plain_path(out)) {
lg_printf(LG_ERR, "Refusing a path that is not absolute or holds ',', ':' or '\\'.");
return SETUP_FAILED;
}
for (size_t i = 0; i < nlayers; i++) {
if (!gl_valid_pkg_ident(layers[i])) {
lg_printf(LG_ERR, "Refusing layer name %s.", layers[i]);
return SETUP_FAILED;
}
}
char p[PATH_MAX];
const char *subdirs[] = { "upper", "ovl", "root" };
for (size_t i = 0; i < 3; i++) {
snprintf(p, sizeof p, "%s/%s", work, subdirs[i]);
if (mkdir(p, 0700) != 0) {
lg_printf(LG_ERR, "Cannot create %s: %s", p, strerror(errno));
return SETUP_FAILED;
}
}
snprintf(p, sizeof p, "%s/skel", work);
if (make_skeleton(p) != 0) {
lg_printf(LG_ERR, "Cannot create %s: %s", p, strerror(errno));
return SETUP_FAILED;
}
uid_t uid = getuid();
gid_t gid = getgid();
if (unshare(CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWNET | CLONE_NEWPID |
CLONE_NEWIPC | CLONE_NEWUTS) != 0) {
lg_printf(LG_ERR, "Builds need unprivileged user namespaces.");
return SETUP_FAILED;
}
char map[64];
snprintf(map, sizeof map, "0 %u 1\n", (unsigned)uid);
if (write_file("/proc/self/setgroups", "deny") != 0 ||
write_file("/proc/self/uid_map", map) != 0) {
lg_printf(LG_ERR, "Cannot map the build user: %s", strerror(errno));
return SETUP_FAILED;
}
snprintf(map, sizeof map, "0 %u 1\n", (unsigned)gid);
if (write_file("/proc/self/gid_map", map) != 0) {
lg_printf(LG_ERR, "Cannot map the build group: %s", strerror(errno));
return SETUP_FAILED;
}
pid_t pid = fork();
if (pid < 0) {
lg_printf(LG_ERR, "Cannot start the build: %s", strerror(errno));
return SETUP_FAILED;
}
if (pid == 0)
child(ldir, layers, nlayers, work, in, out);
int status;
while (waitpid(pid, &status, 0) < 0) {
if (errno != EINTR)
return SETUP_FAILED;
}
if (WIFSIGNALED(status))
return 128 + WTERMSIG(status);
return WEXITSTATUS(status);
}
int
main(int argc, char *argv[])
{
const char *user = NULL, *pkg = NULL, *dest = NULL, *ldir = NULL;
const char *work = NULL, *in = NULL, *out = NULL;
char *layers[MAX_LAYERS];
size_t nlayers = 0;
int mode = 0, c;
while ((c = getopt_long(argc, argv, "hvXRu:p:d:L:l:w:i:o:", longopts, NULL)) != -1) {
switch (c) {
case 'h':
help();
return 0;
case 'v':
printf("v4.0.0\n");
return 0;
case 'X':
case 'R':
if (mode && mode != c) {
usage();
return 1;
}
mode = c;
break;
case 'u': user = optarg; break;
case 'p': pkg = optarg; break;
case 'd': dest = optarg; break;
case 'L': ldir = optarg; break;
case 'l':
if (nlayers == MAX_LAYERS) {
lg_printf(LG_ERR, "At most %d layers.", MAX_LAYERS);
return 1;
}
layers[nlayers++] = optarg;
break;
case 'w': work = optarg; break;
case 'i': in = optarg; break;
case 'o': out = optarg; break;
default:
usage();
return 1;
}
}
if (optind != argc || (mode == 'X' && (!pkg || !dest || ldir || nlayers || work || in || out)) ||
(mode == 'R' && (!ldir || !work || !in || !out || pkg || dest)) || !mode) {
usage();
return 1;
}
if (drop_privileges(user) != 0)
return mode == 'R' ? SETUP_FAILED : 1;
if (mode == 'X') {
gl_install_status_t st = gl_extract_files(pkg, dest);
if (st != GL_INSTALL_OK) {
lg_printf(LG_ERR, "Cannot extract %s into %s.", pkg, dest);
return 1;
}
return 0;
}
return run(ldir, layers, nlayers, work, in, out);
}
+57
View File
@@ -0,0 +1,57 @@
#include <getopt.h>
#include <stdio.h>
#include "sha256.h"
#define USAGE "usage: gsha256sum [-hv] FILE\n"
static const struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ NULL, 0, NULL, 0 }
};
static void
help(void)
{
printf("gsha256sum: Print a file's sha256 as a Glacier sidecar line\n");
printf(USAGE);
printf("\n");
printf("%-25s %s\n", "{-h --help}", "Show this message");
printf("%-25s %s\n", "{-v --version}", "Show the current version");
printf("\n");
printf("This program is free software.\n");
printf("See the GNU GPL version 3 for details.\n");
}
int
main(int argc, char *argv[])
{
int c;
while ((c = getopt_long(argc, argv, "hv", longopts, NULL)) != -1) {
switch (c) {
case 'h':
help();
return 0;
case 'v':
printf("v4.0.0\n");
return 0;
default:
fprintf(stderr, USAGE);
return 1;
}
}
if (optind != argc - 1) {
fprintf(stderr, USAGE);
return 1;
}
char hex[GL_SHA256_HEX_SIZE];
if (gl_sha256_file(argv[optind], hex) != 0) {
perror(argv[optind]);
return 1;
}
printf("sha256:%s\n", hex);
return 0;
}
+212
View File
@@ -0,0 +1,212 @@
/*
* gsign: make signify-compatible Ed25519 keys and signatures
* (REPO_DESIGN.txt section 2). A build/maintainer tool, like
* gsha256sum.
*
* gsign -G -p KEY.pub -s KEY.sec [-c COMMENT]
* gsign -S -s KEY.sec -m FILE [-x SIGFILE]
* gsign -V -p KEY.pub -m FILE [-x SIGFILE]
*
* SIGFILE defaults to FILE.sig. Exit 0 on success, 1 otherwise.
*/
#define _POSIX_C_SOURCE 200809L
#include <getopt.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "log.h"
#include "sign.h"
#define USAGE \
"usage: gsign [-hv]\n" \
" gsign -G -p KEY.pub -s KEY.sec [-c COMMENT]\n" \
" gsign -S -s KEY.sec -m FILE [-x SIGFILE]\n" \
" gsign -V -p KEY.pub -m FILE [-x SIGFILE]\n"
static const struct option longopts[] = {
{ "help", no_argument, NULL, 'h' },
{ "version", no_argument, NULL, 'v' },
{ "generate", no_argument, NULL, 'G' },
{ "sign", no_argument, NULL, 'S' },
{ "verify", no_argument, NULL, 'V' },
{ "pubkey", required_argument, NULL, 'p' },
{ "seckey", required_argument, NULL, 's' },
{ "message", required_argument, NULL, 'm' },
{ "sig", required_argument, NULL, 'x' },
{ "comment", required_argument, NULL, 'c' },
{ NULL, 0, NULL, 0 }
};
static void
usage(void)
{
fprintf(stderr, USAGE);
}
static void
help(void)
{
printf("gsign: Make and check signify-compatible signatures\n");
printf(USAGE);
printf("\n");
printf("%-25s %s\n", "{-h --help}", "Show this message");
printf("%-25s %s\n", "{-v --version}", "Show the current version");
printf("%-25s %s\n", "{-G --generate}", "Generate a new key pair");
printf("%-25s %s\n", "{-S --sign}", "Sign a file");
printf("%-25s %s\n", "{-V --verify}", "Verify a file's signature");
printf("%-25s %s\n", "{-p --pubkey} KEY.pub", "Public key file");
printf("%-25s %s\n", "{-s --seckey} KEY.sec", "Secret key file");
printf("%-25s %s\n", "{-m --message} FILE", "File to sign or verify");
printf("%-25s %s\n", "{-x --sig} SIGFILE", "Signature file (default: FILE.sig)");
printf("%-25s %s\n", "{-c --comment} COMMENT", "Comment for a new key pair (default: gsign)");
printf("\n");
printf("This program is free software.\n");
printf("See the GNU GPL version 3 for details.\n");
}
/* "<what> <path> <problem>." about one file. */
static int
fail(const char *what, const char *path, int st)
{
const char *problem;
switch (st) {
case GL_SIGN_ERR_FORMAT: problem = "is malformed"; break;
case GL_SIGN_ERR_ENCRYPTED: problem = "is encrypted: sign with signify"; break;
case GL_SIGN_ERR_TOOBIG: problem = "is too large"; break;
case GL_SIGN_ERR_EXISTS: problem = "already exists"; break;
case GL_SIGN_ERR_WRITE: problem = "cannot be written"; break;
default: problem = "cannot be read"; break;
}
lg_printf(LG_ERR, "%s %s %s.", what, path, problem);
return 1;
}
int
main(int argc, char *argv[])
{
char mode = 0;
const char *pub = NULL, *sec = NULL, *msg = NULL, *sig = NULL;
const char *comment = "gsign";
int c;
while ((c = getopt_long(argc, argv, "hvGSVp:s:m:x:c:", longopts, NULL)) != -1) {
switch (c) {
case 'h':
help();
return 0;
case 'v':
printf("v4.0.0\n");
return 0;
case 'G': case 'S': case 'V':
if (mode && mode != c) {
usage();
return 1;
}
mode = (char)c;
break;
case 'p': pub = optarg; break;
case 's': sec = optarg; break;
case 'm': msg = optarg; break;
case 'x': sig = optarg; break;
case 'c': comment = optarg; break;
default:
usage();
return 1;
}
}
if (optind != argc) {
usage();
return 1;
}
char sigbuf[PATH_MAX];
if (msg && !sig) {
if ((size_t)snprintf(sigbuf, sizeof sigbuf, "%s.sig", msg) >= sizeof sigbuf) {
lg_printf(LG_ERR, "Path too long: %s", msg);
return 1;
}
sig = sigbuf;
}
int st;
switch (mode) {
case 'G':
if (!pub || !sec || msg) {
usage();
return 1;
}
/* The library refuses these too (O_EXCL); this names which. */
struct stat sb;
if (lstat(sec, &sb) == 0)
return fail("Secret key", sec, GL_SIGN_ERR_EXISTS);
if (lstat(pub, &sb) == 0)
return fail("Public key", pub, GL_SIGN_ERR_EXISTS);
st = gl_sign_generate(pub, sec, comment);
if (st == GL_SIGN_ERR_FORMAT) {
lg_printf(LG_ERR, "Comment must be one line, at most %d characters.",
GL_SIGN_MAX_COMMENT - 11);
return 1;
}
if (st == GL_SIGN_ERR_RANDOM) {
lg_printf(LG_ERR, "Cannot get random bytes for a new key.");
return 1;
}
if (st != GL_SIGN_OK) {
lg_printf(LG_ERR, "Cannot write %s and %s.", pub, sec);
return 1;
}
lg_printf(LG_SUCCESS, "Wrote %s and %s.", pub, sec);
return 0;
case 'S':
if (!sec || !msg || pub) {
usage();
return 1;
}
if ((st = gl_sign_check_seckey(sec)) != GL_SIGN_OK)
return fail("Secret key", sec, st);
st = gl_sign_file(sec, msg, sig);
if (st == GL_SIGN_ERR_WRITE)
return fail("Signature", sig, st);
if (st != GL_SIGN_OK)
return fail("File", msg, st);
lg_printf(LG_SUCCESS, "Signed %s: %s.", msg, sig);
return 0;
case 'V': {
if (!pub || !msg || sec) {
usage();
return 1;
}
gl_sign_pubkey_t pk;
gl_sign_sig_t sg;
if ((st = gl_sign_read_pubkey(pub, &pk)) != GL_SIGN_OK)
return fail("Public key", pub, st);
if ((st = gl_sign_read_sig(sig, &sg)) != GL_SIGN_OK)
return fail("Signature", sig, st);
st = gl_sign_verify_file(pub, msg, sig);
switch (st) {
case GL_SIGN_OK:
lg_printf(LG_SUCCESS, "Signature verified: %s.", msg);
return 0;
case GL_SIGN_ERR_KEYNUM:
lg_printf(LG_ERR, "%s was signed by a different key than %s.", msg, pub);
return 1;
case GL_SIGN_ERR_BAD:
lg_printf(LG_ERR, "Signature does not verify: %s.", msg);
return 1;
default:
return fail("File", msg, st);
}
}
default:
usage();
return 1;
}
}
+1
View File
@@ -0,0 +1 @@
<svg version="1.1" viewBox="0.0 0.0 649.0 485.0" fill="none" stroke="none" stroke-linecap="square" stroke-miterlimit="10" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><clipPath id="p.0"><path d="m0 0l649.0 0l0 485.0l-649.0 0l0 -485.0z" clip-rule="nonzero"/></clipPath><g clip-path="url(#p.0)"><path fill="#000000" fill-opacity="0.0" d="m0 0l649.0 0l0 485.0l-649.0 0z" fill-rule="evenodd"/><path fill="#88c0d0" d="m31.519686 468.3622l194.38202 -378.26773l133.83844 378.26773z" fill-rule="evenodd"/><path stroke="#88c0d0" stroke-width="2.0" stroke-linejoin="round" stroke-linecap="butt" d="m31.519686 468.3622l194.38202 -378.26773l133.83844 378.26773z" fill-rule="evenodd"/><path fill="#5e81ac" d="m412.7575 222.75516l-135.9685 261.5433l-135.9685 -261.5433z" fill-rule="evenodd"/><path stroke="#5e81ac" stroke-width="2.0" stroke-linejoin="round" stroke-linecap="butt" d="m412.7575 222.75516l-135.9685 261.5433l-135.9685 -261.5433z" fill-rule="evenodd"/><path fill="#666666" d="m276.48984 484.30145l135.9685 -261.5433l135.96854 261.5433z" fill-rule="evenodd"/><path stroke="#666666" stroke-width="2.0" stroke-linejoin="round" stroke-linecap="butt" d="m276.48984 484.30145l135.9685 -261.5433l135.96854 261.5433z" fill-rule="evenodd"/><path fill="#5e81ac" d="m0 484.29922l130.77936 -246.89764l98.44899 246.89764z" fill-rule="evenodd"/><path stroke="#5e81ac" stroke-width="2.0" stroke-linejoin="round" stroke-linecap="butt" d="m0 484.29922l130.77936 -246.89764l98.44899 246.89764z" fill-rule="evenodd"/><path fill="#5e81ac" d="m276.4908 484.3176l185.43307 -378.26773l185.43304 378.26773z" fill-rule="evenodd"/><path stroke="#5e81ac" stroke-width="2.0" stroke-linejoin="round" stroke-linecap="butt" d="m276.4908 484.3176l185.43307 -378.26773l185.43304 378.26773z" fill-rule="evenodd"/><path fill="#88c0d0" d="m205.22047 134.99213l71.574814 -134.99213l71.5748 134.99213z" fill-rule="evenodd"/><path stroke="#88c0d0" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m205.22047 134.99213l71.574814 -134.99213l71.5748 134.99213z" fill-rule="evenodd"/><path fill="#5e81ac" d="m140.82677 222.7559l70.13112 -134.99213l131.67477 0l70.131134 134.99213z" fill-rule="evenodd"/><path stroke="#5e81ac" stroke-width="2.0" stroke-linejoin="round" stroke-linecap="butt" d="m140.82677 222.7559l70.13112 -134.99213l131.67477 0l70.131134 134.99213z" fill-rule="evenodd"/><path fill="#5e81ac" d="m205.21523 99.13386l30.761414 -63.27559l112.3882 63.27559z" fill-rule="evenodd"/><path stroke="#5e81ac" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m205.21523 99.13386l30.761414 -63.27559l112.3882 63.27559z" fill-rule="evenodd"/><path fill="#5e81ac" d="m205.22047 199.58267l195.68504 0l0 110.77167l-195.68504 0z" fill-rule="evenodd"/><path stroke="#5e81ac" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m205.22047 199.58267l195.68504 0l0 110.77167l-195.68504 0z" fill-rule="evenodd"/><path fill="#5e81ac" d="m385.25198 283.9475l-106.83533 198.3937l-97.82611 -198.3937z" fill-rule="evenodd"/><path stroke="#5e81ac" stroke-width="1.0" stroke-linejoin="round" stroke-linecap="butt" d="m385.25198 283.9475l-106.83533 198.3937l-97.82611 -198.3937z" fill-rule="evenodd"/></g></svg>

After

Width:  |  Height:  |  Size: 3.2 KiB

+1
View File
@@ -0,0 +1 @@
<svg version="1.1" viewBox="0.0 0.0 433.41207349081367 433.5275590551181" fill="none" stroke="none" stroke-linecap="square" stroke-miterlimit="10" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><clipPath id="p.0"><path d="m0 0l433.41208 0l0 433.52756l-433.41208 0l0 -433.52756z" clip-rule="nonzero"/></clipPath><g clip-path="url(#p.0)"><path fill="#000000" fill-opacity="0.0" d="m0 0l433.41208 0l0 433.52756l-433.41208 0z" fill-rule="evenodd"/><path fill="#88c0d0" d="m0 433.38583l392.89893 -433.38583l40.486908 0l-392.89893 433.38583z" fill-rule="evenodd"/><path fill="#88c0d0" d="m433.38583 433.38583l-392.89893 -433.38583l-40.486904 0l392.89893 433.38583z" fill-rule="evenodd"/><path fill="#5e81ac" d="m199.2126 0l34.960632 0l0 433.38583l-34.960632 0z" fill-rule="evenodd"/><path fill="#5e81ac" d="m433.38583 199.2126l0 34.960632l-433.38583 0l0 -34.960632z" fill-rule="evenodd"/></g></svg>

After

Width:  |  Height:  |  Size: 923 B

+347
View File
@@ -0,0 +1,347 @@
/* css/k2.css - stylesheet for everest-web */
/* Sidebar menu */
.sidenav {
height: 100%;
width: 200px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #1a2030;
overflow-x: hidden;
padding-top: 20px;
}
/* Menu links */
.sidenav a {
padding: 6px 8px 6px 16px;
text-decoration: none;
font-size: 20px;
color: #a0b4cc;
display: block;
}
.sidenav a:hover {
color: #4a86e8;
}
html {
background-color: #1e2535;
color: #a0b4cc;
}
.main {
margin-left: 200px;
padding: 0px 10px;
background-color: #1e2535;
}
.file {
font-family: monospace;
background-color: #141820;
border-left: 4px solid #3a9e78;
border-radius: 2px;
padding: 4px;
/*width: 50%;*/
color: #a0b4cc;
}
.kernel {
font-family: monospace;
background-color: #141820;
border-left: 4px solid #7a6eda;
border-radius: 2px;
padding: 4px;
/*width: 50%;*/
color: #a0b4cc;
}
.note {
background-color: #141c2e;
border-left: 4px solid #4a86e8;
border-radius: 2px;
padding: 4px;
/*width: 50%;*/
color: #a0b4cc;
}
.caution {
background-color: #2a1e00;
border-left: 4px solid #e8a83a;
border-radius: 2px;
padding: 4px;
/*width: 50%;*/
color: #e8a83a;
}
.warning {
background-color: #2a0e08;
border-left: 4px solid #e85a4a;
border-radius: 2px;
padding: 4px;
/*width: 50%;*/
color: #e85a4a;
}
.news {
background-color: #1a2030;
border-left: 4px solid #4a86e8;
border-radius: 2px;
padding: 4px;
/*width: 50%;*/
color: #a0b4cc;
}
table, td {
border: 2px solid #a0b4cc;
border-collapse: collapse;
padding: 4px;
background-color: #141820;
color: #a0b4cc;
}
th {
border: 2px solid #a0b4cc;
background-color: #252d3d;
color: #e8eef8;
}
notehead {
background-color: #141c2e;
border-left: 4px solid #4a86e8;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #4a86e8;
}
fhead {
background-color: #141820;
border-left: 4px solid #3a9e78;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #3a9e78;
}
khead {
background-color: #141820;
border-left: 4px solid #7a6eda;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #7a6eda;
}
cautionhead {
background-color: #2a1e00;
border-left: 4px solid #e8a83a;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #e8a83a;
}
warnhead {
background-color: #2a0e08;
border-left: 4px solid #e85a4a;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #e85a4a;
}
newshead {
background-color: #1a2030;
border-left: 4px solid #4a86e8;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #4a86e8;
}
wikihead {
border-left: 4px solid #e86a9e;
border-radius: 2px;
padding: 6px;
color: #e86a9e;
}
bigcodehead {
background-color: #141820;
border-left: 4px solid #a0b4cc;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #a0b4cc;
}
body {
font-family: sans-serif;
background-color: #1e2535;
color: #a0b4cc;
}
code {
font-family: monospace;
background-color: #141820;
border-left: 4px solid #4a86e8;
border-radius: 2px;
padding: 2px;
color: #a0b4cc;
}
.bigcode {
font-family: monospace;
background-color: #141820;
border-left: 4px solid #a0b4cc;
border-radius: 2px;
padding: 6px;
width: 50%;
}
cil {
font-family: monospace;
background-color: #141820;
padding: 2px;
}
cil-inv {
font-family: monospace;
background-color: #141820;
color: #a0b4cc;
padding: 2px;
}
wiki {
border-left: 4px solid #e86a9e;
border-radius: 2px;
padding: 6px;
}
h2 {
border-left: 6px solid #4a86e8;
padding-left: 4px;
border-radius: 5px;
color: #e8eef8;
}
button {
font-size: 24px;
border: none;
border-left: 8px solid #4a86e8;
padding: 12px 28px;
border-radius: 5px;
background-color: #252d3d;
color: #e8eef8;
}
button:hover {
background-color: #2e3850;
}
hr.dotted {
border-top: 3px dotted #607080;
}
hr {
color: #4a86e8;
width: 50%;
border-width: 4px;
border-radius: 5px;
margin-left: 0;
}
footer {
text-align: center;
font-size: 10px;
padding: 20px;
}
#myInput {
width: 378px;
font-size: 16px;
padding: 10px;
border: 2px solid #4a86e8;
border-radius: 2px;
margin-bottom: 12px;
background-color: #252d3d;
color: #e8eef8;
}
#myUL {
width: 400px;
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border-left: 2px solid #4a86e8;
margin-top: -1px;
background-color: #252d3d;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: #e8eef8;
display: block;
}
#myUL li a:hover:not(.header) {
background-color: #1e2535;
}
img {
padding: 8px;
}
body, html {
height: 100%;
}
.hero-image {
background-image: linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)), url("../img/banner.jpg");
height: 55%;
background-position: 50% 30%;
background-repeat: no-repeat;
background-size: cover;
position: relative;
padding-top: 0px;
padding-right: 0px;
margin-right: -8px;
margin-top: -8px;
}
.hero-text {
text-align: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
}
.tab {
display: inline-block;
margin-left: 80px;
}
pre.bigcode {
margin-top: 0;
margin-bottom; 0;
}
.top-banner {
background-color: #4c566a;
color: #eceff4;
text-align: center;
padding: 11px 16px;
font-size: 0.9rem;
width: 100%;
box-sizing: border-box;
position: sticky;
top: 0;
z-index: 1000;
border-bottom: 2px solid #88c0d0;
}
+407
View File
@@ -0,0 +1,407 @@
/* css/everest.css - stylesheet for everest-web */
/*
Copyright (C) 2023 Everest Linux.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3
or any later version published by the Free Software Foundation;
with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
A copy of the license is included in the section entitled "GNU
Free Documentation License".
*/
/* Sidebar menu */
.sidenav {
height: 100%;
width: 200px;
position: fixed;
z-index: 1;
top: 0;
left: 0;
background-color: #2E3440;
overflow-x: hidden;
padding-top: 20px;
}
/* Menu links */
.sidenav a {
padding: 6px 8px 6px 16px;
text-decoration: none;
font-size: 20px;
color: #D8DEE9;
display: block;
}
.sidenav a:hover {
color: #88c0d0;
}
html {
background-color: #3B4252;
color: #ECEFF4;
}
.main {
margin-left: 200px;
padding: 0px 10px;
background-color: #3B4252;
}
.file {
font-family: monospace;
background-color: #2E3440;
border-left-style: solid;
border-left-color: #A3BE8C;
border-width: 4px;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #ECEFF4;
}
.kernel {
font-family: monospace;
background-color: #2E3440;
border-left-style: solid;
border-left-color: #B48EAD;
border-width: 4px;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #ECEFF4;
}
.note {
background-color: #88C0D0;
border-left-style: solid;
border-left-color: #88C0D0;
border-width: 4px;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #2E3440;
}
.caution {
background-color: #EBCB8B;
border-left-style: solid;
border-left-color: #EBCB8B;
border-width: 4px;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #2E3440;
}
.warning {
background-color: #BF616A;
border-left-style: solid;
border-left-color: #BF616A;
border-width: 4px;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #D8DEE9;
}
.news {
background-color: #2E3440;
border-left-style: solid;
border-left-color: #88C0D0;
border-width: 4px;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #ECEFF4;
}
table, td {
border: 2px solid;
border-color: #ECEFF4;
border-collapse: collapse;
padding: 4px;
background-color: #2E3440;
}
th {
border: 2px solid;
background-color: #88C0D0;
color: #2E3440;
border-color: #ECEFF4;
}
notehead {
background-color: #88C0D0;
border-left-style: solid;
border-left-color: #88C0D0;
border-width: 4px;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #2E3440;
}
fhead {
background-color: #2E3440;
border-left-style: solid;
border-left-color: #A3BE8C;
border-width: 4px;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #A3BE8C;
}
khead {
background-color: #2E3440;
border-left-style: solid;
border-left-color: #B48EAD;
border-width: 4px;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #B48EAD;
}
cautionhead {
background-color: #EBCB8B;
border-left-style: solid;
border-left-color: #EBCB8B;
border-width: 4px;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #2E3440;
}
warnhead {
background-color: #BF616A;
border-left-style: solid;
border-left-color: #BF616A;
border-width: 4px;
border-radius: 2px;
padding: 6px;
width: 50%;
color: #D8DEE9;
}
newshead {
background-color: #2E3440;
border-left-style: solid;
border-left-color: #88C0D0;
border-width: 4px;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #88C0D0;
}
wikihead {
border-left-style: solid;
border-left-color: #D08770;
border-width: 4px;
border-radius: 2px;
padding: 6px;
color: #D08770;
}
bigcodehead {
background-color: #2E3440;
border-left-style: solid;
border-left-color: #ECEFF4;
border-width: 4px;
border-radius: 2px;
padding: 4px;
width: 50%;
color: #ECEFF4;
}
@media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a{font-size: 18px;}
}
body {
font-family: sans-serif;
background-color: #3B4252;
color: #ECEFF4;
}
code {
font-family: monospace;
background-color: #2E3440;
border-left-style: solid;
border-left-width: 4px;
border-radius: 2px;
padding: 2px;
color: #ECEFF4;
}
.bigcode {
font-family: monospace;
background-color: #2E3440;
border-left-style: solid;
border-left-width: 4px;
border-radius: 2px;
padding: 6px;
border-color: #ECEFF4;
width: 50%;
}
cil {
font-family: monospace;
background-color: #2E3440;
padding: 2px;
}
cil-inv {
font-family: monospace;
background-color: #2E3440;
color: #ECEFF4;
padding: 2px;
}
wiki {
border-left-style: solid;
border-left-width: 4px;
border-radius: 2px;
padding: 6px;
border-color: #D08770;
}
/* file {
border-style: solid;
border-width: 4px;
border-radius: 2px;
padding: 2px;
border-color: black;
} */
h2 {
border-left-style: solid;
border-color: #88C0D0;
padding-left: 4px;
border-left-width: 6px;
border-radius: 5px;
color: #ECEFF4;
}
button {
font-size: 24px;
border-style: none;
border-left-style: solid;
border-width: 8px;
padding: 12px 28px;
border-color: #88C0D0;
border-radius: 5px;
background-color: #434C5E;
color: #ECEFF4;
}
button:hover {
background-color: #4C566A;
}
hr.dotted {
border-top: 3px dotted #bbb;
}
/* p {
color: #e6e6e6;
} */
/* strong {
color: #4a86e8ff;
} */
/* i {
color: #e6e6e6;
} */
footer {
text-align: center;
font-size: 10px;
padding: 20px;
}
#myInput {
width: 378px;
font-size: 16px;
padding: 10px;
border: 2px solid #88C0D0;
border-radius: 2px;
margin-bottom: 12px;
background-color: #434C5E;
color: #ECEFF4;
}
#myUL {
width: 400px;
list-style-type: none;
padding: 0;
margin: 0;
}
#myUL li a {
border-left-width: 2px;
border-left-style: solid;
border-left-color: #88C0D0;
margin-top: -1px;
background-color: #434C5E;
padding: 12px;
text-decoration: none;
font-size: 18px;
color: #ECEFF4;
display: block;
}
#myUL li a:hover:not(.header) {
background-color: #4C566A;
}
img {
padding: 8px;
}
/* */
body, html {
height: 100%;
}
/* The hero image */
.hero-image {
background-image: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("../img/banner.jpg");
height: 55%;
background-position: 50% 30%;
background-repeat: no-repeat;
background-size: cover;
position: relative;
padding-top: 0px;
padding-right: 0px;
margin-right: -8px;
margin-top: -8px;
}
.hero-text {
text-align: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
}
hr {
color: #88c0d0;
width: 50%;
border-width: 4px;
border-radius: 5px;
margin-left: 0;
}
.tab {
display: inline-block;
margin-left: 80px;
}
+46
View File
@@ -0,0 +1,46 @@
<!DOCTYPE html>
<html>
<head>
<title>Glacier Packaging Report</title>
<link type="text/css" rel="stylesheet" href="k2.css"/>
</head>
<body>
<div class="sidenav">
<img src="img/glacier-nord.svg" alt="glacier-logo">
</div>
<div class="main">
<h1>Packaging report: [DATE HERE]</h1>
<hr></hr>
<h2>Statistics</h2>
<p>Total transactions: 2</p>
<p>Completed transactions: 0</p>
<p>Failed transactions: 2</p>
<bigcodehead><strong>Indices modified</strong></bigcodehead>
<div class="bigcode">
<p>f localhost:/glacier/usr/index/1000/index-03_24_2026@15:11</p>
</div>
<h2>Systems</h2>
<bigcodehead><strong>Systems modified</strong></bigcodehead>
<div class="bigcode">
<p>* localhost</p>
</div>
<h2>Insights</h2>
<!--PACKAGE INSIGHTS BEGIN HERE-->
<bigcodehead><strong>base::glibc-2.43.0</strong></bigcodehead>
<div class="bigcode">
<p>d localhost:/glacier/usr/store/1000/base/glibc-2.43.0</p>
</div>
<p></p>
<bigcodehead><strong>base::vim-9.2.0</strong></bigcodehead>
<div class="bigcode">
<p>d localhost:/glacier/usr/store/1000/base/vim-9.2.0</p>
</div>
<h2>Problems</h2>
<div class="warning">
<p>[x] ACTUAL signature for base::glibc-2.43.0 differs from EXPECTED</p>
<p>[x] ACTUAL signature for base::vim-9.2.0 differs from EXPECTED</p>
<p>[x] One or more packages did not pass integrity checks!</p></div>
</div>
</body>
</html>
+52
View File
@@ -0,0 +1,52 @@
<!DOCTYPE html>
<html>
<head>
<title>Glacier Packaging Report</title>
<link type="text/css" rel="stylesheet" href="k2.css"/>
</head>
<body>
<div class="sidenav">
<img src="img/glacier-nord.svg" alt="glacier-logo">
</div>
<div class="main">
<h1>Packaging report: [DATE HERE]</h1>
<hr></hr>
<h2>Statistics</h2>
<p>Total transactions: [N_TRANSACTIONS]</p>
<p>Completed transactions: [N_COMP_TRANSACT]</p>
<p>Failed transactions: [N_FAIL_TRANSACT]</p>
<bigcodehead><strong>Indices modified</strong></bigcodehead>
<div class="bigcode">
<p>f localhost:/glacier/usr/index/1000/mmddyyyy@hhmm</p>
<p>f 192.168.30.1:/glacier/usr/index/1000/mmddyyyy@hhmm</p>
<p>f 192.168.30.2:/glacier/usr/index/1000/mmddyyyy@hhmm</p>
</div>
<h2>Systems</h2>
<bigcodehead><strong>Systems modified</strong></bigcodehead>
<div class="bigcode">
<p>* localhost</p>
<p>* 192.168.30.0/24</p>
<p>&emsp;&emsp;&emsp;&emsp;* 192.168.30.1</p>
<p>&emsp;&emsp;&emsp;&emsp;* 192.168.30.2</p>
</div>
<h2>Insights</h2>
<!--PACKAGE INSIGHTS BEGIN HERE-->
<bigcodehead><strong>world::foo-1.0.1</strong></bigcodehead>
<div class="bigcode">
<p>d localhost:/glacier/usr/store/1000/world::foo-1.0.1</p>
<p>d 192.168.30.1:/glacier/usr/store/1000/world::foo-1.0.1</p>
<p>d 192.168.30.2:/glacier/usr/store/1000/world::foo-1.0.1</p>
</div>
<p></p>
<bigcodehead><strong>world::bar-2.3.5</strong></bigcodehead>
<div class="bigcode">
<p>d localhost:/glacier/usr/store/1000/world::bar-2.3.5</p>
<p>d 192.168.30.1:/glacier/usr/store/1000/world::bar-2.3.5</p>
<p>d 192.168.30.2:/glacier/usr/store/1000/workd::bar-2.3.5</p>
</div>
<h2>Problems</h2>
<p>No problems to report.</p>
</div>
</body>
</html>
+2489
View File
File diff suppressed because it is too large. Load diff
+98
View File
@@ -0,0 +1,98 @@
#ifndef ISTOREUTILS_H_
#define ISTOREUTILS_H_
#include <stdbool.h>
#include <stdio.h>
#include <sys/types.h>
#include "pkg.h"
#include "transaction.h"
typedef enum {
INDEX,
STORE
}
index_store_t;
typedef enum {
GL_BACKUP_OK = 0,
GL_BACKUP_ERR_ALLOC = 1,
GL_BACKUP_ERR_OPEN = 2,
GL_BACKUP_ERR_ADD_INDEX = 3,
GL_BACKUP_ERR_ADD_STORE = 4,
GL_BACKUP_ERR_ADD_LINKS = 5,
GL_BACKUP_ERR_CLOSE = 6
}
gl_backup_status_t;
/*
* GL_INSTALL_OK: installation successful
* GL_INSTALL_ERR_OPEN: unable to open .gpkg file
* GL_INSTALL_ERR_MANIFEST: manifest is missing or unparseable
* GL_INSTALL_ERR_EXTRACT: unable to extract files
* GL_INSTALL_ERR_INDEX: unable to update index
* GL_INSTALL_ERR_ALREADY_INSTALLED: package already installed
* GL_INSTALL_ERR_SCOPE: base-repo package under user scope
* GL_INSTALL_ERR_DEPS: unmet dependency or conflict (live context only;
* a staged install is checked at commit, GL_TXN_ERR_DEPS)
*/
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, /* live context only; see deps.h */
}
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, /* live context only; see deps.h */
} gl_remove_status_t;
bool gl_usr_istore_exists(index_store_t index_or_store, int uid);
int gl_usr_base_status(uid_t uid);
int gl_backup_pkg(gl_context_t *ctx, const char *repo, const char *name, const char *out_path);
int gl_prune_backups(const char *dir, int keep);
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);
int gl_rebuild_index(gl_context_t *ctx);
gl_install_status_t gl_extract_files(const char *gpkg_path, const char *dest);
typedef struct {
char **repos;
size_t count;
}
gl_repo_list_t;
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_backup_status_t gl_backup_istore(const char *tar_path, const char *glacier_root,
const char *uid);
int gl_read_pkg_manifest(const char *gpkg_path, gl_pkg_t *pkg);
gl_install_status_t gl_install_pkg(gl_context_t *ctx, const char *gpkg_path);
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);
gl_remove_status_t gl_remove_pkg(gl_context_t *ctx, const char *pkg_name, const char *pkg_repo);
int gl_relink_store(gl_context_t *ctx);
#endif
+60 -101
View File
@@ -8,19 +8,8 @@
#include <stdbool.h> #include <stdbool.h>
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <syslog.h>
#include <time.h>
#include "color.h" #include "log.h"
typedef enum
{
LG_INFO,
LG_WARN,
LG_ERR,
LG_SUCCESS
}
loglevel_t;
static int static int
supports_utf8(void) supports_utf8(void)
@@ -34,26 +23,6 @@ supports_utf8(void)
#endif #endif
} }
/* Converts priority integer to string */
const char
*p2s(int priority)
{
switch (priority)
{
case LOG_EMERG: return "EMERG"; break;
case LOG_ALERT: return "ALERT"; break;
case LOG_CRIT: return "CRIT"; break;
case LOG_ERR: return "ERR"; break;
case LOG_WARNING: return "WARN"; break;
case LOG_NOTICE: return "NOTICE"; break;
case LOG_INFO: return "INFO"; break;
case LOG_DEBUG: return "DEBUG"; break;
default: return "UNKNOWN"; break;
}
}
void void
lg_printf(loglevel_t loglevel, const char *fmt, ...) lg_printf(loglevel_t loglevel, const char *fmt, ...)
{ {
@@ -92,83 +61,73 @@ lg_printf(loglevel_t loglevel, const char *fmt, ...)
printf("\n"); printf("\n");
} }
void
lg_syslog(int priority, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vsyslog(priority, fmt, args);
va_end(args);
}
void
lg_log(bool use_syslog, const char *logfile, int priority, const char *fmt, ...)
{
FILE *log = fopen(logfile, "a");
if (!log) {
perror("fopen");
return;
}
time_t now = time(NULL);
struct tm *t = localtime(&now);
char timestamp[20];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", t);
fprintf(log, "[%s] [%s] ", timestamp, p2s(priority));
va_list args;
va_start(args, fmt);
vfprintf(log, fmt, args);
va_end(args);
fputc('\n', log);
fflush(log);
if (use_syslog) {
va_list args2;
va_start(args2, fmt);
vsyslog(priority, fmt, args2);
va_end(args2);
fclose(log);
}
else {
fclose(log);
return;
}
}
void void
lg_gpkg_help(int argc, char *argv[]) lg_gpkg_help(int argc, char *argv[])
{ {
(void)argc; (void)argc;
printf("%s: Manage the user package index\n", argv[0]); printf("%s: Install, update, and remove packages\n", argv[0]);
printf("usage: %s [OPTIONS] PKG...\n", argv[0]); printf("usage: %s [-hv] [-y] [-flux PKG] [-OSVq]\n", argv[0]);
printf("\n"); printf("\n");
printf("Options:\n" printf("%-25s %s\n", "{-h --help}", "Show this message");
"\t{-h}\tShow this message\n" printf("%-25s %s\n", "{-v --version}", "Show the current version");
"\t{-v}\tShow the current version\n" printf("%-25s %s\n", "{-l --local} FILE...", "Install local package files");
"\t{-f} PKG...\tMerge a package into the user index\n" printf("%-25s %s\n", "{-f --merge} PKG...", "Install packages from a remote repository");
"\t{-u} PKG...\tUpgrade a merged package\n" printf("%-25s %s\n", "{-u --update} [PKG...]", "Update system or individual packages");
"\t{-x} PKG...\tRemove a merged package\n" printf("%-25s %s\n", "{-x --remove} PKG...", "Remove installed packages");
"\n" printf("%-25s %s\n", "{-y --refresh}", "Fetch and verify the remote repositories' indexes");
"This program is free software.\n" printf("%-25s %s\n", "{-O --overwrite}", "Allow Glacier to overwrite existing files");
"See the GNU GPL version 3 for details.\n" printf("%-25s %s\n", "{-S --skip-installed}", "Skip packages that are already up to date");
); printf("%-25s %s\n", "{-V --verbose}", "Log events more verbosely");
printf("%-25s %s\n", "{-q --quiet}", "Hide build output");
printf("\n");
printf("This program is free software.\n");
printf("See the GNU GPL version 3 for details.\n");
} }
int void
main(void) lg_syspkg_help(int argc, char *argv[])
{ {
lg_printf(LG_INFO, "info"); (void)argc;
lg_printf(LG_WARN, "warning");
lg_printf(LG_ERR, "error");
lg_printf(LG_SUCCESS, "success");
lg_log(true, "./glacier.log", LOG_INFO, "Glacier started with PID %d", 12345); printf("%s: Manage the system package index\n", argv[0]);
lg_log(true, "./glacier.log", LOG_ERR, "Failed to install package %s", "glibc"); printf("usage: %s [-hv] [-n] [-y] [-flux PKG] [-OSVq] [-R DIR] [--strict]\n", argv[0]);
printf("\n");
return 0; printf("%-25s %s\n", "{-h --help}", "Show this message");
printf("%-25s %s\n", "{-v --version}", "Show the current version");
printf("%-25s %s\n", "{-n --new}", "Create the system index and store");
printf("%-25s %s\n", "{-l --local} PKG...", "Install a local package into the system index and store");
printf("%-25s %s\n", "{-f --merge} PKG...", "Install packages from a remote repository");
printf("%-25s %s\n", "{-u --update} [PKG...]", "Update system or individual packages");
printf("%-25s %s\n", "{-x --remove} PKG...", "Remove a package from the system index and store");
printf("%-25s %s\n", "{-y --refresh}", "Fetch and verify the remote repositories' indexes");
printf("%-25s %s\n", "{-O --overwrite}", "Allow Glacier to overwrite existing files");
printf("%-25s %s\n", "{-S --skip-installed}", "Skip packages that are already up to date");
printf("%-25s %s\n", "{-V --verbose}", "Log events more verbosely");
printf("%-25s %s\n", "{-q --quiet}", "Hide build output");
printf("%-25s %s\n", "{-R --root} DIR", "Operate on the system installed under DIR (implies --strict)");
printf("%-25s %s\n", "{--strict}", "Refuse the whole transaction if any path can't be linked");
printf("\n");
printf("This program is free software.\n");
printf("See the GNU GPL version 3 for details.\n");
}
void
lg_gstore_help(int argc, char *argv[])
{
(void)argc;
printf("%s: Manage Glacier packages indexes/stores\n", argv[0]);
printf("usage: %s [-hv] [-n [UID]] [-sbx UID] [-V]\n", argv[0]);
printf("\n");
printf("%-25s %s\n", "{-h --help}", "Show this message");
printf("%-25s %s\n", "{-v --version}", "Show the current version");
printf("%-25s %s\n", "{-s --sync} UID", "Sync UID's store with their index");
printf("%-25s %s\n", "{-n --new} [UID]", "Create store and index for UID (as root), or for yourself (doas gstore -n)");
printf("%-25s %s\n", "{-b --backup} UID OUTFILE", "Create tar backup of UID's index and store at OUTFILE");
printf("%-25s %s\n", "{-x --delete} UID", "Delete UID's store and index");
printf("%-25s %s\n", "{-V --verbose}", "Log events more verbosely");
printf("\n");
printf("This program is free software.\n");
printf("See the GNU GPL version 3 for details.\n");
} }
+6 -8
View File
@@ -7,9 +7,6 @@
#include <stdio.h> #include <stdio.h>
#include <stdarg.h> #include <stdarg.h>
#include <stdbool.h>
#include <syslog.h>
#include <time.h>
#include "color.h" #include "color.h"
@@ -26,12 +23,13 @@ typedef enum
} }
loglevel_t; loglevel_t;
int supports_utf8(void); void lg_printf(loglevel_t loglevel, const char *fmt, ...)
const char *p2s(int priority); __attribute__((format(printf, 2, 3)));
void lg_printf(loglevel_t loglevel, const char *fmt, ...); /* The CLIs' -h output. */
void lg_syslog(int priority, const char *fmt, ...); void lg_gpkg_help(int argc, char *argv[]);
void lg_log(bool use_syslog, FILE *logfile, int priority, const char *fmt, ...); void lg_syspkg_help(int argc, char *argv[]);
void lg_gstore_help(int argc, char *argv[]);
#ifdef __cplusplus #ifdef __cplusplus
} }
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<mine-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">
<mime-type type="application/x-glacier-package">
<comment>Glacier Package</comment>
<glob pattern="*.gpkg"/>
<magic priority="50">
<match type="string" offset="0" value="&#x1f;&#x8b;"/>
</magic>
</mime-type>
</mine-info>
-95
View File
@@ -1,95 +0,0 @@
#define _POSIX_C_SOURcE 200809L
#define _DEFAULT_SOURCE
#define _XOPEN_SOURCE 700
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINE 1024
static char
*trim(char *s) {
char *end;
while (isspace((unsigned char)*s)) { s++; }
if (*s == 0) { return s; }
end = s + strlen(s) - 1;
while (end > s && isspace((unsigned char)*end)) { *end-- = 0; }
return s;
}
static char
*expand(char *value)
{
size_t cap = strlen(value) + 1;
char *buffer = malloc(cap);
if (!buffer) { return NULL; }
char *out = buffer;
char *p = value;
while (*p) {
if (*p == '$') {
p++;
char var[128], *vp = var;
while (*p && (isalnum((unsigned char)*p) || *p == '_')) {
*vp++ = *p++;
}
*vp = '\0';
char *val = getenv(var);
if (val) {
size_t len = strlen(val);
size_t used = (size_t)(out - buffer);
if (used + len + 1 > cap) {
cap = used + len + 1;
buffer = realloc(buffer, cap);
if (!buffer) { return NULL; }
out = buffer + used;
}
memcpy(out, val, len);
out += len;
}
}
else {
*out++ = *p++;
}
}
*out = '\0';
return buffer;
}
int
parse_makeconf(const char *filename)
{
FILE *make_conf = fopen(filename, "r");
if (!make_conf) {
perror("fopen");
return -1;
}
char line[MAX_LINE];
while (fgets(line, sizeof(line), make_conf)) {
char *p = trim(line);
if (*p == '\0' || *p == '#') { continue; }
char *eq = strchr(p, '=');
if (!eq) { continue; }
*eq = '\0';
char *key = trim(p);
char *val = trim(eq + 1);
char *expanded = expand(val);
if (expanded) {
setenv(key, expanded, 1);
free(expanded);
}
}
fclose(make_conf);
return 0;
}
+167
View File
@@ -0,0 +1,167 @@
Monocypher as a whole is dual-licensed. Choose whichever licence you
want from the two licences listed below.
The first licence is a regular 2-clause BSD licence. The second licence
is the CC-0 from Creative Commons. It is intended to release Monocypher
to the public domain. The BSD licence serves as a fallback option.
See the individual files for specific information about who contributed
to what file during which years. See below for special notes.
Licence 1 (2-clause BSD)
------------------------
Copyright (c) 2017-2023, Loup Vaillant
Copyright (c) 2017-2019, Michael Savage
Copyright (c) 2017-2023, Fabio Scotoni
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Licence 2 (CC-0)
----------------
> CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
> LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
> ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
> INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
> REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
> PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
> THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
> HEREUNDER.
### Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer
exclusive Copyright and Related Rights (defined below) upon the creator
and subsequent owner(s) (each and all, an "owner") of an original work
of authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for
the purpose of contributing to a commons of creative, cultural and
scientific works ("Commons") that the public can reliably and without
fear of later claims of infringement build upon, modify, incorporate in
other works, reuse and redistribute as freely as possible in any form
whatsoever and for any purposes, including without limitation commercial
purposes. These owners may contribute to the Commons to promote the
ideal of a free culture and the further production of creative, cultural
and scientific works, or to gain reputation or greater distribution for
their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any
expectation of additional consideration or compensation, the person
associating CC0 with a Work (the "Affirmer"), to the extent that he or
she is an owner of Copyright and Related Rights in the Work, voluntarily
elects to apply CC0 to the Work and publicly distribute the Work under
its terms, with knowledge of his or her Copyright and Related Rights in
the Work and the meaning and intended legal effect of CC0 on those
rights.
1. **Copyright and Related Rights.** A Work made available under CC0 may
be protected by copyright and related or neighboring rights
("Copyright and Related Rights"). Copyright and Related Rights
include, but are not limited to, the following:
- the right to reproduce, adapt, distribute, perform, display,
communicate, and translate a Work;
- moral rights retained by the original author(s) and/or
performer(s); publicity and privacy rights pertaining to a person's
image or likeness depicted in a Work;
- rights protecting against unfair competition in regards to a Work,
subject to the limitations in paragraph 4(a), below;
- rights protecting the extraction, dissemination, use and reuse of
data in a Work;
- database rights (such as those arising under Directive 96/9/EC of
the European Parliament and of the Council of 11 March 1996 on the
legal protection of databases, and under any national
implementation thereof, including any amended or successor version
of such directive); and
- other similar, equivalent or corresponding rights throughout the
world based on applicable law or treaty, and any national
implementations thereof.
2. **Waiver.** To the greatest extent permitted by, but not in
contravention of, applicable law, Affirmer hereby overtly, fully,
permanently, irrevocably and unconditionally waives, abandons, and
surrenders all of Affirmer's Copyright and Related Rights and
associated claims and causes of action, whether now known or unknown
(including existing as well as future claims and causes of action),
in the Work (i) in all territories worldwide, (ii) for the maximum
duration provided by applicable law or treaty (including future time
extensions), (iii) in any current or future medium and for any number
of copies, and (iv) for any purpose whatsoever, including without
limitation commercial, advertising or promotional purposes (the
"Waiver"). Affirmer makes the Waiver for the benefit of each member
of the public at large and to the detriment of Affirmer's heirs and
successors, fully intending that such Waiver shall not be subject to
revocation, rescission, cancellation, termination, or any other legal
or equitable action to disrupt the quiet enjoyment of the Work by the
public as contemplated by Affirmer's express Statement of Purpose.
3. **Public License Fallback.** Should any part of the Waiver for any
reason be judged legally invalid or ineffective under applicable law,
then the Waiver shall be preserved to the maximum extent permitted
taking into account Affirmer's express Statement of Purpose. In
addition, to the extent the Waiver is so judged Affirmer hereby
grants to each affected person a royalty-free, non transferable, non
sublicensable, non exclusive, irrevocable and unconditional license
to exercise Affirmer's Copyright and Related Rights in the Work (i)
in all territories worldwide, (ii) for the maximum duration provided
by applicable law or treaty (including future time extensions), (iii)
in any current or future medium and for any number of copies, and
(iv) for any purpose whatsoever, including without limitation
commercial, advertising or promotional purposes (the "License"). The
License shall be deemed effective as of the date CC0 was applied by
Affirmer to the Work. Should any part of the License for any reason
be judged legally invalid or ineffective under applicable law, such
partial invalidity or ineffectiveness shall not invalidate the
remainder of the License, and in such case Affirmer hereby affirms
that he or she will not (i) exercise any of his or her remaining
Copyright and Related Rights in the Work or (ii) assert any
associated claims and causes of action with respect to the Work, in
either case contrary to Affirmer's express Statement of Purpose.
4. **Limitations and Disclaimers.**
- No trademark or patent rights held by Affirmer are waived,
abandoned, surrendered, licensed or otherwise affected by this
document.
- Affirmer offers the Work as-is and makes no representations or
warranties of any kind concerning the Work, express, implied,
statutory or otherwise, including without limitation warranties of
title, merchantability, fitness for a particular purpose, non
infringement, or the absence of latent or other defects, accuracy,
or the present or absence of errors, whether or not discoverable,
all to the greatest extent permissible under applicable law.
- Affirmer disclaims responsibility for clearing rights of other
persons that may apply to the Work or any use thereof, including
without limitation any person's Copyright and Related Rights in the
Work. Further, Affirmer disclaims responsibility for obtaining any
necessary consents, permissions or other rights required for any
use of the Work.
- Affirmer understands and acknowledges that Creative Commons is not
a party to this document and has no duty or obligation with respect
to this CC0 or use of the Work.
+14
View File
@@ -0,0 +1,14 @@
Monocypher 4.0.3, vendored UNMODIFIED (REPO_DESIGN.txt section 1a).
monocypher.c, monocypher.h from src/
monocypher-ed25519.c, monocypher-ed25519.h from src/optional/
LICENCE.md BSD-2-Clause or CC0
Source: monocypher-4.0.3.tar.gz, fetched 2026-10-06 from both
https://github.com/LoupVaillant/Monocypher/releases/download/4.0.3/
and https://monocypher.org/download/ ; identical, sha512
40904ada5c7ee4f7741733e38b69a30a4b0561cbffba5ffe7c2dce16136d540251ec0d9056ff606510d3b5b708fb8a40db7e0870d4a0b2dc17ba2bfb880f8965
Only Ed25519 (with its SHA-512) is used, through src/sign.c. Never
edit these files: replace them with a newer release, and update this
note.
+503
View File
@@ -0,0 +1,503 @@
// Monocypher version 4.0.3
//
// This file is dual-licensed. Choose whichever licence you want from
// the two licences listed below.
//
// The first licence is a regular 2-clause BSD licence. The second licence
// is the CC-0 from Creative Commons. It is intended to release Monocypher
// to the public domain. The BSD licence serves as a fallback option.
//
// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
//
// ------------------------------------------------------------------------
//
// Copyright (c) 2017-2019, Loup Vaillant
// All rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ------------------------------------------------------------------------
//
// Written in 2017-2019 by Loup Vaillant
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see
// <https://creativecommons.org/publicdomain/zero/1.0/>
#include "monocypher-ed25519.h"
#ifdef MONOCYPHER_CPP_NAMESPACE
namespace MONOCYPHER_CPP_NAMESPACE {
#endif
/////////////////
/// Utilities ///
/////////////////
#define FOR(i, min, max) for (size_t i = min; i < max; i++)
#define COPY(dst, src, size) FOR(_i_, 0, size) (dst)[_i_] = (src)[_i_]
#define ZERO(buf, size) FOR(_i_, 0, size) (buf)[_i_] = 0
#define WIPE_CTX(ctx) crypto_wipe(ctx , sizeof(*(ctx)))
#define WIPE_BUFFER(buffer) crypto_wipe(buffer, sizeof(buffer))
#define MIN(a, b) ((a) <= (b) ? (a) : (b))
typedef uint8_t u8;
typedef uint64_t u64;
// Returns the smallest positive integer y such that
// (x + y) % pow_2 == 0
// Basically, it's how many bytes we need to add to "align" x.
// Only works when pow_2 is a power of 2.
// Note: we use ~x+1 instead of -x to avoid compiler warnings
static size_t align(size_t x, size_t pow_2)
{
return (~x + 1) & (pow_2 - 1);
}
static u64 load64_be(const u8 s[8])
{
return((u64)s[0] << 56)
| ((u64)s[1] << 48)
| ((u64)s[2] << 40)
| ((u64)s[3] << 32)
| ((u64)s[4] << 24)
| ((u64)s[5] << 16)
| ((u64)s[6] << 8)
| (u64)s[7];
}
static void store64_be(u8 out[8], u64 in)
{
out[0] = (u8)(in >> 56);
out[1] = (u8)(in >> 48);
out[2] = (u8)(in >> 40);
out[3] = (u8)(in >> 32);
out[4] = (u8)(in >> 24);
out[5] = (u8)(in >> 16);
out[6] = (u8)(in >> 8);
out[7] = (u8) in ;
}
static void load64_be_buf (u64 *dst, const u8 *src, size_t size) {
FOR(i, 0, size) { dst[i] = load64_be(src + i*8); }
}
///////////////
/// SHA 512 ///
///////////////
static u64 rot(u64 x, int c ) { return (x >> c) | (x << (64 - c)); }
static u64 ch (u64 x, u64 y, u64 z) { return (x & y) ^ (~x & z); }
static u64 maj(u64 x, u64 y, u64 z) { return (x & y) ^ ( x & z) ^ (y & z); }
static u64 big_sigma0(u64 x) { return rot(x, 28) ^ rot(x, 34) ^ rot(x, 39); }
static u64 big_sigma1(u64 x) { return rot(x, 14) ^ rot(x, 18) ^ rot(x, 41); }
static u64 lit_sigma0(u64 x) { return rot(x, 1) ^ rot(x, 8) ^ (x >> 7); }
static u64 lit_sigma1(u64 x) { return rot(x, 19) ^ rot(x, 61) ^ (x >> 6); }
static const u64 K[80] = {
0x428a2f98d728ae22,0x7137449123ef65cd,0xb5c0fbcfec4d3b2f,0xe9b5dba58189dbbc,
0x3956c25bf348b538,0x59f111f1b605d019,0x923f82a4af194f9b,0xab1c5ed5da6d8118,
0xd807aa98a3030242,0x12835b0145706fbe,0x243185be4ee4b28c,0x550c7dc3d5ffb4e2,
0x72be5d74f27b896f,0x80deb1fe3b1696b1,0x9bdc06a725c71235,0xc19bf174cf692694,
0xe49b69c19ef14ad2,0xefbe4786384f25e3,0x0fc19dc68b8cd5b5,0x240ca1cc77ac9c65,
0x2de92c6f592b0275,0x4a7484aa6ea6e483,0x5cb0a9dcbd41fbd4,0x76f988da831153b5,
0x983e5152ee66dfab,0xa831c66d2db43210,0xb00327c898fb213f,0xbf597fc7beef0ee4,
0xc6e00bf33da88fc2,0xd5a79147930aa725,0x06ca6351e003826f,0x142929670a0e6e70,
0x27b70a8546d22ffc,0x2e1b21385c26c926,0x4d2c6dfc5ac42aed,0x53380d139d95b3df,
0x650a73548baf63de,0x766a0abb3c77b2a8,0x81c2c92e47edaee6,0x92722c851482353b,
0xa2bfe8a14cf10364,0xa81a664bbc423001,0xc24b8b70d0f89791,0xc76c51a30654be30,
0xd192e819d6ef5218,0xd69906245565a910,0xf40e35855771202a,0x106aa07032bbd1b8,
0x19a4c116b8d2d0c8,0x1e376c085141ab53,0x2748774cdf8eeb99,0x34b0bcb5e19b48a8,
0x391c0cb3c5c95a63,0x4ed8aa4ae3418acb,0x5b9cca4f7763e373,0x682e6ff3d6b2b8a3,
0x748f82ee5defb2fc,0x78a5636f43172f60,0x84c87814a1f0ab72,0x8cc702081a6439ec,
0x90befffa23631e28,0xa4506cebde82bde9,0xbef9a3f7b2c67915,0xc67178f2e372532b,
0xca273eceea26619c,0xd186b8c721c0c207,0xeada7dd6cde0eb1e,0xf57d4f7fee6ed178,
0x06f067aa72176fba,0x0a637dc5a2c898a6,0x113f9804bef90dae,0x1b710b35131c471b,
0x28db77f523047d84,0x32caab7b40c72493,0x3c9ebe0a15c9bebc,0x431d67c49c100d4c,
0x4cc5d4becb3e42b6,0x597f299cfc657e2a,0x5fcb6fab3ad6faec,0x6c44198c4a475817
};
static void sha512_compress(crypto_sha512_ctx *ctx)
{
u64 a = ctx->hash[0]; u64 b = ctx->hash[1];
u64 c = ctx->hash[2]; u64 d = ctx->hash[3];
u64 e = ctx->hash[4]; u64 f = ctx->hash[5];
u64 g = ctx->hash[6]; u64 h = ctx->hash[7];
FOR (j, 0, 16) {
u64 in = K[j] + ctx->input[j];
u64 t1 = big_sigma1(e) + ch (e, f, g) + h + in;
u64 t2 = big_sigma0(a) + maj(a, b, c);
h = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
size_t i16 = 0;
FOR(i, 1, 5) {
i16 += 16;
FOR (j, 0, 16) {
ctx->input[j] += lit_sigma1(ctx->input[(j- 2) & 15]);
ctx->input[j] += lit_sigma0(ctx->input[(j-15) & 15]);
ctx->input[j] += ctx->input[(j- 7) & 15];
u64 in = K[i16 + j] + ctx->input[j];
u64 t1 = big_sigma1(e) + ch (e, f, g) + h + in;
u64 t2 = big_sigma0(a) + maj(a, b, c);
h = g; g = f; f = e; e = d + t1;
d = c; c = b; b = a; a = t1 + t2;
}
}
ctx->hash[0] += a; ctx->hash[1] += b;
ctx->hash[2] += c; ctx->hash[3] += d;
ctx->hash[4] += e; ctx->hash[5] += f;
ctx->hash[6] += g; ctx->hash[7] += h;
}
// Write 1 input byte
static void sha512_set_input(crypto_sha512_ctx *ctx, u8 input)
{
size_t word = ctx->input_idx >> 3;
size_t byte = ctx->input_idx & 7;
ctx->input[word] |= (u64)input << (8 * (7 - byte));
}
// Increment a 128-bit "word".
static void sha512_incr(u64 x[2], u64 y)
{
x[1] += y;
if (x[1] < y) {
x[0]++;
}
}
void crypto_sha512_init(crypto_sha512_ctx *ctx)
{
ctx->hash[0] = 0x6a09e667f3bcc908;
ctx->hash[1] = 0xbb67ae8584caa73b;
ctx->hash[2] = 0x3c6ef372fe94f82b;
ctx->hash[3] = 0xa54ff53a5f1d36f1;
ctx->hash[4] = 0x510e527fade682d1;
ctx->hash[5] = 0x9b05688c2b3e6c1f;
ctx->hash[6] = 0x1f83d9abfb41bd6b;
ctx->hash[7] = 0x5be0cd19137e2179;
ctx->input_size[0] = 0;
ctx->input_size[1] = 0;
ctx->input_idx = 0;
ZERO(ctx->input, 16);
}
void crypto_sha512_update(crypto_sha512_ctx *ctx,
const u8 *message, size_t message_size)
{
// Avoid undefined NULL pointer increments with empty messages
if (message_size == 0) {
return;
}
// Align ourselves with word boundaries
if ((ctx->input_idx & 7) != 0) {
size_t nb_bytes = MIN(align(ctx->input_idx, 8), message_size);
FOR (i, 0, nb_bytes) {
sha512_set_input(ctx, message[i]);
ctx->input_idx++;
}
message += nb_bytes;
message_size -= nb_bytes;
}
// Align ourselves with block boundaries
if ((ctx->input_idx & 127) != 0) {
size_t nb_words = MIN(align(ctx->input_idx, 128), message_size) >> 3;
load64_be_buf(ctx->input + (ctx->input_idx >> 3), message, nb_words);
ctx->input_idx += nb_words << 3;
message += nb_words << 3;
message_size -= nb_words << 3;
}
// Compress block if needed
if (ctx->input_idx == 128) {
sha512_incr(ctx->input_size, 1024); // size is in bits
sha512_compress(ctx);
ctx->input_idx = 0;
ZERO(ctx->input, 16);
}
// Process the message block by block
FOR (i, 0, message_size >> 7) { // number of blocks
load64_be_buf(ctx->input, message, 16);
sha512_incr(ctx->input_size, 1024); // size is in bits
sha512_compress(ctx);
ctx->input_idx = 0;
ZERO(ctx->input, 16);
message += 128;
}
message_size &= 127;
if (message_size != 0) {
// Remaining words
size_t nb_words = message_size >> 3;
load64_be_buf(ctx->input, message, nb_words);
ctx->input_idx += nb_words << 3;
message += nb_words << 3;
message_size -= nb_words << 3;
// Remaining bytes
FOR (i, 0, message_size) {
sha512_set_input(ctx, message[i]);
ctx->input_idx++;
}
}
}
void crypto_sha512_final(crypto_sha512_ctx *ctx, u8 hash[64])
{
// Add padding bit
if (ctx->input_idx == 0) {
ZERO(ctx->input, 16);
}
sha512_set_input(ctx, 128);
// Update size
sha512_incr(ctx->input_size, ctx->input_idx * 8);
// Compress penultimate block (if any)
if (ctx->input_idx > 111) {
sha512_compress(ctx);
ZERO(ctx->input, 14);
}
// Compress last block
ctx->input[14] = ctx->input_size[0];
ctx->input[15] = ctx->input_size[1];
sha512_compress(ctx);
// Copy hash to output (big endian)
FOR (i, 0, 8) {
store64_be(hash + i*8, ctx->hash[i]);
}
WIPE_CTX(ctx);
}
void crypto_sha512(u8 hash[64], const u8 *message, size_t message_size)
{
crypto_sha512_ctx ctx;
crypto_sha512_init (&ctx);
crypto_sha512_update(&ctx, message, message_size);
crypto_sha512_final (&ctx, hash);
}
////////////////////
/// HMAC SHA 512 ///
////////////////////
void crypto_sha512_hmac_init(crypto_sha512_hmac_ctx *ctx,
const u8 *key, size_t key_size)
{
// hash key if it is too long
if (key_size > 128) {
crypto_sha512(ctx->key, key, key_size);
key = ctx->key;
key_size = 64;
}
// Compute inner key: padded key XOR 0x36
FOR (i, 0, key_size) { ctx->key[i] = key[i] ^ 0x36; }
FOR (i, key_size, 128) { ctx->key[i] = 0x36; }
// Start computing inner hash
crypto_sha512_init (&ctx->ctx);
crypto_sha512_update(&ctx->ctx, ctx->key, 128);
}
void crypto_sha512_hmac_update(crypto_sha512_hmac_ctx *ctx,
const u8 *message, size_t message_size)
{
crypto_sha512_update(&ctx->ctx, message, message_size);
}
void crypto_sha512_hmac_final(crypto_sha512_hmac_ctx *ctx, u8 hmac[64])
{
// Finish computing inner hash
crypto_sha512_final(&ctx->ctx, hmac);
// Compute outer key: padded key XOR 0x5c
FOR (i, 0, 128) {
ctx->key[i] ^= 0x36 ^ 0x5c;
}
// Compute outer hash
crypto_sha512_init (&ctx->ctx);
crypto_sha512_update(&ctx->ctx, ctx->key , 128);
crypto_sha512_update(&ctx->ctx, hmac, 64);
crypto_sha512_final (&ctx->ctx, hmac); // outer hash
WIPE_CTX(ctx);
}
void crypto_sha512_hmac(u8 hmac[64], const u8 *key, size_t key_size,
const u8 *message, size_t message_size)
{
crypto_sha512_hmac_ctx ctx;
crypto_sha512_hmac_init (&ctx, key, key_size);
crypto_sha512_hmac_update(&ctx, message, message_size);
crypto_sha512_hmac_final (&ctx, hmac);
}
////////////////////
/// HKDF SHA 512 ///
////////////////////
void crypto_sha512_hkdf_expand(u8 *okm, size_t okm_size,
const u8 *prk, size_t prk_size,
const u8 *info, size_t info_size)
{
int not_first = 0;
u8 ctr = 1;
u8 blk[64];
while (okm_size > 0) {
size_t out_size = MIN(okm_size, sizeof(blk));
crypto_sha512_hmac_ctx ctx;
crypto_sha512_hmac_init(&ctx, prk , prk_size);
if (not_first) {
// For some reason HKDF uses some kind of CBC mode.
// For some reason CTR mode alone wasn't enough.
// Like what, they didn't trust HMAC in 2010? Really??
crypto_sha512_hmac_update(&ctx, blk , sizeof(blk));
}
crypto_sha512_hmac_update(&ctx, info, info_size);
crypto_sha512_hmac_update(&ctx, &ctr, 1);
crypto_sha512_hmac_final(&ctx, blk);
COPY(okm, blk, out_size);
not_first = 1;
okm += out_size;
okm_size -= out_size;
ctr++;
}
WIPE_BUFFER(blk);
}
void crypto_sha512_hkdf(u8 *okm , size_t okm_size,
const u8 *ikm , size_t ikm_size,
const u8 *salt, size_t salt_size,
const u8 *info, size_t info_size)
{
// Extract
u8 prk[64];
crypto_sha512_hmac(prk, salt, salt_size, ikm, ikm_size);
// Expand
crypto_sha512_hkdf_expand(okm, okm_size, prk, sizeof(prk), info, info_size);
WIPE_BUFFER(prk);
}
///////////////
/// Ed25519 ///
///////////////
void crypto_ed25519_key_pair(u8 secret_key[64], u8 public_key[32], u8 seed[32])
{
u8 a[64];
COPY(a, seed, 32); // a[ 0..31] = seed
crypto_wipe(seed, 32);
COPY(secret_key, a, 32); // secret key = seed
crypto_sha512(a, a, 32); // a[ 0..31] = scalar
crypto_eddsa_trim_scalar(a, a); // a[ 0..31] = trimmed scalar
crypto_eddsa_scalarbase(public_key, a); // public key = [trimmed scalar]B
COPY(secret_key + 32, public_key, 32); // secret key includes public half
WIPE_BUFFER(a);
}
static void hash_reduce(u8 h[32],
const u8 *a, size_t a_size,
const u8 *b, size_t b_size,
const u8 *c, size_t c_size,
const u8 *d, size_t d_size)
{
u8 hash[64];
crypto_sha512_ctx ctx;
crypto_sha512_init (&ctx);
crypto_sha512_update(&ctx, a, a_size);
crypto_sha512_update(&ctx, b, b_size);
crypto_sha512_update(&ctx, c, c_size);
crypto_sha512_update(&ctx, d, d_size);
crypto_sha512_final (&ctx, hash);
crypto_eddsa_reduce(h, hash);
}
static void ed25519_dom_sign(u8 signature[64], const u8 secret_key[64],
const u8 *dom, size_t dom_size,
const u8 *message, size_t message_size)
{
u8 a[64]; // secret scalar and prefix
u8 r[32]; // secret deterministic "random" nonce
u8 h[32]; // publically verifiable hash of the message (not wiped)
u8 R[32]; // first half of the signature (allows overlapping inputs)
const u8 *pk = secret_key + 32;
crypto_sha512(a, secret_key, 32);
crypto_eddsa_trim_scalar(a, a);
hash_reduce(r, dom, dom_size, a + 32, 32, message, message_size, 0, 0);
crypto_eddsa_scalarbase(R, r);
hash_reduce(h, dom, dom_size, R, 32, pk, 32, message, message_size);
COPY(signature, R, 32);
crypto_eddsa_mul_add(signature + 32, h, a, r);
WIPE_BUFFER(a);
WIPE_BUFFER(r);
}
void crypto_ed25519_sign(u8 signature [64], const u8 secret_key[64],
const u8 *message, size_t message_size)
{
ed25519_dom_sign(signature, secret_key, 0, 0, message, message_size);
}
int crypto_ed25519_check(const u8 signature[64], const u8 public_key[32],
const u8 *msg, size_t msg_size)
{
u8 h_ram[32];
hash_reduce(h_ram, signature, 32, public_key, 32, msg, msg_size, 0, 0);
return crypto_eddsa_check_equation(signature, public_key, h_ram);
}
static const u8 domain[34] = "SigEd25519 no Ed25519 collisions\1";
void crypto_ed25519_ph_sign(uint8_t signature[64], const uint8_t secret_key[64],
const uint8_t message_hash[64])
{
ed25519_dom_sign(signature, secret_key, domain, sizeof(domain),
message_hash, 64);
}
int crypto_ed25519_ph_check(const uint8_t sig[64], const uint8_t pk[32],
const uint8_t msg_hash[64])
{
u8 h_ram[32];
hash_reduce(h_ram, domain, sizeof(domain), sig, 32, pk, 32, msg_hash, 64);
return crypto_eddsa_check_equation(sig, pk, h_ram);
}
#ifdef MONOCYPHER_CPP_NAMESPACE
}
#endif
+140
View File
@@ -0,0 +1,140 @@
// Monocypher version 4.0.3
//
// This file is dual-licensed. Choose whichever licence you want from
// the two licences listed below.
//
// The first licence is a regular 2-clause BSD licence. The second licence
// is the CC-0 from Creative Commons. It is intended to release Monocypher
// to the public domain. The BSD licence serves as a fallback option.
//
// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
//
// ------------------------------------------------------------------------
//
// Copyright (c) 2017-2019, Loup Vaillant
// All rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ------------------------------------------------------------------------
//
// Written in 2017-2019 by Loup Vaillant
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see
// <https://creativecommons.org/publicdomain/zero/1.0/>
#ifndef ED25519_H
#define ED25519_H
#include "monocypher.h"
#ifdef MONOCYPHER_CPP_NAMESPACE
namespace MONOCYPHER_CPP_NAMESPACE {
#elif defined(__cplusplus)
extern "C" {
#endif
////////////////////////
/// Type definitions ///
////////////////////////
// Do not rely on the size or content on any of those types,
// they may change without notice.
typedef struct {
uint64_t hash[8];
uint64_t input[16];
uint64_t input_size[2];
size_t input_idx;
} crypto_sha512_ctx;
typedef struct {
uint8_t key[128];
crypto_sha512_ctx ctx;
} crypto_sha512_hmac_ctx;
// SHA 512
// -------
void crypto_sha512_init (crypto_sha512_ctx *ctx);
void crypto_sha512_update(crypto_sha512_ctx *ctx,
const uint8_t *message, size_t message_size);
void crypto_sha512_final (crypto_sha512_ctx *ctx, uint8_t hash[64]);
void crypto_sha512(uint8_t hash[64],
const uint8_t *message, size_t message_size);
// SHA 512 HMAC
// ------------
void crypto_sha512_hmac_init(crypto_sha512_hmac_ctx *ctx,
const uint8_t *key, size_t key_size);
void crypto_sha512_hmac_update(crypto_sha512_hmac_ctx *ctx,
const uint8_t *message, size_t message_size);
void crypto_sha512_hmac_final(crypto_sha512_hmac_ctx *ctx, uint8_t hmac[64]);
void crypto_sha512_hmac(uint8_t hmac[64],
const uint8_t *key , size_t key_size,
const uint8_t *message, size_t message_size);
// SHA 512 HKDF
// ------------
void crypto_sha512_hkdf_expand(uint8_t *okm, size_t okm_size,
const uint8_t *prk, size_t prk_size,
const uint8_t *info, size_t info_size);
void crypto_sha512_hkdf(uint8_t *okm , size_t okm_size,
const uint8_t *ikm , size_t ikm_size,
const uint8_t *salt, size_t salt_size,
const uint8_t *info, size_t info_size);
// Ed25519
// -------
// Signatures (EdDSA with curve25519 + SHA-512)
// --------------------------------------------
void crypto_ed25519_key_pair(uint8_t secret_key[64],
uint8_t public_key[32],
uint8_t seed[32]);
void crypto_ed25519_sign(uint8_t signature [64],
const uint8_t secret_key[64],
const uint8_t *message, size_t message_size);
int crypto_ed25519_check(const uint8_t signature [64],
const uint8_t public_key[32],
const uint8_t *message, size_t message_size);
// Pre-hash variants
void crypto_ed25519_ph_sign(uint8_t signature [64],
const uint8_t secret_key [64],
const uint8_t message_hash[64]);
int crypto_ed25519_ph_check(const uint8_t signature [64],
const uint8_t public_key [32],
const uint8_t message_hash[64]);
#ifdef __cplusplus
}
#endif
#endif // ED25519_H
File diff suppressed because it is too large. Load diff
+321
View File
@@ -0,0 +1,321 @@
// Monocypher version 4.0.3
//
// This file is dual-licensed. Choose whichever licence you want from
// the two licences listed below.
//
// The first licence is a regular 2-clause BSD licence. The second licence
// is the CC-0 from Creative Commons. It is intended to release Monocypher
// to the public domain. The BSD licence serves as a fallback option.
//
// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0
//
// ------------------------------------------------------------------------
//
// Copyright (c) 2017-2019, Loup Vaillant
// All rights reserved.
//
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ------------------------------------------------------------------------
//
// Written in 2017-2019 by Loup Vaillant
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along
// with this software. If not, see
// <https://creativecommons.org/publicdomain/zero/1.0/>
#ifndef MONOCYPHER_H
#define MONOCYPHER_H
#include <stddef.h>
#include <stdint.h>
#ifdef MONOCYPHER_CPP_NAMESPACE
namespace MONOCYPHER_CPP_NAMESPACE {
#elif defined(__cplusplus)
extern "C" {
#endif
// Constant time comparisons
// -------------------------
// Return 0 if a and b are equal, -1 otherwise
int crypto_verify16(const uint8_t a[16], const uint8_t b[16]);
int crypto_verify32(const uint8_t a[32], const uint8_t b[32]);
int crypto_verify64(const uint8_t a[64], const uint8_t b[64]);
// Erase sensitive data
// --------------------
void crypto_wipe(void *secret, size_t size);
// Authenticated encryption
// ------------------------
void crypto_aead_lock(uint8_t *cipher_text,
uint8_t mac [16],
const uint8_t key [32],
const uint8_t nonce[24],
const uint8_t *ad, size_t ad_size,
const uint8_t *plain_text, size_t text_size);
int crypto_aead_unlock(uint8_t *plain_text,
const uint8_t mac [16],
const uint8_t key [32],
const uint8_t nonce[24],
const uint8_t *ad, size_t ad_size,
const uint8_t *cipher_text, size_t text_size);
// Authenticated stream
// --------------------
typedef struct {
uint64_t counter;
uint8_t key[32];
uint8_t nonce[8];
} crypto_aead_ctx;
void crypto_aead_init_x(crypto_aead_ctx *ctx,
const uint8_t key[32], const uint8_t nonce[24]);
void crypto_aead_init_djb(crypto_aead_ctx *ctx,
const uint8_t key[32], const uint8_t nonce[8]);
void crypto_aead_init_ietf(crypto_aead_ctx *ctx,
const uint8_t key[32], const uint8_t nonce[12]);
void crypto_aead_write(crypto_aead_ctx *ctx,
uint8_t *cipher_text,
uint8_t mac[16],
const uint8_t *ad , size_t ad_size,
const uint8_t *plain_text, size_t text_size);
int crypto_aead_read(crypto_aead_ctx *ctx,
uint8_t *plain_text,
const uint8_t mac[16],
const uint8_t *ad , size_t ad_size,
const uint8_t *cipher_text, size_t text_size);
// General purpose hash (BLAKE2b)
// ------------------------------
// Direct interface
void crypto_blake2b(uint8_t *hash, size_t hash_size,
const uint8_t *message, size_t message_size);
void crypto_blake2b_keyed(uint8_t *hash, size_t hash_size,
const uint8_t *key, size_t key_size,
const uint8_t *message, size_t message_size);
// Incremental interface
typedef struct {
// Do not rely on the size or contents of this type,
// for they may change without notice.
uint64_t hash[8];
uint64_t input_offset[2];
uint64_t input[16];
size_t input_idx;
size_t hash_size;
} crypto_blake2b_ctx;
void crypto_blake2b_init(crypto_blake2b_ctx *ctx, size_t hash_size);
void crypto_blake2b_keyed_init(crypto_blake2b_ctx *ctx, size_t hash_size,
const uint8_t *key, size_t key_size);
void crypto_blake2b_update(crypto_blake2b_ctx *ctx,
const uint8_t *message, size_t message_size);
void crypto_blake2b_final(crypto_blake2b_ctx *ctx, uint8_t *hash);
// Password key derivation (Argon2)
// --------------------------------
#define CRYPTO_ARGON2_D 0
#define CRYPTO_ARGON2_I 1
#define CRYPTO_ARGON2_ID 2
typedef struct {
uint32_t algorithm; // Argon2d, Argon2i, Argon2id
uint32_t nb_blocks; // memory hardness, >= 8 * nb_lanes
uint32_t nb_passes; // CPU hardness, >= 1 (>= 3 recommended for Argon2i)
uint32_t nb_lanes; // parallelism level (single threaded anyway)
} crypto_argon2_config;
typedef struct {
const uint8_t *pass;
const uint8_t *salt;
uint32_t pass_size;
uint32_t salt_size; // 16 bytes recommended
} crypto_argon2_inputs;
typedef struct {
const uint8_t *key; // may be NULL if no key
const uint8_t *ad; // may be NULL if no additional data
uint32_t key_size; // 0 if no key (32 bytes recommended otherwise)
uint32_t ad_size; // 0 if no additional data
} crypto_argon2_extras;
extern const crypto_argon2_extras crypto_argon2_no_extras;
void crypto_argon2(uint8_t *hash, uint32_t hash_size, void *work_area,
crypto_argon2_config config,
crypto_argon2_inputs inputs,
crypto_argon2_extras extras);
// Key exchange (X-25519)
// ----------------------
// Shared secrets are not quite random.
// Hash them to derive an actual shared key.
void crypto_x25519_public_key(uint8_t public_key[32],
const uint8_t secret_key[32]);
void crypto_x25519(uint8_t raw_shared_secret[32],
const uint8_t your_secret_key [32],
const uint8_t their_public_key [32]);
// Conversion to EdDSA
void crypto_x25519_to_eddsa(uint8_t eddsa[32], const uint8_t x25519[32]);
// scalar "division"
// Used for OPRF. Be aware that exponential blinding is less secure
// than Diffie-Hellman key exchange.
void crypto_x25519_inverse(uint8_t blind_salt [32],
const uint8_t private_key[32],
const uint8_t curve_point[32]);
// "Dirty" versions of x25519_public_key().
// Use with crypto_elligator_rev().
// Leaks 3 bits of the private key.
void crypto_x25519_dirty_small(uint8_t pk[32], const uint8_t sk[32]);
void crypto_x25519_dirty_fast (uint8_t pk[32], const uint8_t sk[32]);
// Signatures
// ----------
// EdDSA with curve25519 + BLAKE2b
void crypto_eddsa_key_pair(uint8_t secret_key[64],
uint8_t public_key[32],
uint8_t seed[32]);
void crypto_eddsa_sign(uint8_t signature [64],
const uint8_t secret_key[64],
const uint8_t *message, size_t message_size);
int crypto_eddsa_check(const uint8_t signature [64],
const uint8_t public_key[32],
const uint8_t *message, size_t message_size);
// Conversion to X25519
void crypto_eddsa_to_x25519(uint8_t x25519[32], const uint8_t eddsa[32]);
// EdDSA building blocks
void crypto_eddsa_trim_scalar(uint8_t out[32], const uint8_t in[32]);
void crypto_eddsa_reduce(uint8_t reduced[32], const uint8_t expanded[64]);
void crypto_eddsa_mul_add(uint8_t r[32],
const uint8_t a[32],
const uint8_t b[32],
const uint8_t c[32]);
void crypto_eddsa_scalarbase(uint8_t point[32], const uint8_t scalar[32]);
int crypto_eddsa_check_equation(const uint8_t signature[64],
const uint8_t public_key[32],
const uint8_t h_ram[32]);
// Chacha20
// --------
// Specialised hash.
// Used to hash X25519 shared secrets.
void crypto_chacha20_h(uint8_t out[32],
const uint8_t key[32],
const uint8_t in [16]);
// Unauthenticated stream cipher.
// Don't forget to add authentication.
uint64_t crypto_chacha20_djb(uint8_t *cipher_text,
const uint8_t *plain_text,
size_t text_size,
const uint8_t key[32],
const uint8_t nonce[8],
uint64_t ctr);
uint32_t crypto_chacha20_ietf(uint8_t *cipher_text,
const uint8_t *plain_text,
size_t text_size,
const uint8_t key[32],
const uint8_t nonce[12],
uint32_t ctr);
uint64_t crypto_chacha20_x(uint8_t *cipher_text,
const uint8_t *plain_text,
size_t text_size,
const uint8_t key[32],
const uint8_t nonce[24],
uint64_t ctr);
// Poly 1305
// ---------
// This is a *one time* authenticator.
// Disclosing the mac reveals the key.
// See crypto_lock() on how to use it properly.
// Direct interface
void crypto_poly1305(uint8_t mac[16],
const uint8_t *message, size_t message_size,
const uint8_t key[32]);
// Incremental interface
typedef struct {
// Do not rely on the size or contents of this type,
// for they may change without notice.
uint8_t c[16]; // chunk of the message
size_t c_idx; // How many bytes are there in the chunk.
uint32_t r [4]; // constant multiplier (from the secret key)
uint32_t pad[4]; // random number added at the end (from the secret key)
uint32_t h [5]; // accumulated hash
} crypto_poly1305_ctx;
void crypto_poly1305_init (crypto_poly1305_ctx *ctx, const uint8_t key[32]);
void crypto_poly1305_update(crypto_poly1305_ctx *ctx,
const uint8_t *message, size_t message_size);
void crypto_poly1305_final (crypto_poly1305_ctx *ctx, uint8_t mac[16]);
// Elligator 2
// -----------
// Elligator mappings proper
void crypto_elligator_map(uint8_t curve [32], const uint8_t hidden[32]);
int crypto_elligator_rev(uint8_t hidden[32], const uint8_t curve [32],
uint8_t tweak);
// Easy to use key pair generation
void crypto_elligator_key_pair(uint8_t hidden[32], uint8_t secret_key[32],
uint8_t seed[32]);
#ifdef __cplusplus
}
#endif
#endif // MONOCYPHER_H
+1453
View File
File diff suppressed because it is too large. Load diff
+181
View File
@@ -0,0 +1,181 @@
#ifndef PKG_H_
#define PKG_H_
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#include <libconfig.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/stat.h>
#include "common.h"
typedef struct {
int maj;
int min;
int pat;
char *tag;
}
semver_t;
typedef struct {
char *dep_name;
semver_t dep_ver;
}
dep_t;
typedef struct {
char *conf_name;
semver_t conf_ver;
}
conf_t;
typedef struct {
char *pkg_name;
semver_t pkg_ver;
char *pkg_desc;
char *pkg_maint;
char *pkg_copyright;
char *pkg_repo;
dep_t *pkg_dependencies;
conf_t *pkg_conflicts;
/* PKG_TRAITS (BUILD_DESIGN.txt section 8): "ssl\n-ldap\n", one
* "NAME" (on) or "-NAME" (off) line per trait; NULL if the manifest
* has none. */
char *pkg_traits;
}
gl_pkg_t;
semver_t gl_parse_semver(const char *str);
void gl_free_semver(semver_t *v);
void gl_free_pkg(gl_pkg_t *pkg);
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);
/* Build settings (BUILD_DESIGN.txt section 5), as gl_conf_build reads
* them from one file; every string is NULL where the file doesn't set
* it, jobs is 0. traits is "NAME\n" / "-NAME\n" lines, configure and
* build_root "S\n" lines. */
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, /* /etc/glacier/glacier.conf */
GL_CONF_USER = 1, /* <user>/config/glacier.conf */
GL_CONF_PACKAGE = 2 /* .../config/NAME.conf */
} 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);
/* A repository index (REPO_DESIGN.txt section 4), as gl_index_parse
* reads it. deps/confs are "NAME VER\n" lines ("" for none). In a -src
* index (BUILD_DESIGN.txt section 3), deps/confs/build_deps lines may
* end in " IF" ("NAME VER ssl\n", "NAME VER -ssl\n") and traits are
* "NAME 1\n" / "NAME 0\n" (the default); both are "" in a binary
* index. */
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);
/* A recipe (BUILD_DESIGN.txt section 4), as gl_recipe_parse reads it.
* Every list is newline-terminated lines, "" for none:
* sources "URL sha256:HEX\n"
* patches "FILE\n"
* configure "ARG\n"
* traits "NAME 1\n" / "NAME 0\n" (the default), as an index
* trait_args "NAME\t+\tARG\n" (ON) / "NAME\t-\tARG\n" (OFF)
* deps, build_deps, confs "NAME VER[ IF]\n", as a -src index
* build is "" (autodetect) or autotools, cmake, meson, make, hooks. */
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;
/* The largest recipe file, and the most traits a recipe declares. */
#define GL_RECIPE_MAX (1024 * 1024)
#define GL_MAX_TRAITS 32
gl_recipe_status_t gl_recipe_parse(const char *text, size_t len, gl_recipe_t *out);
/* Why the last gl_recipe_parse / gl_recipe_read in this thread failed:
* a short phrase, no final period, printable ASCII; "" after a success. */
const char *gl_recipe_error(void);
void gl_recipe_free(gl_recipe_t *r);
bool gl_valid_trait(const char *s);
bool gl_valid_pkg_ident(const char *s);
int gl_gpm2gpkg(const char *filename, gl_pkg_t *pkg);
#endif
+256
View File
@@ -0,0 +1,256 @@
/*
* Recipe bundles (BUILD_DESIGN.txt section 4): NAME-VER.grcp, a gzip
* tar holding NAME-VER/recipe, optionally NAME-VER/build and
* NAME-VER/patches/FILE, and nothing else.
*/
#define _POSIX_C_SOURCE 200809L
#define _XOPEN_SOURCE 700
#include <archive.h>
#include <archive_entry.h>
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "pkg.h"
#include "recipe.h"
/* What an entry below the top directory is: 0 the top itself, 1
* recipe, 2 build, 3 patches/, 4 patches/FILE; -1 anything else. */
static int
entry_kind(const char *rel, bool dir)
{
if (*rel == '\0')
return dir ? 0 : -1;
if (strcmp(rel, "recipe") == 0)
return dir ? -1 : 1;
if (strcmp(rel, "build") == 0)
return dir ? -1 : 2;
if (strcmp(rel, "patches") == 0)
return dir ? 3 : -1;
if (strncmp(rel, "patches/", 8) == 0 && !dir && gl_valid_pkg_ident(rel + 8))
return 4;
return -1;
}
/* Whether "FILE\n" is one of `lines`. */
static bool
listed(const char *lines, const char *file)
{
size_t l = strlen(file);
for (const char *p = lines; *p; p = strchr(p, '\n') + 1)
if (strncmp(p, file, l) == 0 && p[l] == '\n')
return true;
return false;
}
/*
* gl_recipe_read
* DESCRIPTION: read and check a recipe bundle, and parse its recipe
* into *out (zeroed first; gl_recipe_free it on GL_RECIPE_OK).
* Nothing is extracted. Every entry is checked, not only the
* recipe: the builder unpacks the bundle (inside the sandbox),
* so what it holds must be exactly what this function allowed.
*
* The bundle is refused (GL_RECIPE_ERR_BUNDLE) unless: every
* entry is a regular file or directory (no symlinks, hardlinks,
* devices), under one top directory TOP named NAME-VER as the
* recipe says; the only entries are TOP/, TOP/recipe (required),
* TOP/build, TOP/patches/ and TOP/patches/FILE (a
* gl_valid_pkg_ident), none twice; the patches are exactly the
* recipe's PATCHES; BUILD = "hooks" has a TOP/build; the
* entries' sizes add up to at most GL_BUNDLE_MAX.
* RETURNS: GL_RECIPE_OK, GL_RECIPE_ERR_READ (not a readable gzip tar),
* GL_RECIPE_ERR_BUNDLE, GL_RECIPE_ERR_FORMAT (the recipe itself),
* GL_RECIPE_ERR_NOMEM
*/
gl_recipe_status_t
gl_recipe_read(const char *bundle, gl_recipe_t *out)
{
gl_recipe_set_error("%s", "");
if (!out)
return GL_RECIPE_ERR_FORMAT;
memset(out, 0, sizeof(*out));
struct archive *a = archive_read_new();
if (!a) {
gl_recipe_set_error("out of memory");
return GL_RECIPE_ERR_NOMEM;
}
archive_read_support_filter_gzip(a);
archive_read_support_format_tar(a);
if (archive_read_open_filename(a, bundle, 10240) != ARCHIVE_OK) {
gl_recipe_set_error("not a gzip tar (%s)", archive_error_string(a) ?
archive_error_string(a) : "unreadable");
archive_read_free(a);
return GL_RECIPE_ERR_READ;
}
gl_recipe_status_t st = GL_RECIPE_ERR_BUNDLE;
char top[PATH_MAX] = "";
char *recipe = NULL, *patches = NULL;
size_t rlen = 0, plen = 0;
int64_t total = 0;
bool seen[4] = { false, false, false, false };
struct archive_entry *e;
int r;
while ((r = archive_read_next_header(a, &e)) == ARCHIVE_OK) {
const char *path = archive_entry_pathname(e);
mode_t type = archive_entry_filetype(e);
bool dir = type == AE_IFDIR;
if (!path) {
gl_recipe_set_error("an entry has no path");
goto out;
}
if ((!dir && type != AE_IFREG) || archive_entry_hardlink(e) ||
archive_entry_symlink(e) || archive_entry_size(e) < 0) {
gl_recipe_set_error("%s is not a regular file or directory", path);
goto out;
}
total += archive_entry_size(e);
if (total > GL_BUNDLE_MAX) {
gl_recipe_set_error("its files add up to more than %d bytes",
GL_BUNDLE_MAX);
goto out;
}
/* "TOP/rel", a directory possibly with a trailing '/'. */
char p[PATH_MAX];
size_t l = strlen(path);
if (l == 0 || l >= sizeof p) {
gl_recipe_set_error("an entry's path is empty or too long");
goto out;
}
memcpy(p, path, l + 1);
if (dir && p[l - 1] == '/')
p[--l] = '\0';
char *slash = strchr(p, '/');
const char *rel = slash ? slash + 1 : "";
if (slash)
*slash = '\0';
if (!gl_valid_pkg_ident(p)) {
gl_recipe_set_error("%s is not under a NAME-VER directory", path);
goto out;
}
if (*top && strcmp(top, p) != 0) {
gl_recipe_set_error("it has two top directories, %s and %s", top, p);
goto out;
}
snprintf(top, sizeof top, "%s", p);
int kind = entry_kind(rel, dir);
if (kind < 0) {
gl_recipe_set_error("%s is not allowed (only recipe, build and "
"patches/FILE)", path);
goto out;
}
if (kind < 4) {
if (seen[kind]) {
gl_recipe_set_error("%s appears twice", path);
goto out;
}
seen[kind] = true;
} else {
/* One patch twice would be listed twice. */
size_t fl = strlen(rel + 8);
if (patches && listed(patches, rel + 8)) {
gl_recipe_set_error("%s appears twice", path);
goto out;
}
char *grown = realloc(patches, plen + fl + 2);
if (!grown) {
gl_recipe_set_error("out of memory");
st = GL_RECIPE_ERR_NOMEM;
goto out;
}
patches = grown;
memcpy(patches + plen, rel + 8, fl);
patches[plen + fl] = '\n';
plen += fl + 1;
patches[plen] = '\0';
}
if (kind == 1) {
if (archive_entry_size(e) > GL_RECIPE_MAX) {
gl_recipe_set_error("the recipe is larger than %d bytes",
GL_RECIPE_MAX);
goto out;
}
rlen = (size_t)archive_entry_size(e);
if (!(recipe = malloc(rlen + 1))) {
gl_recipe_set_error("out of memory");
st = GL_RECIPE_ERR_NOMEM;
goto out;
}
la_ssize_t got = rlen ? archive_read_data(a, recipe, rlen) : 0;
if (got < 0 || (size_t)got != rlen) {
gl_recipe_set_error("cannot read %s", path);
st = GL_RECIPE_ERR_READ;
goto out;
}
recipe[rlen] = '\0';
} else if (archive_read_data_skip(a) != ARCHIVE_OK) {
gl_recipe_set_error("cannot read %s", path);
st = GL_RECIPE_ERR_READ;
goto out;
}
}
if (r != ARCHIVE_EOF) {
gl_recipe_set_error("not a readable gzip tar (%s)", archive_error_string(a) ?
archive_error_string(a) : "truncated");
st = GL_RECIPE_ERR_READ;
goto out;
}
if (!recipe) {
gl_recipe_set_error("it has no recipe");
goto out;
}
st = gl_recipe_parse(recipe, rlen, out);
if (st != GL_RECIPE_OK)
goto out;
char want[PATH_MAX];
snprintf(want, sizeof want, "%s-%s", out->name, out->ver);
bool ok = strcmp(top, want) == 0;
if (!ok)
gl_recipe_set_error("its top directory is %s, but the recipe says %s",
top, want);
else if (!(ok = strcmp(out->build, "hooks") != 0 || seen[2]))
gl_recipe_set_error("BUILD = \"hooks\" needs a build file");
/* The patches present are exactly the ones PATCHES lists. */
size_t listed_n = 0, present_n = 0;
for (const char *q = out->patches; ok && *q; q = strchr(q, '\n') + 1) {
char f[PATH_MAX];
size_t fl = (size_t)(strchr(q, '\n') - q);
snprintf(f, sizeof f, "%.*s", (int)fl, q);
if (!(ok = patches && listed(patches, f)))
gl_recipe_set_error("PATCHES lists %s, but there is no patches/%s",
f, f);
listed_n++;
}
for (const char *q = patches; ok && q && *q; q = strchr(q, '\n') + 1)
present_n++;
for (const char *q = patches; ok && listed_n != present_n && q && *q;
q = strchr(q, '\n') + 1) {
char f[PATH_MAX];
snprintf(f, sizeof f, "%.*s", (int)(strchr(q, '\n') - q), q);
if (!listed(out->patches, f)) {
gl_recipe_set_error("patches/%s is not in PATCHES", f);
break;
}
}
if (!ok || listed_n != present_n) {
gl_recipe_free(out);
st = GL_RECIPE_ERR_BUNDLE;
}
out:
free(recipe);
free(patches);
archive_read_free(a);
return st;
}
+15
View File
@@ -0,0 +1,15 @@
#ifndef RECIPE_H_
#define RECIPE_H_
#include "pkg.h"
/* The largest recipe bundle, by the sum of its entries' sizes. */
#define GL_BUNDLE_MAX (16 * 1024 * 1024)
gl_recipe_status_t gl_recipe_read(const char *bundle, gl_recipe_t *out);
/* Set what gl_recipe_error returns (internal: pkg.c and recipe.c).
* Always returns false. */
bool gl_recipe_set_error(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
#endif
-4
View File
@@ -1,4 +0,0 @@
#define _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#define _XOPEN_SOURCE 700
-45
View File
@@ -1,45 +0,0 @@
#define _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#define _XOPEN_SOURCE 700
#include <stdbool.h>
#include <stddef.h>
#include <unistd.h>
#include "color.h"
bool
lg_is_root(void)
{
if (getuid() != 0) {
return false;
}
else if (getuid() == 0) {
return true;
}
else {
return false;
}
}
bool
lg_runtime_exists(void)
{
const char *rt_files[] = {
"/etc/glacier/glacier.conf",
"/etc/glacier/make.conf"
};
size_t num_of_files = sizeof(rt_files) / sizeof(rt_files[0]);
for (size_t f_index = 0; f_index < num_of_files; f_index++) {
if (access(rt_files[f_index], F_OK) == 0) {
continue;
}
else {
return false;
}
}
return true;
}
+203
View File
@@ -0,0 +1,203 @@
/*
* gl_sha256 — vendored SHA-256 (FIPS 180-4).
* See sha256.h for API rationale.
*/
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "sha256.h"
#define ROTRIGHT(a, b) (((a) >> (b)) | ((a) << (32 - (b))))
#define CH(x, y, z) (((x) & (y)) ^ (~(x) & (z)))
#define MAJ(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z)))
#define EP0(x) (ROTRIGHT(x, 2) ^ ROTRIGHT(x, 13) ^ ROTRIGHT(x, 22))
#define EP1(x) (ROTRIGHT(x, 6) ^ ROTRIGHT(x, 11) ^ ROTRIGHT(x, 25))
#define SIG0(x) (ROTRIGHT(x, 7) ^ ROTRIGHT(x, 18) ^ ((x) >> 3))
#define SIG1(x) (ROTRIGHT(x, 17) ^ ROTRIGHT(x, 19) ^ ((x) >> 10))
static const uint32_t k[64] = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
};
static void
sha256_transform(gl_sha256_ctx_t *ctx, const uint8_t data[64])
{
uint32_t m[64];
uint32_t i, j;
for (i = 0, j = 0; i < 16; ++i, j += 4) {
m[i] = ((uint32_t)data[j] << 24) |
((uint32_t)data[j + 1] << 16) |
((uint32_t)data[j + 2] << 8) |
((uint32_t)data[j + 3]);
}
for (; i < 64; ++i) {
m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16];
}
uint32_t a = ctx->state[0];
uint32_t b = ctx->state[1];
uint32_t c = ctx->state[2];
uint32_t d = ctx->state[3];
uint32_t e = ctx->state[4];
uint32_t f = ctx->state[5];
uint32_t g = ctx->state[6];
uint32_t h = ctx->state[7];
for (i = 0; i < 64; ++i) {
uint32_t t1 = h + EP1(e) + CH(e, f, g) + k[i] + m[i];
uint32_t t2 = EP0(a) + MAJ(a, b, c);
h = g;
g = f;
f = e;
e = d + t1;
d = c;
c = b;
b = a;
a = t1 + t2;
}
ctx->state[0] += a;
ctx->state[1] += b;
ctx->state[2] += c;
ctx->state[3] += d;
ctx->state[4] += e;
ctx->state[5] += f;
ctx->state[6] += g;
ctx->state[7] += h;
}
void
gl_sha256_init(gl_sha256_ctx_t *ctx)
{
ctx->datalen = 0;
ctx->bitlen = 0;
ctx->state[0] = 0x6a09e667;
ctx->state[1] = 0xbb67ae85;
ctx->state[2] = 0x3c6ef372;
ctx->state[3] = 0xa54ff53a;
ctx->state[4] = 0x510e527f;
ctx->state[5] = 0x9b05688c;
ctx->state[6] = 0x1f83d9ab;
ctx->state[7] = 0x5be0cd19;
}
void
gl_sha256_update(gl_sha256_ctx_t *ctx, const uint8_t *data, size_t len)
{
size_t i;
for (i = 0; i < len; ++i) {
ctx->data[ctx->datalen] = data[i];
ctx->datalen++;
if (ctx->datalen == 64) {
sha256_transform(ctx, ctx->data);
ctx->bitlen += 512;
ctx->datalen = 0;
}
}
}
void
gl_sha256_final(gl_sha256_ctx_t *ctx, uint8_t digest[GL_SHA256_DIGEST_SIZE])
{
size_t i = ctx->datalen;
if (ctx->datalen < 56) {
ctx->data[i++] = 0x80;
while (i < 56) {
ctx->data[i++] = 0x00;
}
} else {
ctx->data[i++] = 0x80;
while (i < 64) {
ctx->data[i++] = 0x00;
}
sha256_transform(ctx, ctx->data);
memset(ctx->data, 0, 56);
}
ctx->bitlen += (uint64_t)ctx->datalen * 8;
ctx->data[63] = (uint8_t)(ctx->bitlen);
ctx->data[62] = (uint8_t)(ctx->bitlen >> 8);
ctx->data[61] = (uint8_t)(ctx->bitlen >> 16);
ctx->data[60] = (uint8_t)(ctx->bitlen >> 24);
ctx->data[59] = (uint8_t)(ctx->bitlen >> 32);
ctx->data[58] = (uint8_t)(ctx->bitlen >> 40);
ctx->data[57] = (uint8_t)(ctx->bitlen >> 48);
ctx->data[56] = (uint8_t)(ctx->bitlen >> 56);
sha256_transform(ctx, ctx->data);
for (i = 0; i < 4; ++i) {
uint32_t shift = 24 - (uint32_t)i * 8;
digest[i] = (uint8_t)((ctx->state[0] >> shift) & 0xffU);
digest[i + 4] = (uint8_t)((ctx->state[1] >> shift) & 0xffU);
digest[i + 8] = (uint8_t)((ctx->state[2] >> shift) & 0xffU);
digest[i + 12] = (uint8_t)((ctx->state[3] >> shift) & 0xffU);
digest[i + 16] = (uint8_t)((ctx->state[4] >> shift) & 0xffU);
digest[i + 20] = (uint8_t)((ctx->state[5] >> shift) & 0xffU);
digest[i + 24] = (uint8_t)((ctx->state[6] >> shift) & 0xffU);
digest[i + 28] = (uint8_t)((ctx->state[7] >> shift) & 0xffU);
}
}
void
gl_sha256_to_hex(const uint8_t digest[GL_SHA256_DIGEST_SIZE], char *out)
{
static const char hexchars[] = "0123456789abcdef";
size_t i;
for (i = 0; i < GL_SHA256_DIGEST_SIZE; i++) {
out[i * 2] = hexchars[(digest[i] >> 4) & 0x0fU];
out[i * 2 + 1] = hexchars[digest[i] & 0x0fU];
}
out[GL_SHA256_DIGEST_SIZE * 2] = '\0';
}
int
gl_sha256_file(const char *path, char *hex_out)
{
FILE *f = fopen(path, "rb");
if (!f) {
return -1;
}
gl_sha256_ctx_t ctx;
gl_sha256_init(&ctx);
uint8_t buf[65536];
size_t n;
while ((n = fread(buf, 1, sizeof(buf), f)) > 0) {
gl_sha256_update(&ctx, buf, n);
}
if (ferror(f)) {
fclose(f);
errno = EIO;
return -1;
}
fclose(f);
uint8_t digest[GL_SHA256_DIGEST_SIZE];
gl_sha256_final(&ctx, digest);
gl_sha256_to_hex(digest, hex_out);
return 0;
}
+26
View File
@@ -0,0 +1,26 @@
#ifndef GL_SHA256_H_
#define GL_SHA256_H_
#include <stddef.h>
#include <stdint.h>
#define GL_SHA256_DIGEST_SIZE 32
#define GL_SHA256_HEX_SIZE (GL_SHA256_DIGEST_SIZE * 2 + 1)
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[GL_SHA256_DIGEST_SIZE]);
void gl_sha256_to_hex(const uint8_t digest[GL_SHA256_DIGEST_SIZE], char *out);
int gl_sha256_file(const char *path, char *hex_out);
#endif
+428
View File
@@ -0,0 +1,428 @@
/*
* gl_sign: Ed25519 signatures in signify's file formats. See sign.h.
*
* Parsing is strict: exactly two lines, the "untrusted comment: "
* prefix, canonical base64 of exactly the expected length, the right
* algorithm bytes. Anything else is GL_SIGN_ERR_FORMAT.
*/
#define _POSIX_C_SOURCE 200809L
#define _DEFAULT_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/random.h>
#include <sys/stat.h>
#include <unistd.h>
#include "sign.h"
#include "monocypher/monocypher.h"
#include "monocypher/monocypher-ed25519.h"
#define COMMENT_PREFIX "untrusted comment: "
#define COMMENT_PREFIX_LEN (sizeof COMMENT_PREFIX - 1)
/* Decoded sizes of the three kinds of file. */
#define PUBKEY_BYTES 42
#define SIG_BYTES 74
#define SECKEY_BYTES 104
/* A key or signature file is a few hundred bytes at most. */
#define MAX_KEYFILE (COMMENT_PREFIX_LEN + GL_SIGN_MAX_COMMENT + 1 + 4 * ((SECKEY_BYTES + 2) / 3) + 1)
/* Reads all of a regular file (at most `max` bytes) into a malloc'd
* buffer. */
static int
read_all(const char *path, size_t max, uint8_t **out, size_t *len)
{
int fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0)
return GL_SIGN_ERR_IO;
struct stat st;
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
close(fd);
return GL_SIGN_ERR_IO;
}
if (st.st_size < 0 || (uintmax_t)st.st_size > max) {
close(fd);
return GL_SIGN_ERR_TOOBIG;
}
size_t size = (size_t)st.st_size;
uint8_t *buf = malloc(size ? size : 1);
if (!buf) {
close(fd);
return GL_SIGN_ERR_IO;
}
size_t got = 0;
while (got < size) {
ssize_t n = read(fd, buf + got, size - got);
if (n < 0 && errno == EINTR)
continue;
if (n <= 0)
break;
got += (size_t)n;
}
/* The file must not have grown or shrunk under us. */
uint8_t extra;
ssize_t more = read(fd, &extra, 1);
close(fd);
if (got != size || more != 0) {
free(buf);
return GL_SIGN_ERR_IO;
}
*out = buf;
*len = size;
return GL_SIGN_OK;
}
static int
b64_value(uint8_t c)
{
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
}
/* Decodes canonical, padded base64 that must yield exactly `outlen`
* bytes. Returns 0 on success. */
static int
b64_decode_exact(const uint8_t *in, size_t n, uint8_t *out, size_t outlen)
{
if (n != (outlen + 2) / 3 * 4)
return -1;
size_t o = 0;
for (size_t i = 0; i < n; i += 4) {
uint32_t t = 0;
size_t pad = 0;
for (size_t j = 0; j < 4; j++) {
uint8_t c = in[i + j];
int v;
if (c == '=') {
/* Padding only in the last quartet's last two places. */
if (i + 4 != n || j < 2)
return -1;
pad++;
v = 0;
} else {
if (pad)
return -1;
v = b64_value(c);
if (v < 0)
return -1;
}
t = (t << 6) | (uint32_t)v;
}
/* Canonical: the bits padding drops must be zero. */
if ((pad == 1 && (t & 0xffu)) || (pad == 2 && (t & 0xffffu)))
return -1;
size_t bytes = 3 - pad;
if (o + bytes > outlen)
return -1;
uint8_t b[3] = { (uint8_t)(t >> 16), (uint8_t)(t >> 8), (uint8_t)t };
memcpy(out + o, b, bytes);
o += bytes;
}
return o == outlen ? 0 : -1;
}
static void
b64_encode(const uint8_t *in, size_t n, char *out)
{
static const char tab[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
size_t o = 0;
for (size_t i = 0; i < n; i += 3) {
uint32_t t = (uint32_t)in[i] << 16;
if (i + 1 < n) t |= (uint32_t)in[i + 1] << 8;
if (i + 2 < n) t |= in[i + 2];
out[o++] = tab[(t >> 18) & 63];
out[o++] = tab[(t >> 12) & 63];
out[o++] = i + 1 < n ? tab[(t >> 6) & 63] : '=';
out[o++] = i + 2 < n ? tab[t & 63] : '=';
}
out[o] = '\0';
}
/* Reads a signify file and decodes its payload into out[0..outlen). */
static int
read_signify(const char *path, uint8_t *out, size_t outlen)
{
uint8_t *buf;
size_t len;
int st = read_all(path, MAX_KEYFILE, &buf, &len);
if (st == GL_SIGN_ERR_TOOBIG)
return GL_SIGN_ERR_FORMAT;
if (st != GL_SIGN_OK)
return st;
st = GL_SIGN_ERR_FORMAT;
if (len < COMMENT_PREFIX_LEN || memcmp(buf, COMMENT_PREFIX, COMMENT_PREFIX_LEN) != 0)
goto out;
uint8_t *nl = memchr(buf, '\n', len);
if (!nl || memchr(buf, '\0', (size_t)(nl - buf)))
goto out;
if ((size_t)(nl - buf) - COMMENT_PREFIX_LEN > GL_SIGN_MAX_COMMENT)
goto out;
/* The base64 line runs to a final newline that ends the file. */
uint8_t *b64 = nl + 1;
uint8_t *end = buf + len;
if (b64 >= end || end[-1] != '\n')
goto out;
if (b64_decode_exact(b64, (size_t)(end - 1 - b64), out, outlen) != 0)
goto out;
if (out[0] != 'E' || out[1] != 'd')
goto out;
st = GL_SIGN_OK;
out:
crypto_wipe(buf, len);
free(buf);
return st;
}
int
gl_sign_read_pubkey(const char *path, gl_sign_pubkey_t *out)
{
uint8_t raw[PUBKEY_BYTES];
int st = read_signify(path, raw, sizeof raw);
if (st != GL_SIGN_OK)
return st;
memcpy(out->keynum, raw + 2, GL_SIGN_KEYNUM_SIZE);
memcpy(out->key, raw + 10, sizeof out->key);
return GL_SIGN_OK;
}
int
gl_sign_read_sig(const char *path, gl_sign_sig_t *out)
{
uint8_t raw[SIG_BYTES];
int st = read_signify(path, raw, sizeof raw);
if (st != GL_SIGN_OK)
return st;
memcpy(out->keynum, raw + 2, GL_SIGN_KEYNUM_SIZE);
memcpy(out->sig, raw + 10, sizeof out->sig);
return GL_SIGN_OK;
}
/* sec[0..64) = seed | public key, as signify and Monocypher both lay
* it out. */
static int
read_seckey(const char *path, uint8_t keynum[GL_SIGN_KEYNUM_SIZE], uint8_t sec[64])
{
uint8_t raw[SECKEY_BYTES];
int st = read_signify(path, raw, sizeof raw);
if (st != GL_SIGN_OK)
goto out;
st = GL_SIGN_ERR_FORMAT;
if (raw[2] != 'B' || raw[3] != 'K')
goto out;
uint32_t rounds = (uint32_t)raw[4] << 24 | (uint32_t)raw[5] << 16
| (uint32_t)raw[6] << 8 | raw[7];
if (rounds != 0) {
st = GL_SIGN_ERR_ENCRYPTED;
goto out;
}
/* checksum = the first 8 bytes of SHA-512(seckey) */
uint8_t digest[64];
crypto_sha512(digest, raw + 40, 64);
int ok = memcmp(digest, raw + 24, 8) == 0;
crypto_wipe(digest, sizeof digest);
if (!ok)
goto out;
memcpy(keynum, raw + 32, GL_SIGN_KEYNUM_SIZE);
memcpy(sec, raw + 40, 64);
st = GL_SIGN_OK;
out:
crypto_wipe(raw, sizeof raw);
return st;
}
int
gl_sign_check_seckey(const char *path)
{
uint8_t keynum[GL_SIGN_KEYNUM_SIZE], sec[64];
int st = read_seckey(path, keynum, sec);
crypto_wipe(sec, sizeof sec);
return st;
}
int
gl_sign_verify(const gl_sign_pubkey_t *pub, const gl_sign_sig_t *sig,
const uint8_t *msg, size_t len)
{
if (memcmp(pub->keynum, sig->keynum, GL_SIGN_KEYNUM_SIZE) != 0)
return GL_SIGN_ERR_KEYNUM;
return crypto_ed25519_check(sig->sig, pub->key, msg, len) == 0
? GL_SIGN_OK : GL_SIGN_ERR_BAD;
}
int
gl_sign_verify_file(const char *pubkey_path, const char *msg_path,
const char *sig_path)
{
gl_sign_pubkey_t pub;
gl_sign_sig_t sig;
int st = gl_sign_read_pubkey(pubkey_path, &pub);
if (st != GL_SIGN_OK)
return st;
st = gl_sign_read_sig(sig_path, &sig);
if (st != GL_SIGN_OK)
return st;
/* Cheap mismatch first: no need to read the message. */
if (memcmp(pub.keynum, sig.keynum, GL_SIGN_KEYNUM_SIZE) != 0)
return GL_SIGN_ERR_KEYNUM;
uint8_t *msg;
size_t len;
st = read_all(msg_path, GL_SIGN_MAX_MSG, &msg, &len);
if (st != GL_SIGN_OK)
return st;
st = gl_sign_verify(&pub, &sig, msg, len);
free(msg);
return st;
}
/* Writes "untrusted comment: COMMENT\n" + base64(raw) + "\n" to an fd
* opened with `flags`. */
static int
write_signify(const char *path, int flags, mode_t mode, const char *comment,
const uint8_t *raw, size_t rawlen)
{
char b64[4 * ((SECKEY_BYTES + 2) / 3) + 1];
if (rawlen > SECKEY_BYTES)
return GL_SIGN_ERR_WRITE;
b64_encode(raw, rawlen, b64);
int fd = open(path, O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC | flags, mode);
if (fd < 0)
return errno == EEXIST ? GL_SIGN_ERR_EXISTS : GL_SIGN_ERR_WRITE;
/* Exactly `mode`, whatever the umask: a secret key 0600, a public
* key 0644 (users' gpkg reads the system's keys). */
if (fchmod(fd, mode) != 0) {
close(fd);
return GL_SIGN_ERR_WRITE;
}
FILE *f = fdopen(fd, "w");
if (!f) {
close(fd);
return GL_SIGN_ERR_WRITE;
}
int bad = fprintf(f, COMMENT_PREFIX "%s\n%s\n", comment, b64) < 0;
crypto_wipe(b64, sizeof b64);
if (fclose(f) != 0 || bad)
return GL_SIGN_ERR_WRITE;
return GL_SIGN_OK;
}
int
gl_sign_file(const char *seckey_path, const char *msg_path, const char *sig_path)
{
uint8_t keynum[GL_SIGN_KEYNUM_SIZE], sec[64];
int st = read_seckey(seckey_path, keynum, sec);
if (st != GL_SIGN_OK)
return st;
uint8_t *msg;
size_t len;
st = read_all(msg_path, GL_SIGN_MAX_MSG, &msg, &len);
if (st != GL_SIGN_OK) {
crypto_wipe(sec, sizeof sec);
return st;
}
uint8_t raw[SIG_BYTES] = { 'E', 'd' };
memcpy(raw + 2, keynum, GL_SIGN_KEYNUM_SIZE);
crypto_ed25519_sign(raw + 10, sec, msg, len);
crypto_wipe(sec, sizeof sec);
free(msg);
/* "verify with NAME.pub", NAME = the secret key's name minus .sec */
const char *base = strrchr(seckey_path, '/');
base = base ? base + 1 : seckey_path;
size_t blen = strlen(base);
if (blen > 4 && strcmp(base + blen - 4, ".sec") == 0)
blen -= 4;
if (blen > GL_SIGN_MAX_COMMENT - 16)
blen = GL_SIGN_MAX_COMMENT - 16;
char comment[GL_SIGN_MAX_COMMENT + 1];
snprintf(comment, sizeof comment, "verify with %.*s.pub", (int)blen, base);
return write_signify(sig_path, O_TRUNC, 0644, comment, raw, sizeof raw);
}
static int
random_bytes(uint8_t *buf, size_t n)
{
while (n > 0) {
ssize_t got = getrandom(buf, n, 0);
if (got < 0 && errno == EINTR)
continue;
if (got <= 0)
return -1;
buf += got;
n -= (size_t)got;
}
return 0;
}
int
gl_sign_generate(const char *pubkey_path, const char *seckey_path,
const char *comment)
{
if (strchr(comment, '\n') || strlen(comment) > GL_SIGN_MAX_COMMENT - 11)
return GL_SIGN_ERR_FORMAT;
/* rand = seed[32] | keynum[8] | salt[16] */
uint8_t rand[56];
if (random_bytes(rand, sizeof rand) != 0)
return GL_SIGN_ERR_RANDOM;
uint8_t sec[64], pub[32];
crypto_ed25519_key_pair(sec, pub, rand); /* wipes the seed */
uint8_t sraw[SECKEY_BYTES] = { 'E', 'd', 'B', 'K', 0, 0, 0, 0 };
memcpy(sraw + 8, rand + 40, 16); /* salt (unused at 0 rounds) */
uint8_t digest[64];
crypto_sha512(digest, sec, sizeof sec);
memcpy(sraw + 24, digest, 8); /* checksum */
memcpy(sraw + 32, rand + 32, GL_SIGN_KEYNUM_SIZE);
memcpy(sraw + 40, sec, sizeof sec);
uint8_t praw[PUBKEY_BYTES] = { 'E', 'd' };
memcpy(praw + 2, rand + 32, GL_SIGN_KEYNUM_SIZE);
memcpy(praw + 10, pub, sizeof pub);
char c[GL_SIGN_MAX_COMMENT + 1];
snprintf(c, sizeof c, "%s secret key", comment);
int st = write_signify(seckey_path, O_EXCL, 0600, c, sraw, sizeof sraw);
if (st == GL_SIGN_OK) {
snprintf(c, sizeof c, "%s public key", comment);
st = write_signify(pubkey_path, O_EXCL, 0644, c, praw, sizeof praw);
/* Never leave a secret key without its public half. */
if (st != GL_SIGN_OK)
unlink(seckey_path);
}
crypto_wipe(rand, sizeof rand);
crypto_wipe(sec, sizeof sec);
crypto_wipe(sraw, sizeof sraw);
crypto_wipe(digest, sizeof digest);
return st;
}
+82
View File
@@ -0,0 +1,82 @@
#ifndef GL_SIGN_H_
#define GL_SIGN_H_
/*
* gl_sign: Ed25519 signatures in OpenBSD signify's file formats
* (REPO_DESIGN.txt section 2). Private to libglacier_verify.so, like
* sha256.h: no public header is installed.
*
* Every file is two lines, "untrusted comment: ..." and base64 of:
* public key "Ed" | keynum[8] | pubkey[32]
* signature "Ed" | keynum[8] | sig[64]
* secret key "Ed" | "BK" | rounds[4, big-endian] | salt[16] |
* checksum[8] | keynum[8] | seckey[64]
* Only unencrypted secret keys (rounds == 0, `signify -G -n`) are
* read; an encrypted one is GL_SIGN_ERR_ENCRYPTED.
*
* Signatures are pure Ed25519 over the whole message, as signify's, so
* `signify -V -p KEY.pub -m FILE` checks what gl_sign_file makes and
* gl_sign_verify_file checks what signify makes.
*/
#include <stddef.h>
#include <stdint.h>
#define GL_SIGN_KEYNUM_SIZE 8
/* Largest message signed or verified: the whole file is read. */
#define GL_SIGN_MAX_MSG (64u * 1024u * 1024u)
/* Longest comment signify accepts. */
#define GL_SIGN_MAX_COMMENT 1024
typedef enum {
GL_SIGN_OK = 0,
GL_SIGN_ERR_IO = 1, /* a file can't be opened or read */
GL_SIGN_ERR_FORMAT = 2, /* not a well-formed file of the expected kind */
GL_SIGN_ERR_ENCRYPTED = 3, /* a passphrase-protected secret key */
GL_SIGN_ERR_KEYNUM = 4, /* the signature was made by another key */
GL_SIGN_ERR_BAD = 5, /* the signature does not verify */
GL_SIGN_ERR_TOOBIG = 6, /* message larger than GL_SIGN_MAX_MSG */
GL_SIGN_ERR_RANDOM = 7, /* no randomness for a new key */
GL_SIGN_ERR_EXISTS = 8, /* a key file to create already exists */
GL_SIGN_ERR_WRITE = 9, /* a file to write can't be created or written */
} gl_sign_status_t;
typedef struct {
uint8_t keynum[GL_SIGN_KEYNUM_SIZE];
uint8_t key[32];
} gl_sign_pubkey_t;
typedef struct {
uint8_t keynum[GL_SIGN_KEYNUM_SIZE];
uint8_t sig[64];
} gl_sign_sig_t;
int gl_sign_read_pubkey(const char *path, gl_sign_pubkey_t *out);
/* Reads a secret key only to check it (then wipes it). */
int gl_sign_check_seckey(const char *path);
int gl_sign_read_sig(const char *path, gl_sign_sig_t *out);
/* Checks `sig` over msg[0..len) with `pub`: GL_SIGN_ERR_KEYNUM before
* any crypto if the keynums differ, else GL_SIGN_OK or GL_SIGN_ERR_BAD. */
int gl_sign_verify(const gl_sign_pubkey_t *pub, const gl_sign_sig_t *sig,
const uint8_t *msg, size_t len);
/* Reads all three files and verifies. The status names the first
* problem found, in the order: public key, signature, message, check. */
int gl_sign_verify_file(const char *pubkey_path, const char *msg_path,
const char *sig_path);
/* Signs msg_path with the secret key, writing sig_path (replaced if it
* exists, never followed if it's a symlink). The signature's comment
* is "verify with NAME.pub", NAME being the secret key's file name
* without ".sec", as signify writes it. */
int gl_sign_file(const char *seckey_path, const char *msg_path,
const char *sig_path);
/* Makes a new keypair. Neither file may exist (GL_SIGN_ERR_EXISTS).
* The secret key is created 0600 and unencrypted; the comments are
* "COMMENT public key" / "COMMENT secret key". */
int gl_sign_generate(const char *pubkey_path, const char *seckey_path,
const char *comment);
#endif
+626
View File
@@ -0,0 +1,626 @@
#include <linux/limits.h>
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "common.h"
#include "deps.h"
#include "istoreutils.h"
#include "log.h"
#include "transaction.h"
/* The one directory a scope owns; everything below derives from it.
* See the layout comment in common.h. */
/* `sysroot` is the install root ("" for the running system, see
* gl_context_t). User scope never has one (set_sysroot refuses it). */
static void
scope_base(gl_ctx_scope_t scope, uid_t uid, const char *sysroot, char *out)
{
switch (scope) {
case GL_SCOPE_USR:
gl_usr_base(uid, out, PATH_MAX);
break;
case GL_SCOPE_SYS:
snprintf(out, PATH_MAX, "%s%s", sysroot, GL_SYS_ROOT);
break;
}
}
static void
scope_subdir(gl_ctx_scope_t scope, uid_t uid, const char *sysroot,
const char *name, char *out)
{
char base[PATH_MAX];
scope_base(scope, uid, sysroot, base);
snprintf(out, PATH_MAX, "%s/%s", base, name);
}
int
gl_check_sysroot(const char *sysroot)
{
char root[PATH_MAX];
if (gl_normalize_sysroot(sysroot, root, sizeof(root)) != 0) {
lg_printf(2, "Refusing install root %s: not an absolute path without . or .. components.",
sysroot ? sysroot : "(null)");
return -1;
}
if (root[0] == '\0') { return 0; }
char bad[PATH_MAX];
const char *why = "";
if (gl_sysroot_trusted(root, bad, sizeof(bad), &why) != 0) {
lg_printf(2, "Refusing install root %s: %s is %s.", root, bad, why);
return -1;
}
return 0;
}
/* Store the install root (gl_normalize_sysroot). Only system scope may
* have one (IMAGE_DESIGN section 3): per-user scope has no business in
* an image. */
static int
set_sysroot(gl_context_t *ctx, gl_ctx_scope_t scope, const char *sysroot)
{
ctx->sysroot[0] = '\0';
if (gl_check_sysroot(sysroot) != 0) {
return -1;
}
gl_normalize_sysroot(sysroot, ctx->sysroot, sizeof(ctx->sysroot));
if (scope == GL_SCOPE_USR && ctx->sysroot[0] != '\0') {
lg_printf(2, "Refusing a user-scope context with install root %s.", ctx->sysroot);
ctx->sysroot[0] = '\0';
return -1;
}
return 0;
}
static int
fsync_dir(const char *path)
{
int fd = open(path, O_RDONLY | O_DIRECTORY);
if (fd < 0) {
return -1;
}
int r = fsync(fd);
close(fd);
return r;
}
static int
atomic_swap(const char *live, const char *stage, const char *backup)
{
if (rename(live, backup) != 0) {
return -1;
}
if (rename(stage, live) != 0) {
rename(backup, live);
return -1;
}
return 0;
}
static void
derive_base_paths(gl_ctx_scope_t scope, uid_t uid, const char *sysroot,
char *index_out, char *store_out, char *links_out)
{
scope_subdir(scope, uid, sysroot, "index", index_out);
scope_subdir(scope, uid, sysroot, "store", store_out);
/* For system scope this is the DEFAULT links location — for
* packages the operator explicitly installs under system scope that
* aren't part of the base system. Base-repo packages get routed to
* /usr instead, but that's a per-package decision made in
* gl_link_pkg/gl_relink_store (which know a package's repo), not
* something the context can decide up front. See GL_BASE_REPO in
* istoreutils.c. */
scope_subdir(scope, uid, sysroot, "links", links_out);
}
static int
check_same_filesystem(const char *a, const char *b)
{
struct stat sa, sb;
if (stat(a, &sa) != 0 || stat(b, &sb) != 0) {
return -1;
}
return sa.st_dev == sb.st_dev;
}
static int
hardlink_tree(const char *src, const char *dest)
{
DIR *dir = opendir(src);
if (!dir) {
return (errno == ENOENT) ? 0 : -1;
}
struct dirent *ent;
while ((ent = readdir(dir))) {
/* Only . and .. — dotfiles are real content here: a package's
* own dotfiles, and the store's .displaced originals (see
* gl_link_pkg), both of which would otherwise be dropped from
* the stage and lost on commit. */
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) {
continue;
}
char s[PATH_MAX], d[PATH_MAX];
snprintf(s, sizeof(s), "%s/%s", src, ent->d_name);
snprintf(d, sizeof(d), "%s/%s", dest, ent->d_name);
struct stat st;
if(lstat(s, &st) != 0) { continue; }
if (S_ISDIR(st.st_mode)) {
/* Exact mode, not umask-filtered: the stage becomes
* live, so seeding must not tighten what it copies. */
if (gl_mkdir_exact(d, st.st_mode & 07777) != 0) {
closedir(dir);
return -1;
}
if (hardlink_tree(s, d) != 0) {
closedir(dir);
return -1;
}
}
else if (S_ISLNK(st.st_mode)) {
char target[PATH_MAX];
ssize_t n = readlink(s, target, sizeof(target) - 1);
if (n < 0) { continue; }
target[n] = '\0';
symlink(target, d);
}
else {
if (link(s, d) != 0 && errno != EEXIST) {
closedir(dir);
return -1;
}
}
}
closedir(dir);
return 0;
}
int
gl_init_live_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid)
{
return gl_init_live_context_at(ctx, scope, uid, "/");
}
int
gl_init_live_context_at(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid,
const char *sysroot)
{
if (!ctx) {
return -1;
}
ctx->uid = uid;
ctx->mode = GL_CTX_LIVE;
ctx->scope = scope;
ctx->lock_fd = -1;
ctx->overwrite = 0;
ctx->link_refusals = 0;
ctx->strict = 0;
if (set_sysroot(ctx, scope, sysroot) != 0) {
return -1;
}
snprintf(ctx->root_path, PATH_MAX, "%s/glacier", ctx->sysroot);
derive_base_paths(scope, uid, ctx->sysroot, ctx->index_path,
ctx->store_path, ctx->links_path);
return 0;
}
gl_txn_status_t
gl_init_stage_context(gl_context_t *ctx, gl_ctx_scope_t scope, uid_t uid)
{
return gl_init_stage_context_at(ctx, scope, 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)
{
if (!ctx) {
return GL_TXN_ERR_NO_TXN;
}
ctx->uid = uid;
ctx->mode = GL_CTX_STAGE;
ctx->scope = scope;
ctx->lock_fd = -1;
ctx->overwrite = 0;
ctx->link_refusals = 0;
ctx->strict = 0;
if (set_sysroot(ctx, scope, sysroot) != 0) {
return GL_TXN_ERR_PERM;
}
snprintf(ctx->root_path, PATH_MAX, "%s/glacier", ctx->sysroot);
if (scope == GL_SCOPE_USR) {
switch (gl_usr_base_check(uid)) {
case GL_USR_BASE_OK:
break;
case GL_USR_BASE_MISSING:
lg_printf(2, "No Glacier directory for UID %u. Run doas gstore -n first.", uid);
return GL_TXN_ERR_PERM;
case GL_USR_BASE_UNSAFE_ROOT:
lg_printf(2, "Refusing to run: %s is not root-owned, or is group/world-writable.",
GL_USR_ROOT);
return GL_TXN_ERR_PERM;
case GL_USR_BASE_UNSAFE:
lg_printf(2, "Refusing to run: %s/%u is not a directory owned by UID %u with mode 0700.",
GL_USR_ROOT, uid, uid);
return GL_TXN_ERR_PERM;
}
}
char stage_base[PATH_MAX - 7];
scope_subdir(scope, uid, ctx->sysroot, "stage", stage_base);
snprintf(ctx->index_path, PATH_MAX, "%s/index", stage_base);
snprintf(ctx->store_path, PATH_MAX, "%s/store", stage_base);
snprintf(ctx->links_path, PATH_MAX, "%s/links", stage_base);
/* Lock BEFORE clearing a leftover stage: the other order let a
* second invocation wipe a running transaction's stage and only
* then discover it couldn't get the lock. */
gl_txn_status_t lock_status = gl_begin_transaction(ctx);
if (lock_status != GL_TXN_OK) {
return lock_status;
}
/* EBUSY: stage_base is itself a mount point. Its contents are gone
* and the directory stays, which is all a fresh stage needs (the
* mkdirps below tolerate it existing). Commit then reports
* GL_TXN_ERR_XDEV, as it should for a stage on another filesystem. */
struct stat st;
if (stat(stage_base, &st) == 0) {
if (gl_rmdir_recursive(stage_base) != 0 && errno != EBUSY) {
gl_abort_transaction(ctx);
return GL_TXN_ERR_MKDIR;
}
}
/* chmod, not just mkdir's mode: the stage becomes live on commit,
* and a system store must be 0755 whatever syspkg's umask is. */
mode_t dir_mode = gl_scope_dir_mode(scope);
if (gl_mkdirp(ctx->index_path, dir_mode) != 0 ||
chmod(ctx->index_path, dir_mode) != 0) {
gl_abort_transaction(ctx);
return GL_TXN_ERR_MKDIR;
}
if (gl_mkdirp(ctx->store_path, dir_mode) != 0 ||
chmod(ctx->store_path, dir_mode) != 0) {
gl_abort_transaction(ctx);
return GL_TXN_ERR_MKDIR;
}
if (gl_mkdirp(ctx->links_path, dir_mode) != 0 ||
chmod(ctx->links_path, dir_mode) != 0) {
gl_abort_transaction(ctx);
return GL_TXN_ERR_MKDIR;
}
if (chown(stage_base, uid, (gid_t)-1) != 0) {
gl_abort_transaction(ctx);
return GL_TXN_ERR_PERM;
}
char live_index[PATH_MAX], live_store[PATH_MAX], live_links[PATH_MAX];
derive_base_paths(scope, uid, ctx->sysroot, live_index, live_store, live_links);
/* live_links is populated (derive_base_paths always fills all
* three) but intentionally unused below — see the comment on the
* hardlink_tree call. */
/* Only index and store need copy-on-write seeding — the staged
* links tree is never actually read from or written to (gl_link_pkg
* skips GL_CTX_STAGE entirely; gl_relink_store always builds its
* own fresh live context rather than touching ctx->links_path of a
* stage context). Seeding it was always wasted work; now that
* live_links can be /usr for system scope, it would also be
* actively dangerous — hardlinking the entire /usr tree on every
* transaction, and risking EXDEV outright if /usr and the stage
* area are on different filesystems. */
if (hardlink_tree(live_index, ctx->index_path) != 0 ||
hardlink_tree(live_store, ctx->store_path) != 0) {
/* link() can't cross filesystems: a stage on a different
* fs than live is caught here, before anything is staged,
* rather than at commit's rename. Same condition, same
* status as commit's check. */
int seed_errno = errno;
gl_abort_transaction(ctx);
return seed_errno == EXDEV ? GL_TXN_ERR_XDEV : GL_TXN_ERR_MKDIR;
}
return GL_TXN_OK;
}
/* parent/name into out (PATH_MAX), created with `mode` if missing, then
* refused unless it is a real directory owned by `owner` with exactly
* that mode. 0, or -1 having printed why. */
static int
checked_subdir(const char *parent, const char *name, uid_t owner, mode_t mode,
char *out)
{
struct stat st;
snprintf(out, PATH_MAX, "%s/%s", parent, name);
if (gl_mkdir_exact(out, mode) != 0 && errno != EEXIST) {
lg_printf(2, "Cannot create %s: %s", out, strerror(errno));
return -1;
}
if (lstat(out, &st) != 0 || !S_ISDIR(st.st_mode) || st.st_uid != owner ||
(st.st_mode & 07777) != mode) {
lg_printf(2, "Refusing %s: not a directory owned by UID %u with mode %o.",
out, owner, (unsigned)mode);
return -1;
}
return 0;
}
/*
* <base>/NAME: a directory for state a scope keeps beside its index and
* store ("repos": the accepted repository indexes, REPO_DESIGN.txt
* section 5). The base must already exist and be the scope's (owned by
* root, or by the uid for user scope; no group/world write). NAME is
* created if missing with the scope's mode, and is then refused unless
* it is a real directory owned like the base with exactly that mode.
* The path goes to out (PATH_MAX). 0, or -1 having printed why.
*/
int
gl_scope_state_dir(const gl_context_t *ctx, const char *name, char *out)
{
if (!ctx || !out || !gl_valid_pkg_ident(name)) {
return -1;
}
uid_t owner = ctx->scope == GL_SCOPE_SYS ? 0 : ctx->uid;
mode_t mode = gl_scope_dir_mode(ctx->scope);
char base[PATH_MAX];
scope_base(ctx->scope, ctx->uid, ctx->sysroot, base);
struct stat st;
if (ctx->scope == GL_SCOPE_USR && gl_usr_base_check(ctx->uid) != GL_USR_BASE_OK) {
lg_printf(2, "Cannot open %s: not a private directory owned by UID %u.",
base, ctx->uid);
return -1;
}
if (lstat(base, &st) != 0) {
lg_printf(2, "Cannot open %s: %s", base, strerror(errno));
return -1;
}
if (!S_ISDIR(st.st_mode) || st.st_uid != owner || (st.st_mode & 022)) {
lg_printf(2, "Refusing %s: not a directory owned by UID %u, or group/world-writable.",
base, owner);
return -1;
}
return checked_subdir(base, name, owner, mode, out);
}
/*
* <base>/build/NAME: where source builds keep their state
* (BUILD_DESIGN.txt section 6). <base>/build is made and checked as
* gl_scope_state_dir makes and checks NAME. With owner -1, NAME is the
* scope's like it; with another uid (system scope only: BUILD_USER),
* NAME is created owned by that uid with mode 0700, and refused unless
* it is a real directory owned by it with exactly that mode. 0, or -1
* having printed why.
*/
int
gl_scope_build_dir(const gl_context_t *ctx, const char *name, int owner, char *out)
{
char build[PATH_MAX];
if (!ctx || !out || !gl_valid_pkg_ident(name) ||
gl_scope_state_dir(ctx, "build", build) != 0) {
return -1;
}
uid_t scope_owner = ctx->scope == GL_SCOPE_SYS ? 0 : ctx->uid;
if (owner < 0 || (uid_t)owner == scope_owner) {
return checked_subdir(build, name, scope_owner, gl_scope_dir_mode(ctx->scope), out);
}
if (ctx->scope != GL_SCOPE_SYS || owner == 0) {
return -1;
}
snprintf(out, PATH_MAX, "%s/%s", build, name);
if (mkdir(out, 0700) == 0) {
if (chmod(out, 0700) != 0 || chown(out, (uid_t)owner, (gid_t)-1) != 0) {
lg_printf(2, "Cannot create %s: %s", out, strerror(errno));
return -1;
}
} else if (errno != EEXIST) {
lg_printf(2, "Cannot create %s: %s", out, strerror(errno));
return -1;
}
struct stat st;
if (lstat(out, &st) != 0 || !S_ISDIR(st.st_mode) || st.st_uid != (uid_t)owner ||
(st.st_mode & 07777) != 0700) {
lg_printf(2, "Refusing %s: not a directory owned by UID %u with mode 700.",
out, (unsigned)owner);
return -1;
}
return 0;
}
/*
* <base>/cache/REPO: where packages fetched from REPO are downloaded
* (REPO_DESIGN.txt section 5). Both levels are made and checked as
* gl_scope_state_dir makes and checks NAME. 0, or -1 having printed why.
*/
int
gl_scope_cache_dir(const gl_context_t *ctx, const char *repo, char *out)
{
char cache[PATH_MAX];
if (!ctx || !out || !gl_valid_pkg_ident(repo) ||
gl_scope_state_dir(ctx, "cache", cache) != 0) {
return -1;
}
return checked_subdir(cache, repo,
ctx->scope == GL_SCOPE_SYS ? 0 : ctx->uid,
gl_scope_dir_mode(ctx->scope), out);
}
gl_txn_status_t
gl_begin_transaction(gl_context_t *ctx)
{
if (!ctx) {
return GL_TXN_ERR_NO_TXN;
}
char lock_path[PATH_MAX];
scope_subdir(ctx->scope, ctx->uid, ctx->sysroot, "lock", lock_path);
int fd = open(lock_path, O_WRONLY | O_CREAT, 0600);
if (fd < 0) {
return GL_TXN_ERR_LOCK;
}
if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
close(fd);
return GL_TXN_ERR_LOCK;
}
ctx->lock_fd = fd;
return GL_TXN_OK;
}
gl_txn_status_t
gl_commit_transaction(gl_context_t *ctx)
{
if (!ctx || ctx->lock_fd < 0) {
return GL_TXN_ERR_NO_TXN;
}
if (ctx->mode != GL_CTX_STAGE) {
return GL_TXN_ERR_NO_TXN;
}
/* Dependencies and conflicts (ROADMAP 2.3). The CLIs check the plan
* before prompting; this holds every other caller of the library to
* the same rules. gl_check_txn reports each problem itself. */
int dep_problems = gl_check_txn(ctx);
if (dep_problems != 0) {
if (dep_problems < 0) {
lg_printf(2, "Cannot read the package store to check dependencies.");
}
return GL_TXN_ERR_DEPS;
}
char stage_base[PATH_MAX];
scope_subdir(ctx->scope, ctx->uid, ctx->sysroot, "stage", stage_base);
int same = check_same_filesystem(ctx->root_path, stage_base);
if (same < 0) {
return GL_TXN_ERR_RENAME; /* failed to stat either side */
}
if (!same) {
return GL_TXN_ERR_XDEV;
}
/* Derive live paths the same way gl_init_live_context would */
char live_index[PATH_MAX], live_store[PATH_MAX], live_links[PATH_MAX];
derive_base_paths(ctx->scope, ctx->uid, ctx->sysroot, live_index,
live_store, live_links);
/* Derive old/backup paths */
char old_base[PATH_MAX];
scope_subdir(ctx->scope, ctx->uid, ctx->sysroot, "old", old_base);
char old_index[PATH_MAX], old_store[PATH_MAX], old_links[PATH_MAX];
snprintf(old_index, PATH_MAX, "%s/index", old_base);
snprintf(old_store, PATH_MAX, "%s/store", old_base);
snprintf(old_links, PATH_MAX, "%s/links", old_base);
struct stat old_st;
if (stat(old_base, &old_st) == 0) {
if (gl_rmdir_recursive(old_base) != 0) {
return GL_TXN_ERR_RENAME;
}
}
if (gl_mkdirp(old_base, 0700) != 0) {
return GL_TXN_ERR_RENAME;
}
if (atomic_swap(live_index, ctx->index_path, old_index) != 0) {
return GL_TXN_ERR_RENAME;
}
if (atomic_swap(live_store, ctx->store_path, old_store) != 0) {
rename(live_index, ctx->index_path);
rename(old_index, live_index);
return GL_TXN_ERR_RENAME;
}
if (atomic_swap(live_links, ctx->links_path, old_links) != 0) {
rename(live_store, ctx->store_path);
rename(old_store, live_store);
rename(live_index, ctx->index_path);
rename(old_index, live_index);
return GL_TXN_ERR_RENAME;
}
/* fsync the directory the renames happened in */
char base[PATH_MAX];
scope_base(ctx->scope, ctx->uid, ctx->sysroot, base);
fsync_dir(base);
if (ctx->scope == GL_SCOPE_SYS) {
char usr[PATH_MAX];
snprintf(usr, sizeof(usr), "%s/usr", ctx->sysroot);
fsync_dir(usr); /* base-repo packages land here instead */
}
gl_context_t live_ctx;
gl_init_live_context_at(&live_ctx, ctx->scope, ctx->uid,
ctx->sysroot[0] ? ctx->sysroot : "/");
if (gl_relink_store(&live_ctx) != 0) {
lg_printf(2, "Post-commit relink incomplete for uid %u", ctx->uid);
}
ctx->link_refusals = live_ctx.link_refusals;
gl_rmdir_recursive(old_base);
/* Remove stage base */
gl_rmdir_recursive(stage_base);
close(ctx->lock_fd);
ctx->lock_fd = -1;
return GL_TXN_OK;
}
gl_txn_status_t
gl_abort_transaction(gl_context_t *ctx)
{
/* Only the lock holder's stage is its own to remove: without the
* lock, this would wipe another process's running transaction. */
if (!ctx || ctx->lock_fd < 0) {
return GL_TXN_ERR_NO_TXN;
}
/* Remove stage area — live is untouched */
char stage_uid[PATH_MAX];
scope_subdir(ctx->scope, ctx->uid, ctx->sysroot, "stage", stage_uid);
gl_rmdir_recursive(stage_uid); /* best-effort; ignore errors */
/* Release lock */
if (ctx->lock_fd >= 0) {
close(ctx->lock_fd);
ctx->lock_fd = -1;
}
return GL_TXN_OK;
}
+137
View File
@@ -0,0 +1,137 @@
#ifndef TRANSACTION_H_
#define TRANSACTION_H_
#define _POSIX_C_SOURCE 200809L
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#define GL_UID_NONE ((uid_t)0)
typedef enum {
GL_CTX_LIVE,
GL_CTX_STAGE
} gl_ctx_mode_t;
typedef enum {
GL_SCOPE_USR,
GL_SCOPE_SYS
} gl_ctx_scope_t;
/* Modes for what glacier creates in a scope. System scope is
* world-readable, like /usr: its store is where /usr's links point, so
* every user must be able to traverse it, and user-scope dependency
* checks read its index. User scope stays private to its uid. */
static inline mode_t
gl_scope_dir_mode(gl_ctx_scope_t scope)
{
return scope == GL_SCOPE_SYS ? 0755 : 0700;
}
static inline mode_t
gl_scope_file_mode(gl_ctx_scope_t scope)
{
return scope == GL_SCOPE_SYS ? 0644 : 0600;
}
typedef struct {
uid_t uid;
char root_path[PATH_MAX];
char index_path[PATH_MAX];
char store_path[PATH_MAX];
char links_path[PATH_MAX];
gl_ctx_mode_t mode;
gl_ctx_scope_t scope;
int lock_fd;
/* Set by the caller after gl_init_*_context (which zero it).
* Packages installed while this is non-zero may displace
* existing non-glacier files at their link destinations; see
* gl_link_pkg. */
int overwrite;
/* Install root (IMAGE_DESIGN section 3), set by the *_at init
* functions: "" for the running system, else e.g. "/mnt/everest".
* The paths above are INSTALL paths, already under it: every
* filesystem operation uses them as they are. What a path MEANS
* once the image is booted (a symlink target, a .displaced key)
* is its runtime path, gl_runtime_path(). System scope only. */
char sysroot[PATH_MAX];
/* Paths the link pass refused to link (a foreign file in the
* way, say), counted only for packages installed in this
* transaction. Zeroed by the init functions; after
* gl_commit_transaction, the post-commit relink's count. A
* non-zero count means the transaction committed but did not
* fully succeed. */
int link_refusals;
/* Set by the caller after gl_init_*_context (which zero it).
* Non-zero: a path the link pass would refuse (a foreign file in
* the way, say) fails the transaction before anything is
* committed, instead of being counted in link_refusals after.
* See deps.h. */
int strict;
} gl_context_t;
/* An install path's runtime meaning: sysroot stripped. A path not under
* the sysroot is returned unchanged. */
static inline const char *
gl_runtime_path(const gl_context_t *ctx, const char *install_path)
{
size_t n = strlen(ctx->sysroot);
if (n > 0 && strncmp(install_path, ctx->sysroot, n) == 0 &&
install_path[n] == '/') {
return install_path + n;
}
return install_path;
}
/* The install path of a runtime path (a symlink's absolute target, say):
* sysroot prepended. Returns -1 if it doesn't fit. */
static inline int
gl_at(const gl_context_t *ctx, const char *runtime_path, char *out, size_t outsz)
{
int n = snprintf(out, outsz, "%s%s", ctx->sysroot, runtime_path);
return (n < 0 || (size_t)n >= outsz) ? -1 : 0;
}
typedef enum {
GL_TXN_OK = 0, /* success */
GL_TXN_ERR_LOCK = 1, /* unable to acquire lock */
GL_TXN_ERR_MKDIR = 2, /* unable to create txn stage */
GL_TXN_ERR_PERM = 3, /* permission error */
GL_TXN_ERR_RENAME = 4, /* atomic swap failed */
GL_TXN_ERR_SYNC = 5, /* fsync failed */
GL_TXN_ERR_CLEANUP = 6, /* cleanup failed */
GL_TXN_ERR_NO_TXN = 7, /* aborted without beginning */
GL_TXN_ERR_XDEV = 8, /* stage and live on different filesystems */
GL_TXN_ERR_DEPS = 9 /* unmet dependency, conflict, file collision,
* or (strict) a link refusal: see deps.h */
} gl_txn_status_t;
/* Is `sysroot` acceptable as an install root (absolute, no . or ..,
* trusted: see gl_sysroot_trusted)? Logs why not. 0 if so. "/" is. */
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);
#endif
BIN
View File
Binary file not shown.