437 Commits

Author SHA1 Message Date
mae
d89715c20b cmd/irdump: formatted disassembly 2026-02-08 21:06:22 +09:00
mae
c7ba7f2a31 cmd/irdump: basic disassembler 2026-02-08 21:06:22 +09:00
mae
5db302110f cmd/irdump: create cli 2026-02-08 21:06:22 +09:00
a3e87dd0ef container: ignore uninterpreted source
These can be set to anything by the distribution.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-08 19:39:39 +09:00
90a38c0708 container: strip host-dependent opts in test cases
This change also improves plumbing for stripping options.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-08 19:35:20 +09:00
39cc8caa93 container: add riscv64 constants
This target is unlikely to become viable any time soon.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-08 19:03:47 +09:00
c4f64f7606 dist: include target in filename
Backport patch will be removed in the next release.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-08 16:03:41 +09:00
a9e2a5e59f internal/rosa/go: 1.25.6 to 1.25.7
Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-08 15:42:58 +09:00
9fb0722cdf internal/rosa/go: alternative bootstrap path
For targets where the bootstrap toolchain is not available.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-08 15:04:03 +09:00
2f3e323c46 internal/rosa/gnu: gcc toolchain artifact
This toolchain is hacked to pieces. It works well enough to bootstrap Go, though.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-08 01:00:15 +09:00
1fc9c3200f internal/rosa: libucontext artifact
Required by GCC on musl.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-07 22:33:12 +09:00
096a25ad3a cmd/mbf: dump IR of artifact presets
This exposes IR outside test cases, useful for verifying correctness of alternative IR emitters.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-07 17:21:43 +09:00
ffd2f979fb internal/pkg: skip duplicate early
This significantly increases IR generation performance.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-07 17:11:41 +09:00
31a8cc9b5c internal/rosa/gnu: binutils artifact
Appears to be required by GCC? It complains with stuff installed by LLVM.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-07 14:02:23 +09:00
bb3f60fc74 internal/rosa/gnu: gmp, mpfr, mpc artifacts
Required by GCC.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-07 13:55:40 +09:00
697c91e04d internal/rosa/cmake: expose earlier build script
This allows for more flexible build setups.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-07 13:23:13 +09:00
3f7b8b4332 internal/rosa/git: git clone helper
For obtaining sources of projects that stubbornly refuse to provide release tarballs.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-06 21:10:59 +09:00
fa94155f42 internal/rosa/etc: resolv.conf
Required by programs that download from the internet in measured execArtifact.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-06 21:04:59 +09:00
233bd163fb internal/rosa/git: disable flaky test
This fails intermittently.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-06 20:45:52 +09:00
f9b69c94bc internal/rosa/ssl: prefix CA paths
This makes prefixes consistent with everything else since this will end up in the final Rosa OS image.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-06 20:41:58 +09:00
68aefa6d59 internal/rosa/openssl: fix paths
Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-06 19:53:51 +09:00
159fd55dbb internal/rosa/ssl: fix dependencies
These used to be provided by busybox.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 19:12:48 +09:00
ce6b3ff53b internal/rosa: unzip artifact
Because the zip format is too awful and cannot be streamed anyway, supporting it natively comes with no benefit.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 19:10:32 +09:00
30afa0e2ab internal/rosa/git: compile with http support
This should be able to fetch repositories deterministically.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 18:51:02 +09:00
9b751de078 internal/rosa/gnu: fix test suite flags
This sets the correct flag and also avoids changing ident per system.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 18:29:47 +09:00
d77ad3bb6e internal/rosa: curl artifact
Required for http support in git.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 18:15:16 +09:00
0142fc90b0 internal/rosa/make: post-configure script
Required for some projects with broken build scripts.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 18:13:48 +09:00
3c9f7cfcd0 internal/rosa: libpsl artifact
Required by curl.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 18:06:33 +09:00
a3526b3ceb internal/rosa: openssl artifact
Optional for many programs.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 18:03:18 +09:00
6ad21e2288 internal/rosa: register custom artifacts
This also encodes extra information for iana-etc.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 17:50:48 +09:00
27e2e3f996 internal/rosa/llvm: drop git dependency
This was added quite early and has no effect. Remove it to avoid compiling git early.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 17:44:58 +09:00
e0c720681b internal/pkg: standardise artifact IR
This should hopefully provide good separation between the artifact curing backend implementation and the (still work in progress) language. Making the IR parseable also guarantees uniqueness of the representation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-05 08:24:09 +09:00
f982b13a59 internal/pkg: improve error resolution
This was taking way too long for early failures.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-03 10:01:44 +09:00
443911ada1 internal/rosa: use stage3 mirror
These get taken down periodically and causes way too many rebuilds when they are taken down. Use mirror until a more elegant solution is available.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-02 23:43:34 +09:00
d7a3706db3 internal/rosa/x: regenerate build system
These come with 16-year-old scripts that do not understand aarch64 or really anything else relevant to Rosa OS.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-02 19:57:39 +09:00
3226dc44dc internal/rosa/gnu: libtool artifact
Required when generating autotools build systems.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-02 19:52:08 +09:00
9f98d12ad8 internal/rosa/gnu: automake artifact
This is very expensive. Avoid.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-02 18:49:18 +09:00
550e83dda9 internal/rosa/gnu: grep artifact
Some GNU software do not like the grep in toybox.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-02 18:38:01 +09:00
7877b4e627 cmd/mbf: print extra stage3 information
This includes ident of all three stages and the matching checksum if check is passing.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-02 18:33:16 +09:00
47ce6f5bd0 internal/rosa/llvm: conditionally add Rosa OS paths
This change also moves rpath flags to a more appropriate method.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-02-02 07:29:35 +09:00
48f4ccba33 internal/rosa/llvm: add rosa vendor
This cleans up checks specific to Rosa OS, and fixes stack overflow in llvm under certain conditions.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 22:47:13 +09:00
c31884bee4 internal/rosa: disable broken tests
These fail when running as users with supplementary groups, since they are unmapped in the container. This was not the case in the development container where all groups were dropped, so the failure was missed.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 14:12:40 +09:00
f8661ad479 internal/rosa/hakurei: backport test case fix
This patch will be removed in the next release.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 12:00:21 +09:00
536f0cbae6 internal/rosa/gnu: gettext 0.26 to 1.0
This now requires kernel headers for some reason.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 11:41:07 +09:00
8d872ff1cd internal/rosa: fetch from gnu mirror
GNU infrastructure is extraordinarily flaky and fetching from it killed the server too many times.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 11:26:48 +09:00
bf14a412e4 container: fix host-dependent test cases
These are not fully controlled by hakurei and may change depending on host configuration.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 10:59:56 +09:00
8b4576bc5f internal/rosa: migrate to make helper
This migrates artifacts that the helper cannot produce an identical instance of.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 08:55:33 +09:00
29ebc52e26 internal/rosa/hakurei: suffix variants
This makes log output more useful.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 05:03:15 +09:00
5f81aac0e2 internal/rosa: make helper
This change only migrates artifacts that remain unchanged under the helper, so this change should not cause any rebuilds.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 05:01:22 +09:00
47490823be internal/rosa: improve cmake interface
This should make the call site look better for new artifacts.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 02:42:01 +09:00
1ac8ca7a80 internal/rosa: isolate make implementation
This will come with a helper eventually.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-31 02:33:14 +09:00
fd8b2fd522 internal/rosa: fix up dependencies
These are no longer provided by the (incomplete) toybox implementations, so they need to be specified explicitly.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-30 03:11:16 +09:00
20a8519044 internal/rosa/mksh: also build lksh
This is better suited for /system/bin/sh. Full mksh is still included, installed at /system/bin/mksh.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-30 00:54:30 +09:00
8c4fd00c50 internal/rosa/ninja: build in $TMPDIR
This used to build in /work/system/bin/ and unfortunately leaves its garbage there. This behaviour is from very early stages of this package, and was never fixed. This change updates it to use the "$(mktemp -d)" convention that every other artifact uses.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-30 00:36:43 +09:00
bc3dd6fbb0 internal/rosa: chmod via patch helper
This works around the zfs overlay mount overhead and significantly reduces I/O in general.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-30 00:29:44 +09:00
616ed29edf internal/rosa: early toybox variant
This is a variant of toybox with unfinished tools enabled, for artifacts that will end up in a dependency loop without them.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-30 00:24:14 +09:00
9d9b7294a4 internal/rosa: flags for toolchain-dependent artifact
This is much cleaner to add extra flags to.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 20:44:43 +09:00
6c1e2f10a7 internal/rosa: remove busybox artifact
This is no longer used and its implementation is unacceptably shaky.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 19:58:51 +09:00
abf96d2283 internal/rosa: replace busybox with toybox
The busybox artifact does not run on aarch64, and the workarounds required for it to compile successfully on x86_64 is unacceptably shaky. This change fully replaces it with toybox.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 19:51:18 +09:00
6c90e879da internal/rosa/llvm: enable asan
This is required by test suite of latest toybox.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 18:30:37 +09:00
d1b404dc3a internal/rosa: findutils artifact
Required by llvm test suite, compiler-rt sanitisers-related tests fail on toybox xargs.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 18:24:01 +09:00
744e4e0632 internal/rosa: sed artifact
Required by various GNU programs as they are not happy with toybox sed.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 18:17:18 +09:00
85eda49b2b internal/rosa: xz artifact
Wanted to avoid this as much as possible. Unfortunately newer versions of GNU findutils only come in xz and is required for llvm compiler-rt sanitisers.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 18:06:17 +09:00
b26bc05bb0 internal/rosa: remove unused receiver
This returns the preset itself, it is up to the caller to load the underlying artifact.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 17:52:50 +09:00
2d63ea8fee internal/rosa: gzip artifact
Toybox does not implement this, and it is used by many programs, including toybox itself.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 17:46:30 +09:00
dd4326418c internal/rosa: toybox artifact
This compiles surprisingly quickly and required no workarounds, unlike busybox.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 17:44:30 +09:00
79c0106ea0 internal/rosa: replace busybox dash with mksh
Toybox does not provide a shell, mksh fills that gap.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 02:00:32 +09:00
536db533de internal/rosa: install bash as sh
This works around software relying on bashisms even when explicitly invoking sh.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 01:25:44 +09:00
07927006a8 internal/pkg: set User-Agent header
Avoid living under the default user agent and be at the mercy of some IDS.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 01:17:35 +09:00
77ea27b038 internal/rosa: mksh artifact
This provides a shell, as part of the effort to replace busybox.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-29 00:51:32 +09:00
e76bc6a13a internal/rosa: resolve preset by name
Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-28 20:57:51 +09:00
cc403c96d8 internal/rosa: remove busybox patch
This allows different versions of busybox to be attempted, to find one that works on arm.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-28 01:24:56 +09:00
66118ba941 internal/rosa: gawk artifact
Replaces broken awk in busybox.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-28 01:22:42 +09:00
823ba08dbc internal/rosa: use patch helper
This is significantly cleaner and runs somewhat faster.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-28 00:58:34 +09:00
660835151e internal/rosa: disable busybox SHA1_HWACCEL
This also pretties up the build output and sets correct linker path.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-28 00:51:09 +09:00
53e6df7e81 internal/rosa: remove uname
This does not change ident based on target.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 23:37:29 +09:00
bd80327a8f internal/rosa: add arm64 strings
This enables building on arm64.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 21:12:39 +09:00
41f9aebbb7 internal/pkg: allow multiarch
The armv8l busybox binary release needs this to run correctly.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 21:07:18 +09:00
a2a0e36802 internal/rosa: cross-platform stage3
The stage3 binary seed is arch-specific.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 20:58:31 +09:00
fbe93fc771 internal/rosa/busybox: cross-platform binary
The initial binary seed is arch-specific.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 20:54:11 +09:00
968d8dbaf1 internal/pkg: encode checksum in ident
This also rearranges the ident ir to be more predictable, and avoids an obvious and somewhat easy to get into inconsistent state.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 20:18:34 +09:00
f1758a6fa8 internal/rosa: nss artifacts
Not used by anything for now, but will be part of Rosa OS.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 08:17:58 +09:00
88aaa4497c internal/rosa/hakurei: dist tarball
The patch will be removed in the next release.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 07:34:45 +09:00
b7ea68de35 internal/rosa/hakurei: isolate hakurei helper
For creating the dist tarball, which runs in the same environment.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 07:28:13 +09:00
67e453f5c4 dist: run tests
This used to be impossible due to nix jank which has been addressed.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 07:00:39 +09:00
67092c835a internal/rosa/hakurei: v0.3.3 to v0.3.4
This now contains the sharefs program which pulls in fuse.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 05:40:53 +09:00
18918d9a0d internal/rosa: fuse artifact
Required by hakurei for sharefs.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 05:34:42 +09:00
380ca4e022 internal/rosa: pytest artifact
Required by libfuse. This pulls in many dependencies.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 05:20:37 +09:00
887aef8514 internal/rosa: python pip helper
Fuse requires pytest which depends on many packages. This helper eases the pain of packaging them.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 05:14:59 +09:00
d61faa09eb release: 0.3.4
Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 03:56:06 +09:00
50153788ef internal/rosa: hakurei artifact
This does not yet have fuse from staging. Everything else works perfectly, though.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 02:24:49 +09:00
c84fe63217 internal/rosa: various X artifacts
Required by xcb which is required by hakurei.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 02:02:49 +09:00
eb67e5e0a8 internal/pkg: exclusive artifacts
This alleviates scheduler overhead when curing many artifacts.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 01:23:50 +09:00
948afe33e5 internal/rosa/acl: use patch helper
This is significantly less ugly.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-27 00:30:50 +09:00
76c657177d internal/rosa: patch ignore whitespace
This makes it work better with patches emitted by git.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 21:56:36 +09:00
4356f978aa internal/rosa: kernel patching
The side effect of this is to work around zfs performance issue with chmod on overlay mount.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 21:20:52 +09:00
4f17dad645 internal/rosa: isolate patching helper
This is useful outside llvm as well.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 21:00:29 +09:00
68b7d41c65 internal/rosa: parallel autoconf tests
These take forever and run sequentially by default for some reason.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 19:52:59 +09:00
e48f303e38 internal/rosa: parallel perl tests
This is found in the github action, the test target does not appear to support parallelisation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 19:45:50 +09:00
f1fd406b82 internal/rosa: link libc ldd
Musl appears to implement this behaviour but does not install the symlink by default.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 08:00:03 +09:00
53b1de3395 internal/rosa: enable static on various artifacts
This is implicitly enabled sometimes, but better to be explicit.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 07:56:14 +09:00
92dcadbf27 internal/acl: connect getfacl stderr
This shows whatever failure is happening in the cure container.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 07:51:16 +09:00
0bd6a18326 internal/rosa: acl artifact
Required by hakurei.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 07:38:56 +09:00
67d592c337 internal/pkg: close gzip reader on success
The Close method panics otherwise.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 07:06:38 +09:00
fdc8a8419b internal/rosa: static libwayland
Required by hakurei.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 06:49:08 +09:00
122cfbf63a internal/rosa: run wayland tests
Broken test is disabled for now.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 06:39:45 +09:00
504f5d28fe internal/rosa: libseccomp artifact
Required by hakurei.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 05:28:36 +09:00
3eadd5c580 internal/rosa: gperf artifact
Required by libseccomp.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 05:25:39 +09:00
4d29333807 internal/rosa: wayland-protocols artifact
Required by hakurei.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 05:13:30 +09:00
e1533fa4c6 internal/rosa: wayland artifact
Required by hakurei.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 05:10:35 +09:00
9a74d5273d internal/rosa: libgd artifact
Required by graphviz which is required by wayland.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 04:20:11 +09:00
2abc8c454e internal/pkg: absolute hard link
This cannot be relative since the curing process is not in the temp directory.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 04:03:05 +09:00
fecb963e85 internal/rosa: libxml2 artifact
Required by wayland. Release tarball is xz only, unfortunately.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 03:47:42 +09:00
cd9da57f20 internal/rosa: libexpat artifact
Required by wayland.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 03:15:25 +09:00
c6a95f5a6a internal/rosa: meson artifact
Required by wayland and pipewire.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 03:03:21 +09:00
228489371d internal/rosa: setuptools artifact
Apparently the only way to install python stuff offline.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 02:28:47 +09:00
490471d22b cmd/mbf: verbose by default
It usually does not make sense to use this without verbose.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 02:12:56 +09:00
763d2572fe internal/rosa: pkg-config artifact
Used by hakurei and many other programs.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 01:26:54 +09:00
bb1b6beb87 internal/rosa: name suffix by toolchain
This makes output more useful during bootstrap.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 00:57:03 +09:00
3224a7da63 cmd/mbf: disable threshold by default
This is not very useful.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-26 00:05:59 +09:00
8a86cf74ee internal/rosa/go: symlink executables
This avoids having to fix up $PATH for every artifact.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-25 23:59:08 +09:00
e34a59e332 internal/rosa/go: run toolchain tests
LLVM patches and a TMPDIR backed by tmpfs fixed most tests. Broken tests in older versions are disabled.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-25 21:21:53 +09:00
861801597d internal/pkg: expose response body
This uses the new measured reader provided by Cache. This should make httpArtifact zero-copy.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-25 16:10:34 +09:00
334578fdde internal/pkg: expose underlying reader
This will be fully implemented in httpArtifact in a future commit.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-25 14:48:25 +09:00
20790af71e internal/rosa: lazy initialise all artifacts
This improves performance, though not as drastically as lazy initialising llvm.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-25 01:43:18 +09:00
43b8a40fc0 internal/rosa: lazy initialise llvm
This significantly improves performance.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-25 00:29:46 +09:00
87c3059214 internal/rosa: run perl tests
A broken test with unexplainable failure is disabled.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-24 18:58:09 +09:00
6956dfc31a internal/pkg: block on implementation entry
This avoids blocking while not in Cure method of the implementation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-24 16:02:50 +09:00
d9ebaf20f8 internal/rosa: stage3 special case helper
This makes it cleaner to specify non-stage3 and stage3-exclusive dependencies.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-24 12:23:35 +09:00
acee0b3632 internal/pkg: increase output buffer size
This avoids truncating unreasonably long lines from llvm.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-24 11:45:44 +09:00
5e55a796df internal/rosa: gnu patch artifact
This is more robust than the busybox implementation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-24 11:32:27 +09:00
f6eaf76ec9 internal/rosa: patch library paths
This removes the need for reference LDFLAGS in the standard toolchain.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-24 11:22:25 +09:00
5c127a7035 internal/rosa: patch header search paths
This removes the need for reference CFLAGS in the standard toolchain.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-23 01:56:52 +09:00
8a26521f5b internal/rosa/go: run bootstrap toolchain tests
The objdump test will be re-enabled after fixing llvm search paths.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-22 07:05:48 +09:00
0fd4556e38 internal/rosa/llvm: fix broken test patch
Both stage1 and stage2 passes at this point.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-22 06:42:04 +09:00
50b82dcf82 internal/rosa/gnu: coreutils artifact
Required by llvm unit and regression tests.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-22 05:42:23 +09:00
20a8d30821 internal/rosa/busybox: link /usr/bin/env
This is required by many scripts which uses bash but still pretends to be portable.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-22 04:21:06 +09:00
cdf2e4a2fb internal/rosa: bash artifact
Required by llvm unit and regression tests.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-22 04:06:48 +09:00
dcb8a6ea06 internal/rosa: fix toolchain layer order
This allows extras to override toolchain artifacts.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-22 03:37:46 +09:00
094a62ba9d internal/rosa: diffutils artifact
LLVM tests are not happy with busybox diff.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-22 03:00:59 +09:00
6420b6e6e8 internal/rosa: libffi artifact
Required by python during llvm test suite.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-22 02:47:47 +09:00
d7d058fdc5 internal/rosa/gnu: disable broken tests
These are documented as broken via comments yet not disabled on musl for some reason.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 23:31:45 +09:00
84795b5d9f internal/rosa/git: add dependencies
These are required outside the stage3 toolchain.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 22:14:48 +09:00
f84d30deed internal/rosa/gnu: run checks
Checks are not run for gettext for now since it contains broken tests.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 22:07:08 +09:00
77821feb8b internal/rosa: gettext artifact
Compile time dependency of git.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 21:52:50 +09:00
eb1060f395 internal/rosa: autoconf artifact
Required by git to reconfigure some options.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 21:44:49 +09:00
0e08254595 internal/rosa: m4 artifact
Autotools dependency.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 21:42:25 +09:00
349d8693bf internal/rosa: perl artifact
This runs without tests for now, will be enabled after some toolchain patches.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 21:33:12 +09:00
e88ae87e50 internal/rosa/llvm: run unit and regression tests
Two tests are marked expected to fail for Rosa OS.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 08:25:36 +09:00
7cd4aa838c internal/rosa/llvm: patch source tree
A few patches are required for disabling broken tests and changing default search paths.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 08:25:17 +09:00
641942a4e3 internal/rosa/cmake: chmod entire source tree
This works around builds that traverse out of the appended pathname.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 07:26:36 +09:00
b6a66acfe4 internal/rosa: git artifact
This is required by the clang unit and regression tests.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 07:00:14 +09:00
b72dc43bc3 internal/pkg: report dependency graph size
This is an interesting value to know when profiling.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 05:35:28 +09:00
8e59ff98b5 internal/rosa: include iana-etc
This is used by some programs and will likely end up in the Rosa OS system image anyway.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 05:28:41 +09:00
f06d7fd387 cmd/mbf: expose some artifacts for curing
This will remain until dist is successfully bootstrapped.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 05:18:08 +09:00
ba75587132 internal/pkg: allow user namespace creation
No good reason to filter this in the execArtifact container, and the extended filter breaks certain programs.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-21 04:49:25 +09:00
9a06ce2db0 internal/rosa: bootstrap go toolchain
This runs without tests for now. Will be fixed in a later commit.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-20 07:14:11 +09:00
3ec15bcdf1 internal/rosa/cmake: use hardcoded build directory
This eliminates some nondeterminism. Still getting 3-stage non-determinism in runtimes and clang, though.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 22:51:34 +09:00
d933234784 internal/pkg: make checksum available to cure
This enables deduplication by value as implemented in execArtifact.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 21:29:56 +09:00
1c49c75f95 cmd/mbf: toolchain 3-stage non-determinism check
This unfortunately fails right now. Requires further investigation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 04:40:44 +09:00
6a01a55d7e internal/rosa: parallel cmake bootstrap
This takes a very long time otherwise.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 03:21:29 +09:00
b14964a66d internal/rosa: standard toolchain via 2-stage bootstrap
This implements the 2-stage bootstrap build without clumping the stages together in the cmake target.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 02:57:28 +09:00
ff98c9ded9 internal/rosa: llvm bootstrap artifacts
This bootstraps the LLVM toolchain across multiple artifacts.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 02:48:44 +09:00
7f3d1d6375 internal/rosa: llvm artifact abstraction
The llvm bootstrap is multi-stage by nature, and cannot be completed in a single artifact.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 02:29:06 +09:00
3a4f20b759 internal/rosa: cmake abstraction
This is a helper for generating cure script for a cmake-based project.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 02:20:37 +09:00
21858ecfe4 internal/rosa: ninja artifact
Generated by cmake, recommended format for llvm toolchain.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 02:08:17 +09:00
574a64aa85 internal/rosa: cpython artifact
Dependency of llvm build scripts, also an optional cure dependency of ninja.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 01:58:53 +09:00
85d27229fd internal/rosa: zlib artifact
Dependency of llvm build scripts.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 01:48:27 +09:00
83fb80d710 internal/rosa: cmake artifact
This is required for compiling the toolchain and many other programs.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 01:36:38 +09:00
fe6dc62ebf internal/rosa: musl libc artifact
This will likely be included in Rosa OS. The installation is modified to be entirely contained in prefix.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 01:25:41 +09:00
823f9c76a7 internal/rosa: busybox from source
This will be part of the standard toolchain.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 01:12:47 +09:00
2df913999b internal/rosa: kernel headers
This is required by the toolchain and many other programs.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 01:03:19 +09:00
52c959bd6a internal/rosa: minimal rsync artifact
For installing kernel headers.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 00:58:34 +09:00
d258dea0bf internal/rosa: bootstrap on gentoo stage3
This contains a fully working musl+llvm toolchain and many build systems in a pretty small package.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 00:51:49 +09:00
dc96302111 internal/rosa: GNU make artifact
This compiles GNU make from source. This is unfortunately required by many programs, but is a cure dependency only.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 00:40:25 +09:00
88e9a143d6 internal/rosa: toolchain abstraction
This provides a clean and easy to use API over toolchains. A toolchain is an opaque set of artifacts and environment fixups. Exported toolchains should be functionally indistinguishable from each other.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 00:28:16 +09:00
8d06c0235b internal/rosa: busybox binary artifact
This installs a statically linked busybox binary distribution for decompressing the gentoo stage3 tarball, since there is no native xz implementation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-19 00:07:56 +09:00
4155adc16a internal/rosa: static etc artifact
This places configuration files with hardcoded content in /etc to silence test suites expecting them to be present.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-18 23:51:45 +09:00
2a9525c77a cmd/mbf: command handling
This tool is a frontend for bootstrapping hakurei via internal/pkg. Named mbf for now for "maiden's best friend" as a tribute to the DOOM source port.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-18 22:19:19 +09:00
efc90c3221 internal/pkg: deduplicate dependency errors
This significantly simplifies error reporting for caller.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-17 14:41:00 +09:00
610ee13ab3 internal/pkg: lock on-filesystem cache
Any fine-grained file-based locking here significantly hurts performance and is not part of the use case of the package. This change guarantees exclusive access to prevent inconsistent state on the filesystem.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-16 18:12:51 +09:00
5936e6a4aa internal/pkg: parallelise scrub
This significantly improves scrubbing performance. Since the cache directory structure is friendly to simultaneous access, this is possible without synchronisation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-16 02:47:59 +09:00
3499a82785 internal/pkg: cache computed identifiers
This eliminates duplicate identifier computations. The new implementation also significantly reduces allocations while computing identifier for a large dependency tree.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-15 23:30:43 +09:00
088d35e4e6 internal/pkg: optional dependency graph size limit
This provides a quick check against cyclic dependencies without hurting cure performance.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-14 18:25:46 +09:00
1667df9c43 internal/pkg: zero atime and mtime
This is significantly more practical than keeping track of them in directory flattening format and setting this in every non-artifact implementation. Only tarArtifact can have meaningful deterministic checksums that are not zero and zeroing them still keeps autotools happy.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-13 01:30:30 +09:00
156dd767ef internal/pkg: remove typeflag promotion loop
Expanding this enables sharing of code common between types.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-13 00:33:13 +09:00
5fe166a4a7 internal/pkg: exec prefix verbose output
This proxies program output through msg with a name and fd prefix. This also avoids introducing additional information to the container via process stdout/stderr.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-12 22:15:01 +09:00
41a8d03dd2 internal/pkg: cure completion verbose messages
This reports cure completions to the user.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-12 21:56:00 +09:00
610572d0e6 internal/pkg: optionally named static file
These are generally for generating configuration files or build scripts, naming them is quite useful.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-12 04:34:50 +09:00
29951c5174 internal/pkg: caller-supplied reporting name for exec
This does not have a reasonable way of inferring the underlying name. For zero value it falls back to base of executable pathname.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-12 04:17:47 +09:00
91c3594dee internal/pkg: append user-facing name in messages
This makes verbose messages much more useful.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-12 03:53:19 +09:00
7ccc2fc5ec internal/pkg: exec with specific timeout
This change also updates the documentation of NewExec.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-11 17:46:04 +09:00
63e137856e internal/pkg: do not discard the result of compact
This result was mistakenly unused resulting in incorrect identifiers for artifacts with duplicate dependencies.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-11 04:40:24 +09:00
e1e46504a1 container/check: return error backed by string type
The struct turned out not necessary during initial implementation but was not unwrapped into its single string field. This change replaces it with the underlying string and removes the indirection.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-11 04:23:55 +09:00
ec9343ebd6 container/check: intern absolute pathnames
This improves performance in heavy users like internal/pkg.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-11 04:18:11 +09:00
423808ac76 nix: use package from module in default
This makes overriding hakurei easier. Also avoids building hakurei twice since nix does that for some reason.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-11 03:50:08 +09:00
2494ede106 container/init: configure interface lo
This enables loopback networking when owning the net namespace.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-11 03:36:20 +09:00
da3848b92f internal/pkg: compare interfaces for host net
An upcoming improvement in the container init makes the current host net check return the same result for both cases. This change

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-11 00:30:32 +09:00
34cb4ebd3b internal/pkg: pass context to file cure
This removes the left over embedded contexts.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-09 05:31:38 +09:00
f712466714 internal/pkg: move dependency flooding to cache
This imposes a hard upper limit to concurrency during dependency satisfaction and moves all dependency-related code out of individual implementations of Artifact. This change also includes ctx and msg as part of Cache.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-09 05:20:34 +09:00
f2430b5f5e internal/pkg: use short wait delay
The cure is condemned at the point of cancellation and all of its state is destroyed by the deferred cleanup, so it makes little sense to wait for it much.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-08 18:58:51 +09:00
863e6f5db6 internal/pkg: use correct artifact count
This updates buffer sizes and counters to use correct total artifact count.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-08 08:45:37 +09:00
23df2ab999 internal/pkg: place ephemeral upperdir in tmp
This enables the use of directories made writable this way as scratch space.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-08 08:23:16 +09:00
7bd4d7d0e6 internal/pkg: support explicit overlay mount
This removes all but the /work/ auto overlay behaviour and enables much greater flexibility. This also renames ExecContainerPath to ExecPath so it is easier to type.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-08 07:55:09 +09:00
b3c30bcc51 internal/pkg: set container WaitDelay
This prevents a container from blocking forever after context is canceled.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-08 06:23:57 +09:00
38059db835 internal/pkg: make tar temporary directory writable
This allows it to be renamed to work directory.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-08 04:32:14 +09:00
409fd3149e internal/pkg: reserve kind range
This is useful for custom implementations of Artifact.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-08 01:21:51 +09:00
4eea136308 internal/pkg: do not connect stdin
This introduces external state when verbose.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-07 23:17:58 +09:00
c86ff02d8d internal/pkg: tar optional file
This allows tar to take a single-file directory Artifact as input.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-07 22:16:26 +09:00
e8dda70c41 internal/pkg: return reader for files
This improves efficiency for cache hits.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-07 21:36:47 +09:00
7ea4e8b643 internal/pkg: support tarball compressed via bzip2
Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-07 20:18:28 +09:00
5eefebcb48 internal/pkg: reject entry types disallowed in the cache
These are not encoded in the format, they are rejected here to serve as a check for cache since checksum is computed for every directory.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-07 03:22:44 +09:00
8e08e8f518 internal/pkg: automatic overlay mount on work
This directly submits the upperdir to cache. It is primarily used in bootstrapping where tools are limited and should not be used unless there is a very good reason to.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-07 03:14:33 +09:00
54da6ce03d internal/pkg: respect mount order for overlay temp
Setting it up after everything else prevents covering files in /tmp.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-07 01:03:49 +09:00
3a21ba1bca internal/pkg: implement file artifact
This is an Artifact implementing File, backed by a constant, caller-supplied byte slice.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-07 00:39:29 +09:00
45301559bf internal/pkg: fail on empty output directory
This works around the fact that execArtifact always creates the work directory when setting up the bind mount.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-07 00:04:32 +09:00
0df87ab111 internal/pkg: automatic overlay mount on tmp
This sets up the last Artifact to target /tmp as a writable overlay mount backed by the host side temp directory. This is useful for an Artifact containing source code to be built for another Artifact for example.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 23:45:08 +09:00
aa0a949cef internal/pkg: do not clear execute bit
Only write should be cleared here, clearing execute causes execArtifact to be unable to start anything since no Artifact is able to produce an executable file.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 22:31:44 +09:00
ce0064384d internal/pkg: automatic overlay mount on root
This makes it possible to use an Artifact as root without arranging for directory creation in the Artifact ahead of time.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 22:19:47 +09:00
53d80f4b66 internal/pkg/testdata: check network
This validates hostNet state.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 21:32:10 +09:00
156096ac98 internal/pkg: known checksum exec artifact
This optionally attaches an output checksum to an execArtifact and enables host networking for the resulting container.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 20:58:34 +09:00
ceb75538cf internal/pkg: update http checksum signature
This was using the old pre-KnownChecksum function signature. It did not affect correctness since httpArtifact performs internal validation to avoid the strict mode vfs roundtrip, but it prevented content-addressed cache hits.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 18:24:31 +09:00
0741a614ed internal/pkg: relocate testtool workaround
This can be reused in other test cases.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 18:06:56 +09:00
e7e9b4caea internal/pkg: exec nil path check during cure
This results in os.ErrInvalid instead of a panic, which hopefully improves user experience.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 17:46:12 +09:00
f6d32e482a internal/pkg: ensure parent for non-directory entries
This works around streams containing out of order entries.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 05:55:24 +09:00
79adf217f4 internal/pkg: implement exec artifact
This runs a program in a container environment. Artifacts can be made available to the container, they are cured concurrently and mounted in order.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 05:05:34 +09:00
8efffd72f4 internal/pkg: destroy temp during deferred cleanup
This avoids missing the cleanup when cure returns an error.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 04:24:54 +09:00
86ad8b72aa internal/pkg: expose cure through cure context
This allows a curing Artifact to cure Artifact it depends on.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 01:04:06 +09:00
e91049c3c5 internal/pkg: pass cure context as single value
This cleans up the function signature and makes backwards compatible API changes possible.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-06 00:56:49 +09:00
3d4d32932d internal/pkg: verify checksum after uneventful scrub
This checks that scrub did not condemn any entry without reporting it.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-05 22:54:16 +09:00
0ab6c13c77 internal/pkg: consistency check for on-disk cache
This change adds a method to check on-disk cache consistency and destroy inconsistent entries as they are encountered. This primarily helps verify artifact implementation correctness, but can also repair a cache that got into an inconsistent state from curing a misbehaving artifact, without having to destroy the entire cache.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-05 05:30:29 +09:00
834cb0d40b internal/pkg: override "." for directory checksum
This makes the checksum consistent with the final resting state of artifact directories without incurring the cost of an extra pair of chown syscalls.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-05 04:00:13 +09:00
7548a627e5 internal/pkg: delete stale done channels
There is no reason to keep these around.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-05 02:12:34 +09:00
b98d27f773 internal/pkg: expand single directory tarball
This enables much cleaner use of their output without giving up any meaningful data.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-05 01:43:23 +09:00
f3aa31e401 internal/pkg: temporary scratch space for cure
This allows for more flexibility during implementation. The use case that required this was for expanding single directory tarballs.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-05 01:39:18 +09:00
4da26681b5 internal/pkg: compute http identifier from url
The previous implementation exposes arbitrary user input to the cache as an identifier, which is highly error-prone and can cause the cache to enter an inconsistent state if the user is not careful. This change replaces the implementation to compute identifier late, using url string as params.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-05 00:43:21 +09:00
4897b0259e internal/pkg: improve artifact interface
This moves all cache I/O code to Cache. Artifact now only contains methods for constructing their actual contents.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-05 00:01:23 +09:00
d6e4f85864 internal/pkg: ignore typeflag 'g'
Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-04 12:46:56 +09:00
3eb927823f internal/pkg: create symlinks for files
These are much easier to handle than hard links and should be just as transparent for this use case.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-04 01:48:53 +09:00
d76b9d04b8 internal/pkg: implement tar artifact
This is useful for unpacking tarballs downloaded from the internet.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-04 01:34:30 +09:00
fa93476896 internal/pkg: override working directory perms
This must be writable to enable renaming, and the final result is conventionally read-only alongside the entire directory contents. This change overrides the permission bits as part of Store.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-04 00:55:52 +09:00
bd0ef086b1 internal/pkg: enable cache access during store
This is still not ideal as it makes entry into Store sequential. This will be improved after more usage code is written.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-04 00:39:14 +09:00
05202cf994 internal/pkg: pass context in request wrapper
This method is for the most common use case, and in actual use there will always be an associated context.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-03 23:53:52 +09:00
40081e7a06 internal/pkg: implement caching for directories
This works on any directories and should be robust against any bad state the artifact curing process might have failed at.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-03 22:54:46 +09:00
863d3dcf9f internal/pkg: wrap checksum string encoding
This wraps base64.URLEncoding.EncodeToString for cleaner call site.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-03 22:03:25 +09:00
8ad9909065 internal/pkg: compute identifier from deps
This provides infrastructure for computing a deterministic identifier based on current artifact kind, opaque parameters data, and optional dependency kind and identifiers.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-03 21:26:25 +09:00
deda16da38 internal/pkg: create work directory
This is used for artifacts that cure into directories.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-03 20:56:11 +09:00
55465c6e72 internal/pkg: optionally validate flat pathnames
This makes the decoder safe against untrusted input without hurting performance for a trusted stream. This should still not be called against untrusted input though.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-03 18:59:18 +09:00
ce249d23f1 internal/pkg: implement http artifact
This is useful for downloading source tarballs from the internet.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-03 15:29:58 +09:00
dd5d792d14 go: 1.25
Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-03 15:25:28 +09:00
d15d2ec2bd internal/pkg: relocate cache test helper
This is useful for other tests that need a cache instance.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-02 16:08:43 +09:00
3078c41ce7 internal/pkg: encode entry in custom format
The fact that Gob serialisation is deterministic is an implementation detail. This change replaces Gob with a simple custom format.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-02 15:39:42 +09:00
e9de5d3aca internal/pkg: implement caching for files
This change contains primitives for validating and caching single-file artifacts.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-02 12:57:19 +09:00
993afde840 dist: install sharefs
This also removes the deprecated hpkg program.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2026-01-02 00:57:51 +09:00
c9cd16fd2a cmd/sharefs: prepare directory early
This change also checks against filesystem daemon running as root early.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 23:17:02 +09:00
e42ea32dbe nix: configure sharefs via fileSystems
Turns out this did not work because in the vm test harness, virtualisation.fileSystems completely and silently overrides fileSystems, causing its contents to not even be evaluated anymore. This is not documented as far as I can tell, and is not obvious by any stretch of the imagination. The current hack is cargo culted from nix-community/impermanence and hopefully lasts until this project fully replaces nix.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 23:14:08 +09:00
e7982b4ee9 cmd/sharefs: create directory as root
This optional behaviour is required on NixOS as it is otherwise impossible to set this up: systemd.mounts breaks startup order somehow even though my unit looks identical to generated ones, fileSystems does not support any kind of initialisation or ordering other than against other mount points.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 22:14:33 +09:00
ef1ebf12d9 cmd/sharefs: handle mount -t fuse.sharefs
This should have been handled in a custom option parsing function, but that much extra complexity is unnecessary for this edge case. Honestly I do not know why libfuse does not handle this itself.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 20:49:27 +09:00
775a9f57c9 cmd/sharefs: check option parsing behaviour
This change makes it possible to check parseOpts behaviour as part of Go tests.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 17:33:12 +09:00
2f8ca83376 cmd/sharefs: containerise filesystem daemon
This replaces the forking daemonise libfuse function which prevents Go callbacks from calling into the runtime. This also enforces least privilege on the daemon process.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 10:16:35 +09:00
3d720ada92 container: optionally allow orphan
This is required for the typical daemonise use case.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 09:12:02 +09:00
2e5362e536 cmd/sharefs: opaque setup state
This allows unrestricted use of the type system and prepares setup code for cross-process initialisation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 04:14:00 +09:00
6d3bd27220 cmd/sharefs: expand fuse_main
This change should not change behaviour other than making output more consistent.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 02:30:28 +09:00
a27305cb4a cmd/sharefs: improve help message
This improves consistency with the fuse_main help message.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-27 02:20:41 +09:00
0e476c5e5b cmd/sharefs: allocate sharefs_private early
This also removes global state used by sharefs_init.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-26 08:08:41 +09:00
54712e0426 nix: set noatime on sharefs
Could improve performance, atime is not useful for this filesystem anyway.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-26 05:34:05 +09:00
b77c1ecfdb cmd/sharefs/test: check option handling
This verifies behaviour related to setuid/setgid when starting as root.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-26 05:28:45 +09:00
dce5839a79 nix: do not restart sharefs
This avoids disrupting running containers.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-26 04:12:14 +09:00
d597592e1f cmd/sharefs: rename fuse-helper to fuse-operations
This is not really just library wrapper functions, but instead implements the callbacks, so fuse-operations makes more sense.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-26 03:19:32 +09:00
056f5b12d4 cmd/sharefs: move translate_pathname body to macro wrapper
This is never called directly anywhere and it is simple enough to be included in the macro. This avoids passing the pointer around and dereferencing errno location, resulting in over 5% increase in throughput on the clang build. No change in the gcc build though.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-26 02:10:59 +09:00
da2bb546ba cmd/sharefs: remove readlink
This filesystem does not support symbolic links, so readlink is not useful, and unreachable in this case because of the check in getattr.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-25 06:00:58 +09:00
7bfbd59810 cmd/sharefs: implement shared filesystem
This is for passing files between applications, similar to android /sdcard.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-25 05:13:02 +09:00
ea815a59e8 nix: disable source fortification in devShell
This generates warnings when compiling without optimisation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-21 02:22:28 +09:00
28a8dc67d2 internal/pipewire: raise Core::Sync timeout
Hopefully relieves spurious failures on a very overloaded system.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-19 00:49:33 +09:00
ec49c63c5f internal/pipewire: EPOLL_CTL_ADD instead of EPOLL_CTL_MOD
Implementation is no longer tied down by the limitations of SyscallConn.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-19 00:43:44 +09:00
5a50bf80ee internal/pipewire: hold socket fd directly
The interface provided by net is not used here and is a leftover from a previous implementation. This change removes it.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-19 00:28:24 +09:00
ce06b7b663 internal/pipewire: inform conn of blocking intent
The interface does not expose underlying kernel notification mechanisms. This change removes the need to poll in situations were the next call might block.

