Initial commit: OCI image mounting via containers-storage

slocker-lite validates an OCI Image Layout tar, imports its layers into
containers-storage's layer store in order, and mounts the assembled image
using fuse-overlayfs, printing the resulting merged path.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-10 08:12:50 +00:00
commit a301dfb44f
16 changed files with 1141 additions and 0 deletions
+13
View File
@@ -0,0 +1,13 @@
# Meson build directory
/buildDir/
# Meson subprojects: keep the .wrap files, ignore fetched sources / download cache
/subprojects/*/
/subprojects/packagecache/
/subprojects/.wraplock
# JetBrains IDE
.idea/
# Claude Code session resume note (local-only, not part of the project)
/RESUME
+57
View File
@@ -0,0 +1,57 @@
# 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`. Given
an image tar path, it validates the layout, imports each layer into containers-storage's
layer store in order (chained by parent), mounts the assembled top layer, and prints the
resulting merged path. There is no README or broader architecture doc yet — treat this
repo as still early-stage.
Source layout (all under `src/`):
- `main.cpp` — CLI entry point, dependency checks, orchestration.
- `oci_image.{h,cpp}` — validates/parses the OCI Image Layout tar (libarchive +
nlohmann_json) and extracts layer blobs.
- `containers_storage.{h,cpp}` — wraps the `containers-storage` CLI (`import-layer`,
`mount`), forcing `fuse-overlayfs` as the overlay `mount_program`.
- `process.{h,cpp}` — argv-based subprocess helper (fork/execvp/pipe, no shell).
Errors are logged via `spdlog::error`; every external command is also traced at debug
level in `run_process()` (`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, the resulting mount lives in a private
user+mount namespace; the printed path is only directly usable from within that same
namespace (e.g. via `containers-storage unshare`), not from an arbitrary external shell.
## 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` (or `ninja -C buildDir`)
- Run the executable: `./buildDir/slocker_lite <image.tar>`
- Run tests: `meson test -C buildDir`
## Code style
- Null-pointer checks: prefer `if (!ptr)` / `if (ptr)` over `if (ptr == nullptr)` / `if (ptr != nullptr)`.
## Licensing
- Every `.c`/`.cpp`/`.h` file under `src/` must start with the GPLv2-or-later copyright
header (see any existing file under `src/` for the exact text).
- After adding a new source file under `src/`, run `./add-license.sh` from the repo
root to prepend the header (it reads `copyright-header` and inserts it via `sed`,
skipping files that already have it, so it's safe to re-run at any time).
## Build configuration notes
- `meson.build` sets `warning_level=3` and `cpp_std=c++20` — keep new code warning-clean under `-Wall -Wextra -Wpedantic`-equivalent settings.
- The single Meson `test()` target runs `slocker_lite` against a fixture OCI image tar generated at build time by `tests/gen_fixture.py` (a `custom_target`) and checks its exit code (no test framework is wired in yet).
+338
View File
@@ -0,0 +1,338 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Moe Ghoul>, 1 April 1989
Moe Ghoul, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
Executable
+10
View File
@@ -0,0 +1,10 @@
#! /bin/bash
if [[ $1 = -f ]]; then
shift
for i in "$@"; do
grep -q 'GNU General Public License' "$i" || sed -i '0 r copyright-header' "$i"
done
else
find src/ \( -name \*.c -o -name \*.cpp -o -name \*.h \) -exec "$0" -f {} +
fi
+16
View File
@@ -0,0 +1,16 @@
// Copyright (C) 2026 Viorel Munteanu
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+29
View File
@@ -0,0 +1,29 @@
project('slocker-lite', 'cpp',
version : '0.0.1',
default_options : ['warning_level=3', 'cpp_std=c++20'])
fmt_dep = dependency('fmt')
catch2_dep = dependency('catch2', required : get_option('enable_tests'))
yaml_dep = dependency('yaml-0.1')
archive_dep = dependency('libarchive')
json_dep = dependency('nlohmann_json')
spdlog_dep = dependency('spdlog')
conf_data = configuration_data()
conf_data.set_quoted('PACKAGE', meson.project_name())
conf_data.set_quoted('VERSION', meson.project_version())
conf_data.set10('ENABLE_TESTS', get_option('enable_tests'))
configure_file(output : 'config.h', configuration : conf_data)
slocker_lite = executable('slocker_lite',
['src/main.cpp', 'src/process.cpp', 'src/oci_image.cpp', 'src/containers_storage.cpp'],
include_directories : include_directories('.'),
dependencies : [fmt_dep, catch2_dep, yaml_dep, archive_dep, json_dep, spdlog_dep],
install : true)
fixture_tar = custom_target('oci-fixture',
output : 'fixture.tar',
command : [find_program('python3'), files('tests/gen_fixture.py'), '@OUTPUT@'])
test('test', slocker_lite, args : [fixture_tar])
+1
View File
@@ -0,0 +1 @@
option('enable_tests', type : 'boolean', value : true, description : 'Enable the Catch2 test dependency and -t test invocation')
+64
View File
@@ -0,0 +1,64 @@
// Copyright (C) 2026 Viorel Munteanu
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#include "containers_storage.h"
#include "process.h"
namespace {
std::string trim(const std::string& s) {
size_t begin = s.find_first_not_of(" \t\r\n");
if (begin == std::string::npos) {
return "";
}
size_t end = s.find_last_not_of(" \t\r\n");
return s.substr(begin, end - begin + 1);
}
} // namespace
std::string kMountProgram;
std::optional<std::string> import_layer(const std::filesystem::path& diff_file,
const std::string& parent_id) {
std::vector<std::string> argv = {
"containers-storage", "import-layer", "--file", diff_file.string(),
"--storage-opt", "overlay.mount_program=" + kMountProgram};
if (!parent_id.empty()) {
argv.push_back(parent_id);
}
ProcessResult result = run_process(argv);
std::string id = trim(result.stdout_output);
if (result.exit_code != 0 || id.empty()) {
return std::nullopt;
}
return id;
}
std::optional<std::string> mount_layer(const std::string& layer_id) {
std::vector<std::string> argv = {
"containers-storage", "mount", "--storage-opt",
"overlay.mount_program=" + kMountProgram, layer_id};
ProcessResult result = run_process(argv);
std::string path = trim(result.stdout_output);
if (result.exit_code != 0 || path.empty()) {
return std::nullopt;
}
return path;
}
+36
View File
@@ -0,0 +1,36 @@
// Copyright (C) 2026 Viorel Munteanu
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#pragma once
#include <filesystem>
#include <optional>
#include <string>
// Absolute path to the fuse-overlayfs binary, passed to containers-storage as
// overlay.mount_program so it performs the actual overlay mounting. Set once in main()
// after find_in_path() resolves it.
extern std::string kMountProgram;
// Runs `containers-storage import-layer --storage-opt overlay.mount_program=<path>
// [--file diff_file] [parent_id]`. Returns the new layer's ID (trimmed stdout) or
// nullopt on failure (containers-storage's own stderr is inherited/visible).
std::optional<std::string> import_layer(const std::filesystem::path& diff_file,
const std::string& parent_id);
// Runs `containers-storage mount --storage-opt overlay.mount_program=<path> <layer_id>`.
// Returns the merged directory path (trimmed stdout) or nullopt on failure.
std::optional<std::string> mount_layer(const std::string& layer_id);
+128
View File
@@ -0,0 +1,128 @@
// Copyright (C) 2026 Viorel Munteanu
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#include <array>
#include <cstdlib>
#include <filesystem>
#include <optional>
#include <string_view>
#include <unistd.h>
#include <fmt/core.h>
#include <spdlog/cfg/env.h>
#include <spdlog/spdlog.h>
#include "containers_storage.h"
#include "oci_image.h"
namespace {
constexpr std::array<std::string_view, 2> kRequiredTools = {"containers-storage", "bwrap"};
bool is_executable_file(const std::filesystem::path& path) {
std::error_code ec;
return std::filesystem::is_regular_file(path, ec) && access(path.c_str(), X_OK) == 0;
}
std::optional<std::filesystem::path> find_in_path(std::string_view name) {
const char* path_env = std::getenv("PATH");
if (!path_env) {
return std::nullopt;
}
std::string_view path{path_env};
for (size_t start = 0; start <= path.size();) {
size_t end = path.find(':', start);
if (end == std::string_view::npos) {
end = path.size();
}
std::filesystem::path dir{path.substr(start, end - start)};
if (!dir.empty()) {
std::filesystem::path candidate = dir / name;
if (is_executable_file(candidate)) {
return candidate;
}
}
start = end + 1;
}
return std::nullopt;
}
} // namespace
bool check_required_dependencies() {
bool all_found = true;
for (auto name : kRequiredTools) {
if (!find_in_path(name)) {
spdlog::error("required dependency not found in PATH: {}", name);
all_found = false;
}
}
return all_found;
}
int main(int argc, char* argv[]) {
spdlog::cfg::load_env_levels();
if (argc != 2) {
spdlog::error("usage: {} <image.tar>", argv[0]);
return 1;
}
const std::filesystem::path image_tar = argv[1];
if (!check_required_dependencies()) {
return 1;
}
auto mount_program = find_in_path("fuse-overlayfs");
if (!mount_program) {
spdlog::error("fuse-overlayfs not found in PATH");
return 1;
}
kMountProgram = mount_program->string();
auto layers = read_oci_layers(image_tar);
if (!layers) {
return 1;
}
std::string parent_id;
for (const auto& layer : *layers) {
std::filesystem::path tmp_file =
std::filesystem::temp_directory_path() /
fmt::format("slocker-lite-{}-{}", getpid(), oci_digest_hex(layer.digest));
if (!extract_blob_to_file(image_tar, oci_digest_hex(layer.digest), tmp_file)) {
return 1;
}
auto layer_id = import_layer(tmp_file, parent_id);
std::filesystem::remove(tmp_file);
if (!layer_id) {
spdlog::error("failed to import layer {}", layer.digest);
return 1;
}
parent_id = *layer_id;
}
auto merged = mount_layer(parent_id);
if (!merged) {
spdlog::error("failed to mount assembled image");
return 1;
}
fmt::print("mounted image at: {}\n", *merged);
return 0;
}
+195
View File
@@ -0,0 +1,195 @@
// Copyright (C) 2026 Viorel Munteanu
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#include "oci_image.h"
#include <archive.h>
#include <archive_entry.h>
#include <fmt/core.h>
#include <nlohmann/json.hpp>
#include <spdlog/spdlog.h>
#include <fstream>
#include <functional>
namespace {
using json = nlohmann::json;
std::string_view normalize_entry_path(std::string_view name) {
if (name.substr(0, 2) == "./") {
name.remove_prefix(2);
}
return name;
}
// Reads a single tar entry's content, calling `sink` with each chunk of data as it's
// read. `sink` is only invoked for the entry whose normalized path equals `target_name`.
// Returns true if the entry was found (regardless of whether it was empty).
bool for_each_chunk_in_entry(const std::filesystem::path& tar_path, std::string_view target_name,
const std::function<void(const char*, size_t)>& sink) {
struct archive* a = archive_read_new();
archive_read_support_filter_all(a);
archive_read_support_format_tar(a);
if (archive_read_open_filename(a, tar_path.c_str(), 65536) != ARCHIVE_OK) {
archive_read_free(a);
return false;
}
bool found = false;
struct archive_entry* entry;
while (archive_read_next_header(a, &entry) == ARCHIVE_OK) {
if (normalize_entry_path(archive_entry_pathname(entry)) != target_name) {
archive_read_data_skip(a);
continue;
}
found = true;
const void* buff;
size_t size;
int64_t offset;
while (true) {
int rc = archive_read_data_block(a, &buff, &size, &offset);
if (rc == ARCHIVE_EOF) {
break;
}
if (rc != ARCHIVE_OK) {
found = false;
break;
}
sink(static_cast<const char*>(buff), size);
}
break;
}
archive_read_free(a);
return found;
}
std::optional<std::string> read_entry_to_string(const std::filesystem::path& tar_path,
std::string_view target_name) {
std::string content;
bool found = for_each_chunk_in_entry(tar_path, target_name, [&](const char* data, size_t size) {
content.append(data, size);
});
if (!found) {
return std::nullopt;
}
return content;
}
} // namespace
std::string oci_digest_hex(std::string_view digest) {
constexpr std::string_view prefix = "sha256:";
if (digest.substr(0, prefix.size()) == prefix) {
digest.remove_prefix(prefix.size());
}
return std::string(digest);
}
bool extract_blob_to_file(const std::filesystem::path& tar_path, std::string_view digest_hex,
const std::filesystem::path& out_file) {
std::string entry_name = fmt::format("blobs/sha256/{}", digest_hex);
std::ofstream out(out_file, std::ios::binary | std::ios::trunc);
if (!out) {
spdlog::error("failed to open {} for writing", out_file.string());
return false;
}
bool found = for_each_chunk_in_entry(tar_path, entry_name,
[&](const char* data, size_t size) { out.write(data, static_cast<std::streamsize>(size)); });
if (!found) {
spdlog::error("blob {} not found in {}", entry_name, tar_path.string());
return false;
}
return true;
}
std::optional<std::vector<OciLayer>> read_oci_layers(const std::filesystem::path& tar_path) {
auto layout = read_entry_to_string(tar_path, "oci-layout");
if (!layout) {
spdlog::error("not an OCI image tar: missing oci-layout");
return std::nullopt;
}
try {
[[maybe_unused]] json parsed_layout = json::parse(*layout);
} catch (const json::parse_error& e) {
spdlog::error("oci-layout is not valid JSON: {}", e.what());
return std::nullopt;
}
auto index_content = read_entry_to_string(tar_path, "index.json");
if (!index_content) {
spdlog::error("not an OCI image tar: missing index.json");
return std::nullopt;
}
json index;
try {
index = json::parse(*index_content);
} catch (const json::parse_error& e) {
spdlog::error("index.json is not valid JSON: {}", e.what());
return std::nullopt;
}
std::string manifest_digest;
for (const auto& m : index.value("manifests", json::array())) {
if (m.value("mediaType", "") == "application/vnd.oci.image.manifest.v1+json") {
manifest_digest = m.value("digest", "");
break;
}
}
if (manifest_digest.empty()) {
spdlog::error("index.json has no OCI image manifest entry");
return std::nullopt;
}
std::string manifest_entry = fmt::format("blobs/sha256/{}", oci_digest_hex(manifest_digest));
auto manifest_content = read_entry_to_string(tar_path, manifest_entry);
if (!manifest_content) {
spdlog::error("missing image manifest blob {}", manifest_digest);
return std::nullopt;
}
json manifest;
try {
manifest = json::parse(*manifest_content);
} catch (const json::parse_error& e) {
spdlog::error("image manifest {} is not valid JSON: {}", manifest_digest, e.what());
return std::nullopt;
}
std::vector<OciLayer> layers;
for (const auto& l : manifest.value("layers", json::array())) {
OciLayer layer;
layer.digest = l.value("digest", "");
layer.media_type = l.value("mediaType", "");
if (layer.digest.empty()) {
spdlog::error("image manifest {} has a layer with no digest", manifest_digest);
return std::nullopt;
}
layers.push_back(std::move(layer));
}
if (layers.empty()) {
spdlog::error("image manifest {} has no layers", manifest_digest);
return std::nullopt;
}
return layers;
}
+44
View File
@@ -0,0 +1,44 @@
// Copyright (C) 2026 Viorel Munteanu
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#pragma once
#include <filesystem>
#include <optional>
#include <string>
#include <string_view>
#include <vector>
struct OciLayer {
std::string digest; // "sha256:<hex>", as it appears in the manifest
std::string media_type;
};
// Validates that `tar_path` is an OCI Image Layout tar (oci-layout + index.json +
// a referenced blobs/sha256/<digest> image manifest) and returns its layers in
// base-to-top order. Logs a specific error via fmt and returns nullopt if anything
// required is missing or malformed.
std::optional<std::vector<OciLayer>> read_oci_layers(const std::filesystem::path& tar_path);
// Extracts the raw bytes of blobs/sha256/<digest_hex> from `tar_path` into `out_file`.
// Returns false (and logs) if the entry isn't found.
bool extract_blob_to_file(const std::filesystem::path& tar_path,
std::string_view digest_hex,
const std::filesystem::path& out_file);
// Strips the "sha256:" algorithm prefix from a digest string, e.g.
// "sha256:abcd" -> "abcd". Returns the input unchanged if there is no such prefix.
std::string oci_digest_hex(std::string_view digest);
+78
View File
@@ -0,0 +1,78 @@
// Copyright (C) 2026 Viorel Munteanu
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#include "process.h"
#include <sys/wait.h>
#include <unistd.h>
#include <cstring>
#include <fmt/ranges.h>
#include <spdlog/spdlog.h>
ProcessResult run_process(const std::vector<std::string>& argv) {
spdlog::debug("running external command: {}", fmt::join(argv, " "));
int stdout_pipe[2];
if (pipe(stdout_pipe) != 0) {
return {-1, ""};
}
pid_t pid = fork();
if (pid < 0) {
close(stdout_pipe[0]);
close(stdout_pipe[1]);
return {-1, ""};
}
if (pid == 0) {
close(stdout_pipe[0]);
dup2(stdout_pipe[1], STDOUT_FILENO);
close(stdout_pipe[1]);
std::vector<char*> c_argv;
c_argv.reserve(argv.size() + 1);
for (const auto& arg : argv) {
c_argv.push_back(const_cast<char*>(arg.c_str()));
}
c_argv.push_back(nullptr);
execvp(c_argv[0], c_argv.data());
const char* msg = "run_process: execvp failed\n";
write(STDERR_FILENO, msg, std::strlen(msg));
_exit(127);
}
close(stdout_pipe[1]);
std::string output;
char buffer[4096];
ssize_t n;
while ((n = read(stdout_pipe[0], buffer, sizeof(buffer))) > 0) {
output.append(buffer, static_cast<size_t>(n));
}
close(stdout_pipe[0]);
int status = 0;
waitpid(pid, &status, 0);
int exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
if (exit_code != 0) {
spdlog::warn("external command failed (exit code {}): {}", exit_code, fmt::join(argv, " "));
}
return {exit_code, output};
}
+29
View File
@@ -0,0 +1,29 @@
// Copyright (C) 2026 Viorel Munteanu
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#pragma once
#include <string>
#include <vector>
struct ProcessResult {
int exit_code;
std::string stdout_output;
};
// Runs argv[0] with the given arguments via fork/execvp, capturing stdout.
// stderr is inherited so the child's own error messages reach the user directly.
ProcessResult run_process(const std::vector<std::string>& argv);
+14
View File
@@ -0,0 +1,14 @@
[wrap-file]
directory = spdlog-1.17.0
source_url = https://github.com/gabime/spdlog/archive/refs/tags/v1.17.0.tar.gz
source_filename = spdlog-1.17.0.tar.gz
source_hash = d8862955c6d74e5846b3f580b1605d2428b11d97a410d86e2fb13e857cd3a744
source_fallback_url = https://wrapdb.mesonbuild.com/v2/spdlog_1.17.0-2/get_source/spdlog-1.17.0.tar.gz
patch_filename = spdlog_1.17.0-2_patch.zip
patch_url = https://wrapdb.mesonbuild.com/v2/spdlog_1.17.0-2/get_patch
patch_fallback_url = https://github.com/mesonbuild/wrapdb/releases/download/spdlog_1.17.0-2/spdlog_1.17.0-2_patch.zip
patch_hash = f5dd3aead18a790b5463f1af514eec63d06893d860966771375d77fd4d9e4acf
wrapdb_version = 1.17.0-2
[provide]
dependency_names = spdlog
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
"""Writes a minimal one-layer OCI Image Layout tar to the path given as argv[1].
Used by meson.build to produce a fixture for the `meson test` smoke test.
"""
import gzip
import hashlib
import io
import json
import sys
import tarfile
def sha256_hex(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def add_bytes(tar: tarfile.TarFile, name: str, data: bytes) -> None:
info = tarfile.TarInfo(name=name)
info.size = len(data)
tar.addfile(info, io.BytesIO(data))
def main() -> None:
out_path = sys.argv[1]
# Uncompressed layer content: a tiny tar with a single file.
layer_tar_buf = io.BytesIO()
with tarfile.open(fileobj=layer_tar_buf, mode="w") as layer_tar:
add_bytes(layer_tar, "hello.txt", b"hello from slocker-lite fixture\n")
layer_tar_bytes = layer_tar_buf.getvalue()
diff_id = sha256_hex(layer_tar_bytes)
layer_gz_bytes = gzip.compress(layer_tar_bytes)
layer_digest = sha256_hex(layer_gz_bytes)
config = {
"architecture": "amd64",
"os": "linux",
"config": {},
"rootfs": {"type": "layers", "diff_ids": [f"sha256:{diff_id}"]},
}
config_bytes = json.dumps(config).encode()
config_digest = sha256_hex(config_bytes)
manifest = {
"schemaVersion": 2,
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"config": {
"mediaType": "application/vnd.oci.image.config.v1+json",
"digest": f"sha256:{config_digest}",
"size": len(config_bytes),
},
"layers": [
{
"mediaType": "application/vnd.oci.image.layer.v1.tar+gzip",
"digest": f"sha256:{layer_digest}",
"size": len(layer_gz_bytes),
}
],
}
manifest_bytes = json.dumps(manifest).encode()
manifest_digest = sha256_hex(manifest_bytes)
index = {
"schemaVersion": 2,
"manifests": [
{
"mediaType": "application/vnd.oci.image.manifest.v1+json",
"digest": f"sha256:{manifest_digest}",
"size": len(manifest_bytes),
}
],
}
index_bytes = json.dumps(index).encode()
oci_layout_bytes = json.dumps({"imageLayoutVersion": "1.0.0"}).encode()
with tarfile.open(out_path, mode="w") as tar:
add_bytes(tar, "oci-layout", oci_layout_bytes)
add_bytes(tar, "index.json", index_bytes)
add_bytes(tar, f"blobs/sha256/{config_digest}", config_bytes)
add_bytes(tar, f"blobs/sha256/{manifest_digest}", manifest_bytes)
add_bytes(tar, f"blobs/sha256/{layer_digest}", layer_gz_bytes)
if __name__ == "__main__":
main()