Files
glacier-ng/lib/gpkg_common.lua.old
2026-10-29 09:15:34 -04:00

1033 lines
43 KiB
Plaintext

-- lib/gpkg_common.lua
--
-- Shared machinery between gpkg (per-user scope only) and syspkg
-- (system scope only). See SECURITY_DESIGN.txt section 7.
--
-- The interface here is deliberately COARSE-GRAINED: M.install() and
-- M.remove() own the entire staged-transaction lifecycle
-- (gl_init_stage_context -> loop -> commit/abort), rather than
-- exporting fine-grained pieces that each caller then has to sequence
-- itself. That's what keeps the sequencing — and, once Checkpoint 2's
-- verification lands, the hash refusal matrix — in exactly ONE place
-- instead of duplicated across two binaries and drifting apart.
--
-- What callers keep for themselves:
-- * argument parsing
-- * deciding WHICH scope they're allowed to request (gpkg never
-- constructs a GL_SCOPE_SYS context — not "doesn't expose a flag
-- for it", the capability isn't in its code path at all)
-- * their own privilege model (only syspkg runs elevated)
--
-- Callers pass a `env` table on construction with the FFI handles and
-- shared state, so this module doesn't ffi.load() anything itself and
-- doesn't care where the .so's came from.
local ffi = require("ffi")
local bit = require("bit")
local glacier_cdef = require("lib/glacier_cdef")
local M = {}
-- Module-level handles, set by M.init(). Kept here rather than passed
-- through every function because every function needs them.
local log, istore, txn, verify
local argv
local isVerbose = false
local skipInstalled = false
local overwrite = false
local txn_name = glacier_cdef.txn_name
--- Initialise the module. Must be called before anything else.
-- env.log / env.istore / env.txn : ffi.load() handles
-- env.verify : libglacier_verify.so handle (installs)
-- env.argv : argv table (for usage messages)
function M.init(env)
log = env.log
istore = env.istore
txn = env.txn
verify = env.verify
argv = env.argv
end
--- Toggle flags the CLIs parse but this module acts on.
function M.set_verbose(v) isVerbose = v end
function M.set_skip_installed(v) skipInstalled = v end
function M.set_overwrite(v) overwrite = v end
-- ---------------------------------------------------------------------
-- Manifest reading
-- ---------------------------------------------------------------------
-- Quote a string for /bin/sh: wrap in single quotes, and turn each
-- embedded ' into '\''. Package paths come from the command line and
-- manifest entry names come from the archive, and syspkg runs all of
-- this as root — an unescaped ' in either is command execution.
local function shell_quote(s)
return "'" .. s:gsub("'", "'\\''") .. "'"
end
--- name, repo and version ("MAJ.MIN.PAT", as the store names versions)
--- of a package, read by the LIBRARY (gl_read_pkg_manifest), the same
--- reader gl_install_pkg uses, so what is shown, compared and installed
--- can never disagree. nil if the manifest can't be read.
local function manifest_of(path)
local m = ffi.new("gl_pkg_t")
if istore.gl_read_pkg_manifest(path, m) ~= 0 then
return nil
end
local name, repo = ffi.string(m.pkg_name), ffi.string(m.pkg_repo)
local ver = string.format("%d.%d.%d", m.pkg_ver.maj, m.pkg_ver.min, m.pkg_ver.pat)
istore.gl_free_pkg(m)
return name, repo, ver
end
-- ---------------------------------------------------------------------
-- Integrity verification (SECURITY_DESIGN.txt sections 3-4)
-- ---------------------------------------------------------------------
-- Private working dir for verified copies, removed by finish().
local private_dir = nil
-- Backups written during this transaction but not yet committed
-- ({ part = ..., final = ..., dir = ... }); finish() deletes any that
-- were never promoted, so an aborted upgrade leaves no stray backup.
local pending_backups = {}
--- Exit, removing the private copies (and uncommitted backups) first.
--- Every exit on the install path goes through here.
local function finish(code)
for _, b in ipairs(pending_backups) do
os.remove(b.part)
end
pending_backups = {}
if private_dir then
os.execute("rm -rf " .. shell_quote(private_dir))
private_dir = nil
end
os.exit(code)
end
--- sha256 of a file as "<hex>", or nil.
local function sha256_file(path)
local f = io.open(path, "rb")
if not f then return nil end
local hctx = ffi.new("gl_sha256_ctx_t")
verify.gl_sha256_init(hctx)
while true do
local chunk = f:read(65536)
if not chunk then break end
verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk)
end
f:close()
local digest = ffi.new("uint8_t[32]")
local hex = ffi.new("char[65]")
verify.gl_sha256_final(hctx, digest)
verify.gl_sha256_to_hex(digest, hex)
return ffi.string(hex)
end
--- Copy `path` into the private dir, hashing it in the same pass, and
--- check the hash against `path`.sha256. Returns the private copy's path,
--- or nil plus a reason.
---
--- Everything after this (summary, manifest read, gl_install_pkg) reads
--- ONLY the copy. Verifying the original and then installing it would
--- leave a gap where it could be swapped — and under syspkg that's root
--- reading a file whose directory another user may control. The copy
--- lives in a mktemp -d dir only the invoking user (root, for syspkg)
--- can write.
---
--- Refusal matrix (section 4). A missing sidecar is treated exactly like
--- a mismatch:
--- repo == base -> always refuse, no exceptions
--- scope == SYS -> always refuse, any repo
--- scope == USR, repo != base -> refuse by default; the ONLY place
--- a future bypass flag may apply
--- No bypass exists, so today every row refuses and the repo (which we
--- couldn't trust before verifying anyway) never needs consulting. A
--- bypass, if ever added, must check scope and the VERIFIED manifest's
--- repo here, before anything else reads the file.
local function verify_and_copy(path)
local sidecar = path .. ".sha256"
local sf = io.open(sidecar, "r")
if not sf then
return nil, "no sidecar " .. sidecar
end
local sidecar_text = sf:read("*a") or ""
sf:close()
local expected = sidecar_text:match("^sha256:(%x+)%s*$")
if not expected or #expected ~= 64 then
return nil, "malformed sidecar " .. sidecar
end
expected = expected:lower()
if not private_dir then
local mk = io.popen("mktemp -d /tmp/gpkg-verify.XXXXXXXXXX 2>/dev/null")
private_dir = mk and mk:read("*l")
if mk then mk:close() end
if not private_dir or private_dir == "" then
private_dir = nil
return nil, "cannot create a private working directory"
end
end
local src = io.open(path, "rb")
if not src then
return nil, "cannot open " .. path
end
-- Unique per argument, so two packages with the same basename
-- (from different directories) can't collide.
local copy_path = string.format("%s/%d-%s", private_dir, M._ncopies or 0,
path:match("([^/]+)$"))
M._ncopies = (M._ncopies or 0) + 1
local dst = io.open(copy_path, "wb")
if not dst then
src:close()
return nil, "cannot write " .. copy_path
end
local hctx = ffi.new("gl_sha256_ctx_t")
verify.gl_sha256_init(hctx)
while true do
local chunk = src:read(65536)
if not chunk then break end
verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk)
dst:write(chunk)
end
src:close()
dst:close()
local digest = ffi.new("uint8_t[32]")
local hex = ffi.new("char[65]")
verify.gl_sha256_final(hctx, digest)
verify.gl_sha256_to_hex(digest, hex)
if ffi.string(hex) ~= expected then
return nil, "hash mismatch (sidecar says " .. expected ..
", file is " .. ffi.string(hex) .. ")"
end
return copy_path, nil, sidecar_text
end
-- ---------------------------------------------------------------------
-- Signatures (REPO_DESIGN.txt section 7)
-- ---------------------------------------------------------------------
-- The system keyring. Read only by syspkg; under -R it is still the
-- HOST's (the build host's trust, as KEEP_OLD).
local REPOS_CONF = "/etc/glacier/repos.conf"
local KEYS_DIR = "/etc/glacier/keys"
ffi.cdef[[
char *gpkg_common_realpath(const char *path, char *resolved) asm("realpath");
]]
-- nil if `path`, every ancestor of it, and every ancestor of its real
-- path are root-owned and not group/world-writable (as syspkg's own
-- lib/: a key a non-root user could swap is no key). Else the path at
-- fault, plus true if it is missing (or can't be resolved).
local function untrusted(path)
local function chain(p)
while true do
local f = io.popen("stat -L -c '%u %a' -- " .. shell_quote(p) .. " 2>/dev/null")
local line = f and f:read("*l")
if f then f:close() end
local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$")
if not uid then return p, true end
if tonumber(uid) ~= 0
or bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then
return p
end
if p == "/" then return nil end
p = p:match("^(.*)/[^/]*$")
if p == "" then p = "/" end
end
end
local bad, missing = chain(path)
if bad then return bad, missing end
local buf = ffi.new("char[4096]")
if ffi.C.gpkg_common_realpath(path, buf) == nil then return path, true end
return chain(ffi.string(buf))
end
-- Whether repos.conf exists, having checked it is trusted (else the run
-- stops: the admin's configuration is at fault, not a package).
local function repos_conf_present()
local f, _, code = io.open(REPOS_CONF, "r")
if f then f:close() end
if not f and code == 2 then return false end
local bad, missing = untrusted(REPOS_CONF)
if bad and missing then
log.lg_printf(2, "Cannot read %s.", bad)
finish(1)
elseif bad then
log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.",
REPOS_CONF, bad)
finish(1)
end
return true
end
-- The public keys repos.conf trusts for `repo`, read once per run:
-- { { name, pub }... }. A missing repos.conf trusts nothing. A
-- repos.conf or listed key that is untrusted or can't be read stops the
-- run: that is the admin's configuration, not the package, at fault.
local trusted_keys_cache = {}
local function trusted_keys(repo)
if trusted_keys_cache[repo] then return trusted_keys_cache[repo] end
local keys = {}
if repos_conf_present() then
local buf = ffi.new("char[4096]")
local st = tonumber(istore.gl_conf_repo_keys(REPOS_CONF, repo, buf, 4096))
if st == 1 or st == 3 or st == 4 or st == 5 then
log.lg_printf(2, "Malformed %s.", REPOS_CONF)
finish(1)
end
for name in ffi.string(buf):gmatch("([^\n]+)\n") do
local path = KEYS_DIR .. "/" .. name .. ".pub"
local bad_key, missing = untrusted(path)
local pub = ffi.new("gl_sign_pubkey_t")
if bad_key and missing then
log.lg_printf(2, "Cannot read %s.", bad_key)
finish(1)
elseif bad_key then
log.lg_printf(2, "Refusing %s: %s is not root-owned, or is group/world-writable.",
path, bad_key)
finish(1)
elseif verify.gl_sign_read_pubkey(path, pub) ~= 0 then
log.lg_printf(2, "Malformed %s.", path)
finish(1)
end
table.insert(keys, { name = name, pub = pub })
end
end
trusted_keys_cache[repo] = keys
return keys
end
-- Whether `path`.sha256.sig is a signature of `sidecar_text` (the very
-- bytes the copy was checked against) by a key trusted for `repo`. The
-- key is picked by the signature's keynum, never by trying each one.
local function signed_for(path, sidecar_text, repo)
local sig = ffi.new("gl_sign_sig_t")
if verify.gl_sign_read_sig(path .. ".sha256.sig", sig) ~= 0 then
return false
end
local keynum = ffi.string(sig.keynum, 8)
for _, k in ipairs(trusted_keys(repo)) do
if ffi.string(k.pub.keynum, 8) == keynum then
return verify.gl_sign_verify(k.pub, sig,
ffi.cast("const uint8_t *", sidecar_text), #sidecar_text) == 0
end
end
return false
end
--- Verify every package up front, before the summary is even shown.
--- Returns the private copies, plus a copy -> original map for messages.
---
--- In system scope, a package whose manifest says base must also have a
--- signed sidecar (REPO_DESIGN.txt section 7). The repo is the one the
--- LIBRARY reads from the copy (gl_read_pkg_manifest, as gl_install_pkg
--- does).
local function verify_all(gpkg_paths, opts)
local copies, original = {}, {}
local refused = false
for _, p in ipairs(gpkg_paths) do
local copy, why, sidecar_text = verify_and_copy(p)
if copy and not manifest_of(copy) then
log.lg_printf(2, "Cannot read the manifest of %s.", p)
refused = true
copy = nil
end
if copy and opts.scope == ffi.C.GL_SCOPE_SYS then
local name, repo = manifest_of(copy)
if repo == "base" and not signed_for(p, sidecar_text, repo) then
log.lg_printf(2, "%s::%s is not signed by a key trusted for %s.",
repo, name, repo)
refused = true
copy = nil
end
end
if copy then
table.insert(copies, copy)
original[copy] = p
elseif why then
log.lg_printf(2, "Refusing %s: %s.", p, why)
refused = true
end
end
if refused then
finish(1)
end
return copies, original
end
-- ---------------------------------------------------------------------
-- Confirmation summary
-- ---------------------------------------------------------------------
--- Print the summary for `entries` ({repo, name, ver} each) and ask.
local function confirm(entries)
log.lg_printf(0, "SUMMARY:")
print("==============================")
print("")
for _, e in ipairs(entries) do
print(string.format(" * %s::%s\t\t%-16s",
e.repo or "unknown", e.name, e.ver or "unknown"))
end
print("")
io.write("Proceed? (y/N): ")
io.stdout:flush()
local response = io.read("*l")
if not response then
return false
end
response = response:lower()
return response == "y" or response == "yes"
end
--- Installed packages, from the live index for this scope: a list of
--- {repo, name, ver, auto}. The index's `current` file holds one
--- `repo::name::version::auto|explicit` line per package (index files
--- written before 2026-10-05 stop at the version).
--- A live context for opts' scope (and install root: syspkg -R only).
local function live_context(opts)
local ctx = ffi.new("gl_context_t")
if txn.gl_init_live_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/") ~= 0 then
finish(1) -- the library said why
end
return ctx
end
local function installed_entries(opts)
local ctx = live_context(opts)
local f = io.open(ffi.string(ctx.index_path) .. "/current", "r")
local out = {}
if not f then return out end
for line in f:lines() do
local repo, name, rest = line:match("^([^:]+)::([^:]+)::(.+)$")
if repo then
local ver, kind = rest:match("^(.-)::(%a+)$")
table.insert(out, { repo = repo, name = name, ver = ver or rest,
auto = kind == "auto" })
end
end
f:close()
return out
end
-- ---------------------------------------------------------------------
-- Repo resolution
-- ---------------------------------------------------------------------
function M.resolve_repo(ctx, pkg_name)
local list = istore.gl_find_pkg_repos(ctx, pkg_name)
if list.count == 0 then
log.lg_printf(2, "Unable to resolve group for package %s.", pkg_name)
istore.gl_free_repo_list(list)
return nil
end
if list.count == 1 then
local repo = ffi.string(list.repos[0])
istore.gl_free_repo_list(list)
return repo
end
log.lg_printf(1, "Multiple instances of %s found:", pkg_name)
for i = 0, tonumber(list.count) - 1 do
print(string.format("\t[%d] %s::%s", i + 1, ffi.string(list.repos[i]), pkg_name))
end
print("")
io.write("Select the instance to be modified [1-" .. tonumber(list.count) .. "]: ")
io.stdout:flush()
local input = io.read("*l")
local choice = tonumber(input)
if not choice or choice < 1 or choice > tonumber(list.count) then
log.lg_printf(2, "Invalid selection.")
istore.gl_free_repo_list(list)
return nil
end
local repo = ffi.string(list.repos[choice - 1])
istore.gl_free_repo_list(list)
return repo
end
-- ---------------------------------------------------------------------
-- Single-package install (with reinstall-if-present handling)
-- ---------------------------------------------------------------------
local function install_with_reinstall(ctx, gpkg_path)
local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path)
if not pkg_name then
log.lg_printf(2, "Cannot read the manifest of %s.", gpkg_path)
finish(1)
end
if isVerbose then
log.lg_printf(0, "Package: %s\tVersion: %s\tRepo: %s\tPath: %s",
pkg_name, version_str, manifest_repo, gpkg_path)
end
local status = istore.gl_install_pkg(ctx, gpkg_path)
if status == ffi.C.GL_INSTALL_ERR_ALREADY_INSTALLED then
if skipInstalled then
log.lg_printf(1, "Skipping %s-%s (up to date)", pkg_name, version_str)
return tonumber(ffi.C.GL_INSTALL_SKIPPED)
end
log.lg_printf(1, "Reinstalling %s-%s (up to date)", pkg_name, version_str)
local rm_status = istore.gl_remove_pkg(ctx, pkg_name, manifest_repo)
if rm_status ~= ffi.C.GL_REMOVE_OK then
log.lg_printf(2, "Failed to remove %s::%s before reinstall (error %s).",
manifest_repo, pkg_name, tostring(tonumber(rm_status)))
return tonumber(rm_status)
end
status = istore.gl_install_pkg(ctx, gpkg_path)
if status == ffi.C.GL_INSTALL_OK then
-- M.install logs the one "staged from" line.
return 0
else
log.lg_printf(2, "Reinstall of %s-%s failed (error %s).",
pkg_name, version_str, tostring(tonumber(status)))
return tonumber(status)
end
elseif status == ffi.C.GL_INSTALL_OK then
return 0
end
return tonumber(status)
end
-- ---------------------------------------------------------------------
-- Transaction lifecycle
-- ---------------------------------------------------------------------
--- Open a staged transaction for the given scope. Exits on failure with
--- a scope-appropriate message. `scope_label` is used only in the
--- lock-contention message ("for UID 1000" vs "for the system scope").
local function begin_staged(opts)
local scope_label = opts.scope_label
local ctx = ffi.new("gl_context_t")
local txn_st = txn.gl_init_stage_context_at(ctx, opts.scope, opts.uid, opts.sysroot or "/")
if txn_st ~= ffi.C.GL_TXN_OK then
if txn_st == ffi.C.GL_TXN_ERR_LOCK then
log.lg_printf(2,
"Another glacier transaction is already in progress %s.",
scope_label)
else
log.lg_printf(2, "Failed to begin transaction: %s", txn_name(txn_st))
end
finish(1)
end
ctx.strict = opts.strict and 1 or 0
return ctx
end
--- Dependencies and conflicts (ROADMAP 2.3), checked before the prompt.
--- The library prints each problem; this exits if there were any. The
--- commit checks again (gl_check_txn), which is what covers a removal
--- whose repo is only chosen after the prompt.
local function check_plan(opts, adds, removes, exit)
local live = live_context(opts)
live.strict = opts.strict and 1 or 0
live.overwrite = overwrite and 1 or 0
local a = ffi.new("const char *[?]", #adds + 1)
for i, p in ipairs(adds) do a[i - 1] = p end
local r = ffi.new("const char *[?]", #removes + 1)
for i, id in ipairs(removes) do r[i - 1] = id end
local problems = tonumber(istore.gl_check_plan(live, a, #adds, r, #removes))
if problems < 0 then
log.lg_printf(2, "Cannot read the package store to check dependencies.")
end
if problems ~= 0 then exit(1) end
end
--- Commit, or abort-and-exit on failure.
local function commit_or_die(ctx)
local commit_st = txn.gl_commit_transaction(ctx)
if commit_st == ffi.C.GL_TXN_ERR_DEPS then
-- The library already said what's wrong, one line each.
txn.gl_abort_transaction(ctx)
finish(1)
elseif commit_st ~= ffi.C.GL_TXN_OK then
log.lg_printf(2, "Failed to commit transaction: %s", txn_name(commit_st))
txn.gl_abort_transaction(ctx)
finish(1)
end
end
--- The last line of a committed transaction. If the link pass refused
--- any path (each refusal is already printed above), the transaction is
--- committed but did not fully succeed: an error, and exit status 1.
local function report_done(ctx, exit)
local n = tonumber(ctx.link_refusals)
if n > 0 then
log.lg_printf(2, "%s %s not linked.", tostring(n),
n == 1 and "path was" or "paths were")
exit(1)
end
log.lg_printf(3, "Completed with no errors.")
exit(0)
end
--- Abort the transaction and exit non-zero. Every failure path inside a
--- staged loop goes through here so live state is never left partially
--- mutated.
local function abort_and_die(ctx)
txn.gl_abort_transaction(ctx)
finish(1)
end
-- ---------------------------------------------------------------------
-- Repository indexes (REPO_DESIGN.txt section 5)
-- ---------------------------------------------------------------------
ffi.cdef[[
int gpkg_common_getpid(void) asm("getpid");
int gpkg_common_chmod(const char *path, unsigned int mode) asm("chmod");
int gpkg_common_close(int fd) asm("close");
]]
-- Largest index accepted: what gl_sign_verify will check.
local MAX_INDEX = 64 * 1024 * 1024
-- A whole file, or nil if it is missing, unreadable or over `max`.
local function read_capped(path, max)
local f = io.open(path, "rb")
if not f then return nil end
local data = f:read(max + 1) or ""
f:close()
if #data > max then return nil end
return data
end
-- Fetch URL/NAME into `dest`. https goes through curl, refusing any
-- other protocol, redirects included; file:// is a plain copy of an
-- absolute path. True on success.
local function fetch(url, name, dest)
local path = url:match("^file://(/.*)$")
if path then
local data = read_capped(path .. "/" .. name, MAX_INDEX)
local f = data and io.open(dest, "wb")
if not f then return false end
local ok = f:write(data)
f:close()
return ok ~= nil
end
if not url:match("^https://") then return false end
local ok = os.execute("curl -sf --proto =https --proto-redir =https" ..
" --connect-timeout 30 --max-filesize " .. MAX_INDEX ..
" -o " .. shell_quote(dest) .. " -- " ..
shell_quote(url .. "/" .. name) .. " >/dev/null 2>&1")
return ok == true or ok == 0
end
-- Whether `text` is signed by `sig_path`, with a key trusted for `repo`
-- (picked by keynum, as signed_for).
local function index_signed(text, sig_path, repo)
local sig = ffi.new("gl_sign_sig_t")
if verify.gl_sign_read_sig(sig_path, sig) ~= 0 then return false end
local keynum = ffi.string(sig.keynum, 8)
for _, k in ipairs(trusted_keys(repo)) do
if ffi.string(k.pub.keynum, 8) == keynum then
return verify.gl_sign_verify(k.pub, sig,
ffi.cast("const uint8_t *", text), #text) == 0
end
end
return false
end
-- SERIAL, VALID_UNTIL and package count of an index's bytes, or the
-- gl_index_parse status.
local function parse_index(text, repo)
local idx = ffi.new("gl_index_t")
local st = tonumber(istore.gl_index_parse(text, #text, repo, idx))
if st ~= 0 then return nil, st end
local r = { serial = idx.serial, valid_until = idx.valid_until,
npkgs = tonumber(idx.npkgs) }
istore.gl_index_free(idx)
return r
end
-- Refresh one repository's index into `dir` (<base>/repos): fetch,
-- verify, parse, refuse a rollback or an expired index, then rename
-- over the accepted copy. Any failure keeps the accepted copy, prints
-- one line and returns false.
local function refresh_one(repo, url, dir, file_mode)
local tmp = string.format("%s/.%s.idx.%d", dir, repo, ffi.C.gpkg_common_getpid())
local tmp_sig = tmp .. ".sig"
local function fail(fmt, ...)
os.remove(tmp)
os.remove(tmp_sig)
log.lg_printf(2, fmt, ...)
return false
end
local text
if fetch(url, "repo.idx", tmp) and fetch(url, "repo.idx.sig", tmp_sig) then
text = read_capped(tmp, MAX_INDEX)
end
if not text then
return fail("Cannot fetch the index for %s.", repo)
end
-- The signature is checked over the very bytes parsed below.
if not index_signed(text, tmp_sig, repo) then
return fail("Index for %s is not signed by a key trusted for %s.", repo, repo)
end
local new, st = parse_index(text, repo)
if st == 2 then
return fail("Index fetched for %s is the index of another repository.", repo)
elseif not new then
return fail("Malformed index for %s.", repo)
end
local stored = dir .. "/" .. repo .. ".idx"
local old_text = read_capped(stored, MAX_INDEX)
local unchanged = false
if old_text then
local old = parse_index(old_text, repo)
if not old then
return fail("Malformed %s.", stored)
end
if new.serial < old.serial then
return fail("Index for %s is older than the one already accepted.", repo)
elseif new.serial == old.serial then
if text ~= old_text then
return fail("Index for %s has the serial of the one already accepted, but other contents.", repo)
end
unchanged = true
end
elseif io.open(stored, "rb") then
return fail("Cannot read %s.", stored)
end
if new.valid_until <= os.time() then
return fail("Index for %s has expired.", repo)
end
local serial = string.format("%d", tonumber(new.serial))
if unchanged then
os.remove(tmp)
os.remove(tmp_sig)
log.lg_printf(0, "Index for %s is up to date: serial %s.", repo, serial)
return true
end
-- Never written in place (bug 25): renamed over the old copy.
if ffi.C.gpkg_common_chmod(tmp, file_mode) ~= 0
or ffi.C.gpkg_common_chmod(tmp_sig, file_mode) ~= 0
or not os.rename(tmp_sig, stored .. ".sig")
or not os.rename(tmp, stored) then
return fail("Cannot write %s.", stored)
end
log.lg_printf(3, "Index for %s: serial %s, %s %s.", repo, serial,
tostring(new.npkgs), new.npkgs == 1 and "package" or "packages")
return true
end
--- Refresh the index of every repository repos.conf gives a url
--- (REPO_DESIGN.txt section 5), into the scope's <base>/repos, holding
--- the scope's lock. Every repository is tried; true if all succeeded.
--- Exits if there is nothing to refresh or the setup is at fault.
-- opts.scope / opts.uid / opts.sysroot / opts.scope_label: as M.install
function M.refresh(opts)
local remotes = {}
if repos_conf_present() then
local buf = ffi.new("char[65536]")
if tonumber(istore.gl_conf_repos(REPOS_CONF, buf, 65536)) ~= 0 then
log.lg_printf(2, "Malformed %s.", REPOS_CONF)
finish(1)
end
for name, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do
if url ~= "" then
table.insert(remotes, { name = name, url = url })
end
end
end
if #remotes == 0 then
log.lg_printf(2, "No remote repositories are configured.")
finish(1)
end
local ctx = live_context(opts)
local dir = ffi.new("char[4096]")
if txn.gl_scope_state_dir(ctx, "repos", dir) ~= 0 then
finish(1) -- the library said why
end
if txn.gl_begin_transaction(ctx) ~= ffi.C.GL_TXN_OK then
log.lg_printf(2, "Another glacier transaction is already in progress %s.",
opts.scope_label)
finish(1)
end
local file_mode = opts.scope == ffi.C.GL_SCOPE_SYS and tonumber("644", 8)
or tonumber("600", 8)
local all = true
for _, r in ipairs(remotes) do
all = refresh_one(r.name, r.url, ffi.string(dir), file_mode) and all
end
ffi.C.gpkg_common_close(ctx.lock_fd)
return all
end
-- ---------------------------------------------------------------------
-- Public: whole-batch install / remove
-- ---------------------------------------------------------------------
--- Install every package in gpkg_paths as ONE atomic staged transaction.
--- Any failure aborts the whole batch, leaving live state untouched.
--- Does not return on failure — exits.
-- opts.scope : ffi.C.GL_SCOPE_USR or ffi.C.GL_SCOPE_SYS
-- opts.uid : uid for USR scope (ignored for SYS)
-- opts.scope_label : human string for the lock-contention message
-- opts.sysroot : install root (syspkg -R; nil = the running system)
-- opts.strict : refuse, before committing, anything the link pass
-- would refuse (syspkg --strict, implied by -R)
--- KEEP_OLD from glacier.conf: how many backups of replaced versions to
--- keep per package. There is no default — it ships as 1 in
--- glacier.conf, and an operation that would replace a version refuses
--- to run if it's missing or not a whole number.
local function keep_old()
local n = ffi.new("int[1]")
local st = tonumber(istore.gl_conf_get_int("/etc/glacier/glacier.conf", "KEEP_OLD", n))
if st == 1 then
log.lg_printf(2, "Cannot read /etc/glacier/glacier.conf.")
elseif st == 2 then
log.lg_printf(2, "KEEP_OLD is not set in /etc/glacier/glacier.conf.")
elseif st == 3 or (st == 0 and n[0] < 0) then
log.lg_printf(2, "KEEP_OLD in /etc/glacier/glacier.conf must be a whole number, 0 or more.")
end
if st ~= 0 or n[0] < 0 then finish(1) end
return tonumber(n[0])
end
function M.install(gpkg_paths, opts)
-- From here on, gpkg_paths are the VERIFIED PRIVATE COPIES; the
-- caller's paths are only used for messages.
local original
gpkg_paths, original = verify_all(gpkg_paths, opts)
-- A different version of a package that's already installed is a
-- REPLACEMENT (upgrade or downgrade). Only -O permits it; without
-- -O it's refused here, before the prompt.
local installed = installed_entries(opts)
local entries, replacing, refused = {}, {}, false
for _, p in ipairs(gpkg_paths) do
local name, repo, ver = manifest_of(p)
local e = { repo = repo, name = name, ver = ver }
for _, i in ipairs(installed) do
if i.name == name and i.repo == repo and i.ver ~= ver then
if overwrite then
replacing[p] = i
e.ver = i.ver .. " -> " .. ver
else
log.lg_printf(2, "%s::%s %s is already installed.",
repo, name, i.ver)
refused = true
end
end
end
table.insert(entries, e)
end
if refused then
finish(1)
end
check_plan(opts, gpkg_paths, {}, finish)
local keep = next(replacing) and keep_old() or 0
if not confirm(entries) then
finish(0)
end
local ctx = begin_staged(opts)
ctx.overwrite = overwrite and 1 or 0
local staged = 0
-- Replacements: back up the installed version (from LIVE, written
-- under a .part name and only promoted after a successful commit),
-- then remove it from the stage so the new version installs into
-- a clean slot in the same transaction.
local live = live_context(opts)
local backup_root = ffi.string(live.store_path):gsub("/store$", "") .. "/backup"
for _, old in pairs(replacing) do
if keep > 0 then
local dir = string.format("%s/%s/%s", backup_root, old.repo, old.name)
local final = string.format("%s/%s-%s.gpkg", dir, old.name, old.ver)
local part = final .. ".part"
if tonumber(istore.gl_backup_pkg(live, old.repo, old.name, part)) ~= 0 then
log.lg_printf(2, "Cannot back up %s::%s %s.", old.repo, old.name, old.ver)
abort_and_die(ctx)
end
table.insert(pending_backups, { part = part, final = final, dir = dir, old = old })
end
if istore.gl_remove_pkg(ctx, old.name, old.repo) ~= ffi.C.GL_REMOVE_OK then
log.lg_printf(2, "Cannot remove %s::%s %s to replace it.", old.repo, old.name, old.ver)
abort_and_die(ctx)
end
end
for _, gpkg_path in ipairs(gpkg_paths) do
local status = install_with_reinstall(ctx, gpkg_path)
local pkg_name, manifest_repo, version_str = manifest_of(gpkg_path)
local abs_path = original[gpkg_path]
if status == 0 then
staged = staged + 1
log.lg_printf(3, "%s::%s-%s: staged from %s.",
manifest_repo, pkg_name, version_str, abs_path)
elseif status == 1 then
log.lg_printf(2, "%s::%s: Failed to open package archive %s.",
manifest_repo, pkg_name, abs_path)
abort_and_die(ctx)
elseif status == 2 then
log.lg_printf(2, "%s::%s: Failed to parse package manifest from archive %s.",
manifest_repo, pkg_name, abs_path)
abort_and_die(ctx)
elseif status == 3 then
log.lg_printf(2, "%s::%s: Failed to extract archive %s into store.",
manifest_repo, pkg_name, abs_path)
abort_and_die(ctx)
elseif status == 4 then
log.lg_printf(2, "%s::%s: Failed to add entry to index.",
manifest_repo, pkg_name)
abort_and_die(ctx)
elseif status == 6 then
-- GL_INSTALL_SKIPPED: not a failure, keep going
elseif status == 7 then
-- GL_INSTALL_ERR_SCOPE: the library refused this
-- package for this scope (base-repo package under
-- user scope). The library already logged the
-- specific reason; don't second-guess it here.
abort_and_die(ctx)
else
log.lg_printf(2, "Unknown error: %s", tostring(tonumber(status)))
abort_and_die(ctx)
end
end
-- Everything was skipped (-S, already up to date): the stage is
-- identical to live, so don't commit it. A commit isn't free — it
-- swaps the trees and re-links the whole store, re-printing every
-- standing link conflict for packages this command never touched.
if staged == 0 then
txn.gl_abort_transaction(ctx)
log.lg_printf(3, "Nothing to do.")
finish(0)
end
commit_or_die(ctx)
-- Committed: promote the backups, give each a sidecar (so it's an
-- installable, verifiable package), and keep only the newest KEEP_OLD.
for _, b in ipairs(pending_backups) do
if os.rename(b.part, b.final) then
local hex = sha256_file(b.final)
local sf = hex and io.open(b.final .. ".sha256", "w")
if sf then
sf:write("sha256:" .. hex .. "\n")
sf:close()
end
istore.gl_prune_backups(b.dir, keep)
log.lg_printf(0, "Backed up %s::%s %s to %s",
b.old.repo, b.old.name, b.old.ver, b.final)
else
log.lg_printf(1, "Could not keep the backup of %s::%s %s.",
b.old.repo, b.old.name, b.old.ver)
end
end
pending_backups = {}
report_done(ctx, finish)
end
--- Remove every named package as ONE atomic staged transaction.
--- Does not return on failure — exits.
function M.remove(pkg_names, opts)
-- Names, not files: resolve them against what's actually installed
-- (the old summary read them as .gpkg paths and printed
-- "unknown::pkg 0.0.0"). Anything not installed fails here, before
-- the prompt, not after the user has already said yes.
local installed = installed_entries(opts)
local entries, missing = {}, false
for _, name in ipairs(pkg_names) do
local found = false
for _, e in ipairs(installed) do
if e.name == name then
table.insert(entries, e)
found = true
end
end
if not found then
log.lg_printf(2, "%s is not installed.", name)
missing = true
end
end
if missing then
os.exit(1)
end
-- A name installed from more than one repo isn't resolved until
-- after the prompt, so only unambiguous names are checked here.
local count, removes = {}, {}
for _, e in ipairs(entries) do count[e.name] = (count[e.name] or 0) + 1 end
for _, e in ipairs(entries) do
if count[e.name] == 1 then table.insert(removes, e.repo .. "::" .. e.name) end
end
check_plan(opts, {}, removes, os.exit)
if not confirm(entries) then
os.exit(0)
end
local ctx = begin_staged(opts)
for _, pkg_name in ipairs(pkg_names) do
local repo = M.resolve_repo(ctx, pkg_name)
if not repo then
log.lg_printf(2, "Failed to resolve group for %s.", pkg_name)
abort_and_die(ctx)
end
local status = istore.gl_remove_pkg(ctx, pkg_name, repo)
if status == ffi.C.GL_REMOVE_OK then
log.lg_printf(3, "Staged removal of %s::%s.", repo, pkg_name)
elseif status == ffi.C.GL_REMOVE_ERR_NOT_FOUND then
log.lg_printf(2, "%s::%s not found.", repo, pkg_name)
abort_and_die(ctx)
elseif status == ffi.C.GL_REMOVE_ERR_UNLINK then
log.lg_printf(2, "Failed to unlink %s::%s.", repo, pkg_name)
abort_and_die(ctx)
elseif status == ffi.C.GL_REMOVE_ERR_INDEX then
log.lg_printf(2, "Failed to update index for %s::%s.", repo, pkg_name)
abort_and_die(ctx)
else
log.lg_printf(2, "Unknown remove error: %s", tostring(tonumber(status)))
abort_and_die(ctx)
end
end
commit_or_die(ctx)
report_done(ctx, os.exit)
end
return M