Creates the host directory if missing (warning if it already exists,
another if it's non-empty) and records name -> directory in the config
file's new "volumes" section. Fails if the name or directory is already
used by an existing volume.
This is a distinct concept from OciImageConfig::volumes (an image's own
declared mount points, still unconsumed) -- a user-defined volume, meant
to be referenced by name once -r/--run starts actually mounting volumes.
config_file.{h,cpp} gains write_config_file(), symmetric to the existing
load_config_file(), built on libyaml's document-building/emitter API.
Rewrites the whole file each time; global.log-level round-trips
untouched alongside the new volumes section.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gv3s5jckJKzh6JkMoi2Akz
12 KiB
CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Project state
slocker-lite (C++20, built with Meson) mounts an OCI Image Layout tar (oci-layout +
index.json + blobs/sha256/*, as produced by skopeo/podman save --format oci-archive/modern docker save) using containers-storage and fuse-overlayfs, then
(via -r/--run) runs a sandboxed command against it with bwrap. The real deployment
target is Android with a stock kernel, where podman/docker don't run (missing
namespace support) and there's no kernel overlayfs (hence fuse-overlayfs); bwrap is
invoked in "degraded mode" using only whichever --unshare-xxx namespaces the running
kernel actually supports. See README.md for the human-facing overview (build/usage/
status); this file stays the dense, file-by-file reference. Still early-stage.
Source layout (all under src/):
main.cpp— CLI entry point, dependency checks, orchestration (mount_image(),run_container(),cleanup_image(),unmount_image(),list_images_command(),create_volume_command()).run_container()unconditionally callsread_oci_image_config()and reuses the result for two independent defaults: the command to run (Entrypoint ++ Cmd) when none is given on the command line, and, when--userwasn't given, the sandboxed process's user/group (config.User, split intoOciImageConfig::user/group) — an explicit--user/--groupon the command line always takes precedence.create_volume_command()implements-v/--volume <name> <directory>: seeconfig_file.{h,cpp}below for what a "volume" means here (a distinct concept fromOciImageConfig::volumes).oci_image.{h,cpp}— validates/parses the OCI Image Layout tar (libarchive + nlohmann_json) and extracts layer blobs.list_oci_images()scans a directory (non-recursively) for*.tar/*.tar.*files and, for each valid OCI archive, derives an image name/tag from itsindex.jsonmanifest annotations (io.containerd.image.namepreferred, elseorg.opencontainers.image.ref.name), falling back to the archive's filename and"latest"respectively.read_oci_image_config()reads the image config blob referenced by the manifest and extractsUser(split on:intoOciImageConfig::user/group),ExposedPorts,Env,Volumes, and the effective default command (Entrypoint ++ Cmd).user/groupand the default command are consumed by-r/--run(seemain.cppabove) —ExposedPorts/Env/Volumesare still just captured for when networking/volumes are implemented.containers_storage.{h,cpp}— wraps thecontainers-storageCLI (import-layer,mount,unmount,layer --json,delete-layer), forcingfuse-overlayfsas the overlaymount_program.cleanup_layer_chain()walks a layer's parent chain (children before parents) deleting each one.bwrap.{h,cpp}—detect_bwrap_unshare_args()probes the kernel (via a forkedunshare(2)per namespace type) for which--unshare-xxxflagsbwrapcan actually use;build_bwrap_args()/run_bwrap()assemble and run the sandboxed command.build_bwrap_args()deliberately drops--unshare-netfrom what's actually passed tobwrapeven when the kernel supports it — without any network setup (e.g.slirp4netns), unsharing it just leaves the sandbox with no network at all. Re-add once network isolation is implemented;detect_bwrap_unshare_args()itself still probes/reports it (e.g. via-t/--test), since that's kernel capability, not policy. Never requests--unshare-userwhen running as root: root doesn't need a fresh user namespace for privilege, and bwrap's own single-mapping uid/gid setup for one triggers the kernel's unprivileged-userns setgroups() restriction, which showed up as every other supplementary group collapsing to the overflow gid ("nobody") inid, andsuinside the sandbox failing with "can't set groups: Operation not permitted". Because of that, bwrap's own--uid/--gid(which require--unshare-user) aren't usable when running as root either —--user/--groupwork around this: when set,build_bwrap_args()/run_bwrap()bind-mount the separateslocker-lite-priv-drophelper (see below) into the sandbox at a fixed hidden path and route the real command through it as<uid>:<gid> -- <command...>. This only actually works without a user namespace (i.e. running as root) — under--unshare-user, the sandbox's uid map has only one valid entry, so the helper's ownsetuid()fails cleanly there instead of silently doing nothing.run_bwrap()fails fast (returns -1) if the helper can't be found next to this binary when--userwas requested, rather than silently running the command as root.priv_drop_helper.cpp→ the separateslocker-lite-priv-dropbinary (its ownexecutable()target inmeson.build, built with-static). Deliberately has zero dependencies on the rest of this project (no fmt/spdlog/etc.) and is fully statically linked: it gets bind-mounted into the container image's own filesystem, which won't haveslocker-lite's own shared library dependencies — a dynamically linked binary bind-mounted that way fails outright ("error while loading shared libraries"), which is exactly what happened before this was split out (the original approach bind-mountedslocker-lite's own — dynamically linked — binary via/proc/self/exeand reexeced it; kept only as a lesson, not as working code). Usage:slocker-lite-priv-drop <uid>:<gid> -- <command> [args...]; doessetgroups(0,…)→setgid()→setuid()→execvp(), in that order (dropping the group needsCAP_SETGID, which is lost oncesetuid()drops root).find_priv_drop_helper()(src/bwrap.cpp) locates it next toslocker-lite's own binary (via/proc/self/exe's directory), which holds both when run straight frombuildDir/and after a realmeson install.user_spec.{h,cpp}—resolve_user_and_group()resolves a user/group spec (each a name or numeric id) against the mounted image's own/etc/passwd//etc/group(not the host's), since names likegitonly mean anything inside that image's own user database. A numeric user with no group and no matching/etc/passwdentry defaults gid to the same numeric value as the uid.run_container()(main.cpp) calls this with either the explicit--user/--groupflags, or, when--userwasn't given, the image's own declaredconfig.User(OciImageConfig::user/group) — so a container defaults to running as whatever user the image itself declares, not root, unless the image declares none.process.{h,cpp}— argv-based subprocess helpers (fork/execvp, no shell):run_process()captures stdout (used forcontainers-storagecalls),run_process_foreground()inherits all of stdio (used for the interactivebwraprun). Alsofind_in_path(), a shared$PATHlookup.run_process_foreground()installs a SIGINT/SIGTERM handler around itswaitpid()that forwards the signal to the running child and keeps waiting instead of letting the default disposition killslocker-liteitself — without this, Ctrl-C (orkill) during-r'sbwraprun would skiprun_container()'s unmount/cleanup entirely, leaving the layer imported and/or mounted.config_file.{h,cpp}—load_config_file()reads and parses (via libyaml's document API,<yaml.h>) theglobalandvolumessections of the local YAML config file located byconfig_file_path()($XDG_CONFIG_HOME/slocker-lite/config.yaml, falling back to$HOME/.config/slocker-lite/config.yaml).global.log-levelis the only supportedglobalkey — other long options are one-shot flags, not settings, so they don't belong in a persistent config file. A missing file returns a default-constructed (empty)AppConfig, not an error; unknown sections/keys (and malformed individual volume entries) are ignored for forward-compatibility; malformed YAML syntax is a hard error.main()appliesconfig->log_level(via the existingapply_log_level()) right afterspdlog::cfg::load_env_levels()and before parsing CLI options, so an explicit--log-levelon the command line always overwrites it afterward — same precedence pattern already used forSPDLOG_LEVEL.write_config_file()writes the whole file back out (via libyaml's document-building/emitter API, symmetric to the read side) — used by-v/--volume(create_volume_command(),main.cpp) to persist a newVolumeEntry {name, directory}into thevolumessection, preservingglobaluntouched.VolumeEntry/thevolumessection is a distinct concept fromOciImageConfig::volumes: this is a user-definedname -> host directorymapping created via-v/--volume, not an image's own declared mount points (still unconsumed, seeoci_image.{h,cpp}above) — the two aren't connected yet, though a future-r/--runvolume-mounting feature would presumably look volumes up here by name.
Errors are logged via spdlog::error; every external command is also traced at debug
level in run_process()/run_process_foreground() (src/process.cpp) — visible via
SPDLOG_LEVEL=debug, since spdlog's default level is info — and a failed external
command additionally logs a spdlog::warn, which is visible by default (no env var
needed). The final "mounted image at: ..." success line is direct stdout program
output, not a log.
Because containers-storage mount runs rootless, it reexecs itself into a private
user+mount namespace to gain the privilege it needs for the overlay mount — which
leaves the result invisible to a plain shell or child process outside that namespace.
Confirmed containers-storage unshare does not rejoin an already-running mount's
namespace; only nsenter targeting the live fuse-overlayfs daemon's PID does.
-r/--run handles this automatically by locating that PID and running bwrap via
nsenter into its namespaces. Running as root sidesteps all of this: no privilege
reexec is needed, so the mount is already directly visible in the current namespace,
and nsenter --user=... into it then fails ("reassociate to namespace 'ns/user'
failed: Invalid argument") since the caller is already in that same user namespace.
-r/--run detects geteuid() == 0 and skips nsenter automatically in that case;
-n/--no-nsenter forces it off manually for any other situation where the mount turns
out to already be directly visible.
Build & test commands
Build directory is buildDir/ (already configured).
- Configure (only needed if
buildDir/is missing or deleted):meson setup buildDir - Build:
meson compile -C buildDir(orninja -C buildDir) — also buildsbuildDir/slocker-lite-priv-drop, the statically-linked helper-r --userneeds (seepriv_drop_helper.cppin "Project state") - Run the executable:
./buildDir/slocker-lite -m <image.tar>(see--helpfor the full flag list:-m/--mount,-r/--run,-u/--umount,-c/--cleanup,-l/--list-images,-n/--no-nsenter,--user,--group,-t/--test,--log-level,-h/--help,-V/--version) - Run tests:
meson test -C buildDir
Code style
- Null-pointer checks: prefer
if (!ptr)/if (ptr)overif (ptr == nullptr)/if (ptr != nullptr).
Licensing
- Every
.c/.cpp/.hfile undersrc/must start with the GPLv2-or-later copyright header (see any existing file undersrc/for the exact text). - After adding a new source file under
src/, run./add-license.shfrom the repo root to prepend the header (it readscopyright-headerand inserts it viased, skipping files that already have it, so it's safe to re-run at any time).
Build configuration notes
meson.buildsetswarning_level=3andcpp_std=c++20— keep new code warning-clean under-Wall -Wextra -Wpedantic-equivalent settings.- The single Meson
test()target runsslocker-liteagainst a fixture OCI image tar generated at build time bytests/gen_fixture.py(acustom_target) and checks its exit code (no test framework is wired in yet).