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