This is made cumbersome by the SyscallConn interface left over from a previous implementation, it will be replaced in a later commit as the current implementation does not make use of any net.Conn methods other than Close.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-19 00:00:33 +09:00
08bdc68f3a internal/pipewire: sendmsg/recvmsg errors are fatal
When returned wrapped as a syscall error, these are impossible to recover from, so wrap them as a fatal error.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-18 23:33:12 +09:00
8cb0b433b2 release: 0.3.3
Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-15 20:34:45 +09:00
767f1844d2 test: check shim private dir cleanup
This asserts that no shim private dir was left behind after all containers terminate.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-15 20:30:19 +09:00
54610aaddc internal/outcome: expose pipewire via pipewire-pulse
This no longer exposes the pipewire socket to the container, and instead mediates access via pipewire-pulse. This makes insecure parts of the protocol inaccessible as explained in the doc comment in hst.

Closes #29.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-15 12:57:06 +09:00
2e80660169 internal/outcome: look up pipewire-pulse path
This is for setting up the pipewire-pulse container in shim, for #29.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-15 12:38:39 +09:00
d0a3c6a2f3 internal/outcome: optional shim private dir
This is a private work directory owned by the specific shim. Useful for sockets owned by this instance of the shim and requires no direct assistance from the priv-side process.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-15 12:32:46 +09:00
0c0e3d6fc2 hst: add direct hardware option
This is unfortunately the only possible setup to securely expose PipeWire to the container. Further explanation explained in the doc comment and #29.

This will be implemented in a future commit.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-15 12:29:32 +09:00
fae910a1ad container: sync stubbed wait4 loop after notify
This ensures consistent state observed by wait4 loop when running against stub.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 10:22:48 +09:00
178c8bc28b internal/pipewire: handle SecurityContext::Create error
This method can result in an error targeting it, so it is handled here. This change also causes a call to Create to also Core::Sync, as it should have done.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 09:41:28 +09:00
30dcab0734 internal/pipewire: SecurityContext as destructible
This proxy can be destroyed by sending a Core::Destroy targeting it. This change implements the Destroy method by embedding destructible.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 09:31:50 +09:00
0ea051062b internal/pipewire: reorder context struct
This change reorders and groups struct elements. This improves readability since this struct holds a lot of state loosely related to each other.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 09:26:30 +09:00
b0f2ab6fff internal/pipewire: implement Core::Destroy
This change also implements pending destructible check on Sync. Destruction method should always be implemented as a wrapper of destructible.destroy.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 09:20:58 +09:00
00a5bdf006 internal/pipewire: do not emit None for spa_dict
Turns out the PipeWire server does not expect a value of type None here at all.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 09:06:44 +09:00
a27dfdc058 internal/pipewire: implement Core::CreateObject
Nothing uses this right now, this would have to be called by wrapper methods on Registry that would search the objects

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 08:10:57 +09:00
6d0d9cecd1 internal/pipewire: handle nil spa_dict correctly
This now marshals into a value of type None when the slice is nil, and correctly unmarshals from type None.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 07:12:00 +09:00
17248d7d61 internal/pipewire: unmarshal nil pointer correctly
This now calls unmarshalCheckTypeBounds to advance to the next message. Additionally, handling for None value is relocated to a function for reuse by other types.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 06:58:53 +09:00
41e5628c67 internal/pipewire: return correct size for nil spa_dict
A nil spa_dict results in a None type value being sent over the wire.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 06:07:46 +09:00
ffbec828e1 internal/pipewire: move Core wrapper methods under Core
These do not belong under Context, and is an early implementation limitation that carried over.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-14 05:37:21 +09:00
de0467a65e internal/pipewire: treat noAck violation as fatal
Receiving this event indicates something has gone terribly wrong somehow, and ignoring Core::BoundProps causes inconsistent state anyway.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-13 22:30:06 +09:00
b5999b8814 internal/pipewire: implement Core::RemoveId
This is emitted by the server when a proxy id is removed for any reason. Currently, the only path for this to be emitted is when a global object is destroyed while some proxy is still bound to it.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-13 21:50:32 +09:00
ebc67bb8ad nix: update flake lock
NixOS 25.11 introduces a crash in cage and an intermittent crash in foot.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-12 08:39:55 +09:00
e60ff660f6 internal/pipewire: treat unknown opcode as fatal
Skipping events can cause local state to diverge from the server.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-11 04:22:03 +09:00
47db461546 internal/pipewire: generic Core::Error handling
This flushes message buffer before queueing the event expecting the error. Since this is quite useful and relatively complex, it is relocated to a method of Context.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-11 04:07:55 +09:00
0a3fe5f907 internal/pipewire: export Registry::Destroy
This handles the error returned by Sync.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-11 03:34:33 +09:00
b72d502f1c internal/outcome: populate instance metadata for PipeWire
These have similar semantics to equivalent Wayland security-context-v1 fields.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-10 03:01:30 +09:00
f8b3db3f66 internal/pipewire: cleaner error message for unsupported type
The error string itself is descriptive enough, so use it as the error message directly.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-10 01:51:06 +09:00
0e2fb1788f internal/pipewire: implement Registry::Destroy
This requires error handling infrastructure in Core that does not yet exist, so it is not exported for now. It has been manually tested via linkname against PipeWire.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-10 01:25:30 +09:00
d8417e2927 internal/pipewire: implement Registry::GlobalRemove
This is emitted by PipeWire when a global object disappears, because PipeWire insists that all clients that had called Core::GetRegistry must constantly sync its local registry state with the remote.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-10 01:00:03 +09:00
ccc0d98bd7 release: 0.3.2
Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-09 08:12:52 +09:00
a3fd05765e container: load initial process started before syscall
This avoids a race between returning from syscall and checking the state.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-09 08:12:22 +09:00
c538df7daa internal/pipewire: expose connection props
Unused in hakurei but could be useful when the package is moved out of internal.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-09 06:51:12 +09:00
44e5aa1a36 internal/pipewire: include remaining size in recvmsg wrapper
This otherwise truncates the received data by len(remaining) bytes.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-09 06:36:46 +09:00
cf0e7d8c27 internal/pipewire: reset per-roundtrip state once per call
This was left in consume when relocating per-roundtrip code out of the per-receive consume method.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-09 06:28:33 +09:00
130add21e5 internal/pipewire: increment remote sequence after establishing bounds
This avoids incrementing it twice proceeding from a partial message.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-09 06:21:41 +09:00
5ec4045e24 internal/pipewire: do not clobber error parsing SCMs
The error is handled later, clobbering it here breaks error handling when SCMs are present.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-09 06:02:15 +09:00
be2075f169 Revert "internal/pipewire: work around remote sequence quirk"
This reverts commit 564db6863b.
2025-12-09 05:25:41 +09:00
e9fb1d7be5 container/initdaemon: copy wstatus from wait4 loop
Due to the special nature of the init process, direct use of wait outside the wait4 loop is racy. This change copies the wstatus from wait4 loop state instead.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 22:58:42 +09:00
dafe9f8efc container: spin instead of block on wait4 ECHILD
Blocking prevents further wait4 processing causing ops to never receive their signals.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 22:56:13 +09:00
96dd7abd80 container: improve error message fallback
This now falls back to message.Error if no other concrete type is matched.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 22:45:54 +09:00
d5fb179012 cmd/hakurei: exec instead of fork/exec from shell
There is no reason to keep the shell process around.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 22:29:41 +09:00
462863e290 container: friendlier error message for op timing out
This includes the string for the failing op which helps with troubleshooting.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 22:19:03 +09:00
2786611b88 test/interactive: add app with bad daemon
This is useful for testing daemon error handling behaviour.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 22:12:07 +09:00
791a1dfa55 container: make wait4 loop available to ops
Due to the special nature of the init process, regular wait calls are unavailable. This change provides infrastructure to access wait4 loop state from Op.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 21:43:49 +09:00
564db6863b internal/pipewire: work around remote sequence quirk
Remote sequence sometimes start with a non-zero value, and keeps the same value for a while before going back to zero. Conditions for reproducing this behaviour is not yet known. This change works around this behaviour.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 20:10:01 +09:00
87781c7658 treewide: include PipeWire op and enforce PulseAudio check
This fully replaces PulseAudio with PipeWire and enforces the PulseAudio check and error message. The pipewire-pulse daemon is handled in the NixOS module.

Closes #26.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 08:53:04 +09:00
0c38fb7b6a hst: expose daemon as fs entry
This is slightly counterintuitive, but it turned out well under this framework since the daemon backs its target file.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 07:38:47 +09:00
357cfcddee container: start daemons within container
This is useful for daemons internal to the container. The only current use case is pipewire-pulse.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 07:21:04 +09:00
6bf245cf1b container: pass context as setup state
This is useful currently for daemon Op, but could be used for many other things.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 06:06:19 +09:00
c8eeb4a4d1 internal/outcome: integrate pipewire server
This is very simple and takes almost no inputs. This is not yet hooked up to anything to prevent breaking any existing behaviour.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 05:03:16 +09:00
5785714b64 container: call op method right before initial process
This is at a point considered to be already "within" the container. Daemons internal to the container can be started here.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 04:57:24 +09:00
422efcf258 hst: check for insecure PulseAudio enablement
This is currently still a noop, but required for #26.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 03:13:02 +09:00
104eeecf65 cmd/hakurei: add pipewire flag
This is for "run" command, formerly permissive defaults behaviour.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-08 02:39:55 +09:00
bf856f06e5 internal/pipewire: constant for PIPEWIRE_REMOTE
This is not defined anywhere in upstream PipeWire, no idea why.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 23:35:29 +09:00
1931b54600 hst: add pipewire flag
These are for #26. None of them are implemented yet. This fixes up test cases for the change to happen. Existing source code and JSON configuration continue to have the same effect. Existing flags get its EPulse bit replaced by EPipeWire.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 22:34:40 +09:00
093e30c788 internal/system: integrate PipeWire SecurityContext
Tests for this Op happens to be the best out of everything due to the robust infrastructure offered by internal/pipewire.

This is now ready to use in internal/outcome for implementing #26.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 17:39:34 +09:00
1b17ccda91 internal/system: optional op check parallelism
The PipeWire Op check cannot be made parallel due to the OS interaction.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 17:31:10 +09:00
7c6fc1128b internal/pipewire: set finalizer on scc
This prevents leaking the socket and pipe fds.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 17:29:22 +09:00
8cdd659239 internal/pipewire: seq access method for consume
This improves readability as the offset is not immediately obvious.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 17:07:30 +09:00
15c2839a09 internal/pipewire: respond to Core::Ping
There is currently no known message that will get the PipeWire server to emit this event. It should be handled regardless.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 14:55:56 +09:00
b9b9705b52 internal/pipewire: specify opcode and file count with message
This adds checking of FileCount while writing a message. Message encoding is relocated to an exported method to be used externally, probably for test stubbing.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 13:54:11 +09:00
246e04214a internal/system: pass syscall error message
This makes wrapped syscall errors produce a cleaner error message.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 02:08:05 +09:00
503bfc6468 internal/system: port connect by name
This behaviour is a bit messy and checks what appears to be a windows-specific environment variable for some reason. Keeping everything intact regardless to match upstream behaviour.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 02:00:19 +09:00
d837628b4c internal/system: remove ineffectual join reverting wayland
Removing the pathname socket used to be handled separately, now it is done during the Close call.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-07 00:43:50 +09:00
3cb58b4b72 internal/pipewire: high level SecurityContext helper
This sets up close pipe and socket internally, and exposes the resulting pathname socket and close_fd cleanup as an io.Closer.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-06 21:16:27 +09:00
bb1fc4c7bc internal/pipewire: check pending ids after done
This is not guaranteed to have completed after a roundtrip. This is leftover from when Roundtrip also sent and waited for sync.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-06 21:09:55 +09:00
f44923da29 internal/pipewire: post-sync cleanup functions
This makes it easier to handle resources who only needs to stay alive before the next sync.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-06 21:03:21 +09:00
5e7861bb00 internal/pipewire: handle dangling files in roundtrip
This should not be handled on every receive as it could cause valid (though impossible in current upstream implementation) messages to be rejected and raise a protocol error.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-06 19:21:57 +09:00
7cb3308a53 internal/pipewire: store proxy errors in context
This change fixes handling of non-fatal errors during a roundtrip as there can be multiple receive calls per roundtrip.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-06 19:13:46 +09:00
490093a659 internal/pipewire: set errno on an empty message
This matches upstream behaviour.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-06 16:50:49 +09:00
2b22efcdf1 internal/pipewire: rename context consume method
This name is more correct since it does not roundtrip, but receives messages. This is also more consistent with the method on event proxies.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-06 16:44:39 +09:00
8a2f9edcf9 internal/pipewire: use sendmsg/recvmsg directly
The PipeWire protocol does not work with Go abstractions. This change makes relevant methods call sendmsg/recvmsg directly.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-06 02:12:47 +09:00
0d3f332d45 internal/pipewire: do not send ancillary msg without files
This is unnecessary and does not match upstream behaviour.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-05 04:20:04 +09:00
d5509cc6e5 internal/pipewire: constants from pipewire/keys.h
These are PipeWire spa_dict keys. Interestingly many keys in the sample are undefined and appear as magic strings in upstream source code.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-05 03:27:30 +09:00
0d3ae6cb23 internal/pipewire: improve protocol error messages
These are mostly small formatting changes, with the biggest change being to UnexpectedEOFError where its kind is now described as part of the error type.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-04 03:15:58 +09:00
69b1131d66 internal/pipewire: use type name in error strings
This provides more useful messages for protocol errors.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-04 02:29:27 +09:00
2c0b92771a internal/pipewire: relocate constants
This should make things easier to navigate, and possible to fully automatically generate the constants in the future.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-03 03:52:17 +09:00
054c91879f internal/pipewire: finalizers for dangling files
This makes their handling much less error-prone.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-03 03:36:02 +09:00
c34439fc5f internal/pipewire: collect non-protocol errors
These errors are recoverable and should not terminate event handling. Only terminate event handling for protocol errors or inconsistent state that makes further event handling impossible.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-03 01:35:43 +09:00
32fb137bb2 internal/pipewire: fail on unacknowledged proxies
These proxies (with special cases documented in the implementation) are only safe for use after acknowledgement from the server.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-02 21:17:46 +09:00
e7a665e043 internal/pipewire: handle Core::Error
This event is not encountered in the pw-container sample, but already has existing sample from an excerpt.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-02 06:16:18 +09:00
af741f20a0 internal/pipewire: implement client context
This consumes the entire sample, is validated to send identical messages and correctly handle received messages.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-02 06:03:21 +09:00
39c6716fb0 internal/pipewire: use correct types in header
This was written when the protocol was still barely understood, so none of the types here are correct and match the rest of the protocol. This change corrects these types.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-02 03:32:10 +09:00
7bc73afadd internal/pipewire: wrap EOF error for deserialisation
The io.ErrUnexpectedEOF error can be returned from multiple places. This change eases error handling.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-02 03:19:37 +09:00
647aa9d02f internal/pipewire: preallocate for footer
This is useful during serialisation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-12-02 03:06:27 +09:00
91aaabaa1b internal/pipewire: benchmarks against Gob and JSON
Performance does not matter for the use case of this library, but it is still interesting to know.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-30 12:13:46 +09:00
3d4c7cdd9e internal/pipewire: implement Core::Error
Sample was captured from pw-cli.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-30 01:39:39 +09:00
4fd6d6c037 internal/pipewire: implement Core::Ping, Core::Pong
I could not get the server to produce these events, however I am confident enough with the implementation to do it by hand.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-29 23:25:29 +09:00
de3fc7ba38 internal/pipewire: implement SecurityContext::Create
This is finally the thing we are after.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-29 16:46:39 +09:00
5a5c4705dd internal/pipewire: implement Registry::Bind
This change also adds test cases for messages before this one.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-29 03:01:53 +09:00
f703aa20a5 internal/pipewire: implement client generation footer
This corresponds with the core generation footer and seem to be the only other possible footer type.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-29 02:55:30 +09:00
5c12425d48 internal/pipewire: implement Registry::Global
Dealing with this event reawakened my burning hatred for OOP.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-28 02:32:45 +09:00
cbe86dc4f0 internal/pipewire: add json struct tags
These match the names found in documentation.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-28 01:33:32 +09:00
d08a1081bd internal/pipewire: do not store spa_dict fields
This is effectively a poor man's slice, it is entirely unnecessary here and can be handled internally.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-28 01:25:18 +09:00
72a2601d74 internal/pipewire: store sample iovec continuously
This removes the need for manual splitting. The understanding of the format is robust enough to allow this to happen anyway.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-28 00:35:10 +09:00
1dab87aaf0 internal/pipewire: add missing constants
These did not appear useful at first since it was assumed to be filenames for loading modules.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-27 21:28:16 +09:00
2bafde99e3 internal/pipewire: shorten test data filenames
These were getting very annoying to type.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-27 20:06:01 +09:00
91efeb101a internal/pipewire: spa_dict size nil check
This fixes serialisation of NULL spa_dict.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-27 02:51:36 +09:00
dcb22a61c0 internal/pipewire: require appending marshaler
This eliminates all non-reflect allocations.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-27 02:33:19 +09:00
e028a61fc1 internal/pipewire: preallocate for known size
This is still not efficient by any means, but it should eliminate most non-reflect allocation (all allocation if PODMarshaler is not used).

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-27 02:26:31 +09:00
73987be7d4 internal/pipewire: size without serialisation
This is required to achieve zero allocation (other than reflect).

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-27 02:17:38 +09:00
563b5e66fc internal/pipewire: simplify spa_dict appends
This change uses the (somewhat) newly exposed MarshalAppend which improves readability.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-27 01:52:13 +09:00
2edcfe1e68 internal/pipewire: define size constants
This gets rid of magic numbers in marshal/unmarshal.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-27 00:54:56 +09:00
2698ca00e8 internal/pipewire: implement Core::Done
The message in the sample does not correspond to any known method call. The spec does not mention what to do with messages like this, but all existing usage code simply drops it.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-26 19:02:21 +09:00
1d0143386d internal/pipewire: optional final trailing garbage check
Omitting the check is only useful for custom unmarshaler.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-26 18:50:39 +09:00
a55c209099 internal/pipewire: additional Client::Info test case
This appears to add *one single entry* compared to the message before it. The inefficiency of this protocol is beyond imagination.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-26 16:28:57 +09:00
10ff276da1 internal/pipewire: additional Client::Info test case
This message follows the other Client::Info event before it. No idea why.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-26 16:17:38 +09:00
fd4d379b67 internal/pipewire: implement Client::Info
Everything is already supported, as usual.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-26 16:05:46 +09:00
77f5b89a41 internal/pipewire: implement Core::BoundProps
Very straightforward type, everything is already supported.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 18:40:19 +09:00
14e33f17e5 internal/pipewire: check nil marshaler
NULL values have special case in the format. This check ensures correctness serialising nil pointers.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 18:36:08 +09:00
cfeb7818eb internal/pipewire: implement Core::Info and generation footer
These are not directly related but are first encountered on the same message in the capture.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 15:16:12 +09:00
05391da556 internal/pipewire: implement footer
The POD itself is serialised without requiring a special case, however its presence is only indicated by the difference in size recorded in the header and payload.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 15:11:22 +09:00
463f8836e6 internal/pipewire: implement Long type
Thankfully no special case here.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 15:05:37 +09:00
2e465c94da internal/pipewire: implement Id type
This is, in fact, just a glorified Int type.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 15:01:58 +09:00
26009fd3f7 internal/pipewire: slice at POD boundary
This prevents incorrectly reading trailing data as part of the current POD.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 14:58:56 +09:00
2d7b896a8c internal/pipewire: bounds check against wire size
This covers cases where wire size is not known ahead of time.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 13:42:31 +09:00
a0eb010aab internal/pipewire: spa_dict trailing garbage within POD
This performs the check within the bounds of the POD only. This was not caught since spa_dict was only used as the final struct field until now.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 13:39:02 +09:00
b1b27ac1df internal/pipewire: zero size before validation
Leftover values from previous invocations cause incorrect behaviour here.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 12:21:37 +09:00
fc3d78fe01 internal/pipewire: implement Core::Sync
Once again, already entirely supported, the offset is not yet fully verified but makes intuitive sense. Will verify this on future occurrences of the message.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 08:52:06 +09:00
591637264a internal/pipewire: implement Core::GetRegistry
This struct is entirely supported, so this change is very straightforward.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 08:34:19 +09:00
e77652bf89 internal/pipewire: move test data to files
These get very big later on, and would be painful to represent as the compound literal.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 08:09:10 +09:00
88d3e46413 internal/pipewire: implement Client::UpdateProperties
This is the second message on the captured sample.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 04:16:11 +09:00
e51e81bb22 internal/pipewire: implement spa_dict type
This is a terrible type that defies the type system. It is implemented on the concrete type to avoid special cases.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 04:08:52 +09:00
8f4a3bcf9f internal/pipewire: use custom marshaler when available
This reduces special cases. This change also exposes unmarshalled message size on the wire.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 04:05:22 +09:00
827dc9e1ba internal/pipewire: implement string type
This is still NUL terminated strings, and an extra NUL character on an 8-byte string does cause an extra 7 bytes of padding.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 04:00:59 +09:00
d92de1c709 internal/pipewire: check for trailing garbage
This is useful during development.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 01:59:29 +09:00
5bcafcf734 internal/pipewire: implement Core::Hello
This implements enough types to correctly marshal and unmarshal Core::Hello.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-25 01:20:30 +09:00
9f7b0c2f46 internal/pipewire: add type constants
This change also centralises encoding testing.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-24 22:00:09 +09:00
3e87187c4c internal/pipewire: implement message header
Test cases are from interactions between pw-container and PipeWire. Results are validated against corresponding body.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-23 16:20:35 +09:00
b651d95e77 workflows: do not duplicate on pulls
This condition causes two runs to be created on a pull, as gitea does not check whether a run has already been created for the current commit.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-19 06:59:32 +09:00
aab92ce3c1 internal/wayland: clean up pathname socket
This is cleaner than cleaning up in internal/system as it covers the failure paths.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-19 06:37:04 +09:00
a495e09a8f internal/wayland: do not double close fd
These are already closed during securityContextBindPipe on a non-nil error.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-17 22:03:29 +09:00
3afca2bd5b internal/wayland: expose WAYLAND_VERSION
This might be useful troubleshooting information.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-17 01:46:01 +09:00
b73a789dfe .clang-format: increase indent width
This significantly increases readability. This patch is pretty big so it is being done after mostly everything has settled.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-16 20:57:29 +09:00
38b5ff0cec internal/wayland: check pathname size
This avoids passing a truncated pathname to the kernel.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-16 03:34:05 +09:00
3c204b9b40 internal/wayland: increase error detail
This includes targeted paths in the returned errors.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-16 02:09:50 +09:00
00771efeb4 internal/wayland: remove fd typecasts
These are no longer necessary since RawConn is no longer used.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-16 01:45:37 +09:00
61972d61f6 internal/wayland: reimplement connect/bind code
The old implementation is relocated to system/wayland/deprecated.go.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-16 01:23:16 +09:00
fe40af7b7e internal/wayland: relocate connection struct
This interface is getting replaced, so relocating it to the deprecated wrapper package before working on its replacement.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-15 23:25:46 +09:00
12751932d1 internal/wayland: improve error handling
Note: wl_registry_add_listener is undocumented everywhere. Its implementation calls wl_proxy_add_listener which returns 0 on success or -1 on failure.
Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-15 21:26:31 +09:00
41b49137a8 .clang-format: do not limit line length
This hard limit destroys readability in some places.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-15 17:06:43 +09:00
c761e1de4d nix: build with clang
Clang is better than gcc in various ways. This also pulls in clang-format which is very helpful.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-15 16:36:36 +09:00
a91920310d internal: relocate packages
Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-15 13:58:34 +09:00
16e674782a cmd/hakurei: reorder show entries
This order semantically makes more sense and generally looks tidier.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 22:14:49 +09:00
47244daefb treewide: migrate ldd callers
This discontinues use of the deprecated ldd.Exec function for #25.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 21:59:59 +09:00
46fa104419 ldd: require absolute pathname
The sandbox which ldd(1) runs in does not inherit parent work directory, so relative pathnames will not work correctly. While it is trivial to support such a use case, the use of relative pathnames is highly error-prone and generally frowned against in this project. The Exec function remains available under the same signature until v0.4.0 where it will be removed.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 21:53:10 +09:00
45953b3d9c ldd: cancel on decoder error
This prevents blocking from failures caused by ldd(1) emitting output that is not anticipated by the decoder.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 21:43:34 +09:00
42759e7a9f ldd: create musl entry representation
This mostly helps with debugging.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 21:38:35 +09:00
8e2d2c8246 ldd: check decoder scan guard
This was unreachable via the Parse wrapper.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 18:32:47 +09:00
299685775a container: provide usage example
This requires cgo so unfortunately will not run in the playground.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 18:25:22 +09:00
b7406cc4c4 ldd: update package doc comment
This should hopefully deter misuse of this package.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 17:49:01 +09:00
690a0ed0d6 ldd: decode from reader
This should reduce memory footprint of the parsing process and allow decoding part of the stream.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 08:33:19 +09:00
a9d72a5eb1 internal/outcome: rename run from main
The "main.go" name is quite confusing as this is often only present in main packages.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 01:06:14 +09:00
6d14bb814f container/fhs: add constant for /dev/shm/
This is mounted for the default read-only /dev/ when programs want to use shm_open(3). Defining it here is less error-prone and saves the extra append at runtime.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-14 01:03:26 +09:00
be0e387ab0 internal/info: relocate from internal
This is cleaner and makes more sense. The longer LDFLAGS was never a valid concern since it is always inserted by a script.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-13 07:29:46 +09:00
abeb67964f treewide: document linkname uses
These provide justification for each use of linkname. Poorly thought out uses of linkname are removed.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-13 07:14:16 +09:00
bf5d10743f treewide: import internal/system
For #24.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-13 01:22:47 +09:00
4e7aab07d5 internal/system: relocate from system
These packages are highly specific to hakurei and are difficult to use safely from other pieces of code.

Their exported symbols are made available until v0.4.0 where they will be removed for #24.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-13 01:17:47 +09:00
15a66a2b31 treewide: import internal/helper
For #24.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-12 23:19:34 +09:00
f347d44c22 internal/helper: relocate from helper
This package is ugly and is pending removal only kept alive by xdg-dbus-proxy.

Its exported symbols are made available until v0.4.0 where it will be removed for #24.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-12 23:16:13 +09:00
b5630f6883 test: move package sandbox internal
This should never be used outside vm tests.

Signed-off-by: Ophestra <cat@gensokyo.uk>
2025-11-12 23:03:22 +09:00
299 changed files with 24805 additions and 1587 deletions

2
.clang-format Normal file
View File

@@ -0,0 +1,2 @@
ColumnLimit: 0
IndentWidth: 4

View File

