#!/usr/bin/luajit -- glacier-bootstrap: build a chrootable Everest system in TARGET from a -- template index and a directory of packages (GLACIER_BOOTSTRAP.txt, -- local mode). -- -- glacier-bootstrap [-hvntV] -d PKGDIR TEMPLATE TARGET -- -- 1. parse TEMPLATE (strict: anything unexpected is an error) -- 2. copy each PKGDIR/NAME-VER.gpkg into a private directory, hashing it -- on the way, against its sidecar and the template's pin if any -- 3. read the copies' manifests: name and version must match the -- template, every dependency must be listed (at least that version), -- and nothing listed may conflict -- 4. syspkg -R TARGET -n (skipped if TARGET is initialised -- and empty) -- 5. syspkg -R TARGET -l COPY... ONE transaction, strict -- 6. syspkg -R TARGET -y fetch the indexes of every -- repository TARGET's own -- repos.conf gives a url (skipped, -- with a warning, if none does) -- 7. -t: chroot TARGET /bin/sh -c true -- -- It NEVER WRITES INTO TARGET ITSELF: every byte there comes from -- syspkg, run through doas (directly when already root). The syspkg is -- the one on PATH. The copies handed to syspkg carry the sidecar -- verified here (its bytes as read, which match the copy's hash and the -- pin), so a pin is enforced by syspkg's own sidecar check too, and a -- file swapped in PKGDIR afterwards is never read. A NAME-VER.gpkg -- .sha256.sig next to it is carried too: syspkg requires one for base -- (REPO_DESIGN.txt section 7) and checks it against the HOST's keyring. -- -- Unprivileged: nothing here needs root, so unlike syspkg and gstore -- there is no root-ownership check. Its own lib/ is still found from -- its real location, not the current directory. -- -- Exit status: 1 usage or target, 2 template, 3 verification, -- 4 resolution, 5 installation, 6 smoke test, 7 repositories (TARGET -- is installed, but its indexes could not all be fetched). local ffi = require("ffi") ffi.cdef[[ char *bootstrap_realpath(const char *path, char *resolved) asm("realpath"); ]] local self_dir do local buf = ffi.new("char[4096]") if ffi.C.bootstrap_realpath(arg[0], buf) == nil then io.stderr:write("glacier-bootstrap: cannot resolve own location\n") os.exit(1) end self_dir = ffi.string(buf):match("^(.*)/[^/]*$") if not self_dir or self_dir == "" then self_dir = "/" end end package.path = self_dir .. "/?.lua" package.cpath = "" require("lib/glacier_cdef") local so_dir = self_dir .. "/lib/glacier" local log = ffi.load(so_dir .. "/libglacier_log.so") local istore = ffi.load(so_dir .. "/libglacier_istoreutils.so") local txn = ffi.load(so_dir .. "/libglacier_transaction.so") local verify = ffi.load(so_dir .. "/libglacier_verify.so") local EXIT_USAGE, EXIT_TEMPLATE, EXIT_VERIFY = 1, 2, 3 local EXIT_RESOLVE, EXIT_INSTALL, EXIT_SMOKE = 4, 5, 6 local EXIT_REPOS = 7 local function msg(level, fmt, ...) log.lg_printf(level, "%s", string.format(fmt, ...)) end local function shell_quote(s) return "'" .. s:gsub("'", "'\\''") .. "'" end local function run(cmd) io.stdout:flush() local ok = os.execute(cmd) return ok == true or ok == 0 end -- The private directory holding verified copies; removed on every exit. local private_dir local function finish(code) if private_dir then os.execute("rm -rf " .. shell_quote(private_dir)) private_dir = nil end os.exit(code) end -- --------------------------------------------------------------------- -- Arguments -- --------------------------------------------------------------------- local usage_line = "usage: glacier-bootstrap [-hvntV] -d PKGDIR TEMPLATE TARGET" local function usage(code) if code ~= 0 then msg(2, "%s", usage_line) os.exit(code) end local function opt(flag, text) print(string.format("%-25s %s", flag, text)) end print("glacier-bootstrap: Install a template's packages into a new system") print(usage_line) print() opt("{-h --help}", "Show this message") opt("{-v --version}", "Show the current version") opt("{-d --pkgdir} PKGDIR", "Take the template's packages from PKGDIR") opt("{-n --dry-run}", "Verify and resolve only, never touch TARGET") opt("{-t --test}", "Run a smoke test in TARGET afterwards") opt("{-V --verbose}", "Log events more verbosely") print() print("This program is free software.") print("See the GNU GPL version 3 for details.") os.exit(0) end -- Long options, as the short flag they stand for. local long_opts = { ["--help"] = "-h", ["--version"] = "-v", ["--pkgdir"] = "-d", ["--dry-run"] = "-n", ["--test"] = "-t", ["--verbose"] = "-V", } local pkgdir, dry_run, smoke, verbose local operands = {} do local i = 1 while i <= #arg do local a = arg[i] if a:sub(1, 2) == "--" and #a > 2 then local name, value = a:match("^(%-%-[^=]+)=(.*)$") if name == "--pkgdir" then a = "-d" table.insert(arg, i + 1, value) elseif long_opts[a] then a = long_opts[a] else msg(2, "Unknown option: %s", a) usage(EXIT_USAGE) end end if a:sub(1, 1) == "-" and #a > 1 then local flags = a:sub(2) for k = 1, #flags do local c = flags:sub(k, k) if c == "h" then usage(0) elseif c == "v" then print("v4.0.0") os.exit(0) elseif c == "n" then dry_run = true elseif c == "t" then smoke = true elseif c == "V" then verbose = true elseif c == "d" then if k ~= #flags then msg(2, "-d must come last in %s.", a) os.exit(EXIT_USAGE) end if pkgdir then msg(2, "-d given more than once.") os.exit(EXIT_USAGE) end i = i + 1 pkgdir = arg[i] if not pkgdir or pkgdir == "" then msg(2, "-d needs a directory.") os.exit(EXIT_USAGE) end else msg(2, "Unknown option: -%s", c) usage(EXIT_USAGE) end end else table.insert(operands, a) end i = i + 1 end end if not pkgdir or #operands ~= 2 then usage(EXIT_USAGE) end local template_path, target = operands[1], operands[2] -- syspkg -R refuses relative roots; say so here, before any work. if target:sub(1, 1) ~= "/" then msg(2, "TARGET must be an absolute path: %s", target) os.exit(EXIT_USAGE) end target = target:gsub("(.)/+$", "%1") if target == "/" then msg(2, "TARGET must not be /.") os.exit(EXIT_USAGE) end -- --------------------------------------------------------------------- -- 1. Template -- --------------------------------------------------------------------- -- -- # comment -- NAME=minimal -- PKG=musl 1.2.5 sha256:<64 hex> (the pin is optional) -- -- Exact versions only. Unknown keys (SYS_PROFILE included, until -- manifests record one: ROADMAP 3.3), a repeated NAME or package, a -- malformed line and an empty package list are all errors. local function valid_ident(s) return s:match("^[A-Za-z0-9._-]+$") ~= nil and s ~= "." and s ~= ".." end local function valid_version(s) return s:match("^%d+%.%d+%.%d+$") ~= nil or s:match("^%d+%.%d+%.%d+%-[A-Za-z0-9.]+$") ~= nil end local function parse_template(path) local f = io.open(path, "r") if not f then msg(2, "Cannot read template %s.", path) finish(EXIT_TEMPLATE) end local t = { pkgs = {} } local seen = {} local bad = false local n = 0 local function err(fmt, ...) msg(2, "%s:%d: " .. fmt, path, n, ...) bad = true end for line in f:lines() do n = n + 1 line = line:gsub("^%s+", ""):gsub("%s+$", "") if line ~= "" and line:sub(1, 1) ~= "#" then local key, value = line:match("^([A-Za-z_]+)=(.*)$") if not key then err("Expected KEY=value.") elseif key == "NAME" then if t.name then err("NAME given more than once.") elseif not valid_ident(value) then err("Invalid NAME: %s", value) else t.name = value end elseif key == "PKG" then local fields = {} for w in value:gmatch("%S+") do table.insert(fields, w) end local name, ver, pin = fields[1], fields[2], fields[3] if #fields < 2 or #fields > 3 then err("Expected PKG=NAME VERSION [sha256:HEX].") elseif not valid_ident(name) then err("Invalid package name: %s", name) elseif not valid_version(ver) then err("Invalid version for %s: %s", name, ver) elseif pin and not (pin:match("^sha256:%x+$") and #pin == 71) then err("Malformed pin for %s: %s", name, pin) elseif seen[name] then err("%s is listed twice (first on line %d).", name, seen[name]) else seen[name] = n table.insert(t.pkgs, { name = name, ver = ver, pin = pin and pin:sub(8):lower(), }) end else err("Unknown key: %s", key) end end end f:close() if not t.name then msg(2, "%s: No NAME.", path) bad = true end if #t.pkgs == 0 and not bad then msg(2, "%s: No packages.", path) bad = true end if bad then finish(EXIT_TEMPLATE) end return t end -- --------------------------------------------------------------------- -- 2. Verification -- --------------------------------------------------------------------- -- Copy `src` to `dst`, returning the sha256 of what was copied (hex), -- or nil. local function copy_hashed(src, dst) local i = io.open(src, "rb") if not i then return nil end local o = io.open(dst, "wb") if not o then i:close(); return nil end local hctx = ffi.new("gl_sha256_ctx_t") verify.gl_sha256_init(hctx) while true do local chunk = i:read(65536) if not chunk then break end verify.gl_sha256_update(hctx, ffi.cast("const uint8_t *", chunk), #chunk) o:write(chunk) end i:close() o:close() local digest = ffi.new("uint8_t[32]") local hex = ffi.new("char[65]") verify.gl_sha256_final(hctx, digest) verify.gl_sha256_to_hex(digest, hex) return ffi.string(hex) end local function verify_all(t) local mk = io.popen("mktemp -d 2>/dev/null") private_dir = mk and mk:read("*l") if mk then mk:close() end if not private_dir or private_dir == "" then private_dir = nil msg(2, "Cannot create a private working directory.") finish(EXIT_VERIFY) end local bad = false for _, p in ipairs(t.pkgs) do local file = string.format("%s-%s.gpkg", p.name, p.ver) local src = pkgdir .. "/" .. file local why local sf = io.open(src .. ".sha256", "r") local sidecar_text = sf and (sf:read("*a") or "") local expected = sidecar_text and sidecar_text:match("^sha256:(%x+)%s*$") if sf then sf:close() end local probe = io.open(src, "rb") if probe then probe:close() end if not probe then why = "no such file" elseif not sf then why = "no sidecar " .. src .. ".sha256" elseif not expected or #expected ~= 64 then why = "malformed sidecar " .. src .. ".sha256" else expected = expected:lower() if p.pin and p.pin ~= expected then why = "the template pins " .. p.pin .. ", the sidecar says " .. expected end end if not why then p.copy = private_dir .. "/" .. file local got = copy_hashed(src, p.copy) if not got then why = "cannot copy it to " .. p.copy elseif got ~= expected then why = "hash mismatch (sidecar says " .. expected .. ", file is " .. got .. ")" else -- The same bytes, not a sidecar written -- anew: a signature covers these. local o = io.open(p.copy .. ".sha256", "w") if not o or not o:write(sidecar_text) then why = "cannot write " .. p.copy .. ".sha256" end if o then o:close() end end end if not why then local sig = io.open(src .. ".sha256.sig", "rb") if sig then local bytes = sig:read("*a") or "" sig:close() local o = io.open(p.copy .. ".sha256.sig", "wb") if not o or not o:write(bytes) then why = "cannot write " .. p.copy .. ".sha256.sig" end if o then o:close() end end end if why then msg(2, "Refusing %s: %s.", src, why) bad = true end end if bad then finish(EXIT_VERIFY) end end -- --------------------------------------------------------------------- -- 3. Resolution -- --------------------------------------------------------------------- local function semver_str(v) local s = string.format("%d.%d.%d", v.maj, v.min, v.pat) if v.tag ~= nil then s = s .. "-" .. ffi.string(v.tag) end return s end -- Same ordering as the library (deps.c semver_cmp): tags are ignored. local function semver_ge(a, b) if a.maj ~= b.maj then return a.maj > b.maj end if a.min ~= b.min then return a.min > b.min end return a.pat >= b.pat end local function resolve(t) local bad = false local by_name = {} for _, p in ipairs(t.pkgs) do local m = ffi.new("gl_pkg_t") if istore.gl_read_pkg_manifest(p.copy, m) ~= 0 then msg(2, "Cannot read the manifest of %s/%s-%s.gpkg.", pkgdir, p.name, p.ver) bad = true else local name = ffi.string(m.pkg_name) local ver = semver_str(m.pkg_ver) p.repo = ffi.string(m.pkg_repo) p.semver = { maj = m.pkg_ver.maj, min = m.pkg_ver.min, pat = m.pkg_ver.pat } p.deps, p.confs = {}, {} local d = m.pkg_dependencies while d ~= nil and d.dep_name ~= nil do table.insert(p.deps, { name = ffi.string(d.dep_name), ver = { maj = d.dep_ver.maj, min = d.dep_ver.min, pat = d.dep_ver.pat }, str = semver_str(d.dep_ver), }) d = d + 1 end local c = m.pkg_conflicts while c ~= nil and c.conf_name ~= nil do table.insert(p.confs, ffi.string(c.conf_name)) c = c + 1 end istore.gl_free_pkg(m) if name ~= p.name or ver ~= p.ver then msg(2, "%s/%s-%s.gpkg is %s %s, not %s %s.", pkgdir, p.name, p.ver, name, ver, p.name, p.ver) bad = true end by_name[p.name] = p end end if bad then finish(EXIT_RESOLVE) end for _, p in ipairs(t.pkgs) do for _, d in ipairs(p.deps) do local q = by_name[d.name] if not q then msg(2, "%s::%s requires %s >= %s, which the template does not list.", p.repo, p.name, d.name, d.str) bad = true elseif not semver_ge(q.semver, d.ver) then msg(2, "%s::%s requires %s >= %s, but the template lists %s.", p.repo, p.name, d.name, d.str, q.ver) bad = true end end end -- Conflicts, by name, either direction; each pair once. for i, p in ipairs(t.pkgs) do for j = i + 1, #t.pkgs do local q = t.pkgs[j] local hit = false for _, c in ipairs(p.confs) do hit = hit or c == q.name end for _, c in ipairs(q.confs) do hit = hit or c == p.name end if hit then msg(2, "%s::%s conflicts with %s::%s.", p.repo, p.name, q.repo, q.name) bad = true end end end if bad then finish(EXIT_RESOLVE) end end -- --------------------------------------------------------------------- -- The target -- --------------------------------------------------------------------- -- Installed packages under TARGET as a set of "repo::name::ver", or nil -- if TARGET has no system index. The index is world-readable. local function target_index() local f = io.open(target .. "/glacier/sys/index/current", "r") if not f then return nil end local set, n = {}, 0 for line in f:lines() do local repo, name, ver = line:match("^([^:]+)::([^:]+)::([^:]+)") if repo then set[repo .. "::" .. name .. "::" .. ver] = true n = n + 1 end end f:close() return set, n end local function exists(path) return run("test -e " .. shell_quote(path) .. " -o -L " .. shell_quote(path)) end -- --------------------------------------------------------------------- -- Main -- --------------------------------------------------------------------- local t = parse_template(template_path) -- The same refusal syspkg -R makes, read-only, before any work. if txn.gl_check_sysroot(target) ~= 0 then finish(EXIT_USAGE) end -- A fresh TARGET, or one syspkg -n initialised with nothing installed -- (a run that stopped at the prompt). Anything else isn't ours to add to. local initialised = exists(target .. "/glacier/sys") if initialised then local _, n = target_index() if n == nil then msg(2, "%s/glacier/sys exists but has no system index.", target) finish(EXIT_USAGE) elseif n > 0 then msg(2, "%s already has packages installed.", target) finish(EXIT_USAGE) end end verify_all(t) resolve(t) msg(0, "Template %s, %d package%s for %s:", t.name, #t.pkgs, #t.pkgs == 1 and "" or "s", target) for _, p in ipairs(t.pkgs) do print(string.format(" * %s::%s %s%s", p.repo, p.name, p.ver, p.pin and " (pinned)" or "")) end if dry_run then msg(3, "Dry run: every package verified and resolved.") finish(0) end local is_root = ffi.C.geteuid() == 0 local as_root = is_root and "" or "doas " local syspkg do local p = io.popen("command -v syspkg 2>/dev/null") syspkg = p and p:read("*l") if p then p:close() end if not syspkg or syspkg:sub(1, 1) ~= "/" then msg(2, "syspkg is not on PATH.") finish(EXIT_INSTALL) end end local sys = as_root .. shell_quote(syspkg) .. " -R " .. shell_quote(target) local v = verbose and " -V" or "" if not initialised then if not run(sys .. " -n" .. v) then finish(EXIT_INSTALL) end end local cmd = sys .. v .. " -l" for _, p in ipairs(t.pkgs) do cmd = cmd .. " " .. shell_quote(p.copy) end if not run(cmd) then finish(EXIT_INSTALL) end -- syspkg exits 0 when its prompt is declined; check what it installed. local installed, n = target_index() local missing = {} for _, p in ipairs(t.pkgs) do if not (installed and installed[p.repo .. "::" .. p.name .. "::" .. p.ver]) then table.insert(missing, p) end end if #missing == #t.pkgs and (n or 0) == 0 then msg(2, "Nothing was installed into %s.", target) finish(EXIT_INSTALL) elseif #missing > 0 then for _, p in ipairs(missing) do msg(2, "%s::%s %s was not installed into %s.", p.repo, p.name, p.ver, target) end finish(EXIT_INSTALL) end -- TARGET's repositories, as its own repos.conf (from a package) gives -- them: syspkg -R reads TARGET's keyring for -y, and fetches into -- TARGET's /glacier/sys/repos. This also sets TARGET's rollback floor. -- A repos.conf this can't parse is left to syspkg to report. do local conf = target:gsub("/+$", "") .. "/etc/glacier/repos.conf" local buf = ffi.new("char[65536]") local st = tonumber(istore.gl_conf_repos(conf, buf, 65536)) local remote = st ~= 0 and exists(conf) if st == 0 then for _, url in ffi.string(buf):gmatch("([^\t\n]+)\t([^\n]*)\n") do if url ~= "" then remote = true end end end if not remote then msg(1, "No remote repositories are configured in %s.", target) elseif not run(sys .. v .. " -y") then finish(EXIT_REPOS) end end msg(3, "Bootstrapped %s into %s.", t.name, target) if smoke then if not run(as_root .. "chroot " .. shell_quote(target) .. " /bin/sh -c true") then msg(2, "chroot %s /bin/sh -c true failed.", target) finish(EXIT_SMOKE) end msg(3, "chroot %s /bin/sh -c true succeeded.", target) end finish(0)