#!/usr/bin/luajit -E

-- syspkg: the SOLE system-scope glacier tool. Install, remove, and
-- system store creation under GL_SCOPE_SYS. See SECURITY_DESIGN.txt
-- sections 5 and 6.
--
-- Always run as root via doas (or sudo). NEVER setuid. syspkg's own
-- job is only to refuse when euid != 0; the privilege boundary itself
-- belongs to doas.
--
-- Unlike gpkg, this file does NOT follow the CWD-relative
-- require("lib/...") / ffi.load("./lib/...") convention. As root, that
-- convention means "load whatever lib/ is in the caller's current
-- directory" — under a doas rule restricted to `cmd syspkg`, that is a
-- full root escalation. So:
--   * -E in the shebang: LuaJIT ignores LUA_PATH/LUA_CPATH/LUA_INIT.
--   * package.path is pinned to this script's own real directory, and
--     every .so is ffi.load()ed by absolute path from the same place.
--   * every directory and file we load from must be root-owned and not
--     group/world-writable, all the way up to /, or we refuse to run.

local ffi = require("ffi")
local bit = require("bit")

-- asm() aliases so these don't collide with glacier_cdef's own
-- declarations of the same libc symbols (ffi.cdef refuses redefinition).
ffi.cdef[[
unsigned int syspkg_geteuid(void) asm("geteuid");
char *syspkg_realpath(const char *path, char *resolved) asm("realpath");
]]

-- Errors raised before the trust checks below have passed. These can't
-- go through libglacier_log's lg_printf: loading that .so as root before
-- verifying it is exactly what the checks exist to prevent. So this
-- reproduces lg_printf(LG_ERR, ...) byte for byte instead (color.h's
-- COL_RED / COL_RESET, stdout, trailing newline).
local function die(fmt, ...)
        io.stdout:write("\27[31m\27[1m[x]\27[0m\27[m " .. string.format(fmt, ...) .. "\n")
        os.exit(1)
end

-- Non-root may still reach -h and -v; anything that touches the system
-- store is refused after argument parsing, below.
local is_root = ffi.C.syspkg_geteuid() == 0

-- This script's own directory, symlinks resolved.
local self_dir
do
        local buf = ffi.new("char[4096]")
        if ffi.C.syspkg_realpath(arg[0], buf) == nil then
                die("Cannot resolve own location from '%s'.", tostring(arg[0]))
        end
        self_dir = ffi.string(buf):match("^(.*)/[^/]*$")
        if not self_dir or self_dir == "" then self_dir = "/" end
end

local function shell_quote(s)
        return "'" .. s:gsub("'", "'\\''") .. "'"
end

-- Refuse unless `path` is owned by root and not writable by group or
-- other. Anything less means a non-root user could swap in code that
-- syspkg would then run as root.
local function require_root_owned(path)
        local p = io.popen("stat -L -c '%u %a' -- " .. shell_quote(path) .. " 2>/dev/null")
        local line = p and p:read("*l")
        if p then p:close() end

        local uid, mode = (line or ""):match("^(%d+) ([0-7]+)$")
        if not uid then
                die("Cannot stat %s.", path)
        end
        if tonumber(uid) ~= 0 then
                die("Refusing to run: %s is not owned by root.", path)
        end
        if bit.band(tonumber(mode, 8), tonumber("022", 8)) ~= 0 then
                die("Refusing to run: %s is group- or world-writable.", path)
        end
end

local trusted = {}
do
        local d = self_dir
        while true do
                table.insert(trusted, d)
                if d == "/" then break end
                d = d:match("^(.*)/[^/]*$")
                if d == "" then d = "/" end
        end
end

local lib_dir = self_dir .. "/lib"
local so_dir = lib_dir .. "/glacier"
local so = {
        log = so_dir .. "/libglacier_log.so",
        istore = so_dir .. "/libglacier_istoreutils.so",
        txn = so_dir .. "/libglacier_transaction.so",
        verify = so_dir .. "/libglacier_verify.so",
}

-- libglacier_pkg.so is never ffi.load()ed directly, but istoreutils
-- pulls it in through its $ORIGIN RUNPATH, so it runs as root too.
for _, p in ipairs({
        lib_dir, so_dir,
        lib_dir .. "/cargs.lua",
        lib_dir .. "/glacier_cdef.lua",
        lib_dir .. "/gpkg_common.lua",
        so.log, so.istore, so.txn, so.verify,
        so_dir .. "/libglacier_pkg.so",
}) do
        table.insert(trusted, p)
end

-- Only meaningful as root: unprivileged, loading a user-owned lib/ gains
-- the caller nothing they couldn't already run themselves.
if is_root then
        -- Installed, lib/glacier and each .so are symlinks out of this
        -- package's store dir (lib/glacier -> /usr/lib/glacier -> links
        -- into libglacier-ng's), so the directories the loader really
        -- walks are the REAL path's ancestors. Check those too.
        local checked = {}
        local buf = ffi.new("char[4096]")
        for _, p in ipairs(trusted) do
                require_root_owned(p)
                if ffi.C.syspkg_realpath(p, buf) == nil then
                        die("Cannot stat %s.", p)
                end
                local d = ffi.string(buf)
                while not checked[d] do
                        checked[d] = true
                        require_root_owned(d)
                        if d == "/" then break end
                        d = d:match("^(.*)/[^/]*$")
                        if d == "" then d = "/" end
                end
        end
end

package.path = self_dir .. "/?.lua"
package.cpath = ""

local cargs = require("lib/cargs")
local glacier_cdef = require("lib/glacier_cdef")
local common = require("lib/gpkg_common")

local log = ffi.load(so.log)
local istore = ffi.load(so.istore)
local txn = ffi.load(so.txn)
local verify = ffi.load(so.verify)

local argc, argv = cargs.get_argv()

local usage_line = "usage: %s [-hv] [-n] [-y] [-flux PKG] [-OSV] [-R DIR] [--strict]"

local longopts = {
        help = "-h",
        version = "-v",
        verbose = "-V",
        ["skip-installed"] = "-S",
        overwrite = "-O",
        new = "-n",
        ["local"] = "-l",
        merge = "-f",
        update = "-u",
        remove = "-x",
        refresh = "-y",
        root = "-R",
        strict = "--strict",
}

local args = {}
for i = 1, argc - 1 do
        table.insert(args, ffi.string(argv[i]))
end

if #args == 0 then
        log.lg_printf(2, usage_line, argv[0])
        os.exit(1)
end

-- Parse everything first, then act once: unlike gpkg, the outcome
-- doesn't depend on whether -V came before or after -l.
local mode
local operands = {}
local isVerbose = false
local root              -- -R DIR: operate on the system installed under DIR
local strict = false    -- --strict (implied by -R)

local function set_mode(m)
        if mode and mode ~= m then
                log.lg_printf(2, "-n, -l, -f, -u, -x and -y are mutually exclusive.")
                os.exit(1)
        end
        mode = m
end

local function handle_flag(flag)
        if flag == "-h" then
                log.lg_syspkg_help(argc, argv)
                os.exit(0)
        elseif flag == "-v" then
                print("v4.0.0")
                os.exit(0)
        elseif flag == "-V" then
                isVerbose = true
                common.set_verbose(true)
        elseif flag == "-S" then
                common.set_skip_installed(true)
        elseif flag == "-O" then
                common.set_overwrite(true)
        elseif flag == "-n" then
                set_mode("new")
        elseif flag == "-l" then
                set_mode("install")
        elseif flag == "-f" then
                set_mode("fetch")
        elseif flag == "-u" then
                set_mode("upgrade")
        elseif flag == "-x" then
                set_mode("remove")
        elseif flag == "-y" then
                set_mode("refresh")
        elseif flag == "--strict" then
                strict = true
        else
                log.lg_printf(2, "Unknown option: %s", flag)
                log.lg_printf(2, usage_line, argv[0])
                os.exit(1)
        end
end

common.init({ log = log, istore = istore, txn = txn, verify = verify, argv = argv })

-- -R takes the next argument (or --root=DIR); in a bundle like -lR it
-- must come last.
local function set_root(dir)
        if not dir or dir == "" then
                log.lg_printf(2, "-R needs a directory.")
                os.exit(1)
        end
        if root then
                log.lg_printf(2, "-R given more than once.")
                os.exit(1)
        end
        root = dir
end

local i = 1
while i <= #args do
        local a = args[i]
        if a:sub(1, 2) == "--" then
                local name, value = a:sub(3):match("^([^=]*)=(.*)$")
                name = name or a:sub(3)
                local short = longopts[name]
                if not short or (value and short ~= "-R") then
                        log.lg_printf(2, "Unknown option: %s", a)
                        log.lg_printf(2, usage_line, argv[0])
                        os.exit(1)
                end
                if short == "-R" then
                        if not value then i = i + 1; value = args[i] end
                        set_root(value)
                else
                        handle_flag(short)
                end
        elseif 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 == "R" then
                                if k ~= #flags then
                                        log.lg_printf(2, "-R must come last in %s.", a)
                                        os.exit(1)
                                end
                                i = i + 1
                                set_root(args[i])
                        else
                                handle_flag("-" .. c)
                        end
                end
        elseif mode == "install" or mode == "remove" or mode == "fetch"
                        or mode == "upgrade" then
                table.insert(operands, a)
        else
                log.lg_printf(2, "Unexpected argument: %s", a)
                os.exit(1)
        end
        i = i + 1
end

if mode and not is_root then
        log.lg_printf(2, "Cannot open system index: Permission denied")
        os.exit(1)
end

-- The install root, refused here (by the library, which says why) before
-- anything reads or writes under it: it and every directory above it
-- must be root-owned directories that aren't group/world-writable.
-- `prefix` is what the messages below put in front of /glacier/...
local prefix = ""
if root then
        if txn.gl_check_sysroot(root) ~= 0 then
                os.exit(1)
        end
        prefix = root:gsub("/+$", "")
end

local function exists(path, test)
        local ok = os.execute("test " .. test .. " " .. shell_quote(path))
        return ok == true or ok == 0
end

local function require_sys_istore()
        local run = ffi.string(argv[0]) .. (root and (" -R " .. root) or "")
        if not exists(prefix .. "/glacier/sys/index/current", "-e") then
                log.lg_printf(2, "No system index found. Run %s -n first.", run)
                os.exit(1)
        end
        if not exists(prefix .. "/glacier/sys/store", "-d") then
                log.lg_printf(2, "No system store found. Run %s -n first.", run)
                os.exit(1)
        end
end

local opts = {
        scope = ffi.C.GL_SCOPE_SYS,
        uid = 0,
        scope_label = "for the system scope",
        sysroot = root,
        -- An image's /usr starts empty: anything refused there is two
        -- packages colliding or a broken package, never a distro file.
        strict = strict or root ~= nil,
}

if mode == "new" then
        if #operands > 0 then
                log.lg_printf(2, "-n takes no arguments.")
                os.exit(1)
        end
        -- gl_init_sys logs its own reason (e.g. "already exists"),
        -- same as gstore -n leaves it to gl_init_user.
        if istore.gl_init_sys_at(root or "/", isVerbose) ~= 0 then
                os.exit(1)
        end
        log.lg_printf(3, "Created system glacier directories:")
        print("\t* " .. prefix .. "/glacier/sys/index")
        print("\t* " .. prefix .. "/glacier/sys/store")
        print("\t* " .. prefix .. "/glacier/sys/links")
        os.exit(0)
elseif mode == "install" then
        if #operands == 0 then
                log.lg_printf(2, "usage: %s -l PKG...", argv[0])
                os.exit(1)
        end
        require_sys_istore()
        common.install(operands, opts)
elseif mode == "fetch" then
        if #operands == 0 then
                log.lg_printf(2, "usage: %s -f PKG...", argv[0])
                os.exit(1)
        end
        require_sys_istore()
        common.fetch(operands, opts)
elseif mode == "upgrade" then
        require_sys_istore()
        common.upgrade(operands, opts)
elseif mode == "remove" then
        if #operands == 0 then
                log.lg_printf(2, "usage: %s -x PKG...", argv[0])
                os.exit(1)
        end
        require_sys_istore()
        common.remove(operands, opts)
elseif mode == "refresh" then
        require_sys_istore()
        os.exit(common.refresh(opts) and 0 or 1)
else
        log.lg_printf(2, usage_line, argv[0])
        os.exit(1)
end