@@ -2,7 +2,6 @@ name: Test
on:
- push
- pull_request
jobs:
hakurei:
@@ -73,6 +72,23 @@ jobs:
path: result/*
retention-days: 1
sharefs:
name: ShareFS
runs-on: nix
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Run NixOS test
run: nix build --out-link "result" --print-out-paths --print-build-logs .#checks.x86_64-linux.sharefs
- name: Upload test output
uses: actions/upload-artifact@v3
with:
name: "sharefs-vm-output"
path: result/*
retention-days: 1
hpkg:
name: Hpkg
runs-on: nix
@@ -97,6 +113,7 @@ jobs:
- race
- sandbox
- sandbox-race
- sharefs
- hpkg
runs-on: nix
steps:

1
.gitignore vendored
View File

@@ -27,6 +27,7 @@ go.work.sum
# go generate
/cmd/hakurei/LICENSE
/internal/pkg/testdata/testtool
# release
/dist/hakurei-*

View File

@@ -11,21 +11,24 @@ import (
"strconv"
"sync"
"time"
_ "unsafe"
_ "unsafe" // for go:linkname
"hakurei.app/command"
"hakurei.app/container/check"
"hakurei.app/container/fhs"
"hakurei.app/hst"
"hakurei.app/internal"
"hakurei.app/internal/dbus"
"hakurei.app/internal/env"
"hakurei.app/internal/info"
"hakurei.app/internal/outcome"
"hakurei.app/message"
"hakurei.app/system/dbus"
)
// optionalErrorUnwrap calls [errors.Unwrap] and returns the resulting value
// if it is not nil, or the original value if it is.
//
//go:linkname optionalErrorUnwrap hakurei.app/container.optionalErrorUnwrap
func optionalErrorUnwrap(_ error) error
func optionalErrorUnwrap(err error) error
func buildCommand(ctx context.Context, msg message.Msg, early *earlyHardeningErrs, out io.Writer) command.Command {
var (
@@ -88,7 +91,7 @@ func buildCommand(ctx context.Context, msg message.Msg, early *earlyHardeningErr
flagPrivateRuntime, flagPrivateTmpdir bool
flagWayland, flagX11, flagDBus, flagPulse bool
flagWayland, flagX11, flagDBus, flagPipeWire, flagPulse bool
)
c.NewCommand("run", "Configure and start a permissive container", func(args []string) error {
@@ -143,8 +146,8 @@ func buildCommand(ctx context.Context, msg message.Msg, early *earlyHardeningErr
if flagDBus {
et |= hst.EDBus
}
if flagPulse {
et |= hst.EPulse
if flagPipeWire || flagPulse {
et |= hst.EPipeWire
}
config := &hst.Config{
@@ -294,8 +297,10 @@ func buildCommand(ctx context.Context, msg message.Msg, early *earlyHardeningErr
"Enable direct connection to X11").
Flag(&flagDBus, "dbus", command.BoolFlag(false),
"Enable proxied connection to D-Bus").
Flag(&flagPipeWire, "pipewire", command.BoolFlag(false),
"Enable connection to PipeWire via SecurityContext").
Flag(&flagPulse, "pulse", command.BoolFlag(false),
"Enable direct connection to PulseAudio")
"Enable PulseAudio compatibility daemon")
}
{
@@ -350,7 +355,7 @@ func buildCommand(ctx context.Context, msg message.Msg, early *earlyHardeningErr
}).Flag(&flagShort, "short", command.BoolFlag(false), "Print instance id")
}
c.Command("version", "Display version information", func(args []string) error { fmt.Println(internal.Version()); return errSuccess })
c.Command("version", "Display version information", func(args []string) error { fmt.Println(info.Version()); return errSuccess })
c.Command("license", "Show full license text", func(args []string) error { fmt.Println(license); return errSuccess })
c.Command("template", "Produce a config template", func(args []string) error { encodeJSON(log.Fatal, os.Stdout, false, hst.Template()); return errSuccess })
c.Command("help", "Show this help message", func([]string) error { c.PrintHelp(); return errSuccess })

View File

@@ -36,7 +36,7 @@ Commands:
},
{
"run", []string{"run", "-h"}, `
Usage: hakurei run [-h | --help] [--dbus-config <value>] [--dbus-system <value>] [--mpris] [--dbus-log] [--id <value>] [-a <int>] [-g <value>] [-d <value>] [-u <value>] [--private-runtime] [--private-tmpdir] [--wayland] [-X] [--dbus] [--pulse] COMMAND [OPTIONS]
Usage: hakurei run [-h | --help] [--dbus-config <value>] [--dbus-system <value>] [--mpris] [--dbus-log] [--id <value>] [-a <int>] [-g <value>] [-d <value>] [-u <value>] [--private-runtime] [--private-tmpdir] [--wayland] [-X] [--dbus] [--pipewire] [--pulse] COMMAND [OPTIONS]
Flags:
-X Enable direct connection to X11
@@ -58,12 +58,14 @@ Flags:
Reverse-DNS style Application identifier, leave empty to inherit instance identifier
-mpris
Allow owning MPRIS D-Bus path, has no effect if custom config is available
-pipewire
Enable connection to PipeWire via SecurityContext
-private-runtime
Do not share XDG_RUNTIME_DIR between containers under the same identity
-private-tmpdir
Do not share TMPDIR between containers under the same identity
-pulse
Enable direct connection to PulseAudio
Enable PulseAudio compatibility daemon
-u string
Passwd user name within sandbox (default "chronos")
-wayland

View File

@@ -1,18 +1,13 @@
package main_test
package main
import (
"io"
"reflect"
"strings"
"testing"
_ "unsafe"
"hakurei.app/container/stub"
)
//go:linkname decodeJSON hakurei.app/cmd/hakurei.decodeJSON
func decodeJSON(fatal func(v ...any), op string, r io.Reader, v any)
func TestDecodeJSON(t *testing.T) {
t.Parallel()
@@ -62,9 +57,6 @@ func TestDecodeJSON(t *testing.T) {
}
}
//go:linkname encodeJSON hakurei.app/cmd/hakurei.encodeJSON
func encodeJSON(fatal func(v ...any), output io.Writer, short bool, v any)
func TestEncodeJSON(t *testing.T) {
t.Parallel()
@@ -74,7 +66,7 @@ func TestEncodeJSON(t *testing.T) {
want string
}{
{"marshaler", errorJSONMarshaler{},
`cannot encode json for main_test.errorJSONMarshaler: unique error 3735928559 injected by the test suite`},
`cannot encode json for main.errorJSONMarshaler: unique error 3735928559 injected by the test suite`},
{"default", func() {},
`cannot write json: json: unsupported type: func()`},
}

View File

@@ -12,8 +12,6 @@ import (
"time"
"hakurei.app/hst"
"hakurei.app/internal"
"hakurei.app/internal/env"
"hakurei.app/internal/outcome"
"hakurei.app/internal/store"
"hakurei.app/message"
@@ -23,21 +21,19 @@ import (
func printShowSystem(output io.Writer, short, flagJSON bool) {
t := newPrinter(output)
defer t.MustFlush()
info := &hst.Info{Version: internal.Version(), User: new(outcome.Hsu).MustID(nil)}
env.CopyPaths().Copy(&info.Paths, info.User)
hi := outcome.Info()
if flagJSON {
encodeJSON(log.Fatal, output, short, info)
encodeJSON(log.Fatal, output, short, hi)
return
}
t.Printf("Version:\t%s\n", info.Version)
t.Printf("User:\t%d\n", info.User)
t.Printf("TempDir:\t%s\n", info.TempDir)
t.Printf("SharePath:\t%s\n", info.SharePath)
t.Printf("RuntimePath:\t%s\n", info.RuntimePath)
t.Printf("RunDirPath:\t%s\n", info.RunDirPath)
t.Printf("Version:\t%s (libwayland %s)\n", hi.Version, hi.WaylandVersion)
t.Printf("User:\t%d\n", hi.User)
t.Printf("TempDir:\t%s\n", hi.TempDir)
t.Printf("SharePath:\t%s\n", hi.SharePath)
t.Printf("RuntimePath:\t%s\n", hi.RuntimePath)
t.Printf("RunDirPath:\t%s\n", hi.RunDirPath)
}
// printShowInstance writes a representation of [hst.State] or [hst.Config] to output.
@@ -90,12 +86,6 @@ func printShowInstance(
t.Printf(" Groups:\t%s\n", strings.Join(config.Groups, ", "))
}
if config.Container != nil {
if config.Container.Home != nil {
t.Printf(" Home:\t%s\n", config.Container.Home)
}
if config.Container.Hostname != "" {
t.Printf(" Hostname:\t%s\n", config.Container.Hostname)
}
flags := config.Container.Flags.String()
// this is included in the upper hst.Config struct but is relevant here
@@ -110,6 +100,12 @@ func printShowInstance(
}
t.Printf(" Flags:\t%s\n", flags)
if config.Container.Home != nil {
t.Printf(" Home:\t%s\n", config.Container.Home)
}
if config.Container.Hostname != "" {
t.Printf(" Hostname:\t%s\n", config.Container.Hostname)
}
if config.Container.Path != nil {
t.Printf(" Path:\t%s\n", config.Container.Path)
}

View File

@@ -32,7 +32,7 @@ var (
PID: 0xbeef,
ShimPID: 0xcafe,
Config: &hst.Config{
Enablements: hst.NewEnablements(hst.EWayland | hst.EPulse),
Enablements: hst.NewEnablements(hst.EWayland | hst.EPipeWire),
Identity: 1,
Container: &hst.ContainerConfig{
Shell: check.MustAbs("/bin/sh"),
@@ -62,11 +62,11 @@ func TestPrintShowInstance(t *testing.T) {
{"nil", nil, nil, false, false, "Error: invalid configuration!\n\n", false},
{"config", nil, hst.Template(), false, false, `App
Identity: 9 (org.chromium.Chromium)
Enablements: wayland, dbus, pulseaudio
Enablements: wayland, dbus, pipewire
Groups: video, dialout, plugdev
Flags: multiarch, compat, devel, userns, net, abstract, tty, mapuid, device, runtime, tmpdir
Home: /data/data/org.chromium.Chromium
Hostname: localhost
Flags: multiarch, compat, devel, userns, net, abstract, tty, mapuid, device, runtime, tmpdir
Path: /run/current-system/sw/bin/chromium
Arguments: chromium --ignore-gpu-blocklist --disable-smooth-scrolling --enable-features=UseOzonePlatform --ozone-platform=wayland
@@ -159,11 +159,11 @@ Session bus
App
Identity: 9 (org.chromium.Chromium)
Enablements: wayland, dbus, pulseaudio
Enablements: wayland, dbus, pipewire
Groups: video, dialout, plugdev
Flags: multiarch, compat, devel, userns, net, abstract, tty, mapuid, device, runtime, tmpdir
Home: /data/data/org.chromium.Chromium
Hostname: localhost
Flags: multiarch, compat, devel, userns, net, abstract, tty, mapuid, device, runtime, tmpdir
Path: /run/current-system/sw/bin/chromium
Arguments: chromium --ignore-gpu-blocklist --disable-smooth-scrolling --enable-features=UseOzonePlatform --ozone-platform=wayland
@@ -215,7 +215,7 @@ App
"enablements": {
"wayland": true,
"dbus": true,
"pulse": true
"pipewire": true
},
"session_bus": {
"see": null,
@@ -366,7 +366,7 @@ App
"enablements": {
"wayland": true,
"dbus": true,
"pulse": true
"pipewire": true
},
"session_bus": {
"see": null,
@@ -564,7 +564,7 @@ func TestPrintPs(t *testing.T) {
"enablements": {
"wayland": true,
"dbus": true,
"pulse": true
"pipewire": true
},
"session_bus": {
"see": null,
@@ -715,7 +715,7 @@ func TestPrintPs(t *testing.T) {
"shim_pid": 51966,
"enablements": {
"wayland": true,
"pulse": true
"pipewire": true
},
"identity": 1,
"groups": null,

View File

@@ -45,7 +45,7 @@
allow_wayland ? true,
allow_x11 ? false,
allow_dbus ? true,
allow_pulse ? true,
allow_audio ? true,
gpu ? allow_wayland || allow_x11,
}:
@@ -175,7 +175,7 @@ let
wayland = allow_wayland;
x11 = allow_x11;
dbus = allow_dbus;
pulse = allow_pulse;
pipewire = allow_audio;
};
mesa = if gpu then mesaWrappers else null;

View File

@@ -10,11 +10,11 @@ import (
"os/exec"
"hakurei.app/hst"
"hakurei.app/internal"
"hakurei.app/internal/info"
"hakurei.app/message"
)
var hakureiPathVal = internal.MustHakureiPath().String()
var hakureiPathVal = info.MustHakureiPath().String()
func mustRunApp(ctx context.Context, msg message.Msg, config *hst.Config, beforeFail func()) {
var (

View File

@@ -1,5 +1,5 @@
{
nixosTest,
testers,
callPackage,
system,
@@ -8,7 +8,7 @@
let
buildPackage = self.buildPackage.${system};
in
nixosTest {
testers.nixosTest {
name = "hpkg";
nodes.machine = {
environment.etc = {

View File

@@ -90,13 +90,13 @@ wait_for_window("hakurei@machine-foot")
machine.send_chars("clear; wayland-info && touch /tmp/success-client\n")
machine.wait_for_file("/tmp/hakurei.0/tmpdir/2/success-client")
collect_state_ui("app_wayland")
check_state("foot", {"wayland": True, "dbus": True, "pulse": True})
check_state("foot", {"wayland": True, "dbus": True, "pipewire": True})
# Verify acl on XDG_RUNTIME_DIR:
print(machine.succeed("getfacl --absolute-names --omit-header --numeric /run/user/1000 | grep 10002"))
print(machine.succeed("getfacl --absolute-names --omit-header --numeric /tmp/hakurei.0/runtime | grep 10002"))
machine.send_chars("exit\n")
machine.wait_until_fails("pgrep foot")
# Verify acl cleanup on XDG_RUNTIME_DIR:
machine.wait_until_fails("getfacl --absolute-names --omit-header --numeric /run/user/1000 | grep 10002")
machine.wait_until_fails("getfacl --absolute-names --omit-header --numeric /tmp/hakurei.0/runtime | grep 10002")
# Exit Sway and verify process exit status 0:
swaymsg("exit", succeed=False)
@@ -107,4 +107,4 @@ print(machine.succeed("find /tmp/hakurei.0 "
+ "-path '/tmp/hakurei.0/runtime/*/*' -prune -o "
+ "-path '/tmp/hakurei.0/tmpdir/*/*' -prune -o "
+ "-print"))
print(machine.succeed("find /run/user/1000/hakurei"))
print(machine.fail("ls /run/user/1000/hakurei"))

76
cmd/irdump/main.go Normal file
View File

@@ -0,0 +1,76 @@
package main
import (
"errors"
"log"
"os"
"hakurei.app/command"
"hakurei.app/internal/pkg"
)
func main() {
log.SetFlags(0)
log.SetPrefix("irdump: ")
var (
flagOutput string
flagReal bool
flagHeader bool
flagForce bool
flagRaw bool
)
c := command.New(os.Stderr, log.Printf, "irdump", func(args []string) (err error) {
var input *os.File
if len(args) != 1 {
return errors.New("irdump requires 1 argument")
}
if input, err = os.Open(args[0]); err != nil {
return
}
defer input.Close()
var output *os.File
if flagOutput == "" {
output = os.Stdout
} else {
defer output.Close()
if output, err = os.Create(flagOutput); err != nil {
return
}
}
var out string
if out, err = pkg.Disassemble(input, flagReal, flagHeader, flagForce, flagRaw); err != nil {
return
}
if _, err = output.WriteString(out); err != nil {
return
}
return
}).Flag(
&flagOutput,
"o", command.StringFlag(""),
"Output file for asm (leave empty for stdout)",
).Flag(
&flagReal,
"r", command.BoolFlag(false),
"skip label generation; idents print real value",
).Flag(
&flagHeader,
"H", command.BoolFlag(false),
"display artifact headers",
).Flag(
&flagForce,
"f", command.BoolFlag(false),
"force display (skip validations)",
).Flag(
&flagRaw,
"R", command.BoolFlag(false),
"don't format output",
)
c.MustParse(os.Args[1:], func(err error) {
log.Fatal(err)
})
}

204
cmd/mbf/main.go Normal file
View File

@@ -0,0 +1,204 @@
package main
import (
"context"
"errors"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"runtime"
"syscall"
"unique"
"hakurei.app/command"
"hakurei.app/container"
"hakurei.app/container/check"
"hakurei.app/internal/pkg"
"hakurei.app/internal/rosa"
"hakurei.app/message"
)
func main() {
container.TryArgv0(nil)
log.SetFlags(0)
log.SetPrefix("mbf: ")
msg := message.New(log.Default())
if os.Geteuid() == 0 {
log.Fatal("this program must not run as root")
}
var cache *pkg.Cache
ctx, stop := signal.NotifyContext(context.Background(),
syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
defer stop()
defer func() {
if cache != nil {
cache.Close()
}
if r := recover(); r != nil {
fmt.Println(r)
log.Fatal("consider scrubbing the on-disk cache")
}
}()
var (
flagQuiet bool
flagCures int
flagBase string
flagTShift int
)
c := command.New(os.Stderr, log.Printf, "mbf", func([]string) (err error) {
msg.SwapVerbose(!flagQuiet)
var base *check.Absolute
if flagBase, err = filepath.Abs(flagBase); err != nil {
return
} else if base, err = check.NewAbs(flagBase); err != nil {
return
}
if cache, err = pkg.Open(ctx, msg, flagCures, base); err == nil {
if flagTShift < 0 {
cache.SetThreshold(0)
} else if flagTShift > 31 {
cache.SetThreshold(1 << 31)
} else {
cache.SetThreshold(1 << flagTShift)
}
}
return
}).Flag(
&flagQuiet,
"q", command.BoolFlag(false),
"Do not print cure messages",
).Flag(
&flagCures,
"cures", command.IntFlag(0),
"Maximum number of dependencies to cure at any given time",
).Flag(
&flagBase,
"d", command.StringFlag("cache"),
"Directory to store cured artifacts",
).Flag(
&flagTShift,
"tshift", command.IntFlag(-1),
"Dependency graph size exponent, to the power of 2",
)
{
var flagShifts int
c.NewCommand(
"scrub", "Examine the on-disk cache for errors",
func(args []string) error {
if len(args) > 0 {
return errors.New("scrub expects no arguments")
}
if flagShifts < 0 || flagShifts > 31 {
flagShifts = 12
}
return cache.Scrub(runtime.NumCPU() << flagShifts)
},
).Flag(
&flagShifts,
"shift", command.IntFlag(12),
"Scrub parallelism size exponent, to the power of 2",
)
}
c.NewCommand(
"stage3",
"Check for toolchain 3-stage non-determinism",
func(args []string) (err error) {
_, _, _, stage1 := (rosa.Std - 2).NewLLVM()
_, _, _, stage2 := (rosa.Std - 1).NewLLVM()
_, _, _, stage3 := rosa.Std.NewLLVM()
var (
pathname *check.Absolute
checksum [2]unique.Handle[pkg.Checksum]
)
if pathname, _, err = cache.Cure(stage1); err != nil {
return err
}
log.Println("stage1:", pathname)
if pathname, checksum[0], err = cache.Cure(stage2); err != nil {
return err
}
log.Println("stage2:", pathname)
if pathname, checksum[1], err = cache.Cure(stage3); err != nil {
return err
}
log.Println("stage3:", pathname)
if checksum[0] != checksum[1] {
err = &pkg.ChecksumMismatchError{
Got: checksum[0].Value(),
Want: checksum[1].Value(),
}
} else {
log.Println(
"stage2 is identical to stage3",
"("+pkg.Encode(checksum[0].Value())+")",
)
}
return
},
)
{
var (
flagDump string
)
c.NewCommand(
"cure",
"Cure the named artifact and show its path",
func(args []string) error {
if len(args) != 1 {
return errors.New("cure requires 1 argument")
}
if p, ok := rosa.ResolveName(args[0]); !ok {
return fmt.Errorf("unsupported artifact %q", args[0])
} else if flagDump == "" {
pathname, _, err := cache.Cure(rosa.Std.Load(p))
if err == nil {
log.Println(pathname)
}
return err
} else {
f, err := os.OpenFile(
flagDump,
os.O_WRONLY|os.O_CREATE|os.O_EXCL,
0644,
)
if err != nil {
return err
}
if err = cache.EncodeAll(f, rosa.Std.Load(p)); err != nil {
_ = f.Close()
return err
}
return f.Close()
}
},
).
Flag(
&flagDump,
"dump", command.StringFlag(""),
"Write IR to specified pathname and terminate",
)
}
c.MustParse(os.Args[1:], func(err error) {
if cache != nil {
cache.Close()
}
log.Fatal(err)
})
}

View File

@@ -0,0 +1,282 @@
#ifndef _GNU_SOURCE
#define _GNU_SOURCE /* O_DIRECT */
#endif
#include <dirent.h>
#include <errno.h>
#include <unistd.h>
/* TODO(ophestra): remove after 05ce67fea99ca09cd4b6625cff7aec9cc222dd5a reaches a release */
#include <sys/syscall.h>
#include "fuse-operations.h"
/* MUST_TRANSLATE_PATHNAME translates a userspace pathname to a relative pathname;
* the resulting address points to a constant string or part of pathname, it is never heap allocated. */
#define MUST_TRANSLATE_PATHNAME(pathname) \
do { \
if (pathname == NULL) \
return -EINVAL; \
while (*pathname == '/') \
pathname++; \
if (*pathname == '\0') \
pathname = "."; \
} while (0)
/* GET_CONTEXT_PRIV obtains fuse context and private data for the calling thread. */
#define GET_CONTEXT_PRIV(ctx, priv) \
do { \
ctx = fuse_get_context(); \
priv = ctx->private_data; \
} while (0)
/* impl_getattr modifies a struct stat from the kernel to present to userspace;
* impl_getattr returns a negative errno style error code. */
static int impl_getattr(struct fuse_context *ctx, struct stat *statbuf) {
/* allowlist of permitted types */
if (!S_ISDIR(statbuf->st_mode) && !S_ISREG(statbuf->st_mode) && !S_ISLNK(statbuf->st_mode)) {
return -ENOTRECOVERABLE; /* returning an errno causes all operations on the file to return EIO */
}
#define OVERRIDE_PERM(v) (statbuf->st_mode & ~0777) | (v & 0777)
if (S_ISDIR(statbuf->st_mode))
statbuf->st_mode = OVERRIDE_PERM(SHAREFS_PERM_DIR);
else if (S_ISREG(statbuf->st_mode))
statbuf->st_mode = OVERRIDE_PERM(SHAREFS_PERM_REG);
else
statbuf->st_mode = 0; /* should always be symlink in this case */
statbuf->st_uid = ctx->uid;
statbuf->st_gid = SHAREFS_MEDIA_RW_ID;
statbuf->st_ctim = statbuf->st_mtim;
statbuf->st_nlink = 1;
return 0;
}
/* fuse_operations implementation */
int sharefs_getattr(const char *pathname, struct stat *statbuf, struct fuse_file_info *fi) {
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
(void)fi;
if (fstatat(priv->dirfd, pathname, statbuf, AT_SYMLINK_NOFOLLOW) == -1)
return -errno;
return impl_getattr(ctx, statbuf);
}
int sharefs_readdir(const char *pathname, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi, enum fuse_readdir_flags flags) {
int fd;
DIR *dp;
struct stat st;
int ret = 0;
struct dirent *de;
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
(void)offset;
(void)fi;
if ((fd = openat(priv->dirfd, pathname, O_RDONLY | O_DIRECTORY | O_CLOEXEC)) == -1)
return -errno;
if ((dp = fdopendir(fd)) == NULL) {
close(fd);
return -errno;
}
errno = 0; /* for the next readdir call */
while ((de = readdir(dp)) != NULL) {
if (flags & FUSE_READDIR_PLUS) {
if (fstatat(dirfd(dp), de->d_name, &st, AT_SYMLINK_NOFOLLOW) == -1) {
ret = -errno;
break;
}
if ((ret = impl_getattr(ctx, &st)) < 0)
break;
errno = 0;
ret = filler(buf, de->d_name, &st, 0, FUSE_FILL_DIR_PLUS);
} else
ret = filler(buf, de->d_name, NULL, 0, 0);
if (ret != 0) {
ret = errno != 0 ? -errno : -EIO; /* filler */
break;
}
errno = 0; /* for the next readdir call */
}
if (ret == 0 && errno != 0)
ret = -errno; /* readdir */
closedir(dp);
return ret;
}
int sharefs_mkdir(const char *pathname, mode_t mode) {
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
(void)mode;
if (mkdirat(priv->dirfd, pathname, SHAREFS_PERM_DIR) == -1)
return -errno;
return 0;
}
int sharefs_unlink(const char *pathname) {
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
if (unlinkat(priv->dirfd, pathname, 0) == -1)
return -errno;
return 0;
}
int sharefs_rmdir(const char *pathname) {
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
if (unlinkat(priv->dirfd, pathname, AT_REMOVEDIR) == -1)
return -errno;
return 0;
}
int sharefs_rename(const char *oldpath, const char *newpath, unsigned int flags) {
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(oldpath);
MUST_TRANSLATE_PATHNAME(newpath);
/* TODO(ophestra): replace with wrapper after 05ce67fea99ca09cd4b6625cff7aec9cc222dd5a reaches a release */
if (syscall(__NR_renameat2, priv->dirfd, oldpath, priv->dirfd, newpath, flags) == -1)
return -errno;
return 0;
}
int sharefs_truncate(const char *pathname, off_t length, struct fuse_file_info *fi) {
int fd;
int ret;
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
(void)fi;
if ((fd = openat(priv->dirfd, pathname, O_WRONLY | O_CLOEXEC)) == -1)
return -errno;
if ((ret = ftruncate(fd, length)) == -1)
ret = -errno;
close(fd);
return ret;
}
int sharefs_utimens(const char *pathname, const struct timespec times[2], struct fuse_file_info *fi) {
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
(void)fi;
if (utimensat(priv->dirfd, pathname, times, AT_SYMLINK_NOFOLLOW) == -1)
return -errno;
return 0;
}
int sharefs_create(const char *pathname, mode_t mode, struct fuse_file_info *fi) {
int fd;
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
(void)mode;
if ((fd = openat(priv->dirfd, pathname, fi->flags & ~SHAREFS_FORBIDDEN_FLAGS, SHAREFS_PERM_REG)) == -1)
return -errno;
fi->fh = fd;
return 0;
}
int sharefs_open(const char *pathname, struct fuse_file_info *fi) {
int fd;
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
if ((fd = openat(priv->dirfd, pathname, fi->flags & ~SHAREFS_FORBIDDEN_FLAGS)) == -1)
return -errno;
fi->fh = fd;
return 0;
}
int sharefs_read(const char *pathname, char *buf, size_t count, off_t offset, struct fuse_file_info *fi) {
int ret;
(void)pathname;
if ((ret = pread(fi->fh, buf, count, offset)) == -1)
return -errno;
return ret;
}
int sharefs_write(const char *pathname, const char *buf, size_t count, off_t offset, struct fuse_file_info *fi) {
int ret;
(void)pathname;
if ((ret = pwrite(fi->fh, buf, count, offset)) == -1)
return -errno;
return ret;
}
int sharefs_statfs(const char *pathname, struct statvfs *statbuf) {
int fd;
int ret;
struct fuse_context *ctx;
struct sharefs_private *priv;
GET_CONTEXT_PRIV(ctx, priv);
MUST_TRANSLATE_PATHNAME(pathname);
if ((fd = openat(priv->dirfd, pathname, O_RDONLY | O_CLOEXEC)) == -1)
return -errno;
if ((ret = fstatvfs(fd, statbuf)) == -1)
ret = -errno;
close(fd);
return ret;
}
int sharefs_release(const char *pathname, struct fuse_file_info *fi) {
(void)pathname;
return close(fi->fh);
}
int sharefs_fsync(const char *pathname, int datasync, struct fuse_file_info *fi) {
(void)pathname;
if (datasync ? fdatasync(fi->fh) : fsync(fi->fh) == -1)
return -errno;
return 0;
}

View File

@@ -0,0 +1,34 @@
#define FUSE_USE_VERSION FUSE_MAKE_VERSION(3, 12)
#include <fuse.h>
#include <fuse_lowlevel.h> /* for fuse_cmdline_help */
#if (FUSE_VERSION < FUSE_MAKE_VERSION(3, 12))
#error This package requires libfuse >= v3.12
#endif
#define SHAREFS_MEDIA_RW_ID (1 << 10) - 1 /* owning gid presented to userspace */
#define SHAREFS_PERM_DIR 0700 /* permission bits for directories presented to userspace */
#define SHAREFS_PERM_REG 0600 /* permission bits for regular files presented to userspace */
#define SHAREFS_FORBIDDEN_FLAGS O_DIRECT /* these open flags are cleared unconditionally */
/* sharefs_private is populated by sharefs_init and contains process-wide context */
struct sharefs_private {
int dirfd; /* source dirfd opened during sharefs_init */
uintptr_t setup; /* cgo handle of opaque setup state */
};
int sharefs_getattr(const char *pathname, struct stat *statbuf, struct fuse_file_info *fi);
int sharefs_readdir(const char *pathname, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi, enum fuse_readdir_flags flags);
int sharefs_mkdir(const char *pathname, mode_t mode);
int sharefs_unlink(const char *pathname);
int sharefs_rmdir(const char *pathname);
int sharefs_rename(const char *oldpath, const char *newpath, unsigned int flags);
int sharefs_truncate(const char *pathname, off_t length, struct fuse_file_info *fi);
int sharefs_utimens(const char *pathname, const struct timespec times[2], struct fuse_file_info *fi);
int sharefs_create(const char *pathname, mode_t mode, struct fuse_file_info *fi);
int sharefs_open(const char *pathname, struct fuse_file_info *fi);
int sharefs_read(const char *pathname, char *buf, size_t count, off_t offset, struct fuse_file_info *fi);
int sharefs_write(const char *pathname, const char *buf, size_t count, off_t offset, struct fuse_file_info *fi);
int sharefs_statfs(const char *pathname, struct statvfs *statbuf);
int sharefs_release(const char *pathname, struct fuse_file_info *fi);
int sharefs_fsync(const char *pathname, int datasync, struct fuse_file_info *fi);

556
cmd/sharefs/fuse.go Normal file
View File

@@ -0,0 +1,556 @@
package main
/*
#cgo pkg-config: --static fuse3
#include "fuse-operations.h"
#include <stdlib.h>
#include <string.h>
extern void *sharefs_init(struct fuse_conn_info *conn, struct fuse_config *cfg);
extern void sharefs_destroy(void *private_data);
typedef void (*closure)();
static inline struct fuse_opt _FUSE_OPT_END() { return (struct fuse_opt)FUSE_OPT_END; };
*/
import "C"
import (
"context"
"encoding/gob"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"os/signal"
"path"
"runtime"
"runtime/cgo"
"strconv"
"syscall"
"unsafe"
"hakurei.app/container"
"hakurei.app/container/check"
"hakurei.app/container/std"
"hakurei.app/hst"
"hakurei.app/internal/helper/proc"
"hakurei.app/internal/info"
"hakurei.app/message"
)
type (
// closure represents a C function pointer.
closure = C.closure
// fuseArgs represents the fuse_args structure.
fuseArgs = C.struct_fuse_args
// setupState holds state used for setup. Its cgo handle is included in
// sharefs_private and considered opaque to non-setup callbacks.
setupState struct {
// Whether sharefs_init failed.
initFailed bool
// Whether to create source directory as root.
mkdir bool
// Open file descriptor to fuse.
Fuse int
// Pathname to open for dirfd.
Source *check.Absolute
// New uid and gid to set by sharefs_init when starting as root.
Setuid, Setgid int
}
)
func init() { gob.Register(new(setupState)) }
// destroySetup invalidates the setup [cgo.Handle] in a sharefs_private structure.
func destroySetup(private_data unsafe.Pointer) (ok bool) {
if private_data == nil {
return false
}
priv := (*C.struct_sharefs_private)(private_data)
if h := cgo.Handle(priv.setup); h != 0 {
priv.setup = 0
h.Delete()
ok = true
}
return
}
//export sharefs_init
func sharefs_init(_ *C.struct_fuse_conn_info, cfg *C.struct_fuse_config) unsafe.Pointer {
ctx := C.fuse_get_context()
priv := (*C.struct_sharefs_private)(ctx.private_data)
setup := cgo.Handle(priv.setup).Value().(*setupState)
if os.Geteuid() == 0 {
log.Println("filesystem daemon must not run as root")
goto fail
}
cfg.use_ino = C.true
cfg.direct_io = C.false
// getattr is context-dependent
cfg.attr_timeout = 0
cfg.entry_timeout = 0
cfg.negative_timeout = 0
// all future filesystem operations happen through this dirfd
if fd, err := syscall.Open(setup.Source.String(), syscall.O_DIRECTORY|syscall.O_RDONLY|syscall.O_CLOEXEC, 0); err != nil {
log.Printf("cannot open %q: %v", setup.Source, err)
goto fail
} else if err = syscall.Fchdir(fd); err != nil {
_ = syscall.Close(fd)
log.Printf("cannot enter %q: %s", setup.Source, err)
goto fail
} else {
priv.dirfd = C.int(fd)
}
return ctx.private_data
fail:
setup.initFailed = true
C.fuse_exit(ctx.fuse)
return nil
}
//export sharefs_destroy
func sharefs_destroy(private_data unsafe.Pointer) {
if private_data != nil {
destroySetup(private_data)
priv := (*C.struct_sharefs_private)(private_data)
if err := syscall.Close(int(priv.dirfd)); err != nil {
log.Printf("cannot close source directory: %v", err)
}
}
}
// showHelp prints the help message.
func showHelp(args *fuseArgs) {
executableName := sharefsName
if args.argc > 0 {
executableName = path.Base(C.GoString(*args.argv))
} else if name, err := os.Executable(); err == nil {
executableName = path.Base(name)
}
fmt.Printf("usage: %s [options] <mountpoint>\n\n", executableName)
fmt.Println("Filesystem options:")
fmt.Println(" -o source=/data/media source directory to be mounted")
fmt.Println(" -o setuid=1023 uid to run as when starting as root")
fmt.Println(" -o setgid=1023 gid to run as when starting as root")
fmt.Println("\nFUSE options:")
C.fuse_cmdline_help()
C.fuse_lib_help(args)
}
// parseOpts parses fuse options via fuse_opt_parse.
func parseOpts(args *fuseArgs, setup *setupState, log *log.Logger) (ok bool) {
var unsafeOpts struct {
// Pathname to writable source directory.
source *C.char
// Whether to create source directory as root.
mkdir C.int
// Decimal string representation of uid to set when running as root.
setuid *C.char
// Decimal string representation of gid to set when running as root.
setgid *C.char
// Decimal string representation of open file descriptor to read setupState from.
// This is an internal detail for containerisation and must not be specified directly.
setup *C.char
}
if C.fuse_opt_parse(args, unsafe.Pointer(&unsafeOpts), &[]C.struct_fuse_opt{
{templ: C.CString("source=%s"), offset: C.ulong(unsafe.Offsetof(unsafeOpts.source)), value: 0},
{templ: C.CString("mkdir"), offset: C.ulong(unsafe.Offsetof(unsafeOpts.mkdir)), value: 1},
{templ: C.CString("setuid=%s"), offset: C.ulong(unsafe.Offsetof(unsafeOpts.setuid)), value: 0},
{templ: C.CString("setgid=%s"), offset: C.ulong(unsafe.Offsetof(unsafeOpts.setgid)), value: 0},
{templ: C.CString("setup=%s"), offset: C.ulong(unsafe.Offsetof(unsafeOpts.setup)), value: 0},
C._FUSE_OPT_END(),
}[0], nil) == -1 {
return false
}
if unsafeOpts.source != nil {
defer C.free(unsafe.Pointer(unsafeOpts.source))
}
if unsafeOpts.setuid != nil {
defer C.free(unsafe.Pointer(unsafeOpts.setuid))
}
if unsafeOpts.setgid != nil {
defer C.free(unsafe.Pointer(unsafeOpts.setgid))
}
if unsafeOpts.setup != nil {
defer C.free(unsafe.Pointer(unsafeOpts.setup))
if v, err := strconv.Atoi(C.GoString(unsafeOpts.setup)); err != nil || v < 3 {
log.Println("invalid value for option setup")
return false
} else {
r := os.NewFile(uintptr(v), "setup")
defer func() {
if err = r.Close(); err != nil {
log.Println(err)
}
}()
if err = gob.NewDecoder(r).Decode(setup); err != nil {
log.Println(err)
return false
}
}
if setup.Fuse < 3 {
log.Println("invalid file descriptor", setup.Fuse)
return false
}
return true
}
if unsafeOpts.source == nil {
showHelp(args)
return false
} else if a, err := check.NewAbs(C.GoString(unsafeOpts.source)); err != nil {
log.Println(err)
return false
} else {
setup.Source = a
}
setup.mkdir = unsafeOpts.mkdir != 0
if unsafeOpts.setuid == nil {
setup.Setuid = -1
} else if v, err := strconv.Atoi(C.GoString(unsafeOpts.setuid)); err != nil || v <= 0 {
log.Println("invalid value for option setuid")
return false
} else {
setup.Setuid = v
}
if unsafeOpts.setgid == nil {
setup.Setgid = -1
} else if v, err := strconv.Atoi(C.GoString(unsafeOpts.setgid)); err != nil || v <= 0 {
log.Println("invalid value for option setgid")
return false
} else {
setup.Setgid = v
}
return true
}
// copyArgs returns a heap allocated copy of an argument slice in fuse_args representation.
func copyArgs(s ...string) fuseArgs {
if len(s) == 0 {
return fuseArgs{argc: 0, argv: nil, allocated: 0}
}
args := unsafe.Slice((**C.char)(C.malloc(C.size_t(uintptr(len(s))*unsafe.Sizeof(s[0])))), len(s))
for i, arg := range s {
args[i] = C.CString(arg)
}
return fuseArgs{argc: C.int(len(s)), argv: &args[0], allocated: 1}
}
// freeArgs frees the contents of argument list.
func freeArgs(args *fuseArgs) { C.fuse_opt_free_args(args) }
// unsafeAddArgument adds an argument to fuseArgs via fuse_opt_add_arg.
// The last byte of arg must be 0.
func unsafeAddArgument(args *fuseArgs, arg string) {
C.fuse_opt_add_arg(args, (*C.char)(unsafe.Pointer(unsafe.StringData(arg))))
}
func _main(s ...string) (exitCode int) {
msg := message.New(log.Default())
container.TryArgv0(msg)
runtime.LockOSThread()
// don't mask creation mode, kernel already did that
syscall.Umask(0)
var pinner runtime.Pinner
defer pinner.Unpin()
args := copyArgs(s...)
defer freeArgs(&args)
// this causes the kernel to enforce access control based on
// struct stat populated by sharefs_getattr
unsafeAddArgument(&args, "-odefault_permissions\x00")
var priv C.struct_sharefs_private
pinner.Pin(&priv)
var setup setupState
priv.setup = C.uintptr_t(cgo.NewHandle(&setup))
defer destroySetup(unsafe.Pointer(&priv))
var opts C.struct_fuse_cmdline_opts
if C.fuse_parse_cmdline(&args, &opts) != 0 {
return 1
}
if opts.mountpoint != nil {
defer C.free(unsafe.Pointer(opts.mountpoint))
}
if opts.show_version != 0 {
fmt.Println("hakurei version", info.Version())
fmt.Println("FUSE library version", C.GoString(C.fuse_pkgversion()))
C.fuse_lowlevel_version()
return 0
}
if opts.show_help != 0 {
showHelp(&args)
return 0
} else if opts.mountpoint == nil {
log.Println("no mountpoint specified")
return 2
} else {
// hack to keep fuse_parse_cmdline happy in the container
mountpoint := C.GoString(opts.mountpoint)
pathnameArg := -1
for i, arg := range s {
if arg == mountpoint {
pathnameArg = i
break
}
}
if pathnameArg < 0 {
log.Println("mountpoint must be absolute")
return 2
}
s[pathnameArg] = container.Nonexistent
}
if !parseOpts(&args, &setup, msg.GetLogger()) {
return 1
}
asRoot := os.Geteuid() == 0
if asRoot {
if setup.Setuid <= 0 || setup.Setgid <= 0 {
log.Println("setuid and setgid must not be 0")
return 1
}
if setup.Fuse >= 3 {
log.Println("filesystem daemon must not run as root")
return 1
}
if setup.mkdir {
if err := os.MkdirAll(setup.Source.String(), 0700); err != nil {
if !errors.Is(err, os.ErrExist) {
log.Println(err)
return 1
}
// skip setup for existing source directory
} else if err = os.Chown(setup.Source.String(), setup.Setuid, setup.Setgid); err != nil {
log.Println(err)
return 1
}
}
} else if setup.Fuse < 3 && (setup.Setuid > 0 || setup.Setgid > 0) {
log.Println("setuid and setgid has no effect when not starting as root")
return 1
} else if setup.mkdir {
log.Println("mkdir has no effect when not starting as root")
return 1
}
op := C.struct_fuse_operations{
init: closure(C.sharefs_init),
destroy: closure(C.sharefs_destroy),
// implemented in fuse-helper.c
getattr: closure(C.sharefs_getattr),
readdir: closure(C.sharefs_readdir),
mkdir: closure(C.sharefs_mkdir),
unlink: closure(C.sharefs_unlink),
rmdir: closure(C.sharefs_rmdir),
rename: closure(C.sharefs_rename),
truncate: closure(C.sharefs_truncate),
utimens: closure(C.sharefs_utimens),
create: closure(C.sharefs_create),
open: closure(C.sharefs_open),
read: closure(C.sharefs_read),
write: closure(C.sharefs_write),
statfs: closure(C.sharefs_statfs),
release: closure(C.sharefs_release),
fsync: closure(C.sharefs_fsync),
}
fuse := C.fuse_new_fn(&args, &op, C.size_t(unsafe.Sizeof(op)), unsafe.Pointer(&priv))
if fuse == nil {
return 3
}
defer C.fuse_destroy(fuse)
se := C.fuse_get_session(fuse)
if setup.Fuse < 3 {
// unconfined, set up mount point and container
if C.fuse_mount(fuse, opts.mountpoint) != 0 {
return 4
}
// unmounted by initial process
defer func() {
if exitCode == 5 {
C.fuse_unmount(fuse)
}
}()
if asRoot {
if err := syscall.Setresgid(setup.Setgid, setup.Setgid, setup.Setgid); err != nil {
log.Printf("cannot set gid: %v", err)
return 5
}
if err := syscall.Setgroups(nil); err != nil {
log.Printf("cannot set supplementary groups: %v", err)
return 5
}
if err := syscall.Setresuid(setup.Setuid, setup.Setuid, setup.Setuid); err != nil {
log.Printf("cannot set uid: %v", err)
return 5
}
}
msg.SwapVerbose(opts.debug != 0)
ctx := context.Background()
if opts.foreground != 0 {
c, cancel := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
defer cancel()
ctx = c
}
z := container.New(ctx, msg)
z.AllowOrphan = opts.foreground == 0
z.Env = os.Environ()
// keep fuse_parse_cmdline happy in the container
z.Tmpfs(check.MustAbs(container.Nonexistent), 1<<10, 0755)
if a, err := check.NewAbs(container.MustExecutable(msg)); err != nil {
log.Println(err)
return 5
} else {
z.Path = a
}
z.Args = s
z.ForwardCancel = true
z.SeccompPresets |= std.PresetStrict
z.ParentPerm = 0700
z.Bind(setup.Source, setup.Source, std.BindWritable)
if !z.AllowOrphan {
z.WaitDelay = hst.WaitDelayMax
z.Stdin, z.Stdout, z.Stderr = os.Stdin, os.Stdout, os.Stderr
}
z.Bind(z.Path, z.Path, 0)
setup.Fuse = int(proc.ExtraFileSlice(&z.ExtraFiles, os.NewFile(uintptr(C.fuse_session_fd(se)), "fuse")))
var setupWriter io.WriteCloser
if fd, w, err := container.Setup(&z.ExtraFiles); err != nil {
log.Println(err)
return 5
} else {
z.Args = append(z.Args, "-osetup="+strconv.Itoa(fd))
setupWriter = w
}
if err := z.Start(); err != nil {
if m, ok := message.GetMessage(err); ok {
log.Println(m)
} else {
log.Println(err)
}
return 5
}
if err := z.Serve(); err != nil {
if m, ok := message.GetMessage(err); ok {
log.Println(m)
} else {
log.Println(err)
}
return 5
}
if err := gob.NewEncoder(setupWriter).Encode(&setup); err != nil {
log.Println(err)
return 5
} else if err = setupWriter.Close(); err != nil {
log.Println(err)
}
if !z.AllowOrphan {
if err := z.Wait(); err != nil {
var exitError *exec.ExitError
if !errors.As(err, &exitError) || exitError == nil {
log.Println(err)
return 5
}
switch code := exitError.ExitCode(); syscall.Signal(code & 0x7f) {
case syscall.SIGINT:
case syscall.SIGTERM:
default:
return code
}
}
}
return 0
} else { // confined
C.free(unsafe.Pointer(opts.mountpoint))
// must be heap allocated
opts.mountpoint = C.CString("/dev/fd/" + strconv.Itoa(setup.Fuse))
if err := os.Chdir("/"); err != nil {
log.Println(err)
}
}
if C.fuse_mount(fuse, opts.mountpoint) != 0 {
return 4
}
defer C.fuse_unmount(fuse)
if C.fuse_set_signal_handlers(se) != 0 {
return 6
}
defer C.fuse_remove_signal_handlers(se)
if opts.singlethread != 0 {
if C.fuse_loop(fuse) != 0 {
return 8
}
} else {
loopConfig := C.fuse_loop_cfg_create()
if loopConfig == nil {
return 7
}
defer C.fuse_loop_cfg_destroy(loopConfig)
C.fuse_loop_cfg_set_clone_fd(loopConfig, C.uint(opts.clone_fd))
C.fuse_loop_cfg_set_idle_threads(loopConfig, opts.max_idle_threads)
C.fuse_loop_cfg_set_max_threads(loopConfig, opts.max_threads)
if C.fuse_loop_mt(fuse, loopConfig) != 0 {
return 8
}
}
if setup.initFailed {
return 1
}
return 0
}

113
cmd/sharefs/fuse_test.go Normal file
View File

@@ -0,0 +1,113 @@
package main
import (
"bytes"
"log"
"reflect"
"testing"
"hakurei.app/container/check"
)
func TestParseOpts(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
args []string
want setupState
wantLog string
wantOk bool
}{
{"zero length", []string{}, setupState{}, "", false},
{"not absolute", []string{"sharefs",
"-o", "source=nonexistent",
"-o", "setuid=1023",
"-o", "setgid=1023",
}, setupState{}, "sharefs: path \"nonexistent\" is not absolute\n", false},
{"not specified", []string{"sharefs",
"-o", "setuid=1023",
"-o", "setgid=1023",
}, setupState{}, "", false},
{"invalid setuid", []string{"sharefs",
"-o", "source=/proc/nonexistent",
"-o", "setuid=ff",
"-o", "setgid=1023",
}, setupState{
Source: check.MustAbs("/proc/nonexistent"),
}, "sharefs: invalid value for option setuid\n", false},
{"invalid setgid", []string{"sharefs",
"-o", "source=/proc/nonexistent",
"-o", "setuid=1023",
"-o", "setgid=ff",
}, setupState{
Source: check.MustAbs("/proc/nonexistent"),
Setuid: 1023,
}, "sharefs: invalid value for option setgid\n", false},
{"simple", []string{"sharefs",
"-o", "source=/proc/nonexistent",
}, setupState{
Source: check.MustAbs("/proc/nonexistent"),
Setuid: -1,
Setgid: -1,
}, "", true},
{"root", []string{"sharefs",
"-o", "source=/proc/nonexistent",
"-o", "setuid=1023",
"-o", "setgid=1023",
}, setupState{
Source: check.MustAbs("/proc/nonexistent"),
Setuid: 1023,
Setgid: 1023,
}, "", true},
{"setuid", []string{"sharefs",
"-o", "source=/proc/nonexistent",
"-o", "setuid=1023",
}, setupState{
Source: check.MustAbs("/proc/nonexistent"),
Setuid: 1023,
Setgid: -1,
}, "", true},
{"setgid", []string{"sharefs",
"-o", "source=/proc/nonexistent",
"-o", "setgid=1023",
}, setupState{
Source: check.MustAbs("/proc/nonexistent"),
Setuid: -1,
Setgid: 1023,
}, "", true},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
var (
got setupState
buf bytes.Buffer
)
args := copyArgs(tc.args...)
defer freeArgs(&args)
unsafeAddArgument(&args, "-odefault_permissions\x00")
if ok := parseOpts(&args, &got, log.New(&buf, "sharefs: ", 0)); ok != tc.wantOk {
t.Errorf("parseOpts: ok = %v, want %v", ok, tc.wantOk)
}
if !reflect.DeepEqual(&got, &tc.want) {
t.Errorf("parseOpts: setup = %#v, want %#v", got, tc.want)
}
if buf.String() != tc.wantLog {
t.Errorf("parseOpts: log =\n%s\nwant\n%s", buf.String(), tc.wantLog)
}
})
}
}

31
cmd/sharefs/main.go Normal file
View File

@@ -0,0 +1,31 @@
package main
import (
"log"
"os"
"slices"
)
// sharefsName is the prefix used by log.std in the sharefs process.
const sharefsName = "sharefs"
// handleMountArgs returns an alternative, libfuse-compatible args slice for
// args passed by mount -t fuse.sharefs [options] sharefs <mountpoint>.
//
// In this case, args always has a length of 5 with index 0 being what comes
// after "fuse." in the filesystem type, 1 is the uninterpreted string passed
// to mount (sharefsName is used as the magic string to enable this hack),
// 2 is passed through to libfuse as mountpoint, and 3 is always "-o".
func handleMountArgs(args []string) []string {
if len(args) == 5 && args[1] == sharefsName && args[3] == "-o" {
return []string{sharefsName, args[2], "-o", args[4]}
}
return slices.Clone(args)
}
func main() {
log.SetFlags(0)
log.SetPrefix(sharefsName + ": ")
os.Exit(_main(handleMountArgs(os.Args)...))
}

29
cmd/sharefs/main_test.go Normal file
View File

@@ -0,0 +1,29 @@
package main
import (
"slices"
"testing"
)
func TestHandleMountArgs(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
args []string
want []string
}{
{"nil", nil, nil},
{"passthrough", []string{"sharefs", "-V"}, []string{"sharefs", "-V"}},
{"replace", []string{"/sbin/sharefs", "sharefs", "/sdcard", "-o", "rw"}, []string{"sharefs", "/sdcard", "-o", "rw"}},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := handleMountArgs(tc.args); !slices.Equal(got, tc.want) {
t.Errorf("handleMountArgs: %q, want %q", got, tc.want)
}
})
}
}

View File

@@ -0,0 +1,41 @@
{ pkgs, ... }:
{
users.users = {
alice = {
isNormalUser = true;
description = "Alice Foobar";
password = "foobar";
uid = 1000;
};
};
home-manager.users.alice.home.stateVersion = "24.11";
# Automatically login on tty1 as a normal user:
services.getty.autologinUser = "alice";
environment = {
# For benchmarking sharefs:
systemPackages = [ pkgs.fsmark ];
};
virtualisation = {
diskSize = 6 * 1024;
qemu.options = [
# Increase test performance:
"-smp 8"
];
};
environment.hakurei = rec {
enable = true;
stateDir = "/var/lib/hakurei";
sharefs.source = "${stateDir}/sdcard";
users.alice = 0;
extraHomeConfig = {
home.stateVersion = "23.05";
};
};
}

View File

@@ -0,0 +1,44 @@
{
testers,
system,
self,
}:
testers.nixosTest {
name = "sharefs";
nodes.machine =
{ options, pkgs, ... }:
let
fhs =
let
hakurei = options.environment.hakurei.package.default;
in
pkgs.buildFHSEnv {
pname = "hakurei-fhs";
inherit (hakurei) version;
targetPkgs = _: hakurei.targetPkgs;
extraOutputsToInstall = [ "dev" ];
profile = ''
export PKG_CONFIG_PATH="/usr/share/pkgconfig:$PKG_CONFIG_PATH"
'';
};
in
{
environment.systemPackages = [
# For go tests:
(pkgs.writeShellScriptBin "sharefs-workload-hakurei-tests" ''
cp -r "${self.packages.${system}.hakurei.src}" "/sdcard/hakurei" && cd "/sdcard/hakurei"
${fhs}/bin/hakurei-fhs -c 'CC="clang -O3 -Werror" go test ./...'
'')
];
imports = [
./configuration.nix
self.nixosModules.hakurei
self.inputs.home-manager.nixosModules.home-manager
];
};
testScript = builtins.readFile ./test.py;
}

60
cmd/sharefs/test/test.py Normal file
View File

@@ -0,0 +1,60 @@
start_all()
machine.wait_for_unit("multi-user.target")
# To check sharefs version:
print(machine.succeed("sharefs -V"))
# Make sure sharefs started:
machine.wait_for_unit("sdcard.mount")
machine.succeed("mkdir /mnt")
def check_bad_opts_output(opts, want, source="/etc", privileged=False):
output = machine.fail(("" if privileged else "sudo -u alice -i ") + f"sharefs -f -o source={source},{opts} /mnt 2>&1")
if output != want:
raise Exception(f"unexpected output: {output}")
# Malformed setuid/setgid representation:
check_bad_opts_output("setuid=ff", "sharefs: invalid value for option setuid\n")
check_bad_opts_output("setgid=ff", "sharefs: invalid value for option setgid\n")
# Bounds check for setuid/setgid:
check_bad_opts_output("setuid=0", "sharefs: invalid value for option setuid\n")
check_bad_opts_output("setgid=0", "sharefs: invalid value for option setgid\n")
check_bad_opts_output("setuid=-1", "sharefs: invalid value for option setuid\n")
check_bad_opts_output("setgid=-1", "sharefs: invalid value for option setgid\n")
# Non-root setuid/setgid:
check_bad_opts_output("setuid=1023", "sharefs: setuid and setgid has no effect when not starting as root\n")
check_bad_opts_output("setgid=1023", "sharefs: setuid and setgid has no effect when not starting as root\n")
check_bad_opts_output("setuid=1023,setgid=1023", "sharefs: setuid and setgid has no effect when not starting as root\n")
check_bad_opts_output("mkdir", "sharefs: mkdir has no effect when not starting as root\n")
# Starting as root without setuid/setgid:
check_bad_opts_output("allow_other", "sharefs: setuid and setgid must not be 0\n", privileged=True)
check_bad_opts_output("setuid=1023", "sharefs: setuid and setgid must not be 0\n", privileged=True)
check_bad_opts_output("setgid=1023", "sharefs: setuid and setgid must not be 0\n", privileged=True)
# Make sure nothing actually got mounted:
machine.fail("umount /mnt")
machine.succeed("rmdir /mnt")
# Unprivileged mount/unmount:
machine.succeed("sudo -u alice -i mkdir /home/alice/{sdcard,persistent}")
machine.succeed("sudo -u alice -i sharefs -o source=/home/alice/persistent /home/alice/sdcard")
machine.succeed("sudo -u alice -i touch /home/alice/sdcard/check")
machine.succeed("sudo -u alice -i umount /home/alice/sdcard")
machine.succeed("sudo -u alice -i rm /home/alice/persistent/check")
machine.succeed("sudo -u alice -i rmdir /home/alice/{sdcard,persistent}")
# Benchmark sharefs:
machine.succeed("fs_mark -v -d /sdcard/fs_mark -l /tmp/fs_log.txt")
machine.copy_from_vm("/tmp/fs_log.txt", "")
# Check permissions:
machine.succeed("sudo -u sharefs touch /var/lib/hakurei/sdcard/fs_mark/.check")
machine.succeed("sudo -u sharefs rm /var/lib/hakurei/sdcard/fs_mark/.check")
machine.succeed("sudo -u alice rm -rf /sdcard/fs_mark")
machine.fail("ls /var/lib/hakurei/sdcard/fs_mark")
# Run hakurei tests on sharefs:
machine.succeed("sudo -u alice -i sharefs-workload-hakurei-tests")

View File

@@ -59,6 +59,7 @@ func (e *AutoEtcOp) apply(state *setupState, k syscallDispatcher) error {
return nil
}
func (e *AutoEtcOp) late(*setupState, syscallDispatcher) error { return nil }
func (e *AutoEtcOp) hostPath() *check.Absolute { return fhs.AbsEtc.Append(e.hostRel()) }
func (e *AutoEtcOp) hostRel() string { return ".host/" + e.Prefix }

View File

@@ -69,6 +69,7 @@ func (r *AutoRootOp) apply(state *setupState, k syscallDispatcher) error {
}
return nil
}
func (r *AutoRootOp) late(*setupState, syscallDispatcher) error { return nil }
func (r *AutoRootOp) Is(op Op) bool {
vr, ok := op.(*AutoRootOp)

View File

@@ -202,7 +202,7 @@ func TestIsAutoRootBindable(t *testing.T) {
t.Parallel()
var msg message.Msg
if tc.log {
msg = &kstub{nil, stub.New(t, func(s *stub.Stub[syscallDispatcher]) syscallDispatcher { panic("unreachable") }, stub.Expect{Calls: []stub.Call{
msg = &kstub{nil, nil, stub.New(t, func(s *stub.Stub[syscallDispatcher]) syscallDispatcher { panic("unreachable") }, stub.Expect{Calls: []stub.Call{
call("verbose", stub.ExpectArgs{[]any{"got unexpected root entry"}}, nil, nil),
}})}
}

View File

@@ -14,6 +14,7 @@ const (
CAP_SYS_ADMIN = 0x15
CAP_SETPCAP = 0x8
CAP_NET_ADMIN = 0xc
CAP_DAC_OVERRIDE = 0x1
)

View File

@@ -9,46 +9,60 @@ import (
"slices"
"strings"
"syscall"
"unique"
)
// AbsoluteError is returned by [NewAbs] and holds the invalid pathname.
type AbsoluteError struct{ Pathname string }
type AbsoluteError string
func (e *AbsoluteError) Error() string { return fmt.Sprintf("path %q is not absolute", e.Pathname) }
func (e *AbsoluteError) Is(target error) bool {
var ce *AbsoluteError
func (e AbsoluteError) Error() string {
return fmt.Sprintf("path %q is not absolute", string(e))
}
func (e AbsoluteError) Is(target error) bool {
var ce AbsoluteError
if !errors.As(target, &ce) {
return errors.Is(target, syscall.EINVAL)
}
return *e == *ce
return e == ce
}
// Absolute holds a pathname checked to be absolute.
type Absolute struct{ pathname string }
type Absolute struct{ pathname unique.Handle[string] }
// ok returns whether [Absolute] is not the zero value.
func (a *Absolute) ok() bool { return a != nil && *a != (Absolute{}) }
// unsafeAbs returns [check.Absolute] on any string value.
func unsafeAbs(pathname string) *Absolute { return &Absolute{pathname} }
func unsafeAbs(pathname string) *Absolute {
return &Absolute{unique.Make(pathname)}
}
// String returns the checked pathname.
func (a *Absolute) String() string {
if a.pathname == "" {
if !a.ok() {
panic("attempted use of zero Absolute")
}
return a.pathname.Value()
}
// Handle returns the underlying [unique.Handle].
func (a *Absolute) Handle() unique.Handle[string] {
return a.pathname
}
// Is efficiently compares the underlying pathname.
func (a *Absolute) Is(v *Absolute) bool {
if a == nil && v == nil {
return true
}
return a != nil && v != nil &&
a.pathname != "" && v.pathname != "" &&
a.pathname == v.pathname
return a.ok() && v.ok() && a.pathname == v.pathname
}
// NewAbs checks pathname and returns a new [Absolute] if pathname is absolute.
func NewAbs(pathname string) (*Absolute, error) {
if !path.IsAbs(pathname) {
return nil, &AbsoluteError{pathname}
return nil, AbsoluteError(pathname)
}
return unsafeAbs(pathname), nil
}
@@ -56,7 +70,7 @@ func NewAbs(pathname string) (*Absolute, error) {
// MustAbs calls [NewAbs] and panics on error.
func MustAbs(pathname string) *Absolute {
if a, err := NewAbs(pathname); err != nil {
panic(err.Error())
panic(err)
} else {
return a
}
@@ -70,35 +84,49 @@ func (a *Absolute) Append(elem ...string) *Absolute {
// Dir calls [path.Dir] with [Absolute] as its argument.
func (a *Absolute) Dir() *Absolute { return unsafeAbs(path.Dir(a.String())) }
func (a *Absolute) GobEncode() ([]byte, error) { return []byte(a.String()), nil }
// GobEncode returns the checked pathname.
func (a *Absolute) GobEncode() ([]byte, error) {
return []byte(a.String()), nil
}
// GobDecode stores data if it represents an absolute pathname.
func (a *Absolute) GobDecode(data []byte) error {
pathname := string(data)
if !path.IsAbs(pathname) {
return &AbsoluteError{pathname}
return AbsoluteError(pathname)
}
a.pathname = pathname
a.pathname = unique.Make(pathname)
return nil
}
func (a *Absolute) MarshalJSON() ([]byte, error) { return json.Marshal(a.String()) }
// MarshalJSON returns a JSON representation of the checked pathname.
func (a *Absolute) MarshalJSON() ([]byte, error) {
return json.Marshal(a.String())
}
// UnmarshalJSON stores data if it represents an absolute pathname.
func (a *Absolute) UnmarshalJSON(data []byte) error {
var pathname string
if err := json.Unmarshal(data, &pathname); err != nil {
return err
}
if !path.IsAbs(pathname) {
return &AbsoluteError{pathname}
return AbsoluteError(pathname)
}
a.pathname = pathname
a.pathname = unique.Make(pathname)
return nil
}
// SortAbs calls [slices.SortFunc] for a slice of [Absolute].
func SortAbs(x []*Absolute) {
slices.SortFunc(x, func(a, b *Absolute) int { return strings.Compare(a.String(), b.String()) })
slices.SortFunc(x, func(a, b *Absolute) int {
return strings.Compare(a.String(), b.String())
})
}
// CompactAbs calls [slices.CompactFunc] for a slice of [Absolute].
func CompactAbs(s []*Absolute) []*Absolute {
return slices.CompactFunc(s, func(a *Absolute, b *Absolute) bool { return a.String() == b.String() })
return slices.CompactFunc(s, func(a *Absolute, b *Absolute) bool {
return a.Is(b)
})
}

View File

@@ -14,8 +14,10 @@ import (
. "hakurei.app/container/check"
)
// unsafeAbs returns check.Absolute on any string value.
//
//go:linkname unsafeAbs hakurei.app/container/check.unsafeAbs
func unsafeAbs(_ string) *Absolute
func unsafeAbs(pathname string) *Absolute
func TestAbsoluteError(t *testing.T) {
t.Parallel()
@@ -29,8 +31,8 @@ func TestAbsoluteError(t *testing.T) {
}{
{"EINVAL", new(AbsoluteError), syscall.EINVAL, true},
{"not EINVAL", new(AbsoluteError), syscall.EBADE, false},
{"ne val", new(AbsoluteError), &AbsoluteError{Pathname: "etc"}, false},
{"equals", &AbsoluteError{Pathname: "etc"}, &AbsoluteError{Pathname: "etc"}, true},
{"ne val", new(AbsoluteError), AbsoluteError("etc"), false},
{"equals", AbsoluteError("etc"), AbsoluteError("etc"), true},
}
for _, tc := range testCases {
@@ -43,7 +45,7 @@ func TestAbsoluteError(t *testing.T) {
t.Parallel()
want := `path "etc" is not absolute`
if got := (&AbsoluteError{Pathname: "etc"}).Error(); got != want {
if got := (AbsoluteError("etc")).Error(); got != want {
t.Errorf("Error: %q, want %q", got, want)
}
})
@@ -60,8 +62,8 @@ func TestNewAbs(t *testing.T) {
wantErr error
}{
{"good", "/etc", MustAbs("/etc"), nil},
{"not absolute", "etc", nil, &AbsoluteError{Pathname: "etc"}},
{"zero", "", nil, &AbsoluteError{Pathname: ""}},
{"not absolute", "etc", nil, AbsoluteError("etc")},
{"zero", "", nil, AbsoluteError("")},
}
for _, tc := range testCases {
@@ -82,9 +84,9 @@ func TestNewAbs(t *testing.T) {
t.Parallel()
defer func() {
wantPanic := `path "etc" is not absolute`
wantPanic := AbsoluteError("etc")
if r := recover(); r != wantPanic {
if r := recover(); !reflect.DeepEqual(r, wantPanic) {
t.Errorf("MustAbs: panic = %v; want %v", r, wantPanic)
}
}()
@@ -173,7 +175,7 @@ func TestCodecAbsolute(t *testing.T) {
`"/etc"`, `{"val":"/etc","magic":3236757504}`},
{"not absolute", nil,
&AbsoluteError{Pathname: "etc"},
AbsoluteError("etc"),
"\t\x7f\x05\x01\x02\xff\x82\x00\x00\x00\a\xff\x80\x00\x03etc",
",\xff\x83\x03\x01\x01\x06sCheck\x01\xff\x84\x00\x01\x02\x01\bPathname\x01\xff\x80\x00\x01\x05Magic\x01\x06\x00\x00\x00\t\x7f\x05\x01\x02\xff\x82\x00\x00\x00\x0f\xff\x84\x01\x03etc\x01\xfb\x01\x81\xda\x00\x00\x00",

View File

@@ -35,6 +35,8 @@ type (
// Container represents a container environment being prepared or run.
// None of [Container] methods are safe for concurrent use.
Container struct {
// Whether the container init should stay alive after its parent terminates.
AllowOrphan bool
// Cgroup fd, nil to disable.
Cgroup *int
// ExtraFiles passed through to initial process in the container,
@@ -252,8 +254,7 @@ func (p *Container) Start() error {
}
p.cmd.Dir = fhs.Root
p.cmd.SysProcAttr = &SysProcAttr{
Setsid: !p.RetainSession,
Pdeathsig: SIGKILL,
Setsid: !p.RetainSession,
Cloneflags: CLONE_NEWUSER | CLONE_NEWPID | CLONE_NEWNS |
CLONE_NEWIPC | CLONE_NEWUTS | CLONE_NEWCGROUP,
@@ -262,12 +263,17 @@ func (p *Container) Start() error {
CAP_SYS_ADMIN,
// drop capabilities
CAP_SETPCAP,
// bring up loopback interface
CAP_NET_ADMIN,
// overlay access to upperdir and workdir
CAP_DAC_OVERRIDE,
},
UseCgroupFD: p.Cgroup != nil,
}
if !p.AllowOrphan {
p.cmd.SysProcAttr.Pdeathsig = SIGKILL
}
if p.cmd.SysProcAttr.UseCgroupFD {
p.cmd.SysProcAttr.CgroupFD = *p.Cgroup
}

View File

@@ -21,6 +21,7 @@ import (
"hakurei.app/command"
"hakurei.app/container"
"hakurei.app/container/check"
"hakurei.app/container/fhs"
"hakurei.app/container/seccomp"
"hakurei.app/container/std"
"hakurei.app/container/vfs"
@@ -29,6 +30,45 @@ import (
"hakurei.app/message"
)
// Note: this package requires cgo, which is unavailable in the Go playground.
func Example() {
// Must be called early if the current process starts containers.
container.TryArgv0(nil)
// Configure the container.
z := container.New(context.Background(), nil)
z.Hostname = "hakurei-example"
z.Proc(fhs.AbsProc).Dev(fhs.AbsDev, true)
z.Stdin, z.Stdout, z.Stderr = os.Stdin, os.Stdout, os.Stderr
// Bind / for demonstration.
z.Bind(fhs.AbsRoot, fhs.AbsRoot, 0)
if name, err := exec.LookPath("hostname"); err != nil {
panic(err)
} else {
z.Path = check.MustAbs(name)
}
// This completes the first stage of container setup and starts the container init process.
// The new process blocks until the Serve method is called.
if err := z.Start(); err != nil {
panic(err)
}
// This serves the setup payload to the container init process,
// starting the second stage of container setup.
if err := z.Serve(); err != nil {
panic(err)
}
// Must be called if the Start method succeeds.
if err := z.Wait(); err != nil {
panic(err)
}
// Output: hakurei-example
}
func TestStartError(t *testing.T) {
t.Parallel()
@@ -234,13 +274,13 @@ var containerTestCases = []struct {
Dev(check.MustAbs("/dev"), true),
),
earlyMnt(
ent("/", "/dev", "ro,nosuid,nodev,relatime", "tmpfs", "devtmpfs", ignore),
ent("/null", "/dev/null", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/zero", "/dev/zero", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/full", "/dev/full", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/random", "/dev/random", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/urandom", "/dev/urandom", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/tty", "/dev/tty", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/", "/dev", "ro,nosuid,nodev,relatime", "tmpfs", ignore, ignore),
ent("/null", "/dev/null", ignore, "devtmpfs", ignore, ignore),
ent("/zero", "/dev/zero", ignore, "devtmpfs", ignore, ignore),
ent("/full", "/dev/full", ignore, "devtmpfs", ignore, ignore),
ent("/random", "/dev/random", ignore, "devtmpfs", ignore, ignore),
ent("/urandom", "/dev/urandom", ignore, "devtmpfs", ignore, ignore),
ent("/tty", "/dev/tty", ignore, "devtmpfs", ignore, ignore),
ent("/", "/dev/pts", "rw,nosuid,noexec,relatime", "devpts", "devpts", "rw,mode=620,ptmxmode=666"),
ent("/", "/dev/mqueue", "rw,nosuid,nodev,noexec,relatime", "mqueue", "mqueue", "rw"),
ent("/", "/dev/shm", "rw,nosuid,nodev,relatime", "tmpfs", "tmpfs", ignore),
@@ -252,13 +292,13 @@ var containerTestCases = []struct {
Dev(check.MustAbs("/dev"), false),
),
earlyMnt(
ent("/", "/dev", "ro,nosuid,nodev,relatime", "tmpfs", "devtmpfs", ignore),
ent("/null", "/dev/null", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/zero", "/dev/zero", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/full", "/dev/full", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/random", "/dev/random", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/urandom", "/dev/urandom", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/tty", "/dev/tty", "rw,nosuid", "devtmpfs", "devtmpfs", ignore),
ent("/", "/dev", "ro,nosuid,nodev,relatime", "tmpfs", ignore, ignore),
ent("/null", "/dev/null", ignore, "devtmpfs", ignore, ignore),
ent("/zero", "/dev/zero", ignore, "devtmpfs", ignore, ignore),
ent("/full", "/dev/full", ignore, "devtmpfs", ignore, ignore),
ent("/random", "/dev/random", ignore, "devtmpfs", ignore, ignore),
ent("/urandom", "/dev/urandom", ignore, "devtmpfs", ignore, ignore),
ent("/tty", "/dev/tty", ignore, "devtmpfs", ignore, ignore),
ent("/", "/dev/pts", "rw,nosuid,noexec,relatime", "devpts", "devpts", "rw,mode=620,ptmxmode=666"),
ent("/", "/dev/shm", "rw,nosuid,nodev,relatime", "tmpfs", "tmpfs", ignore),
),
@@ -650,11 +690,22 @@ func init() {
return fmt.Errorf("got more than %d entries", len(mnt))
}
// ugly hack but should be reliable and is less likely to false negative than comparing by parsed flags
cur.VfsOptstr = strings.TrimSuffix(cur.VfsOptstr, ",relatime")
cur.VfsOptstr = strings.TrimSuffix(cur.VfsOptstr, ",noatime")
mnt[i].VfsOptstr = strings.TrimSuffix(mnt[i].VfsOptstr, ",relatime")
mnt[i].VfsOptstr = strings.TrimSuffix(mnt[i].VfsOptstr, ",noatime")
// ugly hack but should be reliable and is less likely to
//false negative than comparing by parsed flags
for _, s := range []string{
"relatime",
"noatime",
} {
cur.VfsOptstr = strings.TrimSuffix(cur.VfsOptstr, ","+s)
mnt[i].VfsOptstr = strings.TrimSuffix(mnt[i].VfsOptstr, ","+s)
}
for _, s := range []string{
"seclabel",
"inode64",
} {
cur.FsOptstr = strings.Replace(cur.FsOptstr, ","+s, "", 1)
mnt[i].FsOptstr = strings.Replace(mnt[i].FsOptstr, ","+s, "", 1)
}
if !cur.EqualWithIgnore(mnt[i], "\x00") {
fail = true
@@ -722,12 +773,14 @@ func TestMain(m *testing.M) {
func helperNewContainerLibPaths(ctx context.Context, libPaths *[]*check.Absolute, args ...string) (c *container.Container) {
msg := message.New(nil)
msg.SwapVerbose(testing.Verbose())
executable := check.MustAbs(container.MustExecutable(msg))
c = container.NewCommand(ctx, msg, absHelperInnerPath, "helper", args...)
c.Env = append(c.Env, envDoCheck+"=1")
c.Bind(check.MustAbs(os.Args[0]), absHelperInnerPath, 0)
c.Bind(executable, absHelperInnerPath, 0)
// in case test has cgo enabled
if entries, err := ldd.Exec(ctx, msg, os.Args[0]); err != nil {
if entries, err := ldd.Resolve(ctx, msg, executable); err != nil {
log.Fatalf("ldd: %v", err)
} else {
*libPaths = ldd.Path(entries)

View File

@@ -61,6 +61,8 @@ type syscallDispatcher interface {
mountTmpfs(fsname, target string, flags uintptr, size int, perm os.FileMode) error
// ensureFile provides ensureFile.
ensureFile(name string, perm, pperm os.FileMode) error
// mustLoopback provides mustLoopback.
mustLoopback(msg message.Msg)
// seccompLoad provides [seccomp.Load].
seccompLoad(rules []std.NativeRule, flags seccomp.ExportFlag) error
@@ -164,6 +166,7 @@ func (k direct) mountTmpfs(fsname, target string, flags uintptr, size int, perm
func (direct) ensureFile(name string, perm, pperm os.FileMode) error {
return ensureFile(name, perm, pperm)
}
func (direct) mustLoopback(msg message.Msg) { mustLoopback(msg) }
func (direct) seccompLoad(rules []std.NativeRule, flags seccomp.ExportFlag) error {
return seccomp.Load(rules, flags)

View File

@@ -162,7 +162,8 @@ func checkSimple(t *testing.T, fname string, testCases []simpleTestCase) {
t.Parallel()
wait4signal := make(chan struct{})
k := &kstub{wait4signal, stub.New(t, func(s *stub.Stub[syscallDispatcher]) syscallDispatcher { return &kstub{wait4signal, s} }, tc.want)}
lockNotify := make(chan struct{})
k := &kstub{wait4signal, lockNotify, stub.New(t, func(s *stub.Stub[syscallDispatcher]) syscallDispatcher { return &kstub{wait4signal, lockNotify, s} }, tc.want)}
defer stub.HandleExit(t)
if err := tc.f(k); !reflect.DeepEqual(err, tc.wantErr) {
t.Errorf("%s: error = %v, want %v", fname, err, tc.wantErr)
@@ -200,8 +201,8 @@ func checkOpBehaviour(t *testing.T, testCases []opBehaviourTestCase) {
t.Helper()
t.Parallel()
k := &kstub{nil, stub.New(t,
func(s *stub.Stub[syscallDispatcher]) syscallDispatcher { return &kstub{nil, s} },
k := &kstub{nil, nil, stub.New(t,
func(s *stub.Stub[syscallDispatcher]) syscallDispatcher { return &kstub{nil, nil, s} },
stub.Expect{Calls: slices.Concat(tc.early, []stub.Call{{Name: stub.CallSeparator}}, tc.apply)},
)}
state := &setupState{Params: tc.params, Msg: k}
@@ -322,12 +323,19 @@ const (
type kstub struct {
wait4signal chan struct{}
lockNotify chan struct{}
*stub.Stub[syscallDispatcher]
}
func (k *kstub) new(f func(k syscallDispatcher)) { k.Helper(); k.New(f) }
func (k *kstub) lockOSThread() { k.Helper(); k.Expects("lockOSThread") }
func (k *kstub) lockOSThread() {
k.Helper()
expect := k.Expects("lockOSThread")
if k.lockNotify != nil && expect.Ret == magicWait4Signal {
<-k.lockNotify
}
}
func (k *kstub) setPtracer(pid uintptr) error {
k.Helper()
@@ -457,6 +465,8 @@ func (k *kstub) ensureFile(name string, perm, pperm os.FileMode) error {
stub.CheckArg(k.Stub, "pperm", pperm, 2))
}
func (*kstub) mustLoopback(message.Msg) { /* noop */ }
func (k *kstub) seccompLoad(rules []std.NativeRule, flags seccomp.ExportFlag) error {
k.Helper()
return k.Expects("seccompLoad").Error(
@@ -472,6 +482,10 @@ func (k *kstub) notify(c chan<- os.Signal, sig ...os.Signal) {
k.FailNow()
}
if k.lockNotify != nil && expect.Ret == magicWait4Signal {
defer close(k.lockNotify)
}
// export channel for external instrumentation
if chanf, ok := expect.Args[0].(func(c chan<- os.Signal)); ok && chanf != nil {
chanf(c)
@@ -759,7 +773,8 @@ func (k *kstub) checkMsg(msg message.Msg) {
}
func (k *kstub) GetLogger() *log.Logger { panic("unreachable") }
func (k *kstub) IsVerbose() bool { panic("unreachable") }
func (k *kstub) IsVerbose() bool { k.Helper(); return k.Expects("isVerbose").Ret.(bool) }
func (k *kstub) SwapVerbose(verbose bool) bool {
k.Helper()

View File

@@ -7,31 +7,36 @@ import (
"hakurei.app/container/check"
"hakurei.app/container/vfs"
"hakurei.app/message"
)
// messageFromError returns a printable error message for a supported concrete type.
func messageFromError(err error) (string, bool) {
if m, ok := messagePrefixP[MountError]("cannot ", err); ok {
return m, ok
func messageFromError(err error) (m string, ok bool) {
if m, ok = messagePrefixP[MountError]("cannot ", err); ok {
return
}
if m, ok := messagePrefixP[os.PathError]("cannot ", err); ok {
return m, ok
if m, ok = messagePrefixP[os.PathError]("cannot ", err); ok {
return
}
if m, ok := messagePrefixP[check.AbsoluteError]("", err); ok {
return m, ok
if m, ok = messagePrefix[check.AbsoluteError](zeroString, err); ok {
return
}
if m, ok := messagePrefix[OpRepeatError]("", err); ok {
return m, ok
if m, ok = messagePrefix[OpRepeatError](zeroString, err); ok {
return
}
if m, ok := messagePrefix[OpStateError]("", err); ok {
return m, ok
if m, ok = messagePrefix[OpStateError](zeroString, err); ok {
return
}
if m, ok := messagePrefixP[vfs.DecoderError]("cannot ", err); ok {
return m, ok
if m, ok = messagePrefixP[vfs.DecoderError]("cannot ", err); ok {
return
}
if m, ok := messagePrefix[TmpfsSizeError]("", err); ok {
return m, ok
if m, ok = messagePrefix[TmpfsSizeError](zeroString, err); ok {
return
}
if m, ok = message.GetMessage(err); ok {
return
}
return zeroString, false

View File

@@ -37,7 +37,7 @@ func TestMessageFromError(t *testing.T) {
Err: stub.UniqueError(0xdeadbeef),
}, "cannot mount /sysroot: unique error 3735928559 injected by the test suite", true},
{"absolute", &check.AbsoluteError{Pathname: "etc/mtab"},
{"absolute", check.AbsoluteError("etc/mtab"),
`path "etc/mtab" is not absolute`, true},
{"repeat", OpRepeatError("autoetc"),

View File

@@ -8,8 +8,10 @@ import (
/* constants in this file bypass abs check, be extremely careful when changing them! */
// unsafeAbs returns check.Absolute on any string value.
//
//go:linkname unsafeAbs hakurei.app/container/check.unsafeAbs
func unsafeAbs(_ string) *check.Absolute
func unsafeAbs(pathname string) *check.Absolute
var (
// AbsRoot is [Root] as [check.Absolute].
@@ -24,6 +26,8 @@ var (
// AbsRunUser is [RunUser] as [check.Absolute].
AbsRunUser = unsafeAbs(RunUser)
// AbsUsr is [Usr] as [check.Absolute].
AbsUsr = unsafeAbs(Usr)
// AbsUsrBin is [UsrBin] as [check.Absolute].
AbsUsrBin = unsafeAbs(UsrBin)
@@ -34,6 +38,8 @@ var (
// AbsDev is [Dev] as [check.Absolute].
AbsDev = unsafeAbs(Dev)
// AbsDevShm is [DevShm] as [check.Absolute].
AbsDevShm = unsafeAbs(DevShm)
// AbsProc is [Proc] as [check.Absolute].
AbsProc = unsafeAbs(Proc)
// AbsSys is [Sys] as [check.Absolute].

View File

@@ -29,6 +29,8 @@ const (
// Dev points to the root directory for device nodes.
Dev = "/dev/"
// DevShm is the place for POSIX shared memory segments, as created via shm_open(3).
DevShm = "/dev/shm/"
// Proc points to a virtual kernel file system exposing the process list and other functionality.
Proc = "/proc/"
// ProcSys points to a hierarchy below /proc/ that exposes a number of kernel tunables.

View File

@@ -1,6 +1,7 @@
package container
import (
"context"
"errors"
"fmt"
"log"
@@ -9,6 +10,8 @@ import (
"path"
"slices"
"strconv"
"sync"
"sync/atomic"
. "syscall"
"time"
@@ -18,24 +21,28 @@ import (
)
const (
/* intermediate tmpfs mount point
/* intermediateHostPath is the pathname of the intermediate tmpfs mount point.
this path might seem like a weird choice, however there are many good reasons to use it:
- the contents of this path is never exposed to the container:
the tmpfs root established here effectively becomes anonymous after pivot_root
- it is safe to assume this path exists and is a directory:
this program will not work correctly without a proper /proc and neither will most others
- this path belongs to the container init:
the container init is not any more privileged or trusted than the rest of the container
- this path is only accessible by init and root:
the container init sets SUID_DUMP_DISABLE and terminates if that fails;
This path might seem like a weird choice, however there are many good reasons to use it:
- The contents of this path is never exposed to the container:
The tmpfs root established here effectively becomes anonymous after pivot_root.
- It is safe to assume this path exists and is a directory:
This program will not work correctly without a proper /proc and neither will most others.
- This path belongs to the container init:
The container init is not any more privileged or trusted than the rest of the container.
- This path is only accessible by init and root:
The container init sets SUID_DUMP_DISABLE and terminates if that fails.
it should be noted that none of this should become relevant at any point since the resulting
intermediate root tmpfs should be effectively anonymous */
It should be noted that none of this should become relevant at any point since the resulting
intermediate root tmpfs should be effectively anonymous. */
intermediateHostPath = fhs.Proc + "self/fd"
// setup params file descriptor
// setupEnv is the name of the environment variable holding the string representation of
// the read end file descriptor of the setup params pipe.
setupEnv = "HAKUREI_SETUP"
// exitUnexpectedWait4 is the exit code if wait4 returns an unexpected errno.
exitUnexpectedWait4 = 2
)
type (
@@ -49,6 +56,8 @@ type (
early(state *setupState, k syscallDispatcher) error
// apply is called in intermediate root.
apply(state *setupState, k syscallDispatcher) error
// late is called right before starting the initial process.
late(state *setupState, k syscallDispatcher) error
// prefix returns a log message prefix, and whether this Op prints no identifying message on its own.
prefix() (string, bool)
@@ -61,11 +70,29 @@ type (
// setupState persists context between Ops.
setupState struct {
nonrepeatable uintptr
// Whether early reaping has concluded. Must only be accessed in the wait4 loop.
processConcluded bool
// Process to syscall.WaitStatus populated in the wait4 loop. Freed after early reaping concludes.
process map[int]WaitStatus
// Synchronises access to process.
processMu sync.RWMutex
*Params
context.Context
message.Msg
}
)
// terminated returns whether the specified pid has been reaped, and its
// syscall.WaitStatus if it had. This is only usable by [Op].
func (state *setupState) terminated(pid int) (wstatus WaitStatus, ok bool) {
state.processMu.RLock()
wstatus, ok = state.process[pid]
state.processMu.RUnlock()
return
}
// Grow grows the slice Ops points to using [slices.Grow].
func (f *Ops) Grow(n int) { *f = slices.Grow(*f, n) }
@@ -143,6 +170,10 @@ func initEntrypoint(k syscallDispatcher, msg message.Msg) {
offsetSetup = int(setupFd + 1)
}
if !params.HostNet {
k.mustLoopback(msg)
}
// write uid/gid map here so parent does not need to set dumpable
if err := k.setDumpable(SUID_DUMP_USER); err != nil {
k.fatalf(msg, "cannot set SUID_DUMP_USER: %v", err)
@@ -180,7 +211,9 @@ func initEntrypoint(k syscallDispatcher, msg message.Msg) {
k.fatalf(msg, "cannot make / rslave: %v", optionalErrorUnwrap(err))
}
state := &setupState{Params: &params.Params, Msg: msg}
ctx, cancel := context.WithCancel(context.Background())
state := &setupState{process: make(map[int]WaitStatus), Params: &params.Params, Msg: msg, Context: ctx}
defer cancel()
/* early is called right before pivot_root into intermediate root;
this step is mostly for gathering information that would otherwise be difficult to obtain
@@ -330,6 +363,97 @@ func initEntrypoint(k syscallDispatcher, msg message.Msg) {
}
k.umask(oldmask)
// winfo represents an exited process from wait4.
type winfo struct {
wpid int
wstatus WaitStatus
}
// info is closed as the wait4 thread terminates
// when there are no longer any processes left to reap
info := make(chan winfo, 1)
// whether initial process has started
var initialProcessStarted atomic.Bool
k.new(func(k syscallDispatcher) {
k.lockOSThread()
wait4:
var (
err error
wpid = -2
wstatus WaitStatus
// whether initial process has started
started bool
)
// keep going until no child process is left
for wpid != -1 {
if err != nil {
break
}
if wpid != -2 {
if !state.processConcluded {
state.processMu.Lock()
if state.process == nil {
// early reaping has already concluded at this point
state.processConcluded = true
info <- winfo{wpid, wstatus}
} else {
// initial process has not yet been created, and the
// info channel is not yet being received from
state.process[wpid] = wstatus
}
state.processMu.Unlock()
} else {
info <- winfo{wpid, wstatus}
}
}
if !started {
started = initialProcessStarted.Load()
}
err = EINTR
for errors.Is(err, EINTR) {
wpid, err = k.wait4(-1, &wstatus, 0, nil)
}
}
if !errors.Is(err, ECHILD) {
k.printf(msg, "unexpected wait4 response: %v", err)
} else if !started {
// initial process has not yet been reached and all daemons
// terminated or none were started in the first place
time.Sleep(500 * time.Microsecond)
goto wait4
}
close(info)
})
// called right before startup of initial process, all state changes to the
// current process is prohibited during late
for i, op := range *params.Ops {
// ops already checked during early setup
if err := op.late(state, k); err != nil {
if m, ok := messageFromError(err); ok {
k.fatal(msg, m)
} else if errors.Is(err, context.DeadlineExceeded) {
k.fatalf(msg, "%s deadline exceeded", op.String())
} else {
k.fatalf(msg, "cannot complete op at index %d: %v", i, err)
}
}
}
// early reaping has concluded, this must happen before initial process is created
state.processMu.Lock()
state.process = nil
state.processMu.Unlock()
if err := closeSetup(); err != nil {
k.fatalf(msg, "cannot close setup pipe: %v", err)
}
@@ -341,50 +465,11 @@ func initEntrypoint(k syscallDispatcher, msg message.Msg) {
cmd.ExtraFiles = extraFiles
cmd.Dir = params.Dir.String()
msg.Verbosef("starting initial program %s", params.Path)
msg.Verbosef("starting initial process %s", params.Path)
if err := k.start(cmd); err != nil {
k.fatalf(msg, "%v", err)
}
type winfo struct {
wpid int
wstatus WaitStatus
}
// info is closed as the wait4 thread terminates
// when there are no longer any processes left to reap
info := make(chan winfo, 1)
k.new(func(k syscallDispatcher) {
k.lockOSThread()
var (
err error
wpid = -2
wstatus WaitStatus
)
// keep going until no child process is left
for wpid != -1 {
if err != nil {
break
}
if wpid != -2 {
info <- winfo{wpid, wstatus}
}
err = EINTR
for errors.Is(err, EINTR) {
wpid, err = k.wait4(-1, &wstatus, 0, nil)
}
}
if !errors.Is(err, ECHILD) {
k.printf(msg, "unexpected wait4 response: %v", err)
}
close(info)
})
initialProcessStarted.Store(true)
// handle signals to dump withheld messages
sig := make(chan os.Signal, 2)
@@ -394,7 +479,7 @@ func initEntrypoint(k syscallDispatcher, msg message.Msg) {
// closed after residualProcessTimeout has elapsed after initial process death
timeout := make(chan struct{})
r := 2
r := exitUnexpectedWait4
for {
select {
case s := <-sig:
@@ -426,6 +511,9 @@ func initEntrypoint(k syscallDispatcher, msg message.Msg) {
}
if w.wpid == cmd.Process.Pid {
// cancel Op context early
cancel()
// start timeout early
go func() { time.Sleep(params.AdoptWaitDelay); close(timeout) }()

View File

@@ -1983,11 +1983,20 @@ func TestInitEntrypoint(t *testing.T) {
call("newFile", stub.ExpectArgs{uintptr(0x3a), "extra file 0"}, (*os.File)(nil), nil),
call("newFile", stub.ExpectArgs{uintptr(0x3b), "extra file 1"}, (*os.File)(nil), nil),
call("umask", stub.ExpectArgs{022}, 0, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("fatalf", stub.ExpectArgs{"cannot close setup pipe: %v", []any{stub.UniqueError(13)}}, nil, nil),
call("verbosef", stub.ExpectArgs{"starting initial program %s", []any{check.MustAbs("/run/current-system/sw/bin/bash")}}, nil, nil),
call("start", stub.ExpectArgs{"/run/current-system/sw/bin/bash", []string{"bash", "-c", "false"}, ([]string)(nil), "/.hakurei/nonexistent"}, nil, stub.UniqueError(12)),
call("fatalf", stub.ExpectArgs{"%v", []any{stub.UniqueError(12)}}, nil, nil),
},
/* wait4 */
Tracks: []stub.Expect{{Calls: []stub.Call{
call("lockOSThread", stub.ExpectArgs{}, magicWait4Signal, nil),
// this terminates the goroutine at the call, preventing it from leaking while preserving behaviour
call("wait4", stub.ExpectArgs{-1, nil, 0, nil, stub.PanicExit}, 0, syscall.ECHILD),
}}},
}, nil},
{"lowlastcap signaled cancel forward error", func(k *kstub) error { initEntrypoint(k, k); return nil }, stub.Expect{
@@ -2062,11 +2071,11 @@ func TestInitEntrypoint(t *testing.T) {
call("newFile", stub.ExpectArgs{uintptr(0x3a), "extra file 0"}, (*os.File)(nil), nil),
call("newFile", stub.ExpectArgs{uintptr(0x3b), "extra file 1"}, (*os.File)(nil), nil),
call("umask", stub.ExpectArgs{022}, 0, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("fatalf", stub.ExpectArgs{"cannot close setup pipe: %v", []any{stub.UniqueError(10)}}, nil, nil),
call("verbosef", stub.ExpectArgs{"starting initial program %s", []any{check.MustAbs("/run/current-system/sw/bin/bash")}}, nil, nil),
call("start", stub.ExpectArgs{"/run/current-system/sw/bin/bash", []string{"bash", "-c", "false"}, ([]string)(nil), "/.hakurei/nonexistent"}, &os.Process{Pid: 0xbad}, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("notify", stub.ExpectArgs{func(c chan<- os.Signal) { c <- CancelSignal }, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, nil, nil),
call("notify", stub.ExpectArgs{func(c chan<- os.Signal) { c <- CancelSignal }, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, magicWait4Signal, nil),
call("verbose", stub.ExpectArgs{[]any{"forwarding context cancellation"}}, nil, nil),
// magicWait4Signal as ret causes wait4 stub to unblock
call("signal", stub.ExpectArgs{"/run/current-system/sw/bin/bash", []string{"bash", "-c", "false"}, ([]string)(nil), "/.hakurei/nonexistent", os.Interrupt}, magicWait4Signal, stub.UniqueError(9)),
@@ -2081,7 +2090,7 @@ func TestInitEntrypoint(t *testing.T) {
/* wait4 */
Tracks: []stub.Expect{{Calls: []stub.Call{
call("lockOSThread", stub.ExpectArgs{}, nil, nil),
call("lockOSThread", stub.ExpectArgs{}, magicWait4Signal, nil),
// magicWait4Signal as args[4] causes this to block until simulated signal is delivered
call("wait4", stub.ExpectArgs{-1, syscall.WaitStatus(0xfade01ce), 0, nil, magicWait4Signal}, 0xbad, nil),
@@ -2162,11 +2171,11 @@ func TestInitEntrypoint(t *testing.T) {
call("newFile", stub.ExpectArgs{uintptr(0x3a), "extra file 0"}, (*os.File)(nil), nil),
call("newFile", stub.ExpectArgs{uintptr(0x3b), "extra file 1"}, (*os.File)(nil), nil),
call("umask", stub.ExpectArgs{022}, 0, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("fatalf", stub.ExpectArgs{"cannot close setup pipe: %v", []any{stub.UniqueError(7)}}, nil, nil),
call("verbosef", stub.ExpectArgs{"starting initial program %s", []any{check.MustAbs("/run/current-system/sw/bin/bash")}}, nil, nil),
call("start", stub.ExpectArgs{"/run/current-system/sw/bin/bash", []string{"bash", "-c", "false"}, ([]string)(nil), "/.hakurei/nonexistent"}, &os.Process{Pid: 0xbad}, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("notify", stub.ExpectArgs{func(c chan<- os.Signal) { c <- syscall.SIGQUIT }, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, nil, nil),
call("notify", stub.ExpectArgs{func(c chan<- os.Signal) { c <- syscall.SIGQUIT }, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, magicWait4Signal, nil),
call("verbosef", stub.ExpectArgs{"got %s, forwarding to initial process", []any{"quit"}}, nil, nil),
// magicWait4Signal as ret causes wait4 stub to unblock
call("signal", stub.ExpectArgs{"/run/current-system/sw/bin/bash", []string{"bash", "-c", "false"}, ([]string)(nil), "/.hakurei/nonexistent", syscall.SIGQUIT}, magicWait4Signal, stub.UniqueError(0xfe)),
@@ -2181,7 +2190,7 @@ func TestInitEntrypoint(t *testing.T) {
/* wait4 */
Tracks: []stub.Expect{{Calls: []stub.Call{
call("lockOSThread", stub.ExpectArgs{}, nil, nil),
call("lockOSThread", stub.ExpectArgs{}, magicWait4Signal, nil),
// magicWait4Signal as args[4] causes this to block until simulated signal is delivered
call("wait4", stub.ExpectArgs{-1, syscall.WaitStatus(0xfade01ce), 0, nil, magicWait4Signal}, 0xbad, nil),
@@ -2262,11 +2271,11 @@ func TestInitEntrypoint(t *testing.T) {
call("newFile", stub.ExpectArgs{uintptr(0x3a), "extra file 0"}, (*os.File)(nil), nil),
call("newFile", stub.ExpectArgs{uintptr(0x3b), "extra file 1"}, (*os.File)(nil), nil),
call("umask", stub.ExpectArgs{022}, 0, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("fatalf", stub.ExpectArgs{"cannot close setup pipe: %v", []any{stub.UniqueError(7)}}, nil, nil),
call("verbosef", stub.ExpectArgs{"starting initial program %s", []any{check.MustAbs("/run/current-system/sw/bin/bash")}}, nil, nil),
call("start", stub.ExpectArgs{"/run/current-system/sw/bin/bash", []string{"bash", "-c", "false"}, ([]string)(nil), "/.hakurei/nonexistent"}, &os.Process{Pid: 0xbad}, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("notify", stub.ExpectArgs{func(c chan<- os.Signal) { c <- os.Interrupt }, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, nil, nil),
call("notify", stub.ExpectArgs{func(c chan<- os.Signal) { c <- os.Interrupt }, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, magicWait4Signal, nil),
call("verbosef", stub.ExpectArgs{"got %s", []any{"interrupt"}}, nil, nil),
call("beforeExit", stub.ExpectArgs{}, nil, nil),
call("exit", stub.ExpectArgs{0}, nil, nil),
@@ -2274,7 +2283,7 @@ func TestInitEntrypoint(t *testing.T) {
/* wait4 */
Tracks: []stub.Expect{{Calls: []stub.Call{
call("lockOSThread", stub.ExpectArgs{}, nil, nil),
call("lockOSThread", stub.ExpectArgs{}, magicWait4Signal, nil),
// this terminates the goroutine at the call, preventing it from leaking while preserving behaviour
call("wait4", stub.ExpectArgs{-1, nil, 0, nil, stub.PanicExit}, 0, syscall.ECHILD),
@@ -2353,11 +2362,11 @@ func TestInitEntrypoint(t *testing.T) {
call("newFile", stub.ExpectArgs{uintptr(0x3a), "extra file 0"}, (*os.File)(nil), nil),
call("newFile", stub.ExpectArgs{uintptr(0x3b), "extra file 1"}, (*os.File)(nil), nil),
call("umask", stub.ExpectArgs{022}, 0, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("fatalf", stub.ExpectArgs{"cannot close setup pipe: %v", []any{stub.UniqueError(5)}}, nil, nil),
call("verbosef", stub.ExpectArgs{"starting initial program %s", []any{check.MustAbs("/run/current-system/sw/bin/bash")}}, nil, nil),
call("start", stub.ExpectArgs{"/run/current-system/sw/bin/bash", []string{"bash", "-c", "false"}, ([]string)(nil), "/.hakurei/nonexistent"}, &os.Process{Pid: 0xbad}, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("notify", stub.ExpectArgs{nil, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, nil, nil),
call("notify", stub.ExpectArgs{nil, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, magicWait4Signal, nil),
call("verbose", stub.ExpectArgs{[]any{os.ErrInvalid.Error()}}, nil, nil),
call("verbose", stub.ExpectArgs{[]any{os.ErrInvalid.Error()}}, nil, nil),
call("verbosef", stub.ExpectArgs{"initial process exited with signal %s", []any{syscall.Signal(0x4e)}}, nil, nil),
@@ -2368,7 +2377,7 @@ func TestInitEntrypoint(t *testing.T) {
/* wait4 */
Tracks: []stub.Expect{{Calls: []stub.Call{
call("lockOSThread", stub.ExpectArgs{}, nil, nil),
call("lockOSThread", stub.ExpectArgs{}, magicWait4Signal, nil),
call("wait4", stub.ExpectArgs{-1, syscall.WaitStatus(0xfade01ce), 0, nil}, 0xbad, nil),
// this terminates the goroutine at the call, preventing it from leaking while preserving behaviour
@@ -2448,11 +2457,11 @@ func TestInitEntrypoint(t *testing.T) {
call("newFile", stub.ExpectArgs{uintptr(0x3a), "extra file 0"}, (*os.File)(nil), nil),
call("newFile", stub.ExpectArgs{uintptr(0x3b), "extra file 1"}, (*os.File)(nil), nil),
call("umask", stub.ExpectArgs{022}, 0, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("fatalf", stub.ExpectArgs{"cannot close setup pipe: %v", []any{stub.UniqueError(3)}}, nil, nil),
call("verbosef", stub.ExpectArgs{"starting initial program %s", []any{check.MustAbs("/run/current-system/sw/bin/bash")}}, nil, nil),
call("start", stub.ExpectArgs{"/run/current-system/sw/bin/bash", []string{"bash", "-c", "false"}, ([]string)(nil), "/.hakurei/nonexistent"}, &os.Process{Pid: 0xbad}, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("notify", stub.ExpectArgs{nil, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, nil, nil),
call("notify", stub.ExpectArgs{nil, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, magicWait4Signal, nil),
call("verbose", stub.ExpectArgs{[]any{os.ErrInvalid.Error()}}, nil, nil),
call("verbose", stub.ExpectArgs{[]any{os.ErrInvalid.Error()}}, nil, nil),
call("verbosef", stub.ExpectArgs{"initial process exited with signal %s", []any{syscall.Signal(0x4e)}}, nil, nil),
@@ -2462,7 +2471,7 @@ func TestInitEntrypoint(t *testing.T) {
/* wait4 */
Tracks: []stub.Expect{{Calls: []stub.Call{
call("lockOSThread", stub.ExpectArgs{}, nil, nil),
call("lockOSThread", stub.ExpectArgs{}, magicWait4Signal, nil),
call("wait4", stub.ExpectArgs{-1, nil, 0, nil}, 0, syscall.EINTR),
call("wait4", stub.ExpectArgs{-1, nil, 0, nil}, 0, syscall.EINTR),
@@ -2586,11 +2595,11 @@ func TestInitEntrypoint(t *testing.T) {
call("newFile", stub.ExpectArgs{uintptr(0x3a), "extra file 0"}, (*os.File)(nil), nil),
call("newFile", stub.ExpectArgs{uintptr(0x3b), "extra file 1"}, (*os.File)(nil), nil),
call("umask", stub.ExpectArgs{022}, 0, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("fatalf", stub.ExpectArgs{"cannot close setup pipe: %v", []any{stub.UniqueError(1)}}, nil, nil),
call("verbosef", stub.ExpectArgs{"starting initial program %s", []any{check.MustAbs("/run/current-system/sw/bin/bash")}}, nil, nil),
call("start", stub.ExpectArgs{"/run/current-system/sw/bin/bash", []string{"bash", "-c", "false"}, ([]string)(nil), "/.hakurei/nonexistent"}, &os.Process{Pid: 0xbad}, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("notify", stub.ExpectArgs{nil, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, nil, nil),
call("notify", stub.ExpectArgs{nil, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, magicWait4Signal, nil),
call("verbose", stub.ExpectArgs{[]any{os.ErrInvalid.Error()}}, nil, nil),
call("verbose", stub.ExpectArgs{[]any{os.ErrInvalid.Error()}}, nil, nil),
call("verbosef", stub.ExpectArgs{"initial process exited with code %d", []any{1}}, nil, nil),
@@ -2600,7 +2609,7 @@ func TestInitEntrypoint(t *testing.T) {
/* wait4 */
Tracks: []stub.Expect{{Calls: []stub.Call{
call("lockOSThread", stub.ExpectArgs{}, nil, nil),
call("lockOSThread", stub.ExpectArgs{}, magicWait4Signal, nil),
call("wait4", stub.ExpectArgs{-1, nil, 0, nil}, 0, syscall.EINTR),
call("wait4", stub.ExpectArgs{-1, nil, 0, nil}, 0, syscall.EINTR),
@@ -2728,11 +2737,11 @@ func TestInitEntrypoint(t *testing.T) {
call("newFile", stub.ExpectArgs{uintptr(11), "extra file 1"}, (*os.File)(nil), nil),
call("newFile", stub.ExpectArgs{uintptr(12), "extra file 2"}, (*os.File)(nil), nil),
call("umask", stub.ExpectArgs{022}, 0, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("fatalf", stub.ExpectArgs{"cannot close setup pipe: %v", []any{stub.UniqueError(0)}}, nil, nil),
call("verbosef", stub.ExpectArgs{"starting initial program %s", []any{check.MustAbs("/bin/zsh")}}, nil, nil),
call("start", stub.ExpectArgs{"/bin/zsh", []string{"zsh", "-c", "exec vim"}, []string{"DISPLAY=:0"}, "/.hakurei"}, &os.Process{Pid: 0xcafe}, nil),
call("New", stub.ExpectArgs{}, nil, nil),
call("notify", stub.ExpectArgs{nil, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, nil, nil),
call("notify", stub.ExpectArgs{nil, []os.Signal{CancelSignal, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT}}, magicWait4Signal, nil),
call("verbose", stub.ExpectArgs{[]any{os.ErrInvalid.Error()}}, nil, nil),
call("verbose", stub.ExpectArgs{[]any{os.ErrInvalid.Error()}}, nil, nil),
call("verbose", stub.ExpectArgs{[]any{os.ErrInvalid.Error()}}, nil, nil),
@@ -2743,7 +2752,7 @@ func TestInitEntrypoint(t *testing.T) {
/* wait4 */
Tracks: []stub.Expect{{Calls: []stub.Call{
call("lockOSThread", stub.ExpectArgs{}, nil, nil),
call("lockOSThread", stub.ExpectArgs{}, magicWait4Signal, nil),
call("wait4", stub.ExpectArgs{-1, nil, 0, nil}, 0, syscall.EINTR),
call("wait4", stub.ExpectArgs{-1, nil, 0, nil}, 0, syscall.EINTR),

View File

@@ -90,6 +90,7 @@ func (b *BindMountOp) apply(state *setupState, k syscallDispatcher) error {
}
return k.bindMount(state, source, target, flags)
}
func (b *BindMountOp) late(*setupState, syscallDispatcher) error { return nil }
func (b *BindMountOp) Is(op Op) bool {
vb, ok := op.(*BindMountOp)

134
container/initdaemon.go Normal file
View File

@@ -0,0 +1,134 @@
package container
import (
"context"
"encoding/gob"
"errors"
"fmt"
"os"
"os/exec"
"slices"
"strconv"
"syscall"
"time"
"hakurei.app/container/check"
"hakurei.app/container/fhs"
)
func init() { gob.Register(new(DaemonOp)) }
const (
// daemonTimeout is the duration a [DaemonOp] is allowed to block before the
// [DaemonOp.Target] marker becomes available.
daemonTimeout = 5 * time.Second
)
// Daemon appends an [Op] that starts a daemon in the container and blocks until
// [DaemonOp.Target] appears.
func (f *Ops) Daemon(target, path *check.Absolute, args ...string) *Ops {
*f = append(*f, &DaemonOp{target, path, args})
return f
}
// DaemonOp starts a daemon in the container and blocks until Target appears.
type DaemonOp struct {
// Pathname indicating readiness of daemon.
Target *check.Absolute
// Absolute pathname passed to [exec.Cmd].
Path *check.Absolute
// Arguments (excl. first) passed to [exec.Cmd].
Args []string
}
// earlyTerminationError is returned by [DaemonOp] when a daemon terminates
// before [DaemonOp.Target] appears.
type earlyTerminationError struct {
// Returned by [DaemonOp.String].
op string
// Copied from wait4 loop.
wstatus syscall.WaitStatus
}
func (e *earlyTerminationError) Error() string {
res := ""
switch {
case e.wstatus.Exited():
res = "exit status " + strconv.Itoa(e.wstatus.ExitStatus())
case e.wstatus.Signaled():
res = "signal: " + e.wstatus.Signal().String()
case e.wstatus.Stopped():
res = "stop signal: " + e.wstatus.StopSignal().String()
if e.wstatus.StopSignal() == syscall.SIGTRAP && e.wstatus.TrapCause() != 0 {
res += " (trap " + strconv.Itoa(e.wstatus.TrapCause()) + ")"
}
case e.wstatus.Continued():
res = "continued"
}
if e.wstatus.CoreDump() {
res += " (core dumped)"
}
return res
}
func (e *earlyTerminationError) Message() string { return e.op + " " + e.Error() }
func (d *DaemonOp) Valid() bool { return d != nil && d.Target != nil && d.Path != nil }
func (d *DaemonOp) early(*setupState, syscallDispatcher) error { return nil }
func (d *DaemonOp) apply(*setupState, syscallDispatcher) error { return nil }
func (d *DaemonOp) late(state *setupState, k syscallDispatcher) error {
cmd := exec.CommandContext(state.Context, d.Path.String(), d.Args...)
cmd.Env = state.Env
cmd.Dir = fhs.Root
if state.IsVerbose() {
cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
}
// WaitDelay: left unset because lifetime is bound by AdoptWaitDelay on cancellation
cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }
state.Verbosef("starting %s", d.String())
if err := k.start(cmd); err != nil {
return err
}
deadline := time.Now().Add(daemonTimeout)
var wstatusErr error
for {
if _, err := k.stat(d.Target.String()); err != nil {
if !errors.Is(err, os.ErrNotExist) {
_ = k.signal(cmd, os.Kill)
return err
}
if time.Now().After(deadline) {
_ = k.signal(cmd, os.Kill)
return context.DeadlineExceeded
}
if wstatusErr != nil {
return wstatusErr
}
if wstatus, ok := state.terminated(cmd.Process.Pid); ok {
// check once again: process could have satisfied Target between stat and the lookup
wstatusErr = &earlyTerminationError{d.String(), wstatus}
continue
}
time.Sleep(500 * time.Microsecond)
continue
}
state.Verbosef("daemon process %d ready", cmd.Process.Pid)
return nil
}
}
func (d *DaemonOp) Is(op Op) bool {
vd, ok := op.(*DaemonOp)
return ok && d.Valid() && vd.Valid() &&
d.Target.Is(vd.Target) && d.Path.Is(vd.Path) &&
slices.Equal(d.Args, vd.Args)
}
func (*DaemonOp) prefix() (string, bool) { return zeroString, false }
func (d *DaemonOp) String() string { return fmt.Sprintf("daemon providing %q", d.Target) }

View File

@@ -0,0 +1,127 @@
package container
import (
"os"
"testing"
"hakurei.app/container/check"
"hakurei.app/container/stub"
"hakurei.app/message"
)
func TestEarlyTerminationError(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
err error
want string
msg string
}{
{"exited", &earlyTerminationError{
`daemon providing "/run/user/1971/pulse/native"`, 127 << 8,
}, "exit status 127", `daemon providing "/run/user/1971/pulse/native" exit status 127`},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := tc.err.Error(); got != tc.want {
t.Errorf("Error: %q, want %q", got, tc.want)
}
if got := tc.err.(message.Error).Message(); got != tc.msg {
t.Errorf("Message: %s, want %s", got, tc.msg)
}
})
}
}
func TestDaemonOp(t *testing.T) {
t.Parallel()
checkSimple(t, "DaemonOp.late", []simpleTestCase{
{"success", func(k *kstub) error {
state := setupState{Params: &Params{Env: []string{"\x00"}}, Context: t.Context(), Msg: k}
return (&DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
Args: []string{"-v"},
}).late(&state, k)
}, stub.Expect{Calls: []stub.Call{
call("isVerbose", stub.ExpectArgs{}, true, nil),
call("verbosef", stub.ExpectArgs{"starting %s", []any{`daemon providing "/run/user/1971/pulse/native"`}}, nil, nil),
call("start", stub.ExpectArgs{"/run/current-system/sw/bin/pipewire-pulse", []string{"/run/current-system/sw/bin/pipewire-pulse", "-v"}, []string{"\x00"}, "/"}, &os.Process{Pid: 0xcafe}, nil),
call("stat", stub.ExpectArgs{"/run/user/1971/pulse/native"}, isDirFi(false), os.ErrNotExist),
call("stat", stub.ExpectArgs{"/run/user/1971/pulse/native"}, isDirFi(false), os.ErrNotExist),
call("stat", stub.ExpectArgs{"/run/user/1971/pulse/native"}, isDirFi(false), os.ErrNotExist),
call("stat", stub.ExpectArgs{"/run/user/1971/pulse/native"}, isDirFi(false), nil),
call("verbosef", stub.ExpectArgs{"daemon process %d ready", []any{0xcafe}}, nil, nil),
}}, nil},
})
checkOpsValid(t, []opValidTestCase{
{"nil", (*DaemonOp)(nil), false},
{"zero", new(DaemonOp), false},
{"valid", &DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
Args: []string{"-v"},
}, true},
})
checkOpsBuilder(t, []opsBuilderTestCase{
{"pipewire-pulse", new(Ops).Daemon(
check.MustAbs("/run/user/1971/pulse/native"),
check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"), "-v",
), Ops{
&DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
Args: []string{"-v"},
},
}},
})
checkOpIs(t, []opIsTestCase{
{"zero", new(DaemonOp), new(DaemonOp), false},
{"args differs", &DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
Args: []string{"-v"},
}, &DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
}, false},
{"path differs", &DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire"),
}, &DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
}, false},
{"target differs", &DaemonOp{
Target: check.MustAbs("/run/user/65534/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
}, &DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
}, false},
{"equals", &DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
}, &DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
Path: check.MustAbs("/run/current-system/sw/bin/pipewire-pulse"),
}, true},
})
checkOpMeta(t, []opMetaTestCase{
{"pipewire-pulse", &DaemonOp{
Target: check.MustAbs("/run/user/1971/pulse/native"),
}, zeroString, `daemon providing "/run/user/1971/pulse/native"`},
})
}

View File

@@ -126,6 +126,7 @@ func (d *MountDevOp) apply(state *setupState, k syscallDispatcher) error {
}
return k.mountTmpfs(SourceTmpfs, devShmPath, MS_NOSUID|MS_NODEV, 0, 01777)
}
func (d *MountDevOp) late(*setupState, syscallDispatcher) error { return nil }
func (d *MountDevOp) Is(op Op) bool {
vd, ok := op.(*MountDevOp)

View File

@@ -27,6 +27,7 @@ func (m *MkdirOp) early(*setupState, syscallDispatcher) error { return nil }
func (m *MkdirOp) apply(_ *setupState, k syscallDispatcher) error {
return k.mkdirAll(toSysroot(m.Path.String()), m.Perm)
}
func (m *MkdirOp) late(*setupState, syscallDispatcher) error { return nil }
func (m *MkdirOp) Is(op Op) bool {
vm, ok := op.(*MkdirOp)

View File

@@ -205,6 +205,8 @@ func (o *MountOverlayOp) apply(state *setupState, k syscallDispatcher) error {
return k.mount(SourceOverlay, target, FstypeOverlay, 0, strings.Join(options, check.SpecialOverlayOption))
}
func (o *MountOverlayOp) late(*setupState, syscallDispatcher) error { return nil }
func (o *MountOverlayOp) Is(op Op) bool {
vo, ok := op.(*MountOverlayOp)
return ok && o.Valid() && vo.Valid() &&

View File

@@ -312,7 +312,10 @@ func TestMountOverlayOp(t *testing.T) {
},
}},
{"ephemeral", new(Ops).OverlayEphemeral(check.MustAbs("/nix/store"), check.MustAbs("/mnt-root/nix/.ro-store")), Ops{
{"ephemeral", new(Ops).OverlayEphemeral(
check.MustAbs("/nix/store"),
check.MustAbs("/mnt-root/nix/.ro-store"),
), Ops{
&MountOverlayOp{
Target: check.MustAbs("/nix/store"),
Lower: []*check.Absolute{check.MustAbs("/mnt-root/nix/.ro-store")},
@@ -320,7 +323,10 @@ func TestMountOverlayOp(t *testing.T) {
},
}},
{"readonly", new(Ops).OverlayReadonly(check.MustAbs("/nix/store"), check.MustAbs("/mnt-root/nix/.ro-store")), Ops{
{"readonly", new(Ops).OverlayReadonly(
check.MustAbs("/nix/store"),
check.MustAbs("/mnt-root/nix/.ro-store"),
), Ops{
&MountOverlayOp{
Target: check.MustAbs("/nix/store"),
Lower: []*check.Absolute{check.MustAbs("/mnt-root/nix/.ro-store")},

View File

@@ -57,6 +57,7 @@ func (t *TmpfileOp) apply(state *setupState, k syscallDispatcher) error {
}
return nil
}
func (t *TmpfileOp) late(*setupState, syscallDispatcher) error { return nil }
func (t *TmpfileOp) Is(op Op) bool {
vt, ok := op.(*TmpfileOp)

View File

@@ -28,6 +28,7 @@ func (p *MountProcOp) apply(state *setupState, k syscallDispatcher) error {
}
return k.mount(SourceProc, target, FstypeProc, MS_NOSUID|MS_NOEXEC|MS_NODEV, zeroString)
}
func (p *MountProcOp) late(*setupState, syscallDispatcher) error { return nil }
func (p *MountProcOp) Is(op Op) bool {
vp, ok := op.(*MountProcOp)

View File

@@ -26,6 +26,7 @@ func (*RemountOp) early(*setupState, syscallDispatcher) error { return nil }
func (r *RemountOp) apply(state *setupState, k syscallDispatcher) error {
return k.remount(state, toSysroot(r.Target.String()), r.Flags)
}
func (r *RemountOp) late(*setupState, syscallDispatcher) error { return nil }
func (r *RemountOp) Is(op Op) bool {
vr, ok := op.(*RemountOp)

View File

@@ -31,7 +31,7 @@ func (l *SymlinkOp) Valid() bool { return l != nil && l.Target != nil && l.LinkN
func (l *SymlinkOp) early(_ *setupState, k syscallDispatcher) error {
if l.Dereference {
if !path.IsAbs(l.LinkName) {
return &check.AbsoluteError{Pathname: l.LinkName}
return check.AbsoluteError(l.LinkName)
}
if name, err := k.readlink(l.LinkName); err != nil {
return err
@@ -50,6 +50,8 @@ func (l *SymlinkOp) apply(state *setupState, k syscallDispatcher) error {
return k.symlink(l.LinkName, target)
}
func (l *SymlinkOp) late(*setupState, syscallDispatcher) error { return nil }
func (l *SymlinkOp) Is(op Op) bool {
vl, ok := op.(*SymlinkOp)
return ok && l.Valid() && vl.Valid() &&

View File

@@ -23,7 +23,7 @@ func TestSymlinkOp(t *testing.T) {
Target: check.MustAbs("/etc/mtab"),
LinkName: "etc/mtab",
Dereference: true,
}, nil, &check.AbsoluteError{Pathname: "etc/mtab"}, nil, nil},
}, nil, check.AbsoluteError("etc/mtab"), nil, nil},
{"readlink", &Params{ParentPerm: 0755}, &SymlinkOp{
Target: check.MustAbs("/etc/mtab"),

View File

@@ -48,6 +48,7 @@ func (t *MountTmpfsOp) apply(_ *setupState, k syscallDispatcher) error {
}
return k.mountTmpfs(t.FSName, toSysroot(t.Path.String()), t.Flags, t.Size, t.Perm)
}
func (t *MountTmpfsOp) late(*setupState, syscallDispatcher) error { return nil }
func (t *MountTmpfsOp) Is(op Op) bool {
vt, ok := op.(*MountTmpfsOp)

269
container/netlink.go Normal file
View File

@@ -0,0 +1,269 @@
package container
import (
"encoding/binary"
"errors"
"net"
"os"
. "syscall"
"unsafe"
"hakurei.app/container/std"
"hakurei.app/message"
)
// rtnetlink represents a NETLINK_ROUTE socket.
type rtnetlink struct {
// Sent as part of rtnetlink messages.
pid uint32
// AF_NETLINK socket.
fd int
// Whether the socket is open.
ok bool
// Message sequence number.
seq uint32
}
// open creates the underlying NETLINK_ROUTE socket.
func (s *rtnetlink) open() (err error) {
if s.ok || s.fd < 0 {
return os.ErrInvalid
}
s.pid = uint32(Getpid())
if s.fd, err = Socket(
AF_NETLINK,
SOCK_RAW|SOCK_CLOEXEC,
NETLINK_ROUTE,
); err != nil {
return os.NewSyscallError("socket", err)
} else if err = Bind(s.fd, &SockaddrNetlink{
Family: AF_NETLINK,
Pid: s.pid,
}); err != nil {
_ = s.close()
return os.NewSyscallError("bind", err)
} else {
s.ok = true
return nil
}
}
// close closes the underlying NETLINK_ROUTE socket.
func (s *rtnetlink) close() error {
if !s.ok {
return os.ErrInvalid
}
s.ok = false
err := Close(s.fd)
s.fd = -1
return err
}
// roundtrip sends a netlink message and handles the reply.
func (s *rtnetlink) roundtrip(data []byte) error {
if !s.ok {
return os.ErrInvalid
}
defer func() { s.seq++ }()
if err := Sendto(s.fd, data, 0, &SockaddrNetlink{
Family: AF_NETLINK,
}); err != nil {
return os.NewSyscallError("sendto", err)
}
buf := make([]byte, Getpagesize())
done:
for {
p := buf
if n, _, err := Recvfrom(s.fd, p, 0); err != nil {
return os.NewSyscallError("recvfrom", err)
} else if n < NLMSG_HDRLEN {
return errors.ErrUnsupported
} else {
p = p[:n]
}
if msgs, err := ParseNetlinkMessage(p); err != nil {
return err
} else {
for _, m := range msgs {
if m.Header.Seq != s.seq || m.Header.Pid != s.pid {
return errors.ErrUnsupported
}
if m.Header.Type == NLMSG_DONE {
break done
}
if m.Header.Type == NLMSG_ERROR {
if len(m.Data) >= 4 {
errno := Errno(-std.ScmpInt(binary.NativeEndian.Uint32(m.Data)))
if errno == 0 {
return nil
}
return errno
}
return errors.ErrUnsupported
}
}
}
}
return nil
}
// mustRoundtrip calls roundtrip and terminates via msg for a non-nil error.
func (s *rtnetlink) mustRoundtrip(msg message.Msg, data []byte) {
err := s.roundtrip(data)
if err == nil {
return
}
if closeErr := Close(s.fd); closeErr != nil {
msg.Verbosef("cannot close: %v", err)
}
switch err.(type) {
case *os.SyscallError:
msg.GetLogger().Fatalf("cannot %v", err)
case Errno:
msg.GetLogger().Fatalf("RTNETLINK answers: %v", err)
default:
msg.GetLogger().Fatalln("RTNETLINK answers with unexpected message")
}
}
// newaddrLo represents a RTM_NEWADDR message with two addresses.
type newaddrLo struct {
header NlMsghdr
data IfAddrmsg
r0 RtAttr
a0 [4]byte // in_addr
r1 RtAttr
a1 [4]byte // in_addr
}
// sizeofNewaddrLo is the expected size of newaddrLo.
const sizeofNewaddrLo = NLMSG_HDRLEN + SizeofIfAddrmsg + (SizeofRtAttr+4)*2
// newaddrLo returns the address of a populated newaddrLo.
func (s *rtnetlink) newaddrLo(lo int) *newaddrLo {
return &newaddrLo{NlMsghdr{
Len: sizeofNewaddrLo,
Type: RTM_NEWADDR,
Flags: NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL,
Seq: s.seq,
Pid: s.pid,
}, IfAddrmsg{
Family: AF_INET,
Prefixlen: 8,
Flags: IFA_F_PERMANENT,
Scope: RT_SCOPE_HOST,
Index: uint32(lo),
}, RtAttr{
Len: uint16(SizeofRtAttr + len(newaddrLo{}.a0)),
Type: IFA_LOCAL,
}, [4]byte{127, 0, 0, 1}, RtAttr{
Len: uint16(SizeofRtAttr + len(newaddrLo{}.a1)),
Type: IFA_ADDRESS,
}, [4]byte{127, 0, 0, 1}}
}
func (msg *newaddrLo) toWireFormat() []byte {
var buf [sizeofNewaddrLo]byte
*(*uint32)(unsafe.Pointer(&buf[0:4][0])) = msg.header.Len
*(*uint16)(unsafe.Pointer(&buf[4:6][0])) = msg.header.Type
*(*uint16)(unsafe.Pointer(&buf[6:8][0])) = msg.header.Flags
*(*uint32)(unsafe.Pointer(&buf[8:12][0])) = msg.header.Seq
*(*uint32)(unsafe.Pointer(&buf[12:16][0])) = msg.header.Pid
buf[16] = msg.data.Family
buf[17] = msg.data.Prefixlen
buf[18] = msg.data.Flags
buf[19] = msg.data.Scope
*(*uint32)(unsafe.Pointer(&buf[20:24][0])) = msg.data.Index
*(*uint16)(unsafe.Pointer(&buf[24:26][0])) = msg.r0.Len
*(*uint16)(unsafe.Pointer(&buf[26:28][0])) = msg.r0.Type
copy(buf[28:32], msg.a0[:])
*(*uint16)(unsafe.Pointer(&buf[32:34][0])) = msg.r1.Len
*(*uint16)(unsafe.Pointer(&buf[34:36][0])) = msg.r1.Type
copy(buf[36:40], msg.a1[:])
return buf[:]
}
// newlinkLo represents a RTM_NEWLINK message.
type newlinkLo struct {
header NlMsghdr
data IfInfomsg
}
// sizeofNewlinkLo is the expected size of newlinkLo.
const sizeofNewlinkLo = NLMSG_HDRLEN + SizeofIfInfomsg
// newlinkLo returns the address of a populated newlinkLo.
func (s *rtnetlink) newlinkLo(lo int) *newlinkLo {
return &newlinkLo{NlMsghdr{
Len: sizeofNewlinkLo,
Type: RTM_NEWLINK,
Flags: NLM_F_REQUEST | NLM_F_ACK,
Seq: s.seq,
Pid: s.pid,
}, IfInfomsg{
Family: AF_UNSPEC,
Index: int32(lo),
Flags: IFF_UP,
Change: IFF_UP,
}}
}
func (msg *newlinkLo) toWireFormat() []byte {
var buf [sizeofNewlinkLo]byte
*(*uint32)(unsafe.Pointer(&buf[0:4][0])) = msg.header.Len
*(*uint16)(unsafe.Pointer(&buf[4:6][0])) = msg.header.Type
*(*uint16)(unsafe.Pointer(&buf[6:8][0])) = msg.header.Flags
*(*uint32)(unsafe.Pointer(&buf[8:12][0])) = msg.header.Seq
*(*uint32)(unsafe.Pointer(&buf[12:16][0])) = msg.header.Pid
buf[16] = msg.data.Family
*(*uint16)(unsafe.Pointer(&buf[18:20][0])) = msg.data.Type
*(*int32)(unsafe.Pointer(&buf[20:24][0])) = msg.data.Index
*(*uint32)(unsafe.Pointer(&buf[24:28][0])) = msg.data.Flags
*(*uint32)(unsafe.Pointer(&buf[28:32][0])) = msg.data.Change
return buf[:]
}
// mustLoopback creates the loopback address and brings the lo interface up.
// mustLoopback calls a fatal method of the underlying [log.Logger] of m with a
// user-facing error message if RTNETLINK behaves unexpectedly.
func mustLoopback(msg message.Msg) {
log := msg.GetLogger()
var lo int
if ifi, err := net.InterfaceByName("lo"); err != nil {
log.Fatalln(err)
} else {
lo = ifi.Index
}
var s rtnetlink
if err := s.open(); err != nil {
log.Fatalln(err)
}
defer func() {
if err := s.close(); err != nil {
msg.Verbosef("cannot close netlink: %v", err)
}
}()
s.mustRoundtrip(msg, s.newaddrLo(lo).toWireFormat())
s.mustRoundtrip(msg, s.newlinkLo(lo).toWireFormat())
}

72
container/netlink_test.go Normal file
View File

@@ -0,0 +1,72 @@
package container
import (
"testing"
"unsafe"
)
func TestSizeof(t *testing.T) {
if got := unsafe.Sizeof(newaddrLo{}); got != sizeofNewaddrLo {
t.Fatalf("newaddrLo: sizeof = %#x, want %#x", got, sizeofNewaddrLo)
}
if got := unsafe.Sizeof(newlinkLo{}); got != sizeofNewlinkLo {
t.Fatalf("newlinkLo: sizeof = %#x, want %#x", got, sizeofNewlinkLo)
}
}
func TestRtnetlinkMessage(t *testing.T) {
t.Parallel()
testCases := []struct {
name string
msg interface{ toWireFormat() []byte }
want []byte
}{
{"newaddrLo", (&rtnetlink{pid: 1, seq: 0}).newaddrLo(1), []byte{
/* Len */ 0x28, 0, 0, 0,
/* Type */ 0x14, 0,
/* Flags */ 5, 6,
/* Seq */ 0, 0, 0, 0,
/* Pid */ 1, 0, 0, 0,
/* Family */ 2,
/* Prefixlen */ 8,
/* Flags */ 0x80,
/* Scope */ 0xfe,
/* Index */ 1, 0, 0, 0,
/* Len */ 8, 0,
/* Type */ 2, 0,
/* in_addr */ 127, 0, 0, 1,
/* Len */ 8, 0,
/* Type */ 1, 0,
/* in_addr */ 127, 0, 0, 1,
}},
{"newlinkLo", (&rtnetlink{pid: 1, seq: 1}).newlinkLo(1), []byte{
/* Len */ 0x20, 0, 0, 0,
/* Type */ 0x10, 0,
/* Flags */ 5, 0,
/* Seq */ 1, 0, 0, 0,
/* Pid */ 1, 0, 0, 0,
/* Family */ 0,
/* pad */ 0,
/* Type */ 0, 0,
/* Index */ 1, 0, 0, 0,
/* Flags */ 1, 0, 0, 0,
/* Change */ 1, 0, 0, 0,
}},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := tc.msg.toWireFormat(); string(got) != string(tc.want) {
t.Fatalf("toWireFormat: %#v, want %#v", got, tc.want)
}
})
}
}

View File

@@ -9,136 +9,130 @@
#define LEN(arr) (sizeof(arr) / sizeof((arr)[0]))
int32_t hakurei_scmp_make_filter(int *ret_p, uintptr_t allocate_p,
uint32_t arch, uint32_t multiarch,
struct hakurei_syscall_rule *rules,
size_t rules_sz, hakurei_export_flag flags) {
int i;
int last_allowed_family;
int disallowed;
struct hakurei_syscall_rule *rule;
void *buf;
size_t len = 0;
int32_t hakurei_scmp_make_filter(
int *ret_p, uintptr_t allocate_p,
uint32_t arch, uint32_t multiarch,
struct hakurei_syscall_rule *rules,
size_t rules_sz, hakurei_export_flag flags) {
int i;
int last_allowed_family;
int disallowed;
struct hakurei_syscall_rule *rule;
void *buf;
size_t len = 0;
int32_t res = 0; /* refer to resPrefix for message */
int32_t res = 0; /* refer to resPrefix for message */
/* Blocklist all but unix, inet, inet6 and netlink */
struct {
int family;
hakurei_export_flag flags_mask;
} socket_family_allowlist[] = {
/* NOTE: Keep in numerical order */
{AF_UNSPEC, 0},
{AF_LOCAL, 0},
{AF_INET, 0},
{AF_INET6, 0},
{AF_NETLINK, 0},
{AF_CAN, HAKUREI_EXPORT_CAN},
{AF_BLUETOOTH, HAKUREI_EXPORT_BLUETOOTH},
};
/* Blocklist all but unix, inet, inet6 and netlink */
struct {
int family;
hakurei_export_flag flags_mask;
} socket_family_allowlist[] = {
/* NOTE: Keep in numerical order */
{AF_UNSPEC, 0},
{AF_LOCAL, 0},
{AF_INET, 0},
{AF_INET6, 0},
{AF_NETLINK, 0},
{AF_CAN, HAKUREI_EXPORT_CAN},
{AF_BLUETOOTH, HAKUREI_EXPORT_BLUETOOTH},
};
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
if (ctx == NULL) {
res = 1;
goto out;
} else
errno = 0;
/* We only really need to handle arches on multiarch systems.
* If only one arch is supported the default is fine */
if (arch != 0) {
/* This *adds* the target arch, instead of replacing the
* native one. This is not ideal, because we'd like to only
* allow the target arch, but we can't really disallow the
* native arch at this point, because then bubblewrap
* couldn't continue running. */
*ret_p = seccomp_arch_add(ctx, arch);
if (*ret_p < 0 && *ret_p != -EEXIST) {
res = 2;
goto out;
}
if (flags & HAKUREI_EXPORT_MULTIARCH && multiarch != 0) {
*ret_p = seccomp_arch_add(ctx, multiarch);
if (*ret_p < 0 && *ret_p != -EEXIST) {
res = 3;
scmp_filter_ctx ctx = seccomp_init(SCMP_ACT_ALLOW);
if (ctx == NULL) {
res = 1;
goto out;
}
}
}
} else
errno = 0;
for (i = 0; i < rules_sz; i++) {
rule = &rules[i];
assert(rule->m_errno == EPERM || rule->m_errno == ENOSYS);
/* We only really need to handle arches on multiarch systems.
* If only one arch is supported the default is fine */
if (arch != 0) {
/* This *adds* the target arch, instead of replacing the
* native one. This is not ideal, because we'd like to only
* allow the target arch, but we can't really disallow the
* native arch at this point, because then bubblewrap
* couldn't continue running. */
*ret_p = seccomp_arch_add(ctx, arch);
if (*ret_p < 0 && *ret_p != -EEXIST) {
res = 2;
goto out;
}
if (rule->arg)
*ret_p = seccomp_rule_add(ctx, SCMP_ACT_ERRNO(rule->m_errno),
rule->syscall, 1, *rule->arg);
else
*ret_p = seccomp_rule_add(ctx, SCMP_ACT_ERRNO(rule->m_errno),
rule->syscall, 0);
if (*ret_p == -EFAULT) {
res = 4;
goto out;
} else if (*ret_p < 0) {
res = 5;
goto out;
}
}
/* Socket filtering doesn't work on e.g. i386, so ignore failures here
* However, we need to user seccomp_rule_add_exact to avoid libseccomp doing
* something else: https://github.com/seccomp/libseccomp/issues/8 */
last_allowed_family = -1;
for (i = 0; i < LEN(socket_family_allowlist); i++) {
if (socket_family_allowlist[i].flags_mask != 0 &&
(socket_family_allowlist[i].flags_mask & flags) !=
socket_family_allowlist[i].flags_mask)
continue;
for (disallowed = last_allowed_family + 1;
disallowed < socket_family_allowlist[i].family; disallowed++) {
/* Blocklist the in-between valid families */
seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EAFNOSUPPORT),
SCMP_SYS(socket), 1,
SCMP_A0(SCMP_CMP_EQ, disallowed));
}
last_allowed_family = socket_family_allowlist[i].family;
}
/* Blocklist the rest */
seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EAFNOSUPPORT), SCMP_SYS(socket), 1,
SCMP_A0(SCMP_CMP_GE, last_allowed_family + 1));
if (allocate_p == 0) {
*ret_p = seccomp_load(ctx);
if (*ret_p != 0) {
res = 7;
goto out;
}
} else {
*ret_p = seccomp_export_bpf_mem(ctx, NULL, &len);
if (*ret_p != 0) {
res = 6;
goto out;
if (flags & HAKUREI_EXPORT_MULTIARCH && multiarch != 0) {
*ret_p = seccomp_arch_add(ctx, multiarch);
if (*ret_p < 0 && *ret_p != -EEXIST) {
res = 3;
goto out;
}
}
}
buf = hakurei_scmp_allocate(allocate_p, len);
if (buf == NULL) {
res = 4;
goto out;
for (i = 0; i < rules_sz; i++) {
rule = &rules[i];
assert(rule->m_errno == EPERM || rule->m_errno == ENOSYS);
if (rule->arg)
*ret_p = seccomp_rule_add(ctx, SCMP_ACT_ERRNO(rule->m_errno), rule->syscall, 1, *rule->arg);
else
*ret_p = seccomp_rule_add(ctx, SCMP_ACT_ERRNO(rule->m_errno), rule->syscall, 0);
if (*ret_p == -EFAULT) {
res = 4;
goto out;
} else if (*ret_p < 0) {
res = 5;
goto out;
}
}
*ret_p = seccomp_export_bpf_mem(ctx, buf, &len);
if (*ret_p != 0) {
res = 6;
goto out;
/* Socket filtering doesn't work on e.g. i386, so ignore failures here
* However, we need to user seccomp_rule_add_exact to avoid libseccomp doing
* something else: https://github.com/seccomp/libseccomp/issues/8 */
last_allowed_family = -1;
for (i = 0; i < LEN(socket_family_allowlist); i++) {
if (socket_family_allowlist[i].flags_mask != 0 &&
(socket_family_allowlist[i].flags_mask & flags) != socket_family_allowlist[i].flags_mask)
continue;
for (disallowed = last_allowed_family + 1; disallowed < socket_family_allowlist[i].family; disallowed++) {
/* Blocklist the in-between valid families */
seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EAFNOSUPPORT), SCMP_SYS(socket), 1, SCMP_A0(SCMP_CMP_EQ, disallowed));
}
last_allowed_family = socket_family_allowlist[i].family;
}
/* Blocklist the rest */
seccomp_rule_add_exact(ctx, SCMP_ACT_ERRNO(EAFNOSUPPORT), SCMP_SYS(socket), 1, SCMP_A0(SCMP_CMP_GE, last_allowed_family + 1));
if (allocate_p == 0) {
*ret_p = seccomp_load(ctx);
if (*ret_p != 0) {
res = 7;
goto out;
}
} else {
*ret_p = seccomp_export_bpf_mem(ctx, NULL, &len);
if (*ret_p != 0) {
res = 6;
goto out;
}
buf = hakurei_scmp_allocate(allocate_p, len);
if (buf == NULL) {
res = 4;
goto out;
}
*ret_p = seccomp_export_bpf_mem(ctx, buf, &len);
if (*ret_p != 0) {
res = 6;
goto out;
}
}
}
out:
if (ctx)
seccomp_release(ctx);
if (ctx)
seccomp_release(ctx);
return res;
return res;
}

View File

@@ -1,25 +1,26 @@
#include <seccomp.h>
#include <stdint.h>
#if (SCMP_VER_MAJOR < 2) || (SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 5) || \
#if (SCMP_VER_MAJOR < 2) || (SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR < 5) || \
(SCMP_VER_MAJOR == 2 && SCMP_VER_MINOR == 5 && SCMP_VER_MICRO < 1)
#error This package requires libseccomp >= v2.5.1
#endif
typedef enum {
HAKUREI_EXPORT_MULTIARCH = 1 << 0,
HAKUREI_EXPORT_CAN = 1 << 1,
HAKUREI_EXPORT_BLUETOOTH = 1 << 2,
HAKUREI_EXPORT_MULTIARCH = 1 << 0,
HAKUREI_EXPORT_CAN = 1 << 1,
HAKUREI_EXPORT_BLUETOOTH = 1 << 2,
} hakurei_export_flag;
struct hakurei_syscall_rule {
int syscall;
int m_errno;
struct scmp_arg_cmp *arg;
int syscall;
int m_errno;
struct scmp_arg_cmp *arg;
};
extern void *hakurei_scmp_allocate(uintptr_t f, size_t len);
int32_t hakurei_scmp_make_filter(int *ret_p, uintptr_t allocate_p,
uint32_t arch, uint32_t multiarch,
struct hakurei_syscall_rule *rules,
size_t rules_sz, hakurei_export_flag flags);
int32_t hakurei_scmp_make_filter(
int *ret_p, uintptr_t allocate_p,
uint32_t arch, uint32_t multiarch,
struct hakurei_syscall_rule *rules,
size_t rules_sz, hakurei_export_flag flags);

View File

@@ -0,0 +1,27 @@
package seccomp_test
import (
. "hakurei.app/container/seccomp"
. "hakurei.app/container/std"
)
var bpfExpected = bpfLookup{
{AllowMultiarch | AllowCAN |
AllowBluetooth, PresetExt |
PresetDenyNS | PresetDenyTTY | PresetDenyDevel |
PresetLinux32}: toHash(
"a1c4ffa35f4bfbf38061184760b9a09edfcb4964c3b534395e47327b83f3fb61f2f9573ddfcc4772424cc2f5dd12fd32471e6531dbe10e85eda3797dd4fa179f"),
{0, 0}: toHash(
"f3910fd727d087def593e3876c2c6ab9ace71d82ec8cbc992a26223e7bba85e1d7a0b56c5fc6303703f24595825dad8561637edaedd5384b34a6cd080946633c"),
{0, PresetExt}: toHash(
"741438c5e3f11c36c92ae8c5934f13440675c6e719541c2dbffeda79a10081bcfd9ad8314a60c1d1f53db86c8080c13fffa3bbcf7fe753935679b4b902737286"),
{0, PresetStrict}: toHash(
"79e9e464d02405c6d74fd2c771bd72a1311e488221c73a9c32db9270219837c54fccec2f36fe2474895547e60c311514567e2e6cf4e7a7fcf909c1ecd1e254a7"),
{0, PresetDenyNS | PresetDenyTTY | PresetDenyDevel}: toHash(
"3c443715a6c1e557a284862ea8efb70a5d4ecbe67d1226627323e861cd3646fb3e7768ec5b94b93760b7f652cf6916f66e317a4fbf8716d10c3673aa4fc3ae58"),
{0, PresetExt | PresetDenyDevel}: toHash(
"4448a74e8cc75a4ab63799c4f2cc2a5af63e5f4e8e9b8ac15a1873d647dfa67a4c67b39ed466d8dd32abc64136d401879fc6185c9ab00feeaf59ccf4305f8201"),
{0, PresetExt | PresetDenyNS | PresetDenyDevel}: toHash(
"c7c86e793cb7192f5f6c735f372cda27eb43ae1045e587f8eadb64c849520a3280b6570a3d7b601d32cddb38021585a2234db38e506cebfd10aa3d6c75440f17"),
}

View File

@@ -12,6 +12,7 @@ my %syscall_cutoff_arch = (
"x86" => 340,
"x86_64" => 302,
"aarch64" => 281,
"riscv64" => 281,
);
print <<EOF;

View File

@@ -0,0 +1,55 @@
package std
import "syscall"
const (
SYS_NEWFSTATAT = syscall.SYS_FSTATAT
)
var syscallNumExtra = map[string]ScmpSyscall{
"uselib": SNR_USELIB,
"clock_adjtime64": SNR_CLOCK_ADJTIME64,
"clock_settime64": SNR_CLOCK_SETTIME64,
"umount": SNR_UMOUNT,
"chown": SNR_CHOWN,
"chown32": SNR_CHOWN32,
"fchown32": SNR_FCHOWN32,
"lchown": SNR_LCHOWN,
"lchown32": SNR_LCHOWN32,
"setgid32": SNR_SETGID32,
"setgroups32": SNR_SETGROUPS32,
"setregid32": SNR_SETREGID32,
"setresgid32": SNR_SETRESGID32,
"setresuid32": SNR_SETRESUID32,
"setreuid32": SNR_SETREUID32,
"setuid32": SNR_SETUID32,
"modify_ldt": SNR_MODIFY_LDT,
"subpage_prot": SNR_SUBPAGE_PROT,
"switch_endian": SNR_SWITCH_ENDIAN,
"vm86": SNR_VM86,
"vm86old": SNR_VM86OLD,
}
const (
SNR_USELIB ScmpSyscall = __PNR_uselib
SNR_CLOCK_ADJTIME64 ScmpSyscall = __PNR_clock_adjtime64
SNR_CLOCK_SETTIME64 ScmpSyscall = __PNR_clock_settime64
SNR_UMOUNT ScmpSyscall = __PNR_umount
SNR_CHOWN ScmpSyscall = __PNR_chown
SNR_CHOWN32 ScmpSyscall = __PNR_chown32
SNR_FCHOWN32 ScmpSyscall = __PNR_fchown32
SNR_LCHOWN ScmpSyscall = __PNR_lchown
SNR_LCHOWN32 ScmpSyscall = __PNR_lchown32
SNR_SETGID32 ScmpSyscall = __PNR_setgid32
SNR_SETGROUPS32 ScmpSyscall = __PNR_setgroups32
SNR_SETREGID32 ScmpSyscall = __PNR_setregid32
SNR_SETRESGID32 ScmpSyscall = __PNR_setresgid32
SNR_SETRESUID32 ScmpSyscall = __PNR_setresuid32
SNR_SETREUID32 ScmpSyscall = __PNR_setreuid32
SNR_SETUID32 ScmpSyscall = __PNR_setuid32
SNR_MODIFY_LDT ScmpSyscall = __PNR_modify_ldt
SNR_SUBPAGE_PROT ScmpSyscall = __PNR_subpage_prot
SNR_SWITCH_ENDIAN ScmpSyscall = __PNR_switch_endian
SNR_VM86 ScmpSyscall = __PNR_vm86
SNR_VM86OLD ScmpSyscall = __PNR_vm86old
)

View File

@@ -0,0 +1,719 @@
// mksysnum_linux.pl /usr/include/riscv64-linux-gnu/asm/unistd.h
// Code generated by the command above; DO NOT EDIT.
package std
import . "syscall"
var syscallNum = map[string]ScmpSyscall{
"io_setup": SNR_IO_SETUP,
"io_destroy": SNR_IO_DESTROY,
"io_submit": SNR_IO_SUBMIT,
"io_cancel": SNR_IO_CANCEL,
"io_getevents": SNR_IO_GETEVENTS,
"setxattr": SNR_SETXATTR,
"lsetxattr": SNR_LSETXATTR,
"fsetxattr": SNR_FSETXATTR,
"getxattr": SNR_GETXATTR,
"lgetxattr": SNR_LGETXATTR,
"fgetxattr": SNR_FGETXATTR,
"listxattr": SNR_LISTXATTR,
"llistxattr": SNR_LLISTXATTR,
"flistxattr": SNR_FLISTXATTR,
"removexattr": SNR_REMOVEXATTR,
"lremovexattr": SNR_LREMOVEXATTR,
"fremovexattr": SNR_FREMOVEXATTR,
"getcwd": SNR_GETCWD,
"lookup_dcookie": SNR_LOOKUP_DCOOKIE,
"eventfd2": SNR_EVENTFD2,
"epoll_create1": SNR_EPOLL_CREATE1,
"epoll_ctl": SNR_EPOLL_CTL,
"epoll_pwait": SNR_EPOLL_PWAIT,
"dup": SNR_DUP,
"dup3": SNR_DUP3,
"fcntl": SNR_FCNTL,
"inotify_init1": SNR_INOTIFY_INIT1,
"inotify_add_watch": SNR_INOTIFY_ADD_WATCH,
"inotify_rm_watch": SNR_INOTIFY_RM_WATCH,
"ioctl": SNR_IOCTL,
"ioprio_set": SNR_IOPRIO_SET,
"ioprio_get": SNR_IOPRIO_GET,
"flock": SNR_FLOCK,
"mknodat": SNR_MKNODAT,
"mkdirat": SNR_MKDIRAT,
"unlinkat": SNR_UNLINKAT,
"symlinkat": SNR_SYMLINKAT,
"linkat": SNR_LINKAT,
"umount2": SNR_UMOUNT2,
"mount": SNR_MOUNT,
"pivot_root": SNR_PIVOT_ROOT,
"nfsservctl": SNR_NFSSERVCTL,
"statfs": SNR_STATFS,
"fstatfs": SNR_FSTATFS,
"truncate": SNR_TRUNCATE,
"ftruncate": SNR_FTRUNCATE,
"fallocate": SNR_FALLOCATE,
"faccessat": SNR_FACCESSAT,
"chdir": SNR_CHDIR,
"fchdir": SNR_FCHDIR,
"chroot": SNR_CHROOT,
"fchmod": SNR_FCHMOD,
"fchmodat": SNR_FCHMODAT,
"fchownat": SNR_FCHOWNAT,
"fchown": SNR_FCHOWN,
"openat": SNR_OPENAT,
"close": SNR_CLOSE,
"vhangup": SNR_VHANGUP,
"pipe2": SNR_PIPE2,
"quotactl": SNR_QUOTACTL,
"getdents64": SNR_GETDENTS64,
"lseek": SNR_LSEEK,
"read": SNR_READ,
"write": SNR_WRITE,
"readv": SNR_READV,
"writev": SNR_WRITEV,
"pread64": SNR_PREAD64,
"pwrite64": SNR_PWRITE64,
"preadv": SNR_PREADV,
"pwritev": SNR_PWRITEV,
"sendfile": SNR_SENDFILE,
"pselect6": SNR_PSELECT6,
"ppoll": SNR_PPOLL,
"signalfd4": SNR_SIGNALFD4,
"vmsplice": SNR_VMSPLICE,
"splice": SNR_SPLICE,
"tee": SNR_TEE,
"readlinkat": SNR_READLINKAT,
"newfstatat": SNR_NEWFSTATAT,
"fstat": SNR_FSTAT,
"sync": SNR_SYNC,
"fsync": SNR_FSYNC,
"fdatasync": SNR_FDATASYNC,
"sync_file_range": SNR_SYNC_FILE_RANGE,
"timerfd_create": SNR_TIMERFD_CREATE,
"timerfd_settime": SNR_TIMERFD_SETTIME,
"timerfd_gettime": SNR_TIMERFD_GETTIME,
"utimensat": SNR_UTIMENSAT,
"acct": SNR_ACCT,
"capget": SNR_CAPGET,
"capset": SNR_CAPSET,
"personality": SNR_PERSONALITY,
"exit": SNR_EXIT,
"exit_group": SNR_EXIT_GROUP,
"waitid": SNR_WAITID,
"set_tid_address": SNR_SET_TID_ADDRESS,
"unshare": SNR_UNSHARE,
"futex": SNR_FUTEX,
"set_robust_list": SNR_SET_ROBUST_LIST,
"get_robust_list": SNR_GET_ROBUST_LIST,
"nanosleep": SNR_NANOSLEEP,
"getitimer": SNR_GETITIMER,
"setitimer": SNR_SETITIMER,
"kexec_load": SNR_KEXEC_LOAD,
"init_module": SNR_INIT_MODULE,
"delete_module": SNR_DELETE_MODULE,
"timer_create": SNR_TIMER_CREATE,
"timer_gettime": SNR_TIMER_GETTIME,
"timer_getoverrun": SNR_TIMER_GETOVERRUN,
"timer_settime": SNR_TIMER_SETTIME,
"timer_delete": SNR_TIMER_DELETE,
"clock_settime": SNR_CLOCK_SETTIME,
"clock_gettime": SNR_CLOCK_GETTIME,
"clock_getres": SNR_CLOCK_GETRES,
"clock_nanosleep": SNR_CLOCK_NANOSLEEP,
"syslog": SNR_SYSLOG,
"ptrace": SNR_PTRACE,
"sched_setparam": SNR_SCHED_SETPARAM,
"sched_setscheduler": SNR_SCHED_SETSCHEDULER,
"sched_getscheduler": SNR_SCHED_GETSCHEDULER,
"sched_getparam": SNR_SCHED_GETPARAM,
"sched_setaffinity": SNR_SCHED_SETAFFINITY,
"sched_getaffinity": SNR_SCHED_GETAFFINITY,
"sched_yield": SNR_SCHED_YIELD,
"sched_get_priority_max": SNR_SCHED_GET_PRIORITY_MAX,
"sched_get_priority_min": SNR_SCHED_GET_PRIORITY_MIN,
"sched_rr_get_interval": SNR_SCHED_RR_GET_INTERVAL,
"restart_syscall": SNR_RESTART_SYSCALL,
"kill": SNR_KILL,
"tkill": SNR_TKILL,
"tgkill": SNR_TGKILL,
"sigaltstack": SNR_SIGALTSTACK,
"rt_sigsuspend": SNR_RT_SIGSUSPEND,
"rt_sigaction": SNR_RT_SIGACTION,
"rt_sigprocmask": SNR_RT_SIGPROCMASK,
"rt_sigpending": SNR_RT_SIGPENDING,
"rt_sigtimedwait": SNR_RT_SIGTIMEDWAIT,
"rt_sigqueueinfo": SNR_RT_SIGQUEUEINFO,
"rt_sigreturn": SNR_RT_SIGRETURN,
"setpriority": SNR_SETPRIORITY,
"getpriority": SNR_GETPRIORITY,
"reboot": SNR_REBOOT,
"setregid": SNR_SETREGID,
"setgid": SNR_SETGID,
"setreuid": SNR_SETREUID,
"setuid": SNR_SETUID,
"setresuid": SNR_SETRESUID,
"getresuid": SNR_GETRESUID,
"setresgid": SNR_SETRESGID,
"getresgid": SNR_GETRESGID,
"setfsuid": SNR_SETFSUID,
"setfsgid": SNR_SETFSGID,
"times": SNR_TIMES,
"setpgid": SNR_SETPGID,
"getpgid": SNR_GETPGID,
"getsid": SNR_GETSID,
"setsid": SNR_SETSID,
"getgroups": SNR_GETGROUPS,
"setgroups": SNR_SETGROUPS,
"uname": SNR_UNAME,
"sethostname": SNR_SETHOSTNAME,
"setdomainname": SNR_SETDOMAINNAME,
"getrlimit": SNR_GETRLIMIT,
"setrlimit": SNR_SETRLIMIT,
"getrusage": SNR_GETRUSAGE,
"umask": SNR_UMASK,
"prctl": SNR_PRCTL,
"getcpu": SNR_GETCPU,
"gettimeofday": SNR_GETTIMEOFDAY,
"settimeofday": SNR_SETTIMEOFDAY,
"adjtimex": SNR_ADJTIMEX,
"getpid": SNR_GETPID,
"getppid": SNR_GETPPID,
"getuid": SNR_GETUID,
"geteuid": SNR_GETEUID,
"getgid": SNR_GETGID,
"getegid": SNR_GETEGID,
"gettid": SNR_GETTID,
"sysinfo": SNR_SYSINFO,
"mq_open": SNR_MQ_OPEN,
"mq_unlink": SNR_MQ_UNLINK,
"mq_timedsend": SNR_MQ_TIMEDSEND,
"mq_timedreceive": SNR_MQ_TIMEDRECEIVE,
"mq_notify": SNR_MQ_NOTIFY,
"mq_getsetattr": SNR_MQ_GETSETATTR,
"msgget": SNR_MSGGET,
"msgctl": SNR_MSGCTL,
"msgrcv": SNR_MSGRCV,
"msgsnd": SNR_MSGSND,
"semget": SNR_SEMGET,
"semctl": SNR_SEMCTL,
"semtimedop": SNR_SEMTIMEDOP,
"semop": SNR_SEMOP,
"shmget": SNR_SHMGET,
"shmctl": SNR_SHMCTL,
"shmat": SNR_SHMAT,
"shmdt": SNR_SHMDT,
"socket": SNR_SOCKET,
"socketpair": SNR_SOCKETPAIR,
"bind": SNR_BIND,
"listen": SNR_LISTEN,
"accept": SNR_ACCEPT,
"connect": SNR_CONNECT,
"getsockname": SNR_GETSOCKNAME,
"getpeername": SNR_GETPEERNAME,
"sendto": SNR_SENDTO,
"recvfrom": SNR_RECVFROM,
"setsockopt": SNR_SETSOCKOPT,
"getsockopt": SNR_GETSOCKOPT,
"shutdown": SNR_SHUTDOWN,
"sendmsg": SNR_SENDMSG,
"recvmsg": SNR_RECVMSG,
"readahead": SNR_READAHEAD,
"brk": SNR_BRK,
"munmap": SNR_MUNMAP,
"mremap": SNR_MREMAP,
"add_key": SNR_ADD_KEY,
"request_key": SNR_REQUEST_KEY,
"keyctl": SNR_KEYCTL,
"clone": SNR_CLONE,
"execve": SNR_EXECVE,
"mmap": SNR_MMAP,
"fadvise64": SNR_FADVISE64,
"swapon": SNR_SWAPON,
"swapoff": SNR_SWAPOFF,
"mprotect": SNR_MPROTECT,
"msync": SNR_MSYNC,
"mlock": SNR_MLOCK,
"munlock": SNR_MUNLOCK,
"mlockall": SNR_MLOCKALL,
"munlockall": SNR_MUNLOCKALL,
"mincore": SNR_MINCORE,
"madvise": SNR_MADVISE,
"remap_file_pages": SNR_REMAP_FILE_PAGES,
"mbind": SNR_MBIND,
"get_mempolicy": SNR_GET_MEMPOLICY,
"set_mempolicy": SNR_SET_MEMPOLICY,
"migrate_pages": SNR_MIGRATE_PAGES,
"move_pages": SNR_MOVE_PAGES,
"rt_tgsigqueueinfo": SNR_RT_TGSIGQUEUEINFO,
"perf_event_open": SNR_PERF_EVENT_OPEN,
"accept4": SNR_ACCEPT4,
"recvmmsg": SNR_RECVMMSG,
"wait4": SNR_WAIT4,
"prlimit64": SNR_PRLIMIT64,
"fanotify_init": SNR_FANOTIFY_INIT,
"fanotify_mark": SNR_FANOTIFY_MARK,
"name_to_handle_at": SNR_NAME_TO_HANDLE_AT,
"open_by_handle_at": SNR_OPEN_BY_HANDLE_AT,
"clock_adjtime": SNR_CLOCK_ADJTIME,
"syncfs": SNR_SYNCFS,
"setns": SNR_SETNS,
"sendmmsg": SNR_SENDMMSG,
"process_vm_readv": SNR_PROCESS_VM_READV,
"process_vm_writev": SNR_PROCESS_VM_WRITEV,
"kcmp": SNR_KCMP,
"finit_module": SNR_FINIT_MODULE,
"sched_setattr": SNR_SCHED_SETATTR,
"sched_getattr": SNR_SCHED_GETATTR,
"renameat2": SNR_RENAMEAT2,
"seccomp": SNR_SECCOMP,
"getrandom": SNR_GETRANDOM,
"memfd_create": SNR_MEMFD_CREATE,
"bpf": SNR_BPF,
"execveat": SNR_EXECVEAT,
"userfaultfd": SNR_USERFAULTFD,
"membarrier": SNR_MEMBARRIER,
"mlock2": SNR_MLOCK2,
"copy_file_range": SNR_COPY_FILE_RANGE,
"preadv2": SNR_PREADV2,
"pwritev2": SNR_PWRITEV2,
"pkey_mprotect": SNR_PKEY_MPROTECT,
"pkey_alloc": SNR_PKEY_ALLOC,
"pkey_free": SNR_PKEY_FREE,
"statx": SNR_STATX,
"io_pgetevents": SNR_IO_PGETEVENTS,
"rseq": SNR_RSEQ,
"kexec_file_load": SNR_KEXEC_FILE_LOAD,
"pidfd_send_signal": SNR_PIDFD_SEND_SIGNAL,
"io_uring_setup": SNR_IO_URING_SETUP,
"io_uring_enter": SNR_IO_URING_ENTER,
"io_uring_register": SNR_IO_URING_REGISTER,
"open_tree": SNR_OPEN_TREE,
"move_mount": SNR_MOVE_MOUNT,
"fsopen": SNR_FSOPEN,
"fsconfig": SNR_FSCONFIG,
"fsmount": SNR_FSMOUNT,
"fspick": SNR_FSPICK,
"pidfd_open": SNR_PIDFD_OPEN,
"clone3": SNR_CLONE3,
"close_range": SNR_CLOSE_RANGE,
"openat2": SNR_OPENAT2,
"pidfd_getfd": SNR_PIDFD_GETFD,
"faccessat2": SNR_FACCESSAT2,
"process_madvise": SNR_PROCESS_MADVISE,
"epoll_pwait2": SNR_EPOLL_PWAIT2,
"mount_setattr": SNR_MOUNT_SETATTR,
"quotactl_fd": SNR_QUOTACTL_FD,
"landlock_create_ruleset": SNR_LANDLOCK_CREATE_RULESET,
"landlock_add_rule": SNR_LANDLOCK_ADD_RULE,
"landlock_restrict_self": SNR_LANDLOCK_RESTRICT_SELF,
"memfd_secret": SNR_MEMFD_SECRET,
"process_mrelease": SNR_PROCESS_MRELEASE,
"futex_waitv": SNR_FUTEX_WAITV,
"set_mempolicy_home_node": SNR_SET_MEMPOLICY_HOME_NODE,
"cachestat": SNR_CACHESTAT,
"fchmodat2": SNR_FCHMODAT2,
"map_shadow_stack": SNR_MAP_SHADOW_STACK,
"futex_wake": SNR_FUTEX_WAKE,
"futex_wait": SNR_FUTEX_WAIT,
"futex_requeue": SNR_FUTEX_REQUEUE,
"statmount": SNR_STATMOUNT,
"listmount": SNR_LISTMOUNT,
"lsm_get_self_attr": SNR_LSM_GET_SELF_ATTR,
"lsm_set_self_attr": SNR_LSM_SET_SELF_ATTR,
"lsm_list_modules": SNR_LSM_LIST_MODULES,
"mseal": SNR_MSEAL,
"setxattrat": SNR_SETXATTRAT,
"getxattrat": SNR_GETXATTRAT,
"listxattrat": SNR_LISTXATTRAT,
"removexattrat": SNR_REMOVEXATTRAT,
}
const (
SYS_USERFAULTFD = 282
SYS_MEMBARRIER = 283
SYS_MLOCK2 = 284
SYS_COPY_FILE_RANGE = 285
SYS_PREADV2 = 286
SYS_PWRITEV2 = 287
SYS_PKEY_MPROTECT = 288
SYS_PKEY_ALLOC = 289
SYS_PKEY_FREE = 290
SYS_STATX = 291
SYS_IO_PGETEVENTS = 292
SYS_RSEQ = 293
SYS_KEXEC_FILE_LOAD = 294
SYS_PIDFD_SEND_SIGNAL = 424
SYS_IO_URING_SETUP = 425
SYS_IO_URING_ENTER = 426
SYS_IO_URING_REGISTER = 427
SYS_OPEN_TREE = 428
SYS_MOVE_MOUNT = 429
SYS_FSOPEN = 430
SYS_FSCONFIG = 431
SYS_FSMOUNT = 432
SYS_FSPICK = 433
SYS_PIDFD_OPEN = 434
SYS_CLONE3 = 435
SYS_CLOSE_RANGE = 436
SYS_OPENAT2 = 437
SYS_PIDFD_GETFD = 438
SYS_FACCESSAT2 = 439
SYS_PROCESS_MADVISE = 440
SYS_EPOLL_PWAIT2 = 441
SYS_MOUNT_SETATTR = 442
SYS_QUOTACTL_FD = 443
SYS_LANDLOCK_CREATE_RULESET = 444
SYS_LANDLOCK_ADD_RULE = 445
SYS_LANDLOCK_RESTRICT_SELF = 446
SYS_MEMFD_SECRET = 447
SYS_PROCESS_MRELEASE = 448
SYS_FUTEX_WAITV = 449
SYS_SET_MEMPOLICY_HOME_NODE = 450
SYS_CACHESTAT = 451
SYS_FCHMODAT2 = 452
SYS_MAP_SHADOW_STACK = 453
SYS_FUTEX_WAKE = 454
SYS_FUTEX_WAIT = 455
SYS_FUTEX_REQUEUE = 456
SYS_STATMOUNT = 457
SYS_LISTMOUNT = 458
SYS_LSM_GET_SELF_ATTR = 459
SYS_LSM_SET_SELF_ATTR = 460
SYS_LSM_LIST_MODULES = 461
SYS_MSEAL = 462
SYS_SETXATTRAT = 463
SYS_GETXATTRAT = 464
SYS_LISTXATTRAT = 465
SYS_REMOVEXATTRAT = 466
SYS_OPEN_TREE_ATTR = 467
SYS_FILE_GETATTR = 468
SYS_FILE_SETATTR = 469
)
const (
SNR_IO_SETUP ScmpSyscall = SYS_IO_SETUP
SNR_IO_DESTROY ScmpSyscall = SYS_IO_DESTROY
SNR_IO_SUBMIT ScmpSyscall = SYS_IO_SUBMIT
SNR_IO_CANCEL ScmpSyscall = SYS_IO_CANCEL
SNR_IO_GETEVENTS ScmpSyscall = SYS_IO_GETEVENTS
SNR_SETXATTR ScmpSyscall = SYS_SETXATTR
SNR_LSETXATTR ScmpSyscall = SYS_LSETXATTR
SNR_FSETXATTR ScmpSyscall = SYS_FSETXATTR
SNR_GETXATTR ScmpSyscall = SYS_GETXATTR
SNR_LGETXATTR ScmpSyscall = SYS_LGETXATTR
SNR_FGETXATTR ScmpSyscall = SYS_FGETXATTR
SNR_LISTXATTR ScmpSyscall = SYS_LISTXATTR
SNR_LLISTXATTR ScmpSyscall = SYS_LLISTXATTR
SNR_FLISTXATTR ScmpSyscall = SYS_FLISTXATTR
SNR_REMOVEXATTR ScmpSyscall = SYS_REMOVEXATTR
SNR_LREMOVEXATTR ScmpSyscall = SYS_LREMOVEXATTR
SNR_FREMOVEXATTR ScmpSyscall = SYS_FREMOVEXATTR
SNR_GETCWD ScmpSyscall = SYS_GETCWD
SNR_LOOKUP_DCOOKIE ScmpSyscall = SYS_LOOKUP_DCOOKIE
SNR_EVENTFD2 ScmpSyscall = SYS_EVENTFD2
SNR_EPOLL_CREATE1 ScmpSyscall = SYS_EPOLL_CREATE1
SNR_EPOLL_CTL ScmpSyscall = SYS_EPOLL_CTL
SNR_EPOLL_PWAIT ScmpSyscall = SYS_EPOLL_PWAIT
SNR_DUP ScmpSyscall = SYS_DUP
SNR_DUP3 ScmpSyscall = SYS_DUP3
SNR_FCNTL ScmpSyscall = SYS_FCNTL
SNR_INOTIFY_INIT1 ScmpSyscall = SYS_INOTIFY_INIT1
SNR_INOTIFY_ADD_WATCH ScmpSyscall = SYS_INOTIFY_ADD_WATCH
SNR_INOTIFY_RM_WATCH ScmpSyscall = SYS_INOTIFY_RM_WATCH
SNR_IOCTL ScmpSyscall = SYS_IOCTL
SNR_IOPRIO_SET ScmpSyscall = SYS_IOPRIO_SET
SNR_IOPRIO_GET ScmpSyscall = SYS_IOPRIO_GET
SNR_FLOCK ScmpSyscall = SYS_FLOCK
SNR_MKNODAT ScmpSyscall = SYS_MKNODAT
SNR_MKDIRAT ScmpSyscall = SYS_MKDIRAT
SNR_UNLINKAT ScmpSyscall = SYS_UNLINKAT
SNR_SYMLINKAT ScmpSyscall = SYS_SYMLINKAT
SNR_LINKAT ScmpSyscall = SYS_LINKAT
SNR_UMOUNT2 ScmpSyscall = SYS_UMOUNT2
SNR_MOUNT ScmpSyscall = SYS_MOUNT
SNR_PIVOT_ROOT ScmpSyscall = SYS_PIVOT_ROOT
SNR_NFSSERVCTL ScmpSyscall = SYS_NFSSERVCTL
SNR_STATFS ScmpSyscall = SYS_STATFS
SNR_FSTATFS ScmpSyscall = SYS_FSTATFS
SNR_TRUNCATE ScmpSyscall = SYS_TRUNCATE
SNR_FTRUNCATE ScmpSyscall = SYS_FTRUNCATE
SNR_FALLOCATE ScmpSyscall = SYS_FALLOCATE
SNR_FACCESSAT ScmpSyscall = SYS_FACCESSAT
SNR_CHDIR ScmpSyscall = SYS_CHDIR
SNR_FCHDIR ScmpSyscall = SYS_FCHDIR
SNR_CHROOT ScmpSyscall = SYS_CHROOT
SNR_FCHMOD ScmpSyscall = SYS_FCHMOD
SNR_FCHMODAT ScmpSyscall = SYS_FCHMODAT
SNR_FCHOWNAT ScmpSyscall = SYS_FCHOWNAT
SNR_FCHOWN ScmpSyscall = SYS_FCHOWN
SNR_OPENAT ScmpSyscall = SYS_OPENAT
SNR_CLOSE ScmpSyscall = SYS_CLOSE
SNR_VHANGUP ScmpSyscall = SYS_VHANGUP
SNR_PIPE2 ScmpSyscall = SYS_PIPE2
SNR_QUOTACTL ScmpSyscall = SYS_QUOTACTL
SNR_GETDENTS64 ScmpSyscall = SYS_GETDENTS64
SNR_LSEEK ScmpSyscall = SYS_LSEEK
SNR_READ ScmpSyscall = SYS_READ
SNR_WRITE ScmpSyscall = SYS_WRITE
SNR_READV ScmpSyscall = SYS_READV
SNR_WRITEV ScmpSyscall = SYS_WRITEV
SNR_PREAD64 ScmpSyscall = SYS_PREAD64
SNR_PWRITE64 ScmpSyscall = SYS_PWRITE64
SNR_PREADV ScmpSyscall = SYS_PREADV
SNR_PWRITEV ScmpSyscall = SYS_PWRITEV
SNR_SENDFILE ScmpSyscall = SYS_SENDFILE
SNR_PSELECT6 ScmpSyscall = SYS_PSELECT6
SNR_PPOLL ScmpSyscall = SYS_PPOLL
SNR_SIGNALFD4 ScmpSyscall = SYS_SIGNALFD4
SNR_VMSPLICE ScmpSyscall = SYS_VMSPLICE
SNR_SPLICE ScmpSyscall = SYS_SPLICE
SNR_TEE ScmpSyscall = SYS_TEE
SNR_READLINKAT ScmpSyscall = SYS_READLINKAT
SNR_NEWFSTATAT ScmpSyscall = SYS_NEWFSTATAT
SNR_FSTAT ScmpSyscall = SYS_FSTAT
SNR_SYNC ScmpSyscall = SYS_SYNC
SNR_FSYNC ScmpSyscall = SYS_FSYNC
SNR_FDATASYNC ScmpSyscall = SYS_FDATASYNC
SNR_SYNC_FILE_RANGE ScmpSyscall = SYS_SYNC_FILE_RANGE
SNR_TIMERFD_CREATE ScmpSyscall = SYS_TIMERFD_CREATE
SNR_TIMERFD_SETTIME ScmpSyscall = SYS_TIMERFD_SETTIME
SNR_TIMERFD_GETTIME ScmpSyscall = SYS_TIMERFD_GETTIME
SNR_UTIMENSAT ScmpSyscall = SYS_UTIMENSAT
SNR_ACCT ScmpSyscall = SYS_ACCT
SNR_CAPGET ScmpSyscall = SYS_CAPGET
SNR_CAPSET ScmpSyscall = SYS_CAPSET
SNR_PERSONALITY ScmpSyscall = SYS_PERSONALITY
SNR_EXIT ScmpSyscall = SYS_EXIT
SNR_EXIT_GROUP ScmpSyscall = SYS_EXIT_GROUP
SNR_WAITID ScmpSyscall = SYS_WAITID
SNR_SET_TID_ADDRESS ScmpSyscall = SYS_SET_TID_ADDRESS
SNR_UNSHARE ScmpSyscall = SYS_UNSHARE
SNR_FUTEX ScmpSyscall = SYS_FUTEX
SNR_SET_ROBUST_LIST ScmpSyscall = SYS_SET_ROBUST_LIST
SNR_GET_ROBUST_LIST ScmpSyscall = SYS_GET_ROBUST_LIST
SNR_NANOSLEEP ScmpSyscall = SYS_NANOSLEEP
SNR_GETITIMER ScmpSyscall = SYS_GETITIMER
SNR_SETITIMER ScmpSyscall = SYS_SETITIMER
SNR_KEXEC_LOAD ScmpSyscall = SYS_KEXEC_LOAD
SNR_INIT_MODULE ScmpSyscall = SYS_INIT_MODULE
SNR_DELETE_MODULE ScmpSyscall = SYS_DELETE_MODULE
SNR_TIMER_CREATE ScmpSyscall = SYS_TIMER_CREATE
SNR_TIMER_GETTIME ScmpSyscall = SYS_TIMER_GETTIME
SNR_TIMER_GETOVERRUN ScmpSyscall = SYS_TIMER_GETOVERRUN
SNR_TIMER_SETTIME ScmpSyscall = SYS_TIMER_SETTIME
SNR_TIMER_DELETE ScmpSyscall = SYS_TIMER_DELETE
SNR_CLOCK_SETTIME ScmpSyscall = SYS_CLOCK_SETTIME
SNR_CLOCK_GETTIME ScmpSyscall = SYS_CLOCK_GETTIME
SNR_CLOCK_GETRES ScmpSyscall = SYS_CLOCK_GETRES
SNR_CLOCK_NANOSLEEP ScmpSyscall = SYS_CLOCK_NANOSLEEP
SNR_SYSLOG ScmpSyscall = SYS_SYSLOG
SNR_PTRACE ScmpSyscall = SYS_PTRACE
SNR_SCHED_SETPARAM ScmpSyscall = SYS_SCHED_SETPARAM
SNR_SCHED_SETSCHEDULER ScmpSyscall = SYS_SCHED_SETSCHEDULER
SNR_SCHED_GETSCHEDULER ScmpSyscall = SYS_SCHED_GETSCHEDULER
SNR_SCHED_GETPARAM ScmpSyscall = SYS_SCHED_GETPARAM
SNR_SCHED_SETAFFINITY ScmpSyscall = SYS_SCHED_SETAFFINITY
SNR_SCHED_GETAFFINITY ScmpSyscall = SYS_SCHED_GETAFFINITY
SNR_SCHED_YIELD ScmpSyscall = SYS_SCHED_YIELD
SNR_SCHED_GET_PRIORITY_MAX ScmpSyscall = SYS_SCHED_GET_PRIORITY_MAX
SNR_SCHED_GET_PRIORITY_MIN ScmpSyscall = SYS_SCHED_GET_PRIORITY_MIN
SNR_SCHED_RR_GET_INTERVAL ScmpSyscall = SYS_SCHED_RR_GET_INTERVAL
SNR_RESTART_SYSCALL ScmpSyscall = SYS_RESTART_SYSCALL
SNR_KILL ScmpSyscall = SYS_KILL
SNR_TKILL ScmpSyscall = SYS_TKILL
SNR_TGKILL ScmpSyscall = SYS_TGKILL
SNR_SIGALTSTACK ScmpSyscall = SYS_SIGALTSTACK
SNR_RT_SIGSUSPEND ScmpSyscall = SYS_RT_SIGSUSPEND
SNR_RT_SIGACTION ScmpSyscall = SYS_RT_SIGACTION
SNR_RT_SIGPROCMASK ScmpSyscall = SYS_RT_SIGPROCMASK
SNR_RT_SIGPENDING ScmpSyscall = SYS_RT_SIGPENDING
SNR_RT_SIGTIMEDWAIT ScmpSyscall = SYS_RT_SIGTIMEDWAIT
SNR_RT_SIGQUEUEINFO ScmpSyscall = SYS_RT_SIGQUEUEINFO
SNR_RT_SIGRETURN ScmpSyscall = SYS_RT_SIGRETURN
SNR_SETPRIORITY ScmpSyscall = SYS_SETPRIORITY
SNR_GETPRIORITY ScmpSyscall = SYS_GETPRIORITY
SNR_REBOOT ScmpSyscall = SYS_REBOOT
SNR_SETREGID ScmpSyscall = SYS_SETREGID
SNR_SETGID ScmpSyscall = SYS_SETGID
SNR_SETREUID ScmpSyscall = SYS_SETREUID
SNR_SETUID ScmpSyscall = SYS_SETUID
SNR_SETRESUID ScmpSyscall = SYS_SETRESUID
SNR_GETRESUID ScmpSyscall = SYS_GETRESUID
SNR_SETRESGID ScmpSyscall = SYS_SETRESGID
SNR_GETRESGID ScmpSyscall = SYS_GETRESGID
SNR_SETFSUID ScmpSyscall = SYS_SETFSUID
SNR_SETFSGID ScmpSyscall = SYS_SETFSGID
SNR_TIMES ScmpSyscall = SYS_TIMES
SNR_SETPGID ScmpSyscall = SYS_SETPGID
SNR_GETPGID ScmpSyscall = SYS_GETPGID
SNR_GETSID ScmpSyscall = SYS_GETSID
SNR_SETSID ScmpSyscall = SYS_SETSID
SNR_GETGROUPS ScmpSyscall = SYS_GETGROUPS
SNR_SETGROUPS ScmpSyscall = SYS_SETGROUPS
SNR_UNAME ScmpSyscall = SYS_UNAME
SNR_SETHOSTNAME ScmpSyscall = SYS_SETHOSTNAME
SNR_SETDOMAINNAME ScmpSyscall = SYS_SETDOMAINNAME
SNR_GETRLIMIT ScmpSyscall = SYS_GETRLIMIT
SNR_SETRLIMIT ScmpSyscall = SYS_SETRLIMIT
SNR_GETRUSAGE ScmpSyscall = SYS_GETRUSAGE
SNR_UMASK ScmpSyscall = SYS_UMASK
SNR_PRCTL ScmpSyscall = SYS_PRCTL
SNR_GETCPU ScmpSyscall = SYS_GETCPU
SNR_GETTIMEOFDAY ScmpSyscall = SYS_GETTIMEOFDAY
SNR_SETTIMEOFDAY ScmpSyscall = SYS_SETTIMEOFDAY
SNR_ADJTIMEX ScmpSyscall = SYS_ADJTIMEX
SNR_GETPID ScmpSyscall = SYS_GETPID
SNR_GETPPID ScmpSyscall = SYS_GETPPID
SNR_GETUID ScmpSyscall = SYS_GETUID
SNR_GETEUID ScmpSyscall = SYS_GETEUID
SNR_GETGID ScmpSyscall = SYS_GETGID
SNR_GETEGID ScmpSyscall = SYS_GETEGID
SNR_GETTID ScmpSyscall = SYS_GETTID
SNR_SYSINFO ScmpSyscall = SYS_SYSINFO
SNR_MQ_OPEN ScmpSyscall = SYS_MQ_OPEN
SNR_MQ_UNLINK ScmpSyscall = SYS_MQ_UNLINK
SNR_MQ_TIMEDSEND ScmpSyscall = SYS_MQ_TIMEDSEND
SNR_MQ_TIMEDRECEIVE ScmpSyscall = SYS_MQ_TIMEDRECEIVE
SNR_MQ_NOTIFY ScmpSyscall = SYS_MQ_NOTIFY
SNR_MQ_GETSETATTR ScmpSyscall = SYS_MQ_GETSETATTR
SNR_MSGGET ScmpSyscall = SYS_MSGGET
SNR_MSGCTL ScmpSyscall = SYS_MSGCTL
SNR_MSGRCV ScmpSyscall = SYS_MSGRCV
SNR_MSGSND ScmpSyscall = SYS_MSGSND
SNR_SEMGET ScmpSyscall = SYS_SEMGET
SNR_SEMCTL ScmpSyscall = SYS_SEMCTL
SNR_SEMTIMEDOP ScmpSyscall = SYS_SEMTIMEDOP
SNR_SEMOP ScmpSyscall = SYS_SEMOP
SNR_SHMGET ScmpSyscall = SYS_SHMGET
SNR_SHMCTL ScmpSyscall = SYS_SHMCTL
SNR_SHMAT ScmpSyscall = SYS_SHMAT
SNR_SHMDT ScmpSyscall = SYS_SHMDT
SNR_SOCKET ScmpSyscall = SYS_SOCKET
SNR_SOCKETPAIR ScmpSyscall = SYS_SOCKETPAIR
SNR_BIND ScmpSyscall = SYS_BIND
SNR_LISTEN ScmpSyscall = SYS_LISTEN
SNR_ACCEPT ScmpSyscall = SYS_ACCEPT
SNR_CONNECT ScmpSyscall = SYS_CONNECT
SNR_GETSOCKNAME ScmpSyscall = SYS_GETSOCKNAME
SNR_GETPEERNAME ScmpSyscall = SYS_GETPEERNAME
SNR_SENDTO ScmpSyscall = SYS_SENDTO
SNR_RECVFROM ScmpSyscall = SYS_RECVFROM
SNR_SETSOCKOPT ScmpSyscall = SYS_SETSOCKOPT
SNR_GETSOCKOPT ScmpSyscall = SYS_GETSOCKOPT
SNR_SHUTDOWN ScmpSyscall = SYS_SHUTDOWN
SNR_SENDMSG ScmpSyscall = SYS_SENDMSG
SNR_RECVMSG ScmpSyscall = SYS_RECVMSG
SNR_READAHEAD ScmpSyscall = SYS_READAHEAD
SNR_BRK ScmpSyscall = SYS_BRK
SNR_MUNMAP ScmpSyscall = SYS_MUNMAP
SNR_MREMAP ScmpSyscall = SYS_MREMAP
SNR_ADD_KEY ScmpSyscall = SYS_ADD_KEY
SNR_REQUEST_KEY ScmpSyscall = SYS_REQUEST_KEY
SNR_KEYCTL ScmpSyscall = SYS_KEYCTL
SNR_CLONE ScmpSyscall = SYS_CLONE
SNR_EXECVE ScmpSyscall = SYS_EXECVE
SNR_MMAP ScmpSyscall = SYS_MMAP
SNR_FADVISE64 ScmpSyscall = SYS_FADVISE64
SNR_SWAPON ScmpSyscall = SYS_SWAPON
SNR_SWAPOFF ScmpSyscall = SYS_SWAPOFF
SNR_MPROTECT ScmpSyscall = SYS_MPROTECT
SNR_MSYNC ScmpSyscall = SYS_MSYNC
SNR_MLOCK ScmpSyscall = SYS_MLOCK
SNR_MUNLOCK ScmpSyscall = SYS_MUNLOCK
SNR_MLOCKALL ScmpSyscall = SYS_MLOCKALL
SNR_MUNLOCKALL ScmpSyscall = SYS_MUNLOCKALL
SNR_MINCORE ScmpSyscall = SYS_MINCORE
SNR_MADVISE ScmpSyscall = SYS_MADVISE
SNR_REMAP_FILE_PAGES ScmpSyscall = SYS_REMAP_FILE_PAGES
SNR_MBIND ScmpSyscall = SYS_MBIND
SNR_GET_MEMPOLICY ScmpSyscall = SYS_GET_MEMPOLICY
SNR_SET_MEMPOLICY ScmpSyscall = SYS_SET_MEMPOLICY
SNR_MIGRATE_PAGES ScmpSyscall = SYS_MIGRATE_PAGES
SNR_MOVE_PAGES ScmpSyscall = SYS_MOVE_PAGES
SNR_RT_TGSIGQUEUEINFO ScmpSyscall = SYS_RT_TGSIGQUEUEINFO
SNR_PERF_EVENT_OPEN ScmpSyscall = SYS_PERF_EVENT_OPEN
SNR_ACCEPT4 ScmpSyscall = SYS_ACCEPT4
SNR_RECVMMSG ScmpSyscall = SYS_RECVMMSG
SNR_WAIT4 ScmpSyscall = SYS_WAIT4
SNR_PRLIMIT64 ScmpSyscall = SYS_PRLIMIT64
SNR_FANOTIFY_INIT ScmpSyscall = SYS_FANOTIFY_INIT
SNR_FANOTIFY_MARK ScmpSyscall = SYS_FANOTIFY_MARK
SNR_NAME_TO_HANDLE_AT ScmpSyscall = SYS_NAME_TO_HANDLE_AT
SNR_OPEN_BY_HANDLE_AT ScmpSyscall = SYS_OPEN_BY_HANDLE_AT
SNR_CLOCK_ADJTIME ScmpSyscall = SYS_CLOCK_ADJTIME
SNR_SYNCFS ScmpSyscall = SYS_SYNCFS
SNR_SETNS ScmpSyscall = SYS_SETNS
SNR_SENDMMSG ScmpSyscall = SYS_SENDMMSG
SNR_PROCESS_VM_READV ScmpSyscall = SYS_PROCESS_VM_READV
SNR_PROCESS_VM_WRITEV ScmpSyscall = SYS_PROCESS_VM_WRITEV
SNR_KCMP ScmpSyscall = SYS_KCMP
SNR_FINIT_MODULE ScmpSyscall = SYS_FINIT_MODULE
SNR_SCHED_SETATTR ScmpSyscall = SYS_SCHED_SETATTR
SNR_SCHED_GETATTR ScmpSyscall = SYS_SCHED_GETATTR
SNR_RENAMEAT2 ScmpSyscall = SYS_RENAMEAT2
SNR_SECCOMP ScmpSyscall = SYS_SECCOMP
SNR_GETRANDOM ScmpSyscall = SYS_GETRANDOM
SNR_MEMFD_CREATE ScmpSyscall = SYS_MEMFD_CREATE
SNR_BPF ScmpSyscall = SYS_BPF
SNR_EXECVEAT ScmpSyscall = SYS_EXECVEAT
SNR_USERFAULTFD ScmpSyscall = SYS_USERFAULTFD
SNR_MEMBARRIER ScmpSyscall = SYS_MEMBARRIER
SNR_MLOCK2 ScmpSyscall = SYS_MLOCK2
SNR_COPY_FILE_RANGE ScmpSyscall = SYS_COPY_FILE_RANGE
SNR_PREADV2 ScmpSyscall = SYS_PREADV2
SNR_PWRITEV2 ScmpSyscall = SYS_PWRITEV2
SNR_PKEY_MPROTECT ScmpSyscall = SYS_PKEY_MPROTECT
SNR_PKEY_ALLOC ScmpSyscall = SYS_PKEY_ALLOC
SNR_PKEY_FREE ScmpSyscall = SYS_PKEY_FREE
SNR_STATX ScmpSyscall = SYS_STATX
SNR_IO_PGETEVENTS ScmpSyscall = SYS_IO_PGETEVENTS
SNR_RSEQ ScmpSyscall = SYS_RSEQ
SNR_KEXEC_FILE_LOAD ScmpSyscall = SYS_KEXEC_FILE_LOAD
SNR_PIDFD_SEND_SIGNAL ScmpSyscall = SYS_PIDFD_SEND_SIGNAL
SNR_IO_URING_SETUP ScmpSyscall = SYS_IO_URING_SETUP
SNR_IO_URING_ENTER ScmpSyscall = SYS_IO_URING_ENTER
SNR_IO_URING_REGISTER ScmpSyscall = SYS_IO_URING_REGISTER
SNR_OPEN_TREE ScmpSyscall = SYS_OPEN_TREE
SNR_MOVE_MOUNT ScmpSyscall = SYS_MOVE_MOUNT
SNR_FSOPEN ScmpSyscall = SYS_FSOPEN
SNR_FSCONFIG ScmpSyscall = SYS_FSCONFIG
SNR_FSMOUNT ScmpSyscall = SYS_FSMOUNT
SNR_FSPICK ScmpSyscall = SYS_FSPICK
SNR_PIDFD_OPEN ScmpSyscall = SYS_PIDFD_OPEN
SNR_CLONE3 ScmpSyscall = SYS_CLONE3
SNR_CLOSE_RANGE ScmpSyscall = SYS_CLOSE_RANGE
SNR_OPENAT2 ScmpSyscall = SYS_OPENAT2
SNR_PIDFD_GETFD ScmpSyscall = SYS_PIDFD_GETFD
SNR_FACCESSAT2 ScmpSyscall = SYS_FACCESSAT2
SNR_PROCESS_MADVISE ScmpSyscall = SYS_PROCESS_MADVISE
SNR_EPOLL_PWAIT2 ScmpSyscall = SYS_EPOLL_PWAIT2
SNR_MOUNT_SETATTR ScmpSyscall = SYS_MOUNT_SETATTR
SNR_QUOTACTL_FD ScmpSyscall = SYS_QUOTACTL_FD
SNR_LANDLOCK_CREATE_RULESET ScmpSyscall = SYS_LANDLOCK_CREATE_RULESET
SNR_LANDLOCK_ADD_RULE ScmpSyscall = SYS_LANDLOCK_ADD_RULE
SNR_LANDLOCK_RESTRICT_SELF ScmpSyscall = SYS_LANDLOCK_RESTRICT_SELF
SNR_MEMFD_SECRET ScmpSyscall = SYS_MEMFD_SECRET
SNR_PROCESS_MRELEASE ScmpSyscall = SYS_PROCESS_MRELEASE
SNR_FUTEX_WAITV ScmpSyscall = SYS_FUTEX_WAITV
SNR_SET_MEMPOLICY_HOME_NODE ScmpSyscall = SYS_SET_MEMPOLICY_HOME_NODE
SNR_CACHESTAT ScmpSyscall = SYS_CACHESTAT
SNR_FCHMODAT2 ScmpSyscall = SYS_FCHMODAT2
SNR_MAP_SHADOW_STACK ScmpSyscall = SYS_MAP_SHADOW_STACK
SNR_FUTEX_WAKE ScmpSyscall = SYS_FUTEX_WAKE
SNR_FUTEX_WAIT ScmpSyscall = SYS_FUTEX_WAIT
SNR_FUTEX_REQUEUE ScmpSyscall = SYS_FUTEX_REQUEUE
SNR_STATMOUNT ScmpSyscall = SYS_STATMOUNT
SNR_LISTMOUNT ScmpSyscall = SYS_LISTMOUNT
SNR_LSM_GET_SELF_ATTR ScmpSyscall = SYS_LSM_GET_SELF_ATTR
SNR_LSM_SET_SELF_ATTR ScmpSyscall = SYS_LSM_SET_SELF_ATTR
SNR_LSM_LIST_MODULES ScmpSyscall = SYS_LSM_LIST_MODULES
SNR_MSEAL ScmpSyscall = SYS_MSEAL
SNR_SETXATTRAT ScmpSyscall = SYS_SETXATTRAT
SNR_GETXATTRAT ScmpSyscall = SYS_GETXATTRAT
SNR_LISTXATTRAT ScmpSyscall = SYS_LISTXATTRAT
SNR_REMOVEXATTRAT ScmpSyscall = SYS_REMOVEXATTRAT
SNR_OPEN_TREE_ATTR ScmpSyscall = SYS_OPEN_TREE_ATTR
SNR_FILE_GETATTR ScmpSyscall = SYS_FILE_GETATTR
SNR_FILE_SETATTR ScmpSyscall = SYS_FILE_SETATTR
)

View File

@@ -7,8 +7,10 @@ import (
"hakurei.app/container/stub"
)
// Made available here to check panic recovery behaviour.
//
//go:linkname handleExitNew hakurei.app/container/stub.handleExitNew
func handleExitNew(_ testing.TB)
func handleExitNew(t testing.TB)
// overrideTFailNow overrides the Fail and FailNow method.
type overrideTFailNow struct {

3
dist/comp/_hakurei vendored
View File

@@ -17,7 +17,8 @@ _hakurei_run() {
'--wayland[Enable connection to Wayland via security-context-v1]' \
'-X[Enable direct connection to X11]' \
'--dbus[Enable proxied connection to D-Bus]' \
'--pulse[Enable direct connection to PulseAudio]' \
'--pipewire[Enable connection to PipeWire via SecurityContext]' \
'--pulse[Enable PulseAudio compatibility daemon]' \
'--dbus-config[Path to session bus proxy config file]: :_files -g "*.json"' \
'--dbus-system[Path to system bus proxy config file]: :_files -g "*.json"' \
'--mpris[Allow owning MPRIS D-Bus path]' \

12
dist/install.sh vendored
View File

@@ -1,12 +1,12 @@
#!/bin/sh
cd "$(dirname -- "$0")" || exit 1
install -vDm0755 "bin/hakurei" "${HAKUREI_INSTALL_PREFIX}/usr/bin/hakurei"
install -vDm0755 "bin/hpkg" "${HAKUREI_INSTALL_PREFIX}/usr/bin/hpkg"
install -vDm0755 "bin/hakurei" "${DESTDIR}/usr/bin/hakurei"
install -vDm0755 "bin/sharefs" "${DESTDIR}/usr/bin/sharefs"
install -vDm4511 "bin/hsu" "${HAKUREI_INSTALL_PREFIX}/usr/bin/hsu"
if [ ! -f "${HAKUREI_INSTALL_PREFIX}/etc/hsurc" ]; then
install -vDm0400 "hsurc.default" "${HAKUREI_INSTALL_PREFIX}/etc/hsurc"
install -vDm4511 "bin/hsu" "${DESTDIR}/usr/bin/hsu"
if [ ! -f "${DESTDIR}/etc/hsurc" ]; then
install -vDm0400 "hsurc.default" "${DESTDIR}/etc/hsurc"
fi
install -vDm0644 "comp/_hakurei" "${HAKUREI_INSTALL_PREFIX}/usr/share/zsh/site-functions/_hakurei"
install -vDm0644 "comp/_hakurei" "${DESTDIR}/usr/share/zsh/site-functions/_hakurei"

29
dist/release.sh vendored
View File

@@ -1,20 +1,31 @@
#!/bin/sh -e
cd "$(dirname -- "$0")/.."
VERSION="${HAKUREI_VERSION:-untagged}"
pname="hakurei-${VERSION}"
out="dist/${pname}"
pname="hakurei-${VERSION}-$(go env GOARCH)"
out="${DESTDIR:-dist}/${pname}"
echo '# Preparing distribution files.'
mkdir -p "${out}"
cp -v "README.md" "dist/hsurc.default" "dist/install.sh" "${out}"
cp -rv "dist/comp" "${out}"
echo
echo '# Building hakurei.'
go generate ./...
go build -trimpath -v -o "${out}/bin/" -ldflags "-s -w -buildid= -extldflags '-static'
-X hakurei.app/internal.buildVersion=${VERSION}
-X hakurei.app/internal.hakureiPath=/usr/bin/hakurei
-X hakurei.app/internal.hsuPath=/usr/bin/hsu
go build -trimpath -v -o "${out}/bin/" -ldflags "-s -w
-buildid= -extldflags '-static'
-X hakurei.app/internal/info.buildVersion=${VERSION}
-X hakurei.app/internal/info.hakureiPath=/usr/bin/hakurei
-X hakurei.app/internal/info.hsuPath=/usr/bin/hsu
-X main.hakureiPath=/usr/bin/hakurei" ./...
echo
rm -f "./${out}.tar.gz" && tar -C dist -czf "${out}.tar.gz" "${pname}"
rm -rf "./${out}"
(cd dist && sha512sum "${pname}.tar.gz" > "${pname}.tar.gz.sha512")
echo '# Testing hakurei.'
go test -ldflags='-buildid= -extldflags=-static' ./...
echo
echo '# Creating distribution.'
rm -f "${out}.tar.gz" && tar -C "${out}/.." -vczf "${out}.tar.gz" "${pname}"
rm -rf "${out}"
(cd "${out}/.." && sha512sum "${pname}.tar.gz" > "${pname}.tar.gz.sha512")
echo

16
flake.lock generated
View File

@@ -7,32 +7,32 @@
]
},
"locked": {
"lastModified": 1756679287,
"narHash": "sha256-Xd1vOeY9ccDf5VtVK12yM0FS6qqvfUop8UQlxEB+gTQ=",
"lastModified": 1765384171,
"narHash": "sha256-FuFtkJrW1Z7u+3lhzPRau69E0CNjADku1mLQQflUORo=",
"owner": "nix-community",
"repo": "home-manager",
"rev": "07fc025fe10487dd80f2ec694f1cd790e752d0e8",
"rev": "44777152652bc9eacf8876976fa72cc77ca8b9d8",
"type": "github"
},
"original": {
"owner": "nix-community",
"ref": "release-25.05",
"ref": "release-25.11",
"repo": "home-manager",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1757020766,
"narHash": "sha256-PLoSjHRa2bUbi1x9HoXgTx2AiuzNXs54c8omhadyvp0=",
"lastModified": 1765311797,
"narHash": "sha256-mSD5Ob7a+T2RNjvPvOA1dkJHGVrNVl8ZOrAwBjKBDQo=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "fe83bbdde2ccdc2cb9573aa846abe8363f79a97a",
"rev": "09eb77e94fa25202af8f3e81ddc7353d9970ac1b",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-25.05",
"ref": "nixos-25.11",
"repo": "nixpkgs",
"type": "github"
}

View File

@@ -2,10 +2,10 @@
description = "hakurei container tool and nixos module";
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.05";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
home-manager = {
url = "github:nix-community/home-manager/release-25.05";
url = "github:nix-community/home-manager/release-25.11";
inputs.nixpkgs.follows = "nixpkgs";
};
};
@@ -69,6 +69,8 @@
withRace = true;
};
sharefs = callPackage ./cmd/sharefs/test { inherit system self; };
hpkg = callPackage ./cmd/hpkg/test { inherit system self; };
formatting = runCommandLocal "check-formatting" { nativeBuildInputs = [ nixfmt-rfc-style ]; } ''
@@ -114,7 +116,7 @@
inherit (pkgs)
# passthru.buildInputs
go
gcc
clang
# nativeBuildInputs
pkg-config
@@ -129,23 +131,39 @@
zstd
gnutar
coreutils
# for check
util-linux
nettools
;
};
hsu = pkgs.callPackage ./cmd/hsu/package.nix { inherit (self.packages.${system}) hakurei; };
sharefs = pkgs.linkFarm "sharefs" {
"bin/sharefs" = "${hakurei}/libexec/sharefs";
"bin/mount.fuse.sharefs" = "${hakurei}/libexec/sharefs";
};
dist = pkgs.runCommand "${hakurei.name}-dist" { buildInputs = hakurei.targetPkgs ++ [ pkgs.pkgsStatic.musl ]; } ''
# go requires XDG_CACHE_HOME for the build cache
export XDG_CACHE_HOME="$(mktemp -d)"
dist =
pkgs.runCommand "${hakurei.name}-dist"
{
buildInputs = hakurei.targetPkgs ++ [
pkgs.pkgsStatic.musl
];
}
''
cd $(mktemp -d) \
&& cp -r ${hakurei.src}/. . \
&& chmod +w cmd && cp -r ${hsu.src}/. cmd/hsu/ \
&& chmod -R +w .
# get a different workdir as go does not like /build
cd $(mktemp -d) \
&& cp -r ${hakurei.src}/. . \
&& chmod +w cmd && cp -r ${hsu.src}/. cmd/hsu/ \
&& chmod -R +w .
export HAKUREI_VERSION="v${hakurei.version}"
./dist/release.sh && mkdir $out && cp -v "dist/hakurei-$HAKUREI_VERSION.tar.gz"* $out
'';
CC="musl-clang -O3 -Werror -Qunused-arguments" \
GOCACHE="$(mktemp -d)" \
HAKUREI_TEST_SKIP_ACL=1 \
PATH="${pkgs.pkgsStatic.musl.bin}/bin:$PATH" \
DESTDIR="$out" \
HAKUREI_VERSION="v${hakurei.version}" \
./dist/release.sh
'';
}
);
@@ -156,7 +174,10 @@
pkgs = nixpkgsFor.${system};
in
{
default = pkgs.mkShell { buildInputs = hakurei.targetPkgs; };
default = pkgs.mkShell {
buildInputs = hakurei.targetPkgs;
hardeningDisable = [ "fortify" ];
};
withPackage = pkgs.mkShell { buildInputs = [ hakurei ] ++ hakurei.targetPkgs; };
vm =
@@ -181,13 +202,13 @@
hakurei =
let
# this is used for interactive vm testing during development, where tests might be broken
package = self.packages.${pkgs.system}.hakurei.override {
package = self.packages.${pkgs.stdenv.hostPlatform.system}.hakurei.override {
buildGoModule = previousArgs: pkgs.pkgsStatic.buildGoModule (previousArgs // { doCheck = false; });
};
in
{
inherit package;
hsuPackage = self.packages.${pkgs.system}.hsu.override { hakurei = package; };
hsuPackage = self.packages.${pkgs.stdenv.hostPlatform.system}.hsu.override { hakurei = package; };
};
};
}

2
go.mod
View File

@@ -1,3 +1,3 @@
module hakurei.app
go 1.24
go 1.25

73
helper/deprecated.go Normal file
View File

@@ -0,0 +1,73 @@
// Package helper exposes the internal/helper package.
//
// Deprecated: This package will be removed in 0.4.
package helper
import (
"context"
"io"
"os"
"os/exec"
"time"
_ "unsafe" // for go:linkname
"hakurei.app/container"
"hakurei.app/container/check"
"hakurei.app/internal/helper"
"hakurei.app/message"
)
//go:linkname WaitDelay hakurei.app/internal/helper.WaitDelay
var WaitDelay time.Duration
const (
// HakureiHelper is set to 1 when args fd is enabled and 0 otherwise.
HakureiHelper = helper.HakureiHelper
// HakureiStatus is set to 1 when stat fd is enabled and 0 otherwise.
HakureiStatus = helper.HakureiStatus
)
type Helper = helper.Helper
// NewCheckedArgs returns a checked null-terminated argument writer for a copy of args.
//
//go:linkname NewCheckedArgs hakurei.app/internal/helper.NewCheckedArgs
func NewCheckedArgs(args ...string) (wt io.WriterTo, err error)
// MustNewCheckedArgs returns a checked null-terminated argument writer for a copy of args.
// If s contains a NUL byte this function panics instead of returning an error.
//
//go:linkname MustNewCheckedArgs hakurei.app/internal/helper.MustNewCheckedArgs
func MustNewCheckedArgs(args ...string) io.WriterTo
// NewDirect initialises a new direct Helper instance with wt as the null-terminated argument writer.
// Function argF returns an array of arguments passed directly to the child process.
//
//go:linkname NewDirect hakurei.app/internal/helper.NewDirect
func NewDirect(
ctx context.Context,
name string,
wt io.WriterTo,
stat bool,
argF func(argsFd, statFd int) []string,
cmdF func(cmd *exec.Cmd),
extraFiles []*os.File,
) Helper
// New initialises a Helper instance with wt as the null-terminated argument writer.
//
//go:linkname New hakurei.app/internal/helper.New
func New(
ctx context.Context,
msg message.Msg,
pathname *check.Absolute, name string,
wt io.WriterTo,
stat bool,
argF func(argsFd, statFd int) []string,
cmdF func(z *container.Container),
extraFiles []*os.File,
) Helper
// InternalHelperStub is an internal function but exported because it is cross-package;
// it is part of the implementation of the helper stub.
func InternalHelperStub() { helper.InternalHelperStub() }

63
helper/proc/deprecated.go Normal file
View File

@@ -0,0 +1,63 @@
// Deprecated: This package will be removed in 0.4.
package proc
import (
"context"
"io"
"os"
"os/exec"
"time"
_ "unsafe" // for go:linkname
"hakurei.app/internal/helper/proc"
)
//go:linkname FulfillmentTimeout hakurei.app/internal/helper/proc.FulfillmentTimeout
var FulfillmentTimeout time.Duration
// A File is an extra file with deferred initialisation.
type File = proc.File
// ExtraFilesPre is a linked list storing addresses of [os.File].
type ExtraFilesPre = proc.ExtraFilesPre
// Fulfill calls the [File.Fulfill] method on all files, starts cmd and blocks until all fulfillment completes.
//
//go:linkname Fulfill hakurei.app/internal/helper/proc.Fulfill
func Fulfill(ctx context.Context,
v *[]*os.File, start func() error,
files []File, extraFiles *ExtraFilesPre,
) (err error)
// InitFile initialises f as part of the slice extraFiles points to,
// and returns its final fd value.
//
//go:linkname InitFile hakurei.app/internal/helper/proc.InitFile
func InitFile(f File, extraFiles *ExtraFilesPre) (fd uintptr)
// BaseFile implements the Init method of the File interface and provides indirect access to extra file state.
type BaseFile = proc.BaseFile
//go:linkname ExtraFile hakurei.app/internal/helper/proc.ExtraFile
func ExtraFile(cmd *exec.Cmd, f *os.File) (fd uintptr)
//go:linkname ExtraFileSlice hakurei.app/internal/helper/proc.ExtraFileSlice
func ExtraFileSlice(extraFiles *[]*os.File, f *os.File) (fd uintptr)
// NewWriterTo returns a [File] that receives content from wt on fulfillment.
//
//go:linkname NewWriterTo hakurei.app/internal/helper/proc.NewWriterTo
func NewWriterTo(wt io.WriterTo) File
// NewStat returns a [File] implementing the behaviour
// of the receiving end of xdg-dbus-proxy stat fd.
//
//go:linkname NewStat hakurei.app/internal/helper/proc.NewStat
func NewStat(s *io.Closer) File
var (
//go:linkname ErrStatFault hakurei.app/internal/helper/proc.ErrStatFault
ErrStatFault error
//go:linkname ErrStatRead hakurei.app/internal/helper/proc.ErrStatRead
ErrStatRead error
)

View File

@@ -23,9 +23,54 @@ type Config struct {
// System D-Bus proxy configuration.
// If set to nil, system bus proxy is disabled.
SystemBus *BusConfig `json:"system_bus,omitempty"`
// Direct access to wayland socket, no attempt is made to attach security-context-v1
// and the bare socket is made available to the container.
//
// This option is unsupported and most likely enables full control over the Wayland
// session. Do not set this to true unless you are sure you know what you are doing.
DirectWayland bool `json:"direct_wayland,omitempty"`
// Direct access to the PipeWire socket established via SecurityContext::Create, no
// attempt is made to start the pipewire-pulse server.
//
// The SecurityContext machinery is fatally flawed, it blindly sets read and execute
// bits on all objects for clients with the lowest achievable privilege level (by
// setting PW_KEY_ACCESS to "restricted"). This enables them to call any method
// targeting any object, and since Registry::Destroy checks for the read and execute bit,
// allows the destruction of any object other than PW_ID_CORE as well. This behaviour
// is implemented separately in media-session and wireplumber, with the wireplumber
// implementation in Lua via an embedded Lua vm. In all known setups, wireplumber is
// in use, and there is no known way to change its behaviour and set permissions
// differently without replacing the Lua script. Also, since PipeWire relies on these
// permissions to work, reducing them is not possible.
//
// Currently, the only other sandboxed use case is flatpak, which is not aware of
// PipeWire and blindly exposes the bare PulseAudio socket to the container (behaves
// like DirectPulse). This socket is backed by the pipewire-pulse compatibility daemon,
// which obtains client pid via the SO_PEERCRED option. The PipeWire daemon, pipewire-pulse
// daemon and the session manager daemon then separately performs the /.flatpak-info hack
// described in https://git.gensokyo.uk/security/hakurei/issues/21. Under such use case,
// since the client has no direct access to PipeWire, insecure parts of the protocol are
// obscured by pipewire-pulse simply not implementing them, and thus hiding the flaws
// described above.
//
// Hakurei does not rely on the /.flatpak-info hack. Instead, a socket is sets up via
// SecurityContext. A pipewire-pulse server connected through it achieves the same
// permissions as flatpak does via the /.flatpak-info hack and is maintained for the
// life of the container.
//
// This option is unsupported and enables a denial-of-service attack as the sandboxed
// client is able to destroy any client object and thus disconnecting them from PipeWire,
// or destroy the SecurityContext object preventing any further container creation.
// Do not set this to true, it is insecure under any configuration.
DirectPipeWire bool `json:"direct_pipewire,omitempty"`
// Direct access to PulseAudio socket, no attempt is made to establish pipewire-pulse
// server via a PipeWire socket with a SecurityContext attached and the bare socket
// is made available to the container.
//
// This option is unsupported and enables arbitrary code execution as the PulseAudio
// server. Do not set this to true, it is insecure under any configuration.
DirectPulse bool `json:"direct_pulse,omitempty"`
// Extra acl updates to perform before setuid.
ExtraPerms []ExtraPermConfig `json:"extra_perms,omitempty"`
@@ -49,6 +94,9 @@ var (
// ErrEnviron is returned by [Config.Validate] if an environment variable name contains '=' or NUL.
ErrEnviron = errors.New("invalid environment variable name")
// ErrInsecure is returned by [Config.Validate] if the configuration is considered insecure.
ErrInsecure = errors.New("configuration is insecure")
)
// Validate checks [Config] and returns [AppError] if an invalid value is encountered.
@@ -95,6 +143,11 @@ func (config *Config) Validate() error {
}
}
if et := config.Enablements.Unwrap(); !config.DirectPulse && et&EPulse != 0 {
return &AppError{Step: "validate configuration", Err: ErrInsecure,
Msg: "enablement PulseAudio is insecure and no longer supported"}
}
return nil
}

View File

@@ -53,6 +53,12 @@ func TestConfigValidate(t *testing.T) {
Env: map[string]string{"TERM\x00": ""},
}}, &hst.AppError{Step: "validate configuration", Err: hst.ErrEnviron,
Msg: `invalid environment variable "TERM\x00"`}},
{"insecure pulse", &hst.Config{Enablements: hst.NewEnablements(hst.EPulse), Container: &hst.ContainerConfig{
Home: fhs.AbsTmp,
Shell: fhs.AbsTmp,
Path: fhs.AbsTmp,
}}, &hst.AppError{Step: "validate configuration", Err: hst.ErrInsecure,
Msg: "enablement PulseAudio is insecure and no longer supported"}},
{"valid", &hst.Config{Container: &hst.ContainerConfig{
Home: fhs.AbsTmp,
Shell: fhs.AbsTmp,

View File

@@ -17,6 +17,8 @@ const (
EX11
// EDBus enables the per-container xdg-dbus-proxy daemon.
EDBus
// EPipeWire exposes a pipewire pathname socket via SecurityContext.
EPipeWire
// EPulse copies the PulseAudio cookie to [hst.PrivateTmp] and exposes the PulseAudio socket.
EPulse
@@ -35,6 +37,8 @@ func (e Enablement) String() string {
return "x11"
case EDBus:
return "dbus"
case EPipeWire:
return "pipewire"
case EPulse:
return "pulseaudio"
default:
@@ -62,10 +66,11 @@ type Enablements Enablement
// enablementsJSON is the [json] representation of [Enablements].
type enablementsJSON = struct {
Wayland bool `json:"wayland,omitempty"`
X11 bool `json:"x11,omitempty"`
DBus bool `json:"dbus,omitempty"`
Pulse bool `json:"pulse,omitempty"`
Wayland bool `json:"wayland,omitempty"`
X11 bool `json:"x11,omitempty"`
DBus bool `json:"dbus,omitempty"`
PipeWire bool `json:"pipewire,omitempty"`
Pulse bool `json:"pulse,omitempty"`
}
// Unwrap returns the underlying [Enablement].
@@ -81,10 +86,11 @@ func (e *Enablements) MarshalJSON() ([]byte, error) {
return nil, syscall.EINVAL
}
return json.Marshal(&enablementsJSON{
Wayland: Enablement(*e)&EWayland != 0,
X11: Enablement(*e)&EX11 != 0,
DBus: Enablement(*e)&EDBus != 0,
Pulse: Enablement(*e)&EPulse != 0,
Wayland: Enablement(*e)&EWayland != 0,
X11: Enablement(*e)&EX11 != 0,
DBus: Enablement(*e)&EDBus != 0,
PipeWire: Enablement(*e)&EPipeWire != 0,
Pulse: Enablement(*e)&EPulse != 0,
})
}
@@ -108,6 +114,9 @@ func (e *Enablements) UnmarshalJSON(data []byte) error {
if v.DBus {
ve |= EDBus
}
if v.PipeWire {
ve |= EPipeWire
}
if v.Pulse {
ve |= EPulse
}

View File

@@ -32,6 +32,7 @@ func TestEnablementString(t *testing.T) {
{hst.EWayland | hst.EDBus | hst.EPulse, "wayland, dbus, pulseaudio"},
{hst.EX11 | hst.EDBus | hst.EPulse, "x11, dbus, pulseaudio"},
{hst.EWayland | hst.EX11 | hst.EDBus | hst.EPulse, "wayland, x11, dbus, pulseaudio"},
{hst.EM - 1, "wayland, x11, dbus, pipewire, pulseaudio"},
{1 << 5, "e20"},
{1 << 6, "e40"},
@@ -62,8 +63,9 @@ func TestEnablements(t *testing.T) {
{"wayland", hst.NewEnablements(hst.EWayland), `{"wayland":true}`, `{"value":{"wayland":true},"magic":3236757504}`},
{"x11", hst.NewEnablements(hst.EX11), `{"x11":true}`, `{"value":{"x11":true},"magic":3236757504}`},
{"dbus", hst.NewEnablements(hst.EDBus), `{"dbus":true}`, `{"value":{"dbus":true},"magic":3236757504}`},
{"pipewire", hst.NewEnablements(hst.EPipeWire), `{"pipewire":true}`, `{"value":{"pipewire":true},"magic":3236757504}`},
{"pulse", hst.NewEnablements(hst.EPulse), `{"pulse":true}`, `{"value":{"pulse":true},"magic":3236757504}`},
{"all", hst.NewEnablements(hst.EWayland | hst.EX11 | hst.EDBus | hst.EPulse), `{"wayland":true,"x11":true,"dbus":true,"pulse":true}`, `{"value":{"wayland":true,"x11":true,"dbus":true,"pulse":true},"magic":3236757504}`},
{"all", hst.NewEnablements(hst.EM - 1), `{"wayland":true,"x11":true,"dbus":true,"pipewire":true,"pulse":true}`, `{"value":{"wayland":true,"x11":true,"dbus":true,"pipewire":true,"pulse":true},"magic":3236757504}`},
}
for _, tc := range testCases {

View File

@@ -45,6 +45,9 @@ type Ops interface {
Root(host *check.Absolute, flags int) Ops
// Etc appends an op that expands host /etc into a toplevel symlink mirror with /etc semantics.
Etc(host *check.Absolute, prefix string) Ops
// Daemon appends an op that starts a daemon in the container and blocks until target appears.
Daemon(target, path *check.Absolute, args ...string) Ops
}
// ApplyState holds the address of [Ops] and any relevant application state.
@@ -124,6 +127,12 @@ func (f *FilesystemConfigJSON) MarshalJSON() ([]byte, error) {
*FSLink
}{fsType{FilesystemLink}, cv}
case *FSDaemon:
v = &struct {
fsType
*FSDaemon
}{fsType{FilesystemDaemon}, cv}
default:
return nil, FSImplError{f.FilesystemConfig}
}
@@ -152,6 +161,9 @@ func (f *FilesystemConfigJSON) UnmarshalJSON(data []byte) error {
case FilesystemLink:
*f = FilesystemConfigJSON{new(FSLink)}
case FilesystemDaemon:
*f = FilesystemConfigJSON{new(FSDaemon)}
default:
return FSTypeError(t.Type)
}

View File

@@ -84,6 +84,16 @@ func TestFilesystemConfigJSON(t *testing.T) {
}, nil,
`{"type":"link","dst":"/run/current-system","linkname":"/run/current-system","dereference":true}`,
`{"fs":{"type":"link","dst":"/run/current-system","linkname":"/run/current-system","dereference":true},"magic":3236757504}`},
{"daemon", hst.FilesystemConfigJSON{
FilesystemConfig: &hst.FSDaemon{
Target: m("/run/user/1971/pulse/native"),
Exec: m("/run/current-system/sw/bin/pipewire-pulse"),
Args: []string{"-v"},
},
}, nil,
`{"type":"daemon","dst":"/run/user/1971/pulse/native","path":"/run/current-system/sw/bin/pipewire-pulse","args":["-v"]}`,
`{"fs":{"type":"daemon","dst":"/run/user/1971/pulse/native","path":"/run/current-system/sw/bin/pipewire-pulse","args":["-v"]},"magic":3236757504}`},
}
for _, tc := range testCases {
@@ -345,6 +355,10 @@ func (p opsAdapter) Etc(host *check.Absolute, prefix string) hst.Ops {
return opsAdapter{p.Ops.Etc(host, prefix)}
}
func (p opsAdapter) Daemon(target, path *check.Absolute, args ...string) hst.Ops {
return opsAdapter{p.Ops.Daemon(target, path, args...)}
}
func m(pathname string) *check.Absolute { return check.MustAbs(pathname) }
func ms(pathnames ...string) []*check.Absolute {
as := make([]*check.Absolute, len(pathnames))

48
hst/fsdaemon.go Normal file
View File

@@ -0,0 +1,48 @@
package hst
import (
"encoding/gob"
"hakurei.app/container/check"
)
func init() { gob.Register(new(FSDaemon)) }
// FilesystemDaemon is the type string of a daemon.
const FilesystemDaemon = "daemon"
// FSDaemon represents a daemon to be started in the container.
type FSDaemon struct {
// Pathname indicating readiness of daemon.
Target *check.Absolute `json:"dst"`
// Absolute pathname to daemon executable file.
Exec *check.Absolute `json:"path"`
// Arguments (excl. first) passed to daemon.
Args []string `json:"args"`
}
func (d *FSDaemon) Valid() bool { return d != nil && d.Target != nil && d.Exec != nil }
func (d *FSDaemon) Path() *check.Absolute {
if !d.Valid() {
return nil
}
return d.Target
}
func (d *FSDaemon) Host() []*check.Absolute { return nil }
func (d *FSDaemon) Apply(z *ApplyState) {
if !d.Valid() {
return
}
z.Daemon(d.Target, d.Exec, d.Args...)
}
func (d *FSDaemon) String() string {
if !d.Valid() {
return "<invalid>"
}
return "daemon:" + d.Target.String()
}

29
hst/fsdaemon_test.go Normal file
View File

@@ -0,0 +1,29 @@
package hst_test
import (
"testing"
"hakurei.app/container"
"hakurei.app/hst"
)
func TestFSDaemon(t *testing.T) {
t.Parallel()
checkFs(t, []fsTestCase{
{"nil", (*hst.FSDaemon)(nil), false, nil, nil, nil, "<invalid>"},
{"zero", new(hst.FSDaemon), false, nil, nil, nil, "<invalid>"},
{"pipewire-pulse", &hst.FSDaemon{
Target: m("/run/user/1971/pulse/native"),
Exec: m("/run/current-system/sw/bin/pipewire-pulse"),
Args: []string{"-v"},
}, true, container.Ops{
&container.DaemonOp{
Target: m("/run/user/1971/pulse/native"),
Path: m("/run/current-system/sw/bin/pipewire-pulse"),
Args: []string{"-v"},
},
}, m("/run/user/1971/pulse/native"), nil, `daemon:/run/user/1971/pulse/native`},
})
}

View File

@@ -54,6 +54,9 @@ type Paths struct {
// Info holds basic system information collected from the implementation.
type Info struct {
// WaylandVersion is the libwayland value of WAYLAND_VERSION.
WaylandVersion string `json:"WAYLAND_VERSION"`
// Version is a hardcoded version string.
Version string `json:"version"`
// User is the userid according to hsu.
@@ -67,7 +70,7 @@ func Template() *Config {
return &Config{
ID: "org.chromium.Chromium",
Enablements: NewEnablements(EWayland | EDBus | EPulse),
Enablements: NewEnablements(EWayland | EDBus | EPipeWire),
SessionBus: &BusConfig{
See: nil,
@@ -89,7 +92,6 @@ func Template() *Config {
Log: false,
Filter: true,
},
DirectWayland: false,
ExtraPerms: []ExtraPermConfig{
{Path: fhs.AbsVarLib.Append("hakurei/u0"), Ensure: true, Execute: true},

View File

@@ -105,7 +105,7 @@ func TestTemplate(t *testing.T) {
"enablements": {
"wayland": true,
"dbus": true,
"pulse": true
"pipewire": true
},
"session_bus": {
"see": null,

View File

@@ -6,11 +6,13 @@ import (
"reflect"
"testing"
"time"
_ "unsafe"
_ "unsafe" // for go:linkname
"hakurei.app/hst"
)
// Made available here to check time encoding behaviour of [hst.ID].
//
//go:linkname newInstanceID hakurei.app/hst.newInstanceID
func newInstanceID(id *hst.ID, p uint64) error

View File

@@ -13,7 +13,7 @@ import (
"strconv"
"testing"
"hakurei.app/system/acl"
"hakurei.app/internal/acl"
)
const testFileName = "acl.test"
@@ -24,9 +24,8 @@ var (
)
func TestUpdate(t *testing.T) {
if os.Getenv("GO_TEST_SKIP_ACL") == "1" {
t.Log("acl test skipped")
t.SkipNow()
if os.Getenv("HAKUREI_TEST_SKIP_ACL") == "1" {
t.Skip("acl test skipped")
}
testFilePath := path.Join(t.TempDir(), testFileName)
@@ -143,6 +142,7 @@ func (c *getFAclInvocation) run(name string) error {
}
c.cmd = exec.Command("getfacl", "--omit-header", "--absolute-names", "--numeric", name)
c.cmd.Stderr = os.Stderr
scanErr := make(chan error, 1)
if p, err := c.cmd.StdoutPipe(); err != nil {
@@ -254,7 +254,7 @@ func getfacl(t *testing.T, name string) []*getFAclResp {
t.Fatalf("getfacl: error = %v", err)
}
if len(c.pe) != 0 {
t.Errorf("errors encountered parsing getfacl output\n%s", errors.Join(c.pe...).Error())
t.Errorf("errors encountered parsing getfacl output\n%s", errors.Join(c.pe...))
}
return c.val
}

View File

@@ -0,0 +1,90 @@
#include "libacl-helper.h"
#include <acl/libacl.h>
#include <stdbool.h>
#include <stdlib.h>
#include <sys/acl.h>
int hakurei_acl_update_file_by_uid(const char *path_p, uid_t uid,
acl_perm_t *perms, size_t plen) {
int ret;
bool v;
int i;
acl_t acl;
acl_entry_t entry;
acl_tag_t tag_type;
void *qualifier_p;
acl_permset_t permset;
ret = -1; /* acl_get_file */
acl = acl_get_file(path_p, ACL_TYPE_ACCESS);
if (acl == NULL)
goto out;
/* prune entries by uid */
for (i = acl_get_entry(acl, ACL_FIRST_ENTRY, &entry); i == 1;
i = acl_get_entry(acl, ACL_NEXT_ENTRY, &entry)) {
ret = -2; /* acl_get_tag_type */
if (acl_get_tag_type(entry, &tag_type) != 0)
goto out;
if (tag_type != ACL_USER)
continue;
ret = -3; /* acl_get_qualifier */
qualifier_p = acl_get_qualifier(entry);
if (qualifier_p == NULL)
goto out;
v = *(uid_t *)qualifier_p == uid;
acl_free(qualifier_p);
if (!v)
continue;
ret = -4; /* acl_delete_entry */
if (acl_delete_entry(acl, entry) != 0)
goto out;
}
if (plen == 0)
goto set;
ret = -5; /* acl_create_entry */
if (acl_create_entry(&acl, &entry) != 0)
goto out;
ret = -6; /* acl_get_permset */
if (acl_get_permset(entry, &permset) != 0)
goto out;
ret = -7; /* acl_add_perm */
for (i = 0; i < plen; i++) {
if (acl_add_perm(permset, perms[i]) != 0)
goto out;
}
ret = -8; /* acl_set_tag_type */
if (acl_set_tag_type(entry, ACL_USER) != 0)
goto out;
ret = -9; /* acl_set_qualifier */
if (acl_set_qualifier(entry, (void *)&uid) != 0)
goto out;
set:
ret = -10; /* acl_calc_mask */
if (acl_calc_mask(&acl) != 0)
goto out;
ret = -11; /* acl_valid */
if (acl_valid(acl) != 0)
goto out;
ret = -12; /* acl_set_file */
if (acl_set_file(path_p, ACL_TYPE_ACCESS, acl) == 0)
ret = 0;
out:
free((void *)path_p);
if (acl != NULL)
acl_free((void *)acl);
return ret;
}

View File

@@ -3,7 +3,7 @@ package acl_test
import (
"testing"
"hakurei.app/system/acl"
"hakurei.app/internal/acl"
)
func TestPerms(t *testing.T) {

View File

@@ -5,7 +5,7 @@ import (
"reflect"
"testing"
"hakurei.app/system/dbus"
"hakurei.app/internal/dbus"
)
func TestParse(t *testing.T) {

View File

@@ -7,7 +7,7 @@ import (
"testing"
"hakurei.app/hst"
"hakurei.app/system/dbus"
"hakurei.app/internal/dbus"
)
func TestConfigArgs(t *testing.T) {

View File

@@ -11,9 +11,9 @@ import (
"testing"
"time"
"hakurei.app/helper"
"hakurei.app/internal/dbus"
"hakurei.app/internal/helper"
"hakurei.app/message"
"hakurei.app/system/dbus"
)
func TestFinalise(t *testing.T) {

View File

@@ -12,7 +12,7 @@ import (
"hakurei.app/container/check"
"hakurei.app/container/seccomp"
"hakurei.app/container/std"
"hakurei.app/helper"
"hakurei.app/internal/helper"
"hakurei.app/ldd"
)
@@ -54,7 +54,7 @@ func (p *Proxy) Start() error {
}
var libPaths []*check.Absolute
if entries, err := ldd.Exec(ctx, p.msg, toolPath.String()); err != nil {
if entries, err := ldd.Resolve(ctx, p.msg, toolPath); err != nil {
return err
} else {
libPaths = ldd.Path(entries)

View File

@@ -5,7 +5,7 @@ import (
"testing"
"hakurei.app/container"
"hakurei.app/helper"
"hakurei.app/internal/helper"
)
func TestMain(m *testing.M) { container.TryArgv0(nil); helper.InternalHelperStub(); os.Exit(m.Run()) }

View File

@@ -6,8 +6,8 @@ import (
"sync"
"syscall"
"hakurei.app/helper"
"hakurei.app/hst"
"hakurei.app/internal/helper"
"hakurei.app/message"
)

Some files were not shown because too many files have changed in this diff Show More