Compare commits
316 Commits
b651d95e77
...
v0.3.4
| Author | SHA1 | Date | |
|---|---|---|---|
|
d61faa09eb
|
|||
|
50153788ef
|
|||
|
c84fe63217
|
|||
|
eb67e5e0a8
|
|||
|
948afe33e5
|
|||
|
76c657177d
|
|||
|
4356f978aa
|
|||
|
4f17dad645
|
|||
|
68b7d41c65
|
|||
|
e48f303e38
|
|||
|
f1fd406b82
|
|||
|
53b1de3395
|
|||
|
92dcadbf27
|
|||
|
0bd6a18326
|
|||
|
67d592c337
|
|||
|
fdc8a8419b
|
|||
|
122cfbf63a
|
|||
|
504f5d28fe
|
|||
|
3eadd5c580
|
|||
|
4d29333807
|
|||
|
e1533fa4c6
|
|||
|
9a74d5273d
|
|||
|
2abc8c454e
|
|||
|
fecb963e85
|
|||
|
cd9da57f20
|
|||
|
c6a95f5a6a
|
|||
|
228489371d
|
|||
|
490471d22b
|
|||
|
763d2572fe
|
|||
|
bb1b6beb87
|
|||
|
3224a7da63
|
|||
|
8a86cf74ee
|
|||
|
e34a59e332
|
|||
|
861801597d
|
|||
|
334578fdde
|
|||
|
20790af71e
|
|||
|
43b8a40fc0
|
|||
|
87c3059214
|
|||
|
6956dfc31a
|
|||
|
d9ebaf20f8
|
|||
|
acee0b3632
|
|||
|
5e55a796df
|
|||
|
f6eaf76ec9
|
|||
|
5c127a7035
|
|||
|
8a26521f5b
|
|||
|
0fd4556e38
|
|||
|
50b82dcf82
|
|||
|
20a8d30821
|
|||
|
cdf2e4a2fb
|
|||
|
dcb8a6ea06
|
|||
|
094a62ba9d
|
|||
|
6420b6e6e8
|
|||
|
d7d058fdc5
|
|||
|
84795b5d9f
|
|||
|
f84d30deed
|
|||
|
77821feb8b
|
|||
|
eb1060f395
|
|||
|
0e08254595
|
|||
|
349d8693bf
|
|||
|
e88ae87e50
|
|||
|
7cd4aa838c
|
|||
|
641942a4e3
|
|||
|
b6a66acfe4
|
|||
|
b72dc43bc3
|
|||
|
8e59ff98b5
|
|||
|
f06d7fd387
|
|||
|
ba75587132
|
|||
|
9a06ce2db0
|
|||
|
3ec15bcdf1
|
|||
|
d933234784
|
|||
|
1c49c75f95
|
|||
|
6a01a55d7e
|
|||
|
b14964a66d
|
|||
|
ff98c9ded9
|
|||
|
7f3d1d6375
|
|||
|
3a4f20b759
|
|||
|
21858ecfe4
|
|||
|
574a64aa85
|
|||
|
85d27229fd
|
|||
|
83fb80d710
|
|||
|
fe6dc62ebf
|
|||
|
823f9c76a7
|
|||
|
2df913999b
|
|||
|
52c959bd6a
|
|||
|
d258dea0bf
|
|||
|
dc96302111
|
|||
|
88e9a143d6
|
|||
|
8d06c0235b
|
|||
|
4155adc16a
|
|||
|
2a9525c77a
|
|||
|
efc90c3221
|
|||
|
610ee13ab3
|
|||
|
5936e6a4aa
|
|||
|
3499a82785
|
|||
|
088d35e4e6
|
|||
|
1667df9c43
|
|||
|
156dd767ef
|
|||
|
5fe166a4a7
|
|||
|
41a8d03dd2
|
|||
|
610572d0e6
|
|||
|
29951c5174
|
|||
|
91c3594dee
|
|||
|
7ccc2fc5ec
|
|||
|
63e137856e
|
|||
|
e1e46504a1
|
|||
|
ec9343ebd6
|
|||
|
423808ac76
|
|||
|
2494ede106
|
|||
|
da3848b92f
|
|||
|
34cb4ebd3b
|
|||
|
f712466714
|
|||
|
f2430b5f5e
|
|||
|
863e6f5db6
|
|||
|
23df2ab999
|
|||
|
7bd4d7d0e6
|
|||
|
b3c30bcc51
|
|||
|
38059db835
|
|||
|
409fd3149e
|
|||
|
4eea136308
|
|||
|
c86ff02d8d
|
|||
|
e8dda70c41
|
|||
|
7ea4e8b643
|
|||
|
5eefebcb48
|
|||
|
8e08e8f518
|
|||
|
54da6ce03d
|
|||
|
3a21ba1bca
|
|||
|
45301559bf
|
|||
|
0df87ab111
|
|||
|
aa0a949cef
|
|||
|
ce0064384d
|
|||
|
53d80f4b66
|
|||
|
156096ac98
|
|||
|
ceb75538cf
|
|||
|
0741a614ed
|
|||
|
e7e9b4caea
|
|||
|
f6d32e482a
|
|||
|
79adf217f4
|
|||
|
8efffd72f4
|
|||
|
86ad8b72aa
|
|||
|
e91049c3c5
|
|||
|
3d4d32932d
|
|||
|
0ab6c13c77
|
|||
|
834cb0d40b
|
|||
|
7548a627e5
|
|||
|
b98d27f773
|
|||
|
f3aa31e401
|
|||
|
4da26681b5
|
|||
|
4897b0259e
|
|||
|
d6e4f85864
|
|||
|
3eb927823f
|
|||
|
d76b9d04b8
|
|||
|
fa93476896
|
|||
|
bd0ef086b1
|
|||
|
05202cf994
|
|||
|
40081e7a06
|
|||
|
863d3dcf9f
|
|||
|
8ad9909065
|
|||
|
deda16da38
|
|||
|
55465c6e72
|
|||
|
ce249d23f1
|
|||
|
dd5d792d14
|
|||
|
d15d2ec2bd
|
|||
|
3078c41ce7
|
|||
|
e9de5d3aca
|
|||
|
993afde840
|
|||
|
c9cd16fd2a
|
|||
|
e42ea32dbe
|
|||
|
e7982b4ee9
|
|||
|
ef1ebf12d9
|
|||
|
775a9f57c9
|
|||
|
2f8ca83376
|
|||
|
3d720ada92
|
|||
|
2e5362e536
|
|||
|
6d3bd27220
|
|||
|
a27305cb4a
|
|||
|
0e476c5e5b
|
|||
|
54712e0426
|
|||
|
b77c1ecfdb
|
|||
|
dce5839a79
|
|||
|
d597592e1f
|
|||
|
056f5b12d4
|
|||
|
da2bb546ba
|
|||
|
7bfbd59810
|
|||
|
ea815a59e8
|
|||
|
28a8dc67d2
|
|||
|
ec49c63c5f
|
|||
|
5a50bf80ee
|
|||
|
ce06b7b663
|
|||
|
08bdc68f3a
|
|||
|
8cb0b433b2
|
|||
|
767f1844d2
|
|||
|
54610aaddc
|
|||
|
2e80660169
|
|||
|
d0a3c6a2f3
|
|||
|
0c0e3d6fc2
|
|||
|
fae910a1ad
|
|||
|
178c8bc28b
|
|||
|
30dcab0734
|
|||
|
0ea051062b
|
|||
|
b0f2ab6fff
|
|||
|
00a5bdf006
|
|||
|
a27dfdc058
|
|||
|
6d0d9cecd1
|
|||
|
17248d7d61
|
|||
|
41e5628c67
|
|||
|
ffbec828e1
|
|||
|
de0467a65e
|
|||
|
b5999b8814
|
|||
|
ebc67bb8ad
|
|||
|
e60ff660f6
|
|||
|
47db461546
|
|||
|
0a3fe5f907
|
|||
|
b72d502f1c
|
|||
|
f8b3db3f66
|
|||
|
0e2fb1788f
|
|||
|
d8417e2927
|
|||
|
ccc0d98bd7
|
|||
|
a3fd05765e
|
|||
|
c538df7daa
|
|||
|
44e5aa1a36
|
|||
|
cf0e7d8c27
|
|||
|
130add21e5
|
|||
|
5ec4045e24
|
|||
|
be2075f169
|
|||
|
e9fb1d7be5
|
|||
|
dafe9f8efc
|
|||
|
96dd7abd80
|
|||
|
d5fb179012
|
|||
|
462863e290
|
|||
|
2786611b88
|
|||
|
791a1dfa55
|
|||
|
564db6863b
|
|||
|
87781c7658
|
|||
|
0c38fb7b6a
|
|||
|
357cfcddee
|
|||
|
6bf245cf1b
|
|||
|
c8eeb4a4d1
|
|||
|
5785714b64
|
|||
|
422efcf258
|
|||
|
104eeecf65
|
|||
|
bf856f06e5
|
|||
|
1931b54600
|
|||
|
093e30c788
|
|||
|
1b17ccda91
|
|||
|
7c6fc1128b
|
|||
|
8cdd659239
|
|||
|
15c2839a09
|
|||
|
b9b9705b52
|
|||
|
246e04214a
|
|||
|
503bfc6468
|
|||
|
d837628b4c
|
|||
|
3cb58b4b72
|
|||
|
bb1fc4c7bc
|
|||
|
f44923da29
|
|||
|
5e7861bb00
|
|||
|
7cb3308a53
|
|||
|
490093a659
|
|||
|
2b22efcdf1
|
|||
|
8a2f9edcf9
|
|||
|
0d3f332d45
|
|||
|
d5509cc6e5
|
|||
|
0d3ae6cb23
|
|||
|
69b1131d66
|
|||
|
2c0b92771a
|
|||
|
054c91879f
|
|||
|
c34439fc5f
|
|||
|
32fb137bb2
|
|||
|
e7a665e043
|
|||
|
af741f20a0
|
|||
|
39c6716fb0
|
|||
|
7bc73afadd
|
|||
|
647aa9d02f
|
|||
|
91aaabaa1b
|
|||
|
3d4c7cdd9e
|
|||
|
4fd6d6c037
|
|||
|
de3fc7ba38
|
|||
|
5a5c4705dd
|
|||
|
f703aa20a5
|
|||
|
5c12425d48
|
|||
|
cbe86dc4f0
|
|||
|
d08a1081bd
|
|||
|
72a2601d74
|
|||
|
1dab87aaf0
|
|||
|
2bafde99e3
|
|||
|
91efeb101a
|
|||
|
dcb22a61c0
|
|||
|
e028a61fc1
|
|||
|
73987be7d4
|
|||
|
563b5e66fc
|
|||
|
2edcfe1e68
|
|||
|
2698ca00e8
|
|||
|
1d0143386d
|
|||
|
a55c209099
|
|||
|
10ff276da1
|
|||
|
fd4d379b67
|
|||
|
77f5b89a41
|
|||
|
14e33f17e5
|
|||
|
cfeb7818eb
|
|||
|
05391da556
|
|||
|
463f8836e6
|
|||
|
2e465c94da
|
|||
|
26009fd3f7
|
|||
|
2d7b896a8c
|
|||
|
a0eb010aab
|
|||
|
b1b27ac1df
|
|||
|
fc3d78fe01
|
|||
|
591637264a
|
|||
|
e77652bf89
|
|||
|
88d3e46413
|
|||
|
e51e81bb22
|
|||
|
8f4a3bcf9f
|
|||
|
827dc9e1ba
|
|||
|
d92de1c709
|
|||
|
5bcafcf734
|
|||
|
9f7b0c2f46
|
|||
|
3e87187c4c
|
@@ -72,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
|
||||
@@ -96,6 +113,7 @@ jobs:
|
||||
- race
|
||||
- sandbox
|
||||
- sandbox-race
|
||||
- sharefs
|
||||
- hpkg
|
||||
runs-on: nix
|
||||
steps:
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -27,6 +27,7 @@ go.work.sum
|
||||
|
||||
# go generate
|
||||
/cmd/hakurei/LICENSE
|
||||
/internal/pkg/testdata/testtool
|
||||
|
||||
# release
|
||||
/dist/hakurei-*
|
||||
|
||||
@@ -91,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 {
|
||||
@@ -146,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{
|
||||
@@ -297,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")
|
||||
}
|
||||
|
||||
{
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,7 +62,7 @@ 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
|
||||
@@ -159,7 +159,7 @@ 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
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 = {
|
||||
|
||||
@@ -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"))
|
||||
|
||||
243
cmd/mbf/main.go
Normal file
243
cmd/mbf/main.go
Normal file
@@ -0,0 +1,243 @@
|
||||
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) {
|
||||
_, _, _, stage2 := (rosa.Std - 1).NewLLVM()
|
||||
_, _, _, stage3 := rosa.Std.NewLLVM()
|
||||
var (
|
||||
pathname *check.Absolute
|
||||
checksum [2]unique.Handle[pkg.Checksum]
|
||||
)
|
||||
|
||||
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(),
|
||||
}
|
||||
}
|
||||
return
|
||||
},
|
||||
)
|
||||
|
||||
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")
|
||||
}
|
||||
var p rosa.PArtifact
|
||||
switch args[0] {
|
||||
case "acl":
|
||||
p = rosa.ACL
|
||||
case "attr":
|
||||
p = rosa.Attr
|
||||
case "autoconf":
|
||||
p = rosa.Autoconf
|
||||
case "bash":
|
||||
p = rosa.Bash
|
||||
case "busybox":
|
||||
p = rosa.Busybox
|
||||
case "cmake":
|
||||
p = rosa.CMake
|
||||
case "coreutils":
|
||||
p = rosa.Coreutils
|
||||
case "diffutils":
|
||||
p = rosa.Diffutils
|
||||
case "gettext":
|
||||
p = rosa.Gettext
|
||||
case "git":
|
||||
p = rosa.Git
|
||||
case "go":
|
||||
p = rosa.Go
|
||||
case "gperf":
|
||||
p = rosa.Gperf
|
||||
case "hakurei":
|
||||
p = rosa.Hakurei
|
||||
case "kernel-headers":
|
||||
p = rosa.KernelHeaders
|
||||
case "libXau":
|
||||
p = rosa.LibXau
|
||||
case "libexpat":
|
||||
p = rosa.Libexpat
|
||||
case "libseccomp":
|
||||
p = rosa.Libseccomp
|
||||
case "libxml2":
|
||||
p = rosa.Libxml2
|
||||
case "libffi":
|
||||
p = rosa.Libffi
|
||||
case "libgd":
|
||||
p = rosa.Libgd
|
||||
case "m4":
|
||||
p = rosa.M4
|
||||
case "make":
|
||||
p = rosa.Make
|
||||
case "meson":
|
||||
p = rosa.Meson
|
||||
case "ninja":
|
||||
p = rosa.Ninja
|
||||
case "patch":
|
||||
p = rosa.Patch
|
||||
case "perl":
|
||||
p = rosa.Perl
|
||||
case "pkg-config":
|
||||
p = rosa.PkgConfig
|
||||
case "python":
|
||||
p = rosa.Python
|
||||
case "rsync":
|
||||
p = rosa.Rsync
|
||||
case "setuptools":
|
||||
p = rosa.Setuptools
|
||||
case "wayland":
|
||||
p = rosa.Wayland
|
||||
case "wayland-protocols":
|
||||
p = rosa.WaylandProtocols
|
||||
case "xcb":
|
||||
p = rosa.XCB
|
||||
case "xcb-proto":
|
||||
p = rosa.XCBProto
|
||||
case "xproto":
|
||||
p = rosa.Xproto
|
||||
case "zlib":
|
||||
p = rosa.Zlib
|
||||
|
||||
default:
|
||||
return fmt.Errorf("unsupported artifact %q", args[0])
|
||||
}
|
||||
|
||||
pathname, _, err := cache.Cure(rosa.Std.Load(p))
|
||||
if err == nil {
|
||||
log.Println(pathname)
|
||||
}
|
||||
return err
|
||||
|
||||
},
|
||||
)
|
||||
|
||||
c.MustParse(os.Args[1:], func(err error) {
|
||||
if cache != nil {
|
||||
cache.Close()
|
||||
}
|
||||
log.Fatal(err)
|
||||
})
|
||||
}
|
||||
282
cmd/sharefs/fuse-operations.c
Normal file
282
cmd/sharefs/fuse-operations.c
Normal 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;
|
||||
}
|
||||
34
cmd/sharefs/fuse-operations.h
Normal file
34
cmd/sharefs/fuse-operations.h
Normal 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
556
cmd/sharefs/fuse.go
Normal 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
113
cmd/sharefs/fuse_test.go
Normal 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
31
cmd/sharefs/main.go
Normal 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
29
cmd/sharefs/main_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
41
cmd/sharefs/test/configuration.nix
Normal file
41
cmd/sharefs/test/configuration.nix
Normal 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";
|
||||
};
|
||||
};
|
||||
}
|
||||
44
cmd/sharefs/test/default.nix
Normal file
44
cmd/sharefs/test/default.nix
Normal 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
60
cmd/sharefs/test/test.py
Normal 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")
|
||||
@@ -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 }
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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),
|
||||
}})}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ const (
|
||||
|
||||
CAP_SYS_ADMIN = 0x15
|
||||
CAP_SETPCAP = 0x8
|
||||
CAP_NET_ADMIN = 0xc
|
||||
CAP_DAC_OVERRIDE = 0x1
|
||||
)
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -31,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 {
|
||||
@@ -45,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)
|
||||
}
|
||||
})
|
||||
@@ -62,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 {
|
||||
@@ -84,7 +84,7 @@ func TestNewAbs(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
defer func() {
|
||||
wantPanic := &AbsoluteError{Pathname: "etc"}
|
||||
wantPanic := AbsoluteError("etc")
|
||||
|
||||
if r := recover(); !reflect.DeepEqual(r, wantPanic) {
|
||||
t.Errorf("MustAbs: panic = %v; want %v", r, wantPanic)
|
||||
@@ -175,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",
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -26,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)
|
||||
|
||||
|
||||
@@ -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: ¶ms.Params, Msg: msg}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
state := &setupState{process: make(map[int]WaitStatus), Params: ¶ms.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) }()
|
||||
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
134
container/initdaemon.go
Normal 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) }
|
||||
127
container/initdaemon_test.go
Normal file
127
container/initdaemon_test.go
Normal 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"`},
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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() &&
|
||||
|
||||
@@ -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")},
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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() &&
|
||||
|
||||
@@ -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"),
|
||||
|
||||
@@ -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
269
container/netlink.go
Normal 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
72
container/netlink_test.go
Normal 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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
3
dist/comp/_hakurei
vendored
3
dist/comp/_hakurei
vendored
@@ -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
12
dist/install.sh
vendored
@@ -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"
|
||||
16
flake.lock
generated
16
flake.lock
generated
@@ -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"
|
||||
}
|
||||
|
||||
19
flake.nix
19
flake.nix
@@ -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 ]; } ''
|
||||
@@ -136,6 +138,10 @@
|
||||
;
|
||||
};
|
||||
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
|
||||
@@ -160,7 +166,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 =
|
||||
@@ -185,13 +194,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; };
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
12
hst/fs.go
12
hst/fs.go
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
48
hst/fsdaemon.go
Normal 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
29
hst/fsdaemon_test.go
Normal 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`},
|
||||
})
|
||||
}
|
||||
@@ -70,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,
|
||||
@@ -92,7 +92,6 @@ func Template() *Config {
|
||||
Log: false,
|
||||
Filter: true,
|
||||
},
|
||||
DirectWayland: false,
|
||||
|
||||
ExtraPerms: []ExtraPermConfig{
|
||||
{Path: fhs.AbsVarLib.Append("hakurei/u0"), Ensure: true, Execute: true},
|
||||
|
||||
@@ -105,7 +105,7 @@ func TestTemplate(t *testing.T) {
|
||||
"enablements": {
|
||||
"wayland": true,
|
||||
"dbus": true,
|
||||
"pulse": true
|
||||
"pipewire": true
|
||||
},
|
||||
"session_bus": {
|
||||
"see": null,
|
||||
|
||||
@@ -25,8 +25,7 @@ var (
|
||||
|
||||
func TestUpdate(t *testing.T) {
|
||||
if os.Getenv("GO_TEST_SKIP_ACL") == "1" {
|
||||
t.Log("acl test skipped")
|
||||
t.SkipNow()
|
||||
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
|
||||
}
|
||||
|
||||
@@ -53,6 +53,10 @@ type syscallDispatcher interface {
|
||||
readdir(name string) ([]os.DirEntry, error)
|
||||
// tempdir provides [os.TempDir].
|
||||
tempdir() string
|
||||
// mkdir provides [os.Mkdir].
|
||||
mkdir(name string, perm os.FileMode) error
|
||||
// removeAll provides [os.RemoveAll].
|
||||
removeAll(path string) error
|
||||
// exit provides [os.Exit].
|
||||
exit(code int)
|
||||
|
||||
@@ -62,6 +66,8 @@ type syscallDispatcher interface {
|
||||
// lookupGroupId calls [user.LookupGroup] and returns the Gid field of the resulting [user.Group] struct.
|
||||
lookupGroupId(name string) (string, error)
|
||||
|
||||
// lookPath provides exec.LookPath.
|
||||
lookPath(file string) (string, error)
|
||||
// cmdOutput provides the Output method of [exec.Cmd].
|
||||
cmdOutput(cmd *exec.Cmd) ([]byte, error)
|
||||
|
||||
@@ -121,6 +127,8 @@ func (direct) stat(name string) (os.FileInfo, error) { return os.Stat(name)
|
||||
func (direct) open(name string) (osFile, error) { return os.Open(name) }
|
||||
func (direct) readdir(name string) ([]os.DirEntry, error) { return os.ReadDir(name) }
|
||||
func (direct) tempdir() string { return os.TempDir() }
|
||||
func (direct) mkdir(name string, perm os.FileMode) error { return os.Mkdir(name, perm) }
|
||||
func (direct) removeAll(path string) error { return os.RemoveAll(path) }
|
||||
func (direct) exit(code int) { os.Exit(code) }
|
||||
|
||||
func (direct) evalSymlinks(path string) (string, error) { return filepath.EvalSymlinks(path) }
|
||||
@@ -134,6 +142,7 @@ func (direct) lookupGroupId(name string) (gid string, err error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (direct) lookPath(file string) (string, error) { return exec.LookPath(file) }
|
||||
func (direct) cmdOutput(cmd *exec.Cmd) ([]byte, error) { return cmd.Output() }
|
||||
|
||||
func (direct) notifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc) {
|
||||
|
||||
@@ -701,10 +701,13 @@ func (panicDispatcher) stat(string) (os.FileInfo, error) { pa
|
||||
func (panicDispatcher) open(string) (osFile, error) { panic("unreachable") }
|
||||
func (panicDispatcher) readdir(string) ([]os.DirEntry, error) { panic("unreachable") }
|
||||
func (panicDispatcher) tempdir() string { panic("unreachable") }
|
||||
func (panicDispatcher) mkdir(string, os.FileMode) error { panic("unreachable") }
|
||||
func (panicDispatcher) removeAll(string) error { panic("unreachable") }
|
||||
func (panicDispatcher) exit(int) { panic("unreachable") }
|
||||
func (panicDispatcher) evalSymlinks(string) (string, error) { panic("unreachable") }
|
||||
func (panicDispatcher) prctl(uintptr, uintptr, uintptr) error { panic("unreachable") }
|
||||
func (panicDispatcher) lookupGroupId(string) (string, error) { panic("unreachable") }
|
||||
func (panicDispatcher) lookPath(string) (string, error) { panic("unreachable") }
|
||||
func (panicDispatcher) cmdOutput(*exec.Cmd) ([]byte, error) { panic("unreachable") }
|
||||
func (panicDispatcher) overflowUid(message.Msg) int { panic("unreachable") }
|
||||
func (panicDispatcher) overflowGid(message.Msg) int { panic("unreachable") }
|
||||
|
||||
@@ -70,7 +70,7 @@ type outcomeState struct {
|
||||
// Copied from their respective exported values.
|
||||
mapuid, mapgid *stringPair[int]
|
||||
|
||||
// Copied from [EnvPaths] per-process.
|
||||
// Copied from [env.Paths] per-process.
|
||||
sc hst.Paths
|
||||
*env.Paths
|
||||
|
||||
@@ -172,6 +172,10 @@ type outcomeStateSys struct {
|
||||
|
||||
// Copied from [hst.Config]. Safe for read by spWaylandOp.toSystem only.
|
||||
directWayland bool
|
||||
// Copied from [hst.Config]. Safe for read by spPipeWireOp.toSystem only.
|
||||
directPipeWire bool
|
||||
// Copied from [hst.Config]. Safe for read by spPulseOp.toSystem only.
|
||||
directPulse bool
|
||||
// Copied header from [hst.Config]. Safe for read by spFilesystemOp.toSystem only.
|
||||
extraPerms []hst.ExtraPermConfig
|
||||
// Copied address from [hst.Config]. Safe for read by spDBusOp.toSystem only.
|
||||
@@ -185,8 +189,8 @@ type outcomeStateSys struct {
|
||||
func (s *outcomeState) newSys(config *hst.Config, sys *system.I) *outcomeStateSys {
|
||||
return &outcomeStateSys{
|
||||
appId: config.ID, et: config.Enablements.Unwrap(),
|
||||
directWayland: config.DirectWayland, extraPerms: config.ExtraPerms,
|
||||
sessionBus: config.SessionBus, systemBus: config.SystemBus,
|
||||
directWayland: config.DirectWayland, directPipeWire: config.DirectPipeWire, directPulse: config.DirectPulse,
|
||||
extraPerms: config.ExtraPerms, sessionBus: config.SessionBus, systemBus: config.SystemBus,
|
||||
sys: sys, outcomeState: s,
|
||||
}
|
||||
}
|
||||
@@ -253,6 +257,10 @@ type outcomeStateParams struct {
|
||||
// Populated by spRuntimeOp.
|
||||
runtimeDir *check.Absolute
|
||||
|
||||
// Path to pipewire-pulse server.
|
||||
// Populated by spPipeWireOp if DirectPipeWire is false.
|
||||
pipewirePulsePath *check.Absolute
|
||||
|
||||
as hst.ApplyState
|
||||
*outcomeState
|
||||
}
|
||||
@@ -292,6 +300,7 @@ func (state *outcomeStateSys) toSystem() error {
|
||||
// optional via enablements
|
||||
&spWaylandOp{},
|
||||
&spX11Op{},
|
||||
&spPipeWireOp{},
|
||||
&spPulseOp{},
|
||||
&spDBusOp{},
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ import (
|
||||
"hakurei.app/message"
|
||||
)
|
||||
|
||||
func TestOutcomeMain(t *testing.T) {
|
||||
func TestOutcomeRun(t *testing.T) {
|
||||
t.Parallel()
|
||||
msg := message.New(nil)
|
||||
msg.SwapVerbose(testing.Verbose())
|
||||
@@ -67,18 +67,12 @@ func TestOutcomeMain(t *testing.T) {
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
).
|
||||
|
||||
// ensureRuntimeDir
|
||||
Ensure(m("/run/user/1971"), 0700).
|
||||
UpdatePermType(system.User, m("/run/user/1971"), acl.Execute).
|
||||
Ensure(m("/run/user/1971/hakurei"), 0700).
|
||||
UpdatePermType(system.User, m("/run/user/1971/hakurei"), acl.Execute).
|
||||
|
||||
// runtime
|
||||
Ephemeral(system.Process, m("/run/user/1971/hakurei/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), 0700).
|
||||
UpdatePerm(m("/run/user/1971/hakurei/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"), acl.Execute).
|
||||
|
||||
// spPulseOp
|
||||
Link(m("/run/user/1971/pulse/native"), m("/run/user/1971/hakurei/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/pulse")).
|
||||
// spPipeWireOp
|
||||
PipeWire(
|
||||
m("/tmp/hakurei.0/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/pipewire"),
|
||||
"org.chromium.Chromium",
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
).
|
||||
|
||||
// spDBusOp
|
||||
MustProxyDBus(
|
||||
@@ -106,8 +100,6 @@ func TestOutcomeMain(t *testing.T) {
|
||||
"GOOGLE_DEFAULT_CLIENT_ID=77185425430.apps.googleusercontent.com",
|
||||
"GOOGLE_DEFAULT_CLIENT_SECRET=OTJgUOQcT7lO7GsGZq2G4IlT",
|
||||
"HOME=/data/data/org.chromium.Chromium",
|
||||
"PULSE_COOKIE=/.hakurei/pulse-cookie",
|
||||
"PULSE_SERVER=unix:/run/user/1971/pulse/native",
|
||||
"SHELL=/run/current-system/sw/bin/zsh",
|
||||
"TERM=xterm-256color",
|
||||
"USER=chronos",
|
||||
@@ -144,7 +136,7 @@ func TestOutcomeMain(t *testing.T) {
|
||||
Tmpfs(fhs.AbsDevShm, 0, 01777).
|
||||
|
||||
// spRuntimeOp
|
||||
Tmpfs(fhs.AbsRunUser, 1<<12, 0755).
|
||||
Tmpfs(fhs.AbsRunUser, xdgRuntimeDirSize, 0755).
|
||||
Bind(m("/tmp/hakurei.0/runtime/9"), m("/run/user/1971"), std.BindWritable).
|
||||
|
||||
// spTmpdirOp
|
||||
@@ -157,10 +149,6 @@ func TestOutcomeMain(t *testing.T) {
|
||||
// spWaylandOp
|
||||
Bind(m("/tmp/hakurei.0/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/wayland"), m("/run/user/1971/wayland-0"), 0).
|
||||
|
||||
// spPulseOp
|
||||
Bind(m("/run/user/1971/hakurei/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/pulse"), m("/run/user/1971/pulse/native"), 0).
|
||||
Place(m("/.hakurei/pulse-cookie"), bytes.Repeat([]byte{0}, pulseCookieSizeMax)).
|
||||
|
||||
// spDBusOp
|
||||
Bind(m("/tmp/hakurei.0/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bus"), m("/run/user/1971/bus"), 0).
|
||||
Bind(m("/tmp/hakurei.0/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/system_bus_socket"), m("/var/run/dbus/system_bus_socket"), 0).
|
||||
@@ -182,7 +170,7 @@ func TestOutcomeMain(t *testing.T) {
|
||||
Remount(fhs.AbsRoot, syscall.MS_RDONLY),
|
||||
}},
|
||||
|
||||
{"nixos permissive defaults no enablements", new(stubNixOS), &hst.Config{Container: &hst.ContainerConfig{
|
||||
{"nixos permissive defaults no enablements", new(stubNixOS), &hst.Config{DirectPipeWire: true, Container: &hst.ContainerConfig{
|
||||
Filesystem: []hst.FilesystemConfigJSON{
|
||||
{FilesystemConfig: &hst.FSBind{
|
||||
Target: fhs.AbsRoot,
|
||||
@@ -244,7 +232,7 @@ func TestOutcomeMain(t *testing.T) {
|
||||
Tmpfs(hst.AbsPrivateTmp, 4096, 0755).
|
||||
DevWritable(m("/dev/"), true).
|
||||
Tmpfs(m("/dev/shm/"), 0, 01777).
|
||||
Tmpfs(m("/run/user/"), 4096, 0755).
|
||||
Tmpfs(m("/run/user/"), xdgRuntimeDirSize, 0755).
|
||||
Bind(m("/tmp/hakurei.0/runtime/0"), m("/run/user/65534"), std.BindWritable).
|
||||
Bind(m("/tmp/hakurei.0/tmpdir/0"), m("/tmp/"), std.BindWritable).
|
||||
Place(m("/etc/passwd"), []byte("chronos:x:65534:65534:Hakurei:/home/chronos:/run/current-system/sw/bin/zsh\n")).
|
||||
@@ -264,6 +252,8 @@ func TestOutcomeMain(t *testing.T) {
|
||||
}},
|
||||
|
||||
{"nixos permissive defaults chromium", new(stubNixOS), &hst.Config{
|
||||
DirectPipeWire: true,
|
||||
|
||||
ID: "org.chromium.Chromium",
|
||||
Identity: 9,
|
||||
Groups: []string{"video"},
|
||||
@@ -298,7 +288,7 @@ func TestOutcomeMain(t *testing.T) {
|
||||
},
|
||||
Filter: true,
|
||||
},
|
||||
Enablements: hst.NewEnablements(hst.EWayland | hst.EDBus | hst.EPulse),
|
||||
Enablements: hst.NewEnablements(hst.EWayland | hst.EDBus | hst.EPipeWire | hst.EPulse),
|
||||
|
||||
Container: &hst.ContainerConfig{
|
||||
Filesystem: []hst.FilesystemConfigJSON{
|
||||
@@ -347,10 +337,7 @@ func TestOutcomeMain(t *testing.T) {
|
||||
Ensure(m("/tmp/hakurei.0/tmpdir/9"), 01700).UpdatePermType(system.User, m("/tmp/hakurei.0/tmpdir/9"), acl.Read, acl.Write, acl.Execute).
|
||||
Ephemeral(system.Process, m("/tmp/hakurei.0/ebf083d1b175911782d413369b64ce7c"), 0711).
|
||||
Wayland(m("/tmp/hakurei.0/ebf083d1b175911782d413369b64ce7c/wayland"), m("/run/user/1971/wayland-0"), "org.chromium.Chromium", "ebf083d1b175911782d413369b64ce7c").
|
||||
Ensure(m("/run/user/1971"), 0700).UpdatePermType(system.User, m("/run/user/1971"), acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
|
||||
Ensure(m("/run/user/1971/hakurei"), 0700).UpdatePermType(system.User, m("/run/user/1971/hakurei"), acl.Execute).
|
||||
Ephemeral(system.Process, m("/run/user/1971/hakurei/ebf083d1b175911782d413369b64ce7c"), 0700).UpdatePermType(system.Process, m("/run/user/1971/hakurei/ebf083d1b175911782d413369b64ce7c"), acl.Execute).
|
||||
Link(m("/run/user/1971/pulse/native"), m("/run/user/1971/hakurei/ebf083d1b175911782d413369b64ce7c/pulse")).
|
||||
PipeWire(m("/tmp/hakurei.0/ebf083d1b175911782d413369b64ce7c/pipewire"), "org.chromium.Chromium", "ebf083d1b175911782d413369b64ce7c").
|
||||
MustProxyDBus(&hst.BusConfig{
|
||||
Talk: []string{
|
||||
"org.freedesktop.Notifications",
|
||||
@@ -397,8 +384,7 @@ func TestOutcomeMain(t *testing.T) {
|
||||
"DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/65534/bus",
|
||||
"DBUS_SYSTEM_BUS_ADDRESS=unix:path=/var/run/dbus/system_bus_socket",
|
||||
"HOME=/home/chronos",
|
||||
"PULSE_COOKIE=" + hst.PrivateTmp + "/pulse-cookie",
|
||||
"PULSE_SERVER=unix:/run/user/65534/pulse/native",
|
||||
"PIPEWIRE_REMOTE=/run/user/65534/pipewire-0",
|
||||
"SHELL=/run/current-system/sw/bin/zsh",
|
||||
"TERM=xterm-256color",
|
||||
"USER=chronos",
|
||||
@@ -413,14 +399,13 @@ func TestOutcomeMain(t *testing.T) {
|
||||
Tmpfs(hst.AbsPrivateTmp, 4096, 0755).
|
||||
DevWritable(m("/dev/"), true).
|
||||
Tmpfs(m("/dev/shm/"), 0, 01777).
|
||||
Tmpfs(m("/run/user/"), 4096, 0755).
|
||||
Tmpfs(m("/run/user/"), xdgRuntimeDirSize, 0755).
|
||||
Bind(m("/tmp/hakurei.0/runtime/9"), m("/run/user/65534"), std.BindWritable).
|
||||
Bind(m("/tmp/hakurei.0/tmpdir/9"), m("/tmp/"), std.BindWritable).
|
||||
Place(m("/etc/passwd"), []byte("chronos:x:65534:65534:Hakurei:/home/chronos:/run/current-system/sw/bin/zsh\n")).
|
||||
Place(m("/etc/group"), []byte("hakurei:x:65534:\n")).
|
||||
Bind(m("/tmp/hakurei.0/ebf083d1b175911782d413369b64ce7c/wayland"), m("/run/user/65534/wayland-0"), 0).
|
||||
Bind(m("/run/user/1971/hakurei/ebf083d1b175911782d413369b64ce7c/pulse"), m("/run/user/65534/pulse/native"), 0).
|
||||
Place(m(hst.PrivateTmp+"/pulse-cookie"), bytes.Repeat([]byte{0}, pulseCookieSizeMax)).
|
||||
Bind(m("/tmp/hakurei.0/ebf083d1b175911782d413369b64ce7c/pipewire"), m("/run/user/65534/pipewire-0"), 0).
|
||||
Bind(m("/tmp/hakurei.0/ebf083d1b175911782d413369b64ce7c/bus"), m("/run/user/65534/bus"), 0).
|
||||
Bind(m("/tmp/hakurei.0/ebf083d1b175911782d413369b64ce7c/system_bus_socket"), m("/var/run/dbus/system_bus_socket"), 0).
|
||||
Bind(m("/dev/dri"), m("/dev/dri"), std.BindWritable|std.BindDevice|std.BindOptional).
|
||||
@@ -439,8 +424,10 @@ func TestOutcomeMain(t *testing.T) {
|
||||
}},
|
||||
|
||||
{"nixos chromium direct wayland", new(stubNixOS), &hst.Config{
|
||||
DirectPipeWire: true,
|
||||
|
||||
ID: "org.chromium.Chromium",
|
||||
Enablements: hst.NewEnablements(hst.EWayland | hst.EDBus | hst.EPulse),
|
||||
Enablements: hst.NewEnablements(hst.EWayland | hst.EDBus | hst.EPipeWire | hst.EPulse),
|
||||
Container: &hst.ContainerConfig{
|
||||
Env: nil,
|
||||
Filesystem: []hst.FilesystemConfigJSON{
|
||||
@@ -502,9 +489,8 @@ func TestOutcomeMain(t *testing.T) {
|
||||
Ensure(m("/run/user/1971"), 0700).UpdatePermType(system.User, m("/run/user/1971"), acl.Execute). // this is ordered as is because the previous Ensure only calls mkdir if XDG_RUNTIME_DIR is unset
|
||||
Ensure(m("/run/user/1971/hakurei"), 0700).UpdatePermType(system.User, m("/run/user/1971/hakurei"), acl.Execute).
|
||||
UpdatePermType(hst.EWayland, m("/run/user/1971/wayland-0"), acl.Read, acl.Write, acl.Execute).
|
||||
Ephemeral(system.Process, m("/run/user/1971/hakurei/8e2c76b066dabe574cf073bdb46eb5c1"), 0700).UpdatePermType(system.Process, m("/run/user/1971/hakurei/8e2c76b066dabe574cf073bdb46eb5c1"), acl.Execute).
|
||||
Link(m("/run/user/1971/pulse/native"), m("/run/user/1971/hakurei/8e2c76b066dabe574cf073bdb46eb5c1/pulse")).
|
||||
Ephemeral(system.Process, m("/tmp/hakurei.0/8e2c76b066dabe574cf073bdb46eb5c1"), 0711).
|
||||
PipeWire(m("/tmp/hakurei.0/8e2c76b066dabe574cf073bdb46eb5c1/pipewire"), "org.chromium.Chromium", "8e2c76b066dabe574cf073bdb46eb5c1").
|
||||
MustProxyDBus(&hst.BusConfig{
|
||||
Talk: []string{
|
||||
"org.freedesktop.FileManager1", "org.freedesktop.Notifications",
|
||||
@@ -544,8 +530,7 @@ func TestOutcomeMain(t *testing.T) {
|
||||
"DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1971/bus",
|
||||
"DBUS_SYSTEM_BUS_ADDRESS=unix:path=/var/run/dbus/system_bus_socket",
|
||||
"HOME=/var/lib/persist/module/hakurei/0/1",
|
||||
"PULSE_COOKIE=" + hst.PrivateTmp + "/pulse-cookie",
|
||||
"PULSE_SERVER=unix:/run/user/1971/pulse/native",
|
||||
"PIPEWIRE_REMOTE=/run/user/1971/pipewire-0",
|
||||
"SHELL=/run/current-system/sw/bin/zsh",
|
||||
"TERM=xterm-256color",
|
||||
"USER=u0_a1",
|
||||
@@ -559,14 +544,13 @@ func TestOutcomeMain(t *testing.T) {
|
||||
Tmpfs(hst.AbsPrivateTmp, 4096, 0755).
|
||||
DevWritable(m("/dev/"), true).
|
||||
Tmpfs(m("/dev/shm/"), 0, 01777).
|
||||
Tmpfs(m("/run/user/"), 4096, 0755).
|
||||
Tmpfs(m("/run/user/"), xdgRuntimeDirSize, 0755).
|
||||
Bind(m("/tmp/hakurei.0/runtime/1"), m("/run/user/1971"), std.BindWritable).
|
||||
Bind(m("/tmp/hakurei.0/tmpdir/1"), m("/tmp/"), std.BindWritable).
|
||||
Place(m("/etc/passwd"), []byte("u0_a1:x:1971:100:Hakurei:/var/lib/persist/module/hakurei/0/1:/run/current-system/sw/bin/zsh\n")).
|
||||
Place(m("/etc/group"), []byte("hakurei:x:100:\n")).
|
||||
Bind(m("/run/user/1971/wayland-0"), m("/run/user/1971/wayland-0"), 0).
|
||||
Bind(m("/run/user/1971/hakurei/8e2c76b066dabe574cf073bdb46eb5c1/pulse"), m("/run/user/1971/pulse/native"), 0).
|
||||
Place(m(hst.PrivateTmp+"/pulse-cookie"), bytes.Repeat([]byte{0}, pulseCookieSizeMax)).
|
||||
Bind(m("/tmp/hakurei.0/8e2c76b066dabe574cf073bdb46eb5c1/pipewire"), m("/run/user/1971/pipewire-0"), 0).
|
||||
Bind(m("/tmp/hakurei.0/8e2c76b066dabe574cf073bdb46eb5c1/bus"), m("/run/user/1971/bus"), 0).
|
||||
Bind(m("/tmp/hakurei.0/8e2c76b066dabe574cf073bdb46eb5c1/system_bus_socket"), m("/var/run/dbus/system_bus_socket"), 0).
|
||||
Bind(m("/bin"), m("/bin"), 0).
|
||||
@@ -899,6 +883,16 @@ func (k *stubNixOS) lookupGroupId(name string) (string, error) {
|
||||
}
|
||||
}
|
||||
|
||||
func (k *stubNixOS) lookPath(file string) (string, error) {
|
||||
switch file {
|
||||
case "pipewire-pulse":
|
||||
return "/run/current-system/sw/bin/pipewire-pulse", nil
|
||||
|
||||
default:
|
||||
panic(fmt.Sprintf("unexpected file %q", file))
|
||||
}
|
||||
}
|
||||
|
||||
func (k *stubNixOS) cmdOutput(cmd *exec.Cmd) ([]byte, error) {
|
||||
switch cmd.Path {
|
||||
case "/proc/nonexistent/hsu":
|
||||
|
||||
@@ -14,9 +14,12 @@ import (
|
||||
"time"
|
||||
|
||||
"hakurei.app/container"
|
||||
"hakurei.app/container/check"
|
||||
"hakurei.app/container/fhs"
|
||||
"hakurei.app/container/seccomp"
|
||||
"hakurei.app/container/std"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal/pipewire"
|
||||
"hakurei.app/message"
|
||||
)
|
||||
|
||||
@@ -83,6 +86,55 @@ func Shim(msg message.Msg) {
|
||||
shimEntrypoint(direct{msg})
|
||||
}
|
||||
|
||||
// A shimPrivate holds state of the private work directory owned by shim.
|
||||
type shimPrivate struct {
|
||||
// Path to directory if created.
|
||||
pathname *check.Absolute
|
||||
|
||||
k syscallDispatcher
|
||||
id *stringPair[hst.ID]
|
||||
}
|
||||
|
||||
// unwrap returns the underlying pathname.
|
||||
func (sp *shimPrivate) unwrap() *check.Absolute {
|
||||
if sp.pathname == nil {
|
||||
if a, err := check.NewAbs(sp.k.tempdir()); err != nil {
|
||||
sp.k.fatal(err)
|
||||
panic("unreachable")
|
||||
} else {
|
||||
pathname := a.Append(".hakurei-shim-" + sp.id.String())
|
||||
sp.k.getMsg().Verbosef("creating private work directory %q", pathname)
|
||||
if err = sp.k.mkdir(pathname.String(), 0700); err != nil {
|
||||
sp.k.fatal(err)
|
||||
panic("unreachable")
|
||||
}
|
||||
sp.pathname = pathname
|
||||
return sp.unwrap()
|
||||
}
|
||||
} else {
|
||||
return sp.pathname
|
||||
}
|
||||
}
|
||||
|
||||
// String returns the absolute pathname to the directory held by shimPrivate.
|
||||
func (sp *shimPrivate) String() string { return sp.unwrap().String() }
|
||||
|
||||
// destroy removes the directory held by shimPrivate.
|
||||
func (sp *shimPrivate) destroy() {
|
||||
defer func() { sp.pathname = nil }()
|
||||
if sp.pathname != nil {
|
||||
sp.k.getMsg().Verbosef("destroying private work directory %q", sp.pathname)
|
||||
if err := sp.k.removeAll(sp.pathname.String()); err != nil {
|
||||
sp.k.getMsg().GetLogger().Println(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
// shimPipeWireTimeout is the duration pipewire-pulse is allowed to run before its socket becomes available.
|
||||
shimPipeWireTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
func shimEntrypoint(k syscallDispatcher) {
|
||||
msg := k.getMsg()
|
||||
if msg == nil {
|
||||
@@ -208,6 +260,7 @@ func shimEntrypoint(k syscallDispatcher) {
|
||||
|
||||
ctx, stop := k.notifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
cancelContainer.Store(&stop)
|
||||
sp := shimPrivate{k: k, id: state.id}
|
||||
z := container.New(ctx, msg)
|
||||
z.Params = *stateParams.params
|
||||
z.Stdin, z.Stdout, z.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
@@ -215,6 +268,79 @@ func shimEntrypoint(k syscallDispatcher) {
|
||||
// bounds and default enforced in finalise.go
|
||||
z.WaitDelay = state.Shim.WaitDelay
|
||||
|
||||
if stateParams.pipewirePulsePath != nil {
|
||||
zpw := container.NewCommand(ctx, msg, stateParams.pipewirePulsePath, pipewirePulseName)
|
||||
zpw.Hostname = "hakurei-" + pipewirePulseName
|
||||
zpw.SeccompFlags |= seccomp.AllowMultiarch
|
||||
zpw.SeccompPresets |= std.PresetStrict
|
||||
zpw.Env = []string{
|
||||
// pipewire SecurityContext socket path
|
||||
pipewire.Remote + "=" + stateParams.instancePath().Append("pipewire").String(),
|
||||
// pipewire-pulse socket directory path
|
||||
envXDGRuntimeDir + "=" + sp.String(),
|
||||
}
|
||||
if msg.IsVerbose() {
|
||||
zpw.Stdin, zpw.Stdout, zpw.Stderr = os.Stdin, os.Stdout, os.Stderr
|
||||
}
|
||||
zpw.
|
||||
Bind(fhs.AbsRoot, fhs.AbsRoot, 0).
|
||||
Bind(sp.unwrap(), sp.unwrap(), std.BindWritable).
|
||||
Proc(fhs.AbsProc).Dev(fhs.AbsDev, true)
|
||||
socketPath := sp.unwrap().Append("pulse", "native")
|
||||
innerSocketPath := stateParams.runtimeDir.Append("pulse", "native")
|
||||
|
||||
if err := k.containerStart(zpw); err != nil {
|
||||
sp.destroy()
|
||||
printMessageError(func(v ...any) { k.fatal(fmt.Sprintln(v...)) },
|
||||
"cannot start "+pipewirePulseName+" container:", err)
|
||||
}
|
||||
if err := k.containerServe(zpw); err != nil {
|
||||
sp.destroy()
|
||||
printMessageError(func(v ...any) { k.fatal(fmt.Sprintln(v...)) },
|
||||
"cannot configure "+pipewirePulseName+" container:", err)
|
||||
}
|
||||
|
||||
done := make(chan error, 1)
|
||||
k.new(func(k syscallDispatcher, msg message.Msg) { done <- k.containerWait(zpw) })
|
||||
|
||||
socketTimer := time.NewTimer(shimPipeWireTimeout)
|
||||
for {
|
||||
select {
|
||||
case <-socketTimer.C:
|
||||
sp.destroy()
|
||||
k.fatal(pipewirePulseName + " exceeded deadline before socket appeared")
|
||||
break
|
||||
|
||||
case err := <-done:
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) {
|
||||
msg.Verbosef("cannot wait: %v", err)
|
||||
k.exit(127)
|
||||
}
|
||||
sp.destroy()
|
||||
k.fatal(pipewirePulseName + " " + exitError.ProcessState.String())
|
||||
break
|
||||
|
||||
default:
|
||||
if _, err := k.stat(socketPath.String()); err != nil {
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
sp.destroy()
|
||||
k.fatal(err)
|
||||
break
|
||||
}
|
||||
|
||||
time.Sleep(500 * time.Microsecond)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
z.Bind(socketPath, innerSocketPath, 0)
|
||||
z.Env = append(z.Env, "PULSE_SERVER=unix:"+innerSocketPath.String())
|
||||
}
|
||||
|
||||
if err := k.containerStart(z); err != nil {
|
||||
var f func(v ...any)
|
||||
if logger := msg.GetLogger(); logger != nil {
|
||||
@@ -225,9 +351,11 @@ func shimEntrypoint(k syscallDispatcher) {
|
||||
}
|
||||
}
|
||||
printMessageError(f, "cannot start container:", err)
|
||||
sp.destroy()
|
||||
k.exit(hst.ExitFailure)
|
||||
}
|
||||
if err := k.containerServe(z); err != nil {
|
||||
sp.destroy()
|
||||
printMessageError(func(v ...any) { k.fatal(fmt.Sprintln(v...)) },
|
||||
"cannot configure container:", err)
|
||||
}
|
||||
@@ -236,10 +364,13 @@ func shimEntrypoint(k syscallDispatcher) {
|
||||
seccomp.Preset(std.PresetStrict, seccomp.AllowMultiarch),
|
||||
seccomp.AllowMultiarch,
|
||||
); err != nil {
|
||||
sp.destroy()
|
||||
k.fatalf("cannot load syscall filter: %v", err)
|
||||
}
|
||||
|
||||
if err := k.containerWait(z); err != nil {
|
||||
sp.destroy()
|
||||
|
||||
var exitError *exec.ExitError
|
||||
if !errors.As(err, &exitError) {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
@@ -250,4 +381,5 @@ func shimEntrypoint(k syscallDispatcher) {
|
||||
}
|
||||
k.exit(exitError.ExitCode())
|
||||
}
|
||||
sp.destroy()
|
||||
}
|
||||
|
||||
@@ -69,7 +69,7 @@ func TestShimEntrypoint(t *testing.T) {
|
||||
Tmpfs(fhs.AbsDevShm, 0, 01777).
|
||||
|
||||
// spRuntimeOp
|
||||
Tmpfs(fhs.AbsRunUser, 1<<12, 0755).
|
||||
Tmpfs(fhs.AbsRunUser, xdgRuntimeDirSize, 0755).
|
||||
Bind(m("/tmp/hakurei.10/runtime/9999"), m("/run/user/1000"), std.BindWritable).
|
||||
|
||||
// spTmpdirOp
|
||||
|
||||
@@ -382,6 +382,10 @@ func (p opsAdapter) Link(target *check.Absolute, linkName string, dereference bo
|
||||
return opsAdapter{p.Ops.Link(target, linkName, dereference)}
|
||||
}
|
||||
|
||||
func (p opsAdapter) Daemon(target, path *check.Absolute, args ...string) hst.Ops {
|
||||
return opsAdapter{p.Ops.Daemon(target, path, args...)}
|
||||
}
|
||||
|
||||
func (p opsAdapter) Root(host *check.Absolute, flags int) hst.Ops {
|
||||
return opsAdapter{p.Ops.Root(host, flags)}
|
||||
}
|
||||
|
||||
53
internal/outcome/sppipewire.go
Normal file
53
internal/outcome/sppipewire.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package outcome
|
||||
|
||||
import (
|
||||
"encoding/gob"
|
||||
|
||||
"hakurei.app/container/check"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal/pipewire"
|
||||
)
|
||||
|
||||
const pipewirePulseName = "pipewire-pulse"
|
||||
|
||||
func init() { gob.Register(new(spPipeWireOp)) }
|
||||
|
||||
// spPipeWireOp exports the PipeWire server to the container via SecurityContext.
|
||||
// Runs after spRuntimeOp.
|
||||
type spPipeWireOp struct {
|
||||
// Path to pipewire-pulse server. Populated during toSystem if DirectPipeWire is false.
|
||||
CompatServerPath *check.Absolute
|
||||
}
|
||||
|
||||
func (s *spPipeWireOp) toSystem(state *outcomeStateSys) error {
|
||||
if state.et&hst.EPipeWire == 0 {
|
||||
return errNotEnabled
|
||||
}
|
||||
if !state.directPipeWire {
|
||||
if n, err := state.k.lookPath(pipewirePulseName); err != nil {
|
||||
return &hst.AppError{Step: "look up " + pipewirePulseName, Err: err}
|
||||
} else if s.CompatServerPath, err = check.NewAbs(n); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
appId := state.appId
|
||||
if appId == "" {
|
||||
// use instance ID in case app id is not set
|
||||
appId = "app.hakurei." + state.id.String()
|
||||
}
|
||||
state.sys.PipeWire(state.instance().Append("pipewire"), appId, state.id.String())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *spPipeWireOp) toContainer(state *outcomeStateParams) error {
|
||||
if s.CompatServerPath == nil {
|
||||
innerPath := state.runtimeDir.Append(pipewire.PW_DEFAULT_REMOTE)
|
||||
state.env[pipewire.Remote] = innerPath.String()
|
||||
state.params.Bind(state.instancePath().Append("pipewire"), innerPath, 0)
|
||||
}
|
||||
|
||||
// pipewire-pulse behaviour implemented in shim.go
|
||||
state.pipewirePulsePath = s.CompatServerPath
|
||||
return nil
|
||||
}
|
||||
49
internal/outcome/sppipewire_test.go
Normal file
49
internal/outcome/sppipewire_test.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package outcome
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"hakurei.app/container"
|
||||
"hakurei.app/container/stub"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal/pipewire"
|
||||
"hakurei.app/internal/system"
|
||||
)
|
||||
|
||||
func TestSpPipeWireOp(t *testing.T) {
|
||||
t.Parallel()
|
||||
config := hst.Template()
|
||||
|
||||
checkOpBehaviour(t, []opBehaviourTestCase{
|
||||
{"not enabled", func(bool, bool) outcomeOp {
|
||||
return new(spPipeWireOp)
|
||||
}, func() *hst.Config {
|
||||
c := hst.Template()
|
||||
*c.Enablements = 0
|
||||
return c
|
||||
}, nil, nil, nil, nil, errNotEnabled, nil, nil, nil, nil, nil},
|
||||
|
||||
{"success", func(bool, bool) outcomeOp {
|
||||
return new(spPipeWireOp)
|
||||
}, func() *hst.Config {
|
||||
c := hst.Template()
|
||||
c.DirectPipeWire = true
|
||||
return c
|
||||
}, nil, []stub.Call{}, newI().
|
||||
// state.instance
|
||||
Ephemeral(system.Process, m(wantInstancePrefix), 0711).
|
||||
// toSystem
|
||||
PipeWire(
|
||||
m(wantInstancePrefix+"/pipewire"),
|
||||
"org.chromium.Chromium",
|
||||
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
), sysUsesInstance(nil), nil, insertsOps(afterSpRuntimeOp(nil)), []stub.Call{
|
||||
// this op configures the container state and does not make calls during toContainer
|
||||
}, &container.Params{
|
||||
Ops: new(container.Ops).
|
||||
Bind(m(wantInstancePrefix+"/pipewire"), m("/run/user/1000/pipewire-0"), 0),
|
||||
}, paramsWantEnv(config, map[string]string{
|
||||
pipewire.Remote: "/run/user/1000/pipewire-0",
|
||||
}, nil), nil},
|
||||
})
|
||||
}
|
||||
@@ -29,7 +29,7 @@ type spPulseOp struct {
|
||||
}
|
||||
|
||||
func (s *spPulseOp) toSystem(state *outcomeStateSys) error {
|
||||
if state.et&hst.EPulse == 0 {
|
||||
if !state.directPulse || state.et&hst.EPulse == 0 {
|
||||
return errNotEnabled
|
||||
}
|
||||
|
||||
|
||||
@@ -18,24 +18,40 @@ import (
|
||||
func TestSpPulseOp(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
config := hst.Template()
|
||||
newConfig := func() *hst.Config {
|
||||
config := hst.Template()
|
||||
config.DirectPulse = true
|
||||
config.Enablements = hst.NewEnablements(hst.EPulse)
|
||||
return config
|
||||
}
|
||||
|
||||
config := newConfig()
|
||||
sampleCookie := bytes.Repeat([]byte{0xfc}, pulseCookieSizeMax)
|
||||
|
||||
checkOpBehaviour(t, []opBehaviourTestCase{
|
||||
{"not enabled", func(bool, bool) outcomeOp {
|
||||
return new(spPulseOp)
|
||||
}, func() *hst.Config {
|
||||
c := hst.Template()
|
||||
c := newConfig()
|
||||
c.DirectPulse = true
|
||||
*c.Enablements = 0
|
||||
return c
|
||||
}, nil, nil, nil, nil, errNotEnabled, nil, nil, nil, nil, nil},
|
||||
|
||||
{"not enabled direct", func(bool, bool) outcomeOp {
|
||||
return new(spPulseOp)
|
||||
}, func() *hst.Config {
|
||||
c := newConfig()
|
||||
c.DirectPulse = false
|
||||
return c
|
||||
}, nil, nil, nil, nil, errNotEnabled, nil, nil, nil, nil, nil},
|
||||
|
||||
{"socketDir stat", func(isShim, _ bool) outcomeOp {
|
||||
if !isShim {
|
||||
return new(spPulseOp)
|
||||
}
|
||||
return &spPulseOp{Cookie: (*[256]byte)(sampleCookie)}
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), stub.UniqueError(2)),
|
||||
}, nil, nil, &hst.AppError{
|
||||
Step: `access PulseAudio directory "/proc/nonexistent/xdg_runtime_dir/pulse"`,
|
||||
@@ -44,7 +60,7 @@ func TestSpPulseOp(t *testing.T) {
|
||||
|
||||
{"socketDir nonexistent", func(bool, bool) outcomeOp {
|
||||
return new(spPulseOp)
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), os.ErrNotExist),
|
||||
}, nil, nil, &hst.AppError{
|
||||
Step: "finalise",
|
||||
@@ -54,7 +70,7 @@ func TestSpPulseOp(t *testing.T) {
|
||||
|
||||
{"socket stat", func(bool, bool) outcomeOp {
|
||||
return new(spPulseOp)
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), nil),
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse/native"}, (*stubFi)(nil), stub.UniqueError(1)),
|
||||
}, nil, nil, &hst.AppError{
|
||||
@@ -64,7 +80,7 @@ func TestSpPulseOp(t *testing.T) {
|
||||
|
||||
{"socket nonexistent", func(bool, bool) outcomeOp {
|
||||
return new(spPulseOp)
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), nil),
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse/native"}, (*stubFi)(nil), os.ErrNotExist),
|
||||
}, nil, nil, &hst.AppError{
|
||||
@@ -75,7 +91,7 @@ func TestSpPulseOp(t *testing.T) {
|
||||
|
||||
{"socket mode", func(bool, bool) outcomeOp {
|
||||
return new(spPulseOp)
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), nil),
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse/native"}, &stubFi{mode: 0660}, nil),
|
||||
}, nil, nil, &hst.AppError{
|
||||
@@ -86,18 +102,18 @@ func TestSpPulseOp(t *testing.T) {
|
||||
|
||||
{"cookie notAbs", func(bool, bool) outcomeOp {
|
||||
return new(spPulseOp)
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), nil),
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse/native"}, &stubFi{mode: 0666}, nil),
|
||||
call("lookupEnv", stub.ExpectArgs{"PULSE_COOKIE"}, "proc/nonexistent/cookie", nil),
|
||||
}, nil, nil, &hst.AppError{
|
||||
Step: "locate PulseAudio cookie",
|
||||
Err: &check.AbsoluteError{Pathname: "proc/nonexistent/cookie"},
|
||||
Err: check.AbsoluteError("proc/nonexistent/cookie"),
|
||||
}, nil, nil, nil, nil, nil},
|
||||
|
||||
{"cookie loadFile", func(bool, bool) outcomeOp {
|
||||
return new(spPulseOp)
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), nil),
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse/native"}, &stubFi{mode: 0666}, nil),
|
||||
call("lookupEnv", stub.ExpectArgs{"PULSE_COOKIE"}, "/proc/nonexistent/cookie", nil),
|
||||
@@ -118,7 +134,7 @@ func TestSpPulseOp(t *testing.T) {
|
||||
op.CookieSize += +0xfd
|
||||
}
|
||||
return op
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), nil),
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse/native"}, &stubFi{mode: 0666}, nil),
|
||||
call("lookupEnv", stub.ExpectArgs{"PULSE_COOKIE"}, "/proc/nonexistent/cookie", nil),
|
||||
@@ -150,7 +166,7 @@ func TestSpPulseOp(t *testing.T) {
|
||||
sampleCookieTrunc := make([]byte, pulseCookieSizeMax)
|
||||
copy(sampleCookieTrunc, sampleCookie[:len(sampleCookie)-0xe])
|
||||
return &spPulseOp{Cookie: (*[pulseCookieSizeMax]byte)(sampleCookieTrunc), CookieSize: pulseCookieSizeMax - 0xe}
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), nil),
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse/native"}, &stubFi{mode: 0666}, nil),
|
||||
call("lookupEnv", stub.ExpectArgs{"PULSE_COOKIE"}, "/proc/nonexistent/cookie", nil),
|
||||
@@ -183,7 +199,7 @@ func TestSpPulseOp(t *testing.T) {
|
||||
return new(spPulseOp)
|
||||
}
|
||||
return &spPulseOp{Cookie: (*[pulseCookieSizeMax]byte)(sampleCookie), CookieSize: pulseCookieSizeMax}
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), nil),
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse/native"}, &stubFi{mode: 0666}, nil),
|
||||
call("lookupEnv", stub.ExpectArgs{"PULSE_COOKIE"}, "/proc/nonexistent/cookie", nil),
|
||||
@@ -213,7 +229,7 @@ func TestSpPulseOp(t *testing.T) {
|
||||
|
||||
{"success", func(bool, bool) outcomeOp {
|
||||
return new(spPulseOp)
|
||||
}, hst.Template, nil, []stub.Call{
|
||||
}, newConfig, nil, []stub.Call{
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse"}, (*stubFi)(nil), nil),
|
||||
call("stat", stub.ExpectArgs{wantRuntimePath + "/pulse/native"}, &stubFi{mode: 0666}, nil),
|
||||
call("lookupEnv", stub.ExpectArgs{"PULSE_COOKIE"}, nil, nil),
|
||||
@@ -256,7 +272,7 @@ func TestDiscoverPulseCookie(t *testing.T) {
|
||||
call("verbose", stub.ExpectArgs{[]any{(*check.Absolute)(nil)}}, nil, nil),
|
||||
}}, &hst.AppError{
|
||||
Step: "locate PulseAudio cookie",
|
||||
Err: &check.AbsoluteError{Pathname: "proc/nonexistent/pulse-cookie"},
|
||||
Err: check.AbsoluteError("proc/nonexistent/pulse-cookie"),
|
||||
}},
|
||||
|
||||
{"success override", fCheckPathname, stub.Expect{Calls: []stub.Call{
|
||||
@@ -270,7 +286,7 @@ func TestDiscoverPulseCookie(t *testing.T) {
|
||||
call("verbose", stub.ExpectArgs{[]any{(*check.Absolute)(nil)}}, nil, nil),
|
||||
}}, &hst.AppError{
|
||||
Step: "locate PulseAudio cookie",
|
||||
Err: &check.AbsoluteError{Pathname: "proc/nonexistent/home"},
|
||||
Err: check.AbsoluteError("proc/nonexistent/home"),
|
||||
}},
|
||||
|
||||
{"home stat", fCheckPathname, stub.Expect{Calls: []stub.Call{
|
||||
@@ -305,7 +321,7 @@ func TestDiscoverPulseCookie(t *testing.T) {
|
||||
call("verbose", stub.ExpectArgs{[]any{(*check.Absolute)(nil)}}, nil, nil),
|
||||
}}, &hst.AppError{
|
||||
Step: "locate PulseAudio cookie",
|
||||
Err: &check.AbsoluteError{Pathname: "proc/nonexistent/xdg"},
|
||||
Err: check.AbsoluteError("proc/nonexistent/xdg"),
|
||||
}},
|
||||
|
||||
{"xdg stat", fCheckPathname, stub.Expect{Calls: []stub.Call{
|
||||
|
||||
@@ -91,6 +91,9 @@ func (s *spRuntimeOp) toSystem(state *outcomeStateSys) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// xdgRuntimeDirSize is the size of the filesystem mounted on inner XDG_RUNTIME_DIR.
|
||||
const xdgRuntimeDirSize = 1 << 24
|
||||
|
||||
func (s *spRuntimeOp) toContainer(state *outcomeStateParams) error {
|
||||
state.runtimeDir = fhs.AbsRunUser.Append(state.mapuid.String())
|
||||
state.env[envXDGRuntimeDir] = state.runtimeDir.String()
|
||||
@@ -108,7 +111,7 @@ func (s *spRuntimeOp) toContainer(state *outcomeStateParams) error {
|
||||
|
||||
}
|
||||
|
||||
state.params.Tmpfs(fhs.AbsRunUser, 1<<12, 0755)
|
||||
state.params.Tmpfs(fhs.AbsRunUser, xdgRuntimeDirSize, 0755)
|
||||
if state.Container.Flags&hst.FShareRuntime != 0 {
|
||||
_, runtimeDirInst := s.commonPaths(state.outcomeState)
|
||||
state.params.Bind(runtimeDirInst, state.runtimeDir, std.BindWritable)
|
||||
|
||||
@@ -40,7 +40,7 @@ func TestSpRuntimeOp(t *testing.T) {
|
||||
// this op configures the container state and does not make calls during toContainer
|
||||
}, &container.Params{
|
||||
Ops: new(container.Ops).
|
||||
Tmpfs(fhs.AbsRunUser, 1<<12, 0755).
|
||||
Tmpfs(fhs.AbsRunUser, xdgRuntimeDirSize, 0755).
|
||||
Bind(m("/proc/nonexistent/tmp/hakurei.0/runtime/9"), m("/run/user/1000"), std.BindWritable),
|
||||
}, paramsWantEnv(config, map[string]string{
|
||||
"XDG_RUNTIME_DIR": "/run/user/1000",
|
||||
@@ -67,7 +67,7 @@ func TestSpRuntimeOp(t *testing.T) {
|
||||
// this op configures the container state and does not make calls during toContainer
|
||||
}, &container.Params{
|
||||
Ops: new(container.Ops).
|
||||
Tmpfs(fhs.AbsRunUser, 1<<12, 0755).
|
||||
Tmpfs(fhs.AbsRunUser, xdgRuntimeDirSize, 0755).
|
||||
Bind(m("/proc/nonexistent/tmp/hakurei.0/runtime/9"), m("/run/user/1000"), std.BindWritable),
|
||||
}, paramsWantEnv(config, map[string]string{
|
||||
"XDG_RUNTIME_DIR": "/run/user/1000",
|
||||
@@ -94,7 +94,7 @@ func TestSpRuntimeOp(t *testing.T) {
|
||||
// this op configures the container state and does not make calls during toContainer
|
||||
}, &container.Params{
|
||||
Ops: new(container.Ops).
|
||||
Tmpfs(fhs.AbsRunUser, 1<<12, 0755).
|
||||
Tmpfs(fhs.AbsRunUser, xdgRuntimeDirSize, 0755).
|
||||
Bind(m("/proc/nonexistent/tmp/hakurei.0/runtime/9"), m("/run/user/1000"), std.BindWritable),
|
||||
}, paramsWantEnv(config, map[string]string{
|
||||
"XDG_RUNTIME_DIR": "/run/user/1000",
|
||||
@@ -117,7 +117,7 @@ func TestSpRuntimeOp(t *testing.T) {
|
||||
// this op configures the container state and does not make calls during toContainer
|
||||
}, &container.Params{
|
||||
Ops: new(container.Ops).
|
||||
Tmpfs(fhs.AbsRunUser, 1<<12, 0755).
|
||||
Tmpfs(fhs.AbsRunUser, xdgRuntimeDirSize, 0755).
|
||||
Bind(m("/proc/nonexistent/tmp/hakurei.0/runtime/9"), m("/run/user/1000"), std.BindWritable),
|
||||
}, paramsWantEnv(config, map[string]string{
|
||||
"XDG_RUNTIME_DIR": "/run/user/1000",
|
||||
|
||||
129
internal/pipewire/client.go
Normal file
129
internal/pipewire/client.go
Normal file
@@ -0,0 +1,129 @@
|
||||
package pipewire
|
||||
|
||||
/* pipewire/client.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_Client = PW_TYPE_INFO_INTERFACE_BASE + "Client"
|
||||
PW_CLIENT_PERM_MASK = PW_PERM_RWXM
|
||||
PW_VERSION_CLIENT = 3
|
||||
|
||||
PW_ID_CLIENT = 1
|
||||
)
|
||||
|
||||
const (
|
||||
PW_CLIENT_CHANGE_MASK_PROPS = 1 << iota
|
||||
|
||||
PW_CLIENT_CHANGE_MASK_ALL = 1<<iota - 1
|
||||
)
|
||||
|
||||
const (
|
||||
PW_CLIENT_EVENT_INFO = iota
|
||||
PW_CLIENT_EVENT_PERMISSIONS
|
||||
PW_CLIENT_EVENT_NUM
|
||||
|
||||
PW_VERSION_CLIENT_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_CLIENT_METHOD_ADD_LISTENER = iota
|
||||
PW_CLIENT_METHOD_ERROR
|
||||
PW_CLIENT_METHOD_UPDATE_PROPERTIES
|
||||
PW_CLIENT_METHOD_GET_PERMISSIONS
|
||||
PW_CLIENT_METHOD_UPDATE_PERMISSIONS
|
||||
PW_CLIENT_METHOD_NUM
|
||||
|
||||
PW_VERSION_CLIENT_METHODS = 0
|
||||
)
|
||||
|
||||
// The ClientInfo event provides client information updates.
|
||||
// This is emitted when binding to a client or when the client info is updated later.
|
||||
type ClientInfo struct {
|
||||
// The global id of the client.
|
||||
ID Int `json:"id"`
|
||||
// The changes emitted by this event.
|
||||
ChangeMask Long `json:"change_mask"`
|
||||
// Properties of this object, valid when change_mask has PW_CLIENT_CHANGE_MASK_PROPS.
|
||||
Properties *SPADict `json:"props"`
|
||||
}
|
||||
|
||||
// Opcode satisfies [Message] with a constant value.
|
||||
func (c *ClientInfo) Opcode() byte { return PW_CLIENT_EVENT_INFO }
|
||||
|
||||
// FileCount satisfies [Message] with a constant value.
|
||||
func (c *ClientInfo) FileCount() Int { return 0 }
|
||||
|
||||
// Size satisfies [KnownSize] with a value computed at runtime.
|
||||
func (c *ClientInfo) Size() Word {
|
||||
return SizePrefix +
|
||||
Size(SizeInt) +
|
||||
Size(SizeLong) +
|
||||
c.Properties.Size()
|
||||
}
|
||||
|
||||
// MarshalBinary satisfies [encoding.BinaryMarshaler] via [Marshal].
|
||||
func (c *ClientInfo) MarshalBinary() ([]byte, error) { return Marshal(c) }
|
||||
|
||||
// UnmarshalBinary satisfies [encoding.BinaryUnmarshaler] via [Unmarshal].
|
||||
func (c *ClientInfo) UnmarshalBinary(data []byte) error { return Unmarshal(data, c) }
|
||||
|
||||
// ClientUpdateProperties is used to update the properties of a client.
|
||||
type ClientUpdateProperties struct {
|
||||
// Properties to update on the client.
|
||||
Properties *SPADict `json:"props"`
|
||||
}
|
||||
|
||||
// Opcode satisfies [Message] with a constant value.
|
||||
func (c *ClientUpdateProperties) Opcode() byte { return PW_CLIENT_METHOD_UPDATE_PROPERTIES }
|
||||
|
||||
// FileCount satisfies [Message] with a constant value.
|
||||
func (c *ClientUpdateProperties) FileCount() Int { return 0 }
|
||||
|
||||
// Size satisfies [KnownSize] with a value computed at runtime.
|
||||
func (c *ClientUpdateProperties) Size() Word { return SizePrefix + c.Properties.Size() }
|
||||
|
||||
// MarshalBinary satisfies [encoding.BinaryMarshaler] via [Marshal].
|
||||
func (c *ClientUpdateProperties) MarshalBinary() ([]byte, error) { return Marshal(c) }
|
||||
|
||||
// UnmarshalBinary satisfies [encoding.BinaryUnmarshaler] via [Unmarshal].
|
||||
func (c *ClientUpdateProperties) UnmarshalBinary(data []byte) error { return Unmarshal(data, c) }
|
||||
|
||||
// clientUpdateProperties queues a [ClientUpdateProperties] message for the PipeWire server.
|
||||
// This method should not be called directly, the New function queues this message.
|
||||
func (ctx *Context) clientUpdateProperties(props SPADict) error {
|
||||
return ctx.writeMessage(
|
||||
PW_ID_CLIENT,
|
||||
&ClientUpdateProperties{&props},
|
||||
)
|
||||
}
|
||||
|
||||
// Client holds state of [PW_TYPE_INTERFACE_Client].
|
||||
type Client struct {
|
||||
// Additional information from the server, populated or updated during [Context.Roundtrip].
|
||||
Info *ClientInfo `json:"info"`
|
||||
|
||||
// Populated by [CoreBoundProps] events targeting [Client].
|
||||
Properties SPADict `json:"props"`
|
||||
|
||||
noRemove
|
||||
}
|
||||
|
||||
func (client *Client) consume(opcode byte, files []int, unmarshal func(v any)) error {
|
||||
closeReceivedFiles(files...)
|
||||
switch opcode {
|
||||
case PW_CLIENT_EVENT_INFO:
|
||||
unmarshal(&client.Info)
|
||||
return nil
|
||||
|
||||
default:
|
||||
panic(&UnsupportedOpcodeError{opcode, client.String()})
|
||||
}
|
||||
}
|
||||
|
||||
func (client *Client) setBoundProps(event *CoreBoundProps) error {
|
||||
if event.Properties != nil {
|
||||
client.Properties = *event.Properties
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (client *Client) String() string { return PW_TYPE_INTERFACE_Registry }
|
||||
157
internal/pipewire/client_test.go
Normal file
157
internal/pipewire/client_test.go
Normal file
@@ -0,0 +1,157 @@
|
||||
package pipewire_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"hakurei.app/internal/pipewire"
|
||||
)
|
||||
|
||||
func TestClientInfo(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.ClientInfo, *pipewire.ClientInfo]{
|
||||
{"sample", samplePWContainer[1][2][1], pipewire.ClientInfo{
|
||||
ID: 34,
|
||||
ChangeMask: pipewire.PW_CLIENT_CHANGE_MASK_PROPS,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-0"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_ID, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "34"},
|
||||
}}, nil},
|
||||
|
||||
{"sample*", samplePWContainer[1][3][1], pipewire.ClientInfo{
|
||||
ID: 34,
|
||||
ChangeMask: pipewire.PW_CLIENT_CHANGE_MASK_PROPS,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-alice-1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_ID, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_REMOTE_INTENTION, Value: "manager"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_BINARY, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_LANGUAGE, Value: "en_US.UTF-8"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_ID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_USER, Value: "alice"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_HOST, Value: "nixos"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_SESSION_ID, Value: "1"},
|
||||
{Key: pipewire.PW_KEY_WINDOW_X11_DISPLAY, Value: ":0"},
|
||||
{Key: "cpu.vm.name", Value: "qemu"},
|
||||
{Key: "log.level", Value: "0"},
|
||||
{Key: pipewire.PW_KEY_CPU_MAX_ALIGN, Value: "32"},
|
||||
{Key: "default.clock.rate", Value: "48000"},
|
||||
{Key: "default.clock.quantum", Value: "1024"},
|
||||
{Key: "default.clock.min-quantum", Value: "32"},
|
||||
{Key: "default.clock.max-quantum", Value: "2048"},
|
||||
{Key: "default.clock.quantum-limit", Value: "8192"},
|
||||
{Key: "default.clock.quantum-floor", Value: "4"},
|
||||
{Key: "default.video.width", Value: "640"},
|
||||
{Key: "default.video.height", Value: "480"},
|
||||
{Key: "default.video.rate.num", Value: "25"},
|
||||
{Key: "default.video.rate.denom", Value: "1"},
|
||||
{Key: "clock.power-of-two-quantum", Value: "true"},
|
||||
{Key: "link.max-buffers", Value: "64"},
|
||||
{Key: "mem.warn-mlock", Value: "false"},
|
||||
{Key: "mem.allow-mlock", Value: "true"},
|
||||
{Key: "settings.check-quantum", Value: "false"},
|
||||
{Key: "settings.check-rate", Value: "false"},
|
||||
{Key: pipewire.PW_KEY_CORE_VERSION, Value: "1.4.7"},
|
||||
}}, nil},
|
||||
|
||||
{"sample**", samplePWContainer[1][4][1], pipewire.ClientInfo{
|
||||
ID: 34,
|
||||
ChangeMask: pipewire.PW_CLIENT_CHANGE_MASK_PROPS,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-alice-1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_ID, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_REMOTE_INTENTION, Value: "manager"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_BINARY, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_LANGUAGE, Value: "en_US.UTF-8"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_ID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_USER, Value: "alice"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_HOST, Value: "nixos"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_SESSION_ID, Value: "1"},
|
||||
{Key: pipewire.PW_KEY_WINDOW_X11_DISPLAY, Value: ":0"},
|
||||
{Key: "cpu.vm.name", Value: "qemu"},
|
||||
{Key: "log.level", Value: "0"},
|
||||
{Key: pipewire.PW_KEY_CPU_MAX_ALIGN, Value: "32"},
|
||||
{Key: "default.clock.rate", Value: "48000"},
|
||||
{Key: "default.clock.quantum", Value: "1024"},
|
||||
{Key: "default.clock.min-quantum", Value: "32"},
|
||||
{Key: "default.clock.max-quantum", Value: "2048"},
|
||||
{Key: "default.clock.quantum-limit", Value: "8192"},
|
||||
{Key: "default.clock.quantum-floor", Value: "4"},
|
||||
{Key: "default.video.width", Value: "640"},
|
||||
{Key: "default.video.height", Value: "480"},
|
||||
{Key: "default.video.rate.num", Value: "25"},
|
||||
{Key: "default.video.rate.denom", Value: "1"},
|
||||
{Key: "clock.power-of-two-quantum", Value: "true"},
|
||||
{Key: "link.max-buffers", Value: "64"},
|
||||
{Key: "mem.warn-mlock", Value: "false"},
|
||||
{Key: "mem.allow-mlock", Value: "true"},
|
||||
{Key: "settings.check-quantum", Value: "false"},
|
||||
{Key: "settings.check-rate", Value: "false"},
|
||||
{Key: pipewire.PW_KEY_CORE_VERSION, Value: "1.4.7"},
|
||||
{Key: pipewire.PW_KEY_ACCESS, Value: "unrestricted"},
|
||||
},
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestClientUpdateProperties(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.ClientUpdateProperties, *pipewire.ClientUpdateProperties]{
|
||||
{"sample", samplePWContainer[0][1][1], pipewire.ClientUpdateProperties{Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_REMOTE_INTENTION, Value: "manager"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_BINARY, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_LANGUAGE, Value: "en_US.UTF-8"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_ID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_USER, Value: "alice"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_HOST, Value: "nixos"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_SESSION_ID, Value: "1"},
|
||||
{Key: pipewire.PW_KEY_WINDOW_X11_DISPLAY, Value: ":0"},
|
||||
{Key: "cpu.vm.name", Value: "qemu"},
|
||||
{Key: "log.level", Value: "0"},
|
||||
{Key: pipewire.PW_KEY_CPU_MAX_ALIGN, Value: "32"},
|
||||
{Key: "default.clock.rate", Value: "48000"},
|
||||
{Key: "default.clock.quantum", Value: "1024"},
|
||||
{Key: "default.clock.min-quantum", Value: "32"},
|
||||
{Key: "default.clock.max-quantum", Value: "2048"},
|
||||
{Key: "default.clock.quantum-limit", Value: "8192"},
|
||||
{Key: "default.clock.quantum-floor", Value: "4"},
|
||||
{Key: "default.video.width", Value: "640"},
|
||||
{Key: "default.video.height", Value: "480"},
|
||||
{Key: "default.video.rate.num", Value: "25"},
|
||||
{Key: "default.video.rate.denom", Value: "1"},
|
||||
{Key: "clock.power-of-two-quantum", Value: "true"},
|
||||
{Key: "link.max-buffers", Value: "64"},
|
||||
{Key: "mem.warn-mlock", Value: "false"},
|
||||
{Key: "mem.allow-mlock", Value: "true"},
|
||||
{Key: "settings.check-quantum", Value: "false"},
|
||||
{Key: "settings.check-rate", Value: "false"},
|
||||
{Key: pipewire.PW_KEY_CORE_VERSION, Value: "1.4.7"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-alice-1443"},
|
||||
}}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
1054
internal/pipewire/core.go
Normal file
1054
internal/pipewire/core.go
Normal file
File diff suppressed because it is too large
Load Diff
888
internal/pipewire/core_test.go
Normal file
888
internal/pipewire/core_test.go
Normal file
@@ -0,0 +1,888 @@
|
||||
package pipewire_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"hakurei.app/internal/pipewire"
|
||||
)
|
||||
|
||||
func TestFooterCoreGeneration(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.Footer[pipewire.FooterCoreGeneration], *pipewire.Footer[pipewire.FooterCoreGeneration]]{
|
||||
|
||||
/* recvmsg 0 */
|
||||
|
||||
{"sample0", samplePWContainer[1][0][2], pipewire.Footer[pipewire.FooterCoreGeneration]{
|
||||
Opcode: pipewire.FOOTER_CORE_OPCODE_GENERATION,
|
||||
Payload: pipewire.FooterCoreGeneration{RegistryGeneration: 0x22},
|
||||
}, nil},
|
||||
|
||||
{"sample1", samplePWContainer[1][5][2], pipewire.Footer[pipewire.FooterCoreGeneration]{
|
||||
Opcode: pipewire.FOOTER_CORE_OPCODE_GENERATION,
|
||||
Payload: pipewire.FooterCoreGeneration{RegistryGeneration: 0x23},
|
||||
}, nil},
|
||||
|
||||
// happens on the last message, client footer sent in the next roundtrip
|
||||
{"sample2", samplePWContainer[1][42][2], pipewire.Footer[pipewire.FooterCoreGeneration]{
|
||||
Opcode: pipewire.FOOTER_CORE_OPCODE_GENERATION,
|
||||
Payload: pipewire.FooterCoreGeneration{RegistryGeneration: 0x24},
|
||||
}, nil},
|
||||
}.run(t)
|
||||
|
||||
encodingTestCases[pipewire.Footer[pipewire.FooterClientGeneration], *pipewire.Footer[pipewire.FooterClientGeneration]]{
|
||||
|
||||
/* sendmsg 1 */
|
||||
|
||||
{"sample0", samplePWContainer[3][0][2], pipewire.Footer[pipewire.FooterClientGeneration]{
|
||||
Opcode: pipewire.FOOTER_CORE_OPCODE_GENERATION,
|
||||
// triggered by difference in sample1, sample0 is overwritten in the same roundtrip
|
||||
Payload: pipewire.FooterClientGeneration{ClientGeneration: 0x23},
|
||||
}, nil},
|
||||
|
||||
/* sendmsg 2 */
|
||||
|
||||
{"sample1", samplePWContainer[6][0][2], pipewire.Footer[pipewire.FooterClientGeneration]{
|
||||
// triggered by difference in sample2, last footer in the previous roundtrip
|
||||
Opcode: pipewire.FOOTER_CORE_OPCODE_GENERATION,
|
||||
Payload: pipewire.FooterClientGeneration{ClientGeneration: 0x24},
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreInfo(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreInfo, *pipewire.CoreInfo]{
|
||||
{"sample", samplePWContainer[1][0][1], pipewire.CoreInfo{
|
||||
ID: 0,
|
||||
Cookie: -2069267610,
|
||||
UserName: "alice",
|
||||
HostName: "nixos",
|
||||
Version: "1.4.7",
|
||||
Name: "pipewire-0",
|
||||
ChangeMask: pipewire.PW_CORE_CHANGE_MASK_PROPS,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_CONFIG_NAME, Value: "pipewire.conf"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "pipewire"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_BINARY, Value: "pipewire"},
|
||||
{Key: pipewire.PW_KEY_APP_LANGUAGE, Value: "en_US.UTF-8"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_ID, Value: "1446"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_USER, Value: "alice"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_HOST, Value: "nixos"},
|
||||
{Key: pipewire.PW_KEY_WINDOW_X11_DISPLAY, Value: ":0"},
|
||||
{Key: "cpu.vm.name", Value: "qemu"},
|
||||
{Key: "link.max-buffers", Value: "16"},
|
||||
{Key: pipewire.PW_KEY_CORE_DAEMON, Value: "true"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-0"},
|
||||
{Key: "default.clock.min-quantum", Value: "1024"},
|
||||
{Key: pipewire.PW_KEY_CPU_MAX_ALIGN, Value: "32"},
|
||||
{Key: "default.clock.rate", Value: "48000"},
|
||||
{Key: "default.clock.quantum", Value: "1024"},
|
||||
{Key: "default.clock.max-quantum", Value: "2048"},
|
||||
{Key: "default.clock.quantum-limit", Value: "8192"},
|
||||
{Key: "default.clock.quantum-floor", Value: "4"},
|
||||
{Key: "default.video.width", Value: "640"},
|
||||
{Key: "default.video.height", Value: "480"},
|
||||
{Key: "default.video.rate.num", Value: "25"},
|
||||
{Key: "default.video.rate.denom", Value: "1"},
|
||||
{Key: "log.level", Value: "2"},
|
||||
{Key: "clock.power-of-two-quantum", Value: "true"},
|
||||
{Key: "mem.warn-mlock", Value: "false"},
|
||||
{Key: "mem.allow-mlock", Value: "true"},
|
||||
{Key: "settings.check-quantum", Value: "false"},
|
||||
{Key: "settings.check-rate", Value: "false"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_ID, Value: "0"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "0"}},
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreDone(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreDone, *pipewire.CoreDone]{
|
||||
{"sample0", samplePWContainer[1][5][1], pipewire.CoreDone{
|
||||
ID: -1,
|
||||
Sequence: 0,
|
||||
}, nil},
|
||||
|
||||
// matches the Core::Sync sample
|
||||
{"sample1", samplePWContainer[1][41][1], pipewire.CoreDone{
|
||||
ID: 0,
|
||||
Sequence: pipewire.CoreSyncSequenceOffset + 3,
|
||||
}, nil},
|
||||
|
||||
// matches the second Core::Sync sample
|
||||
{"sample2", samplePWContainer[7][0][1], pipewire.CoreDone{
|
||||
ID: 0,
|
||||
Sequence: pipewire.CoreSyncSequenceOffset + 6,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCorePing(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CorePing, *pipewire.CorePing]{
|
||||
// handmade sample
|
||||
{"sample", []byte{
|
||||
/* size: rest of data */ 0x20, 0, 0, 0,
|
||||
/* type: Struct */ byte(pipewire.SPA_TYPE_Struct), 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ byte(pipewire.SPA_TYPE_Int), 0, 0, 0,
|
||||
/* value: -1 */ 0xff, 0xff, 0xff, 0xff,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ byte(pipewire.SPA_TYPE_Int), 0, 0, 0,
|
||||
/* value: 0 */ 0, 0, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
}, pipewire.CorePing{
|
||||
ID: -1,
|
||||
Sequence: 0,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreError(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreError, *pipewire.CoreError]{
|
||||
// captured from pw-cli
|
||||
{"pw-cli", []byte{
|
||||
/* size: rest of data */ 0x58, 0, 0, 0,
|
||||
/* type: Struct */ 0xe, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: 2 */ 2, 0, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: 0x67 */ 0x67, 0, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: -1 */ 0xff, 0xff, 0xff, 0xff,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
|
||||
/* size: 0x1b bytes */ 0x1b, 0, 0, 0,
|
||||
/* type: String */ 8, 0, 0, 0,
|
||||
|
||||
// value: "no permission to destroy 0\x00"
|
||||
0x6e, 0x6f, 0x20, 0x70,
|
||||
0x65, 0x72, 0x6d, 0x69,
|
||||
0x73, 0x73, 0x69, 0x6f,
|
||||
0x6e, 0x20, 0x74, 0x6f,
|
||||
0x20, 0x64, 0x65, 0x73,
|
||||
0x74, 0x72, 0x6f, 0x79,
|
||||
0x20, 0x30, 0,
|
||||
|
||||
/* padding */ 0, 0, 0, 0, 0,
|
||||
}, pipewire.CoreError{
|
||||
ID: 2,
|
||||
Sequence: 0x67,
|
||||
Result: -1,
|
||||
Message: "no permission to destroy 0",
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreRemoveId(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreRemoveId, *pipewire.CoreRemoveId]{
|
||||
{"sample", []byte{
|
||||
/* size: rest of data */ 0x10, 0, 0, 0,
|
||||
/* type: Struct */ 0xe, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: 3 */ 3, 0, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
}, pipewire.CoreRemoveId{
|
||||
ID: 3,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreBoundProps(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreBoundProps, *pipewire.CoreBoundProps]{
|
||||
|
||||
/* recvmsg 0 */
|
||||
|
||||
{"sample0", samplePWContainer[1][1][1], pipewire.CoreBoundProps{
|
||||
ID: pipewire.PW_ID_CLIENT,
|
||||
GlobalID: 34,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
/* recvmsg 1 */
|
||||
|
||||
{"sample1", samplePWContainer[4][0][1], pipewire.CoreBoundProps{
|
||||
ID: 3,
|
||||
GlobalID: 3,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "3"},
|
||||
},
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreHello(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreHello, *pipewire.CoreHello]{
|
||||
{"sample", samplePWContainer[0][0][1], pipewire.CoreHello{
|
||||
Version: pipewire.PW_VERSION_CORE,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreSync(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreSync, *pipewire.CoreSync]{
|
||||
{"sample0", samplePWContainer[0][3][1], pipewire.CoreSync{
|
||||
ID: 0,
|
||||
Sequence: pipewire.CoreSyncSequenceOffset + 3,
|
||||
}, nil},
|
||||
|
||||
{"sample1", samplePWContainer[6][1][1], pipewire.CoreSync{
|
||||
ID: 0,
|
||||
Sequence: pipewire.CoreSyncSequenceOffset + 6,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCorePong(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CorePong, *pipewire.CorePong]{
|
||||
// handmade sample
|
||||
{"sample", []byte{
|
||||
/* size: rest of data */ 0x20, 0, 0, 0,
|
||||
/* type: Struct */ byte(pipewire.SPA_TYPE_Struct), 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ byte(pipewire.SPA_TYPE_Int), 0, 0, 0,
|
||||
/* value: -1 */ 0xff, 0xff, 0xff, 0xff,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ byte(pipewire.SPA_TYPE_Int), 0, 0, 0,
|
||||
/* value: 0 */ 0, 0, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
}, pipewire.CorePong{
|
||||
ID: -1,
|
||||
Sequence: 0,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreGetRegistry(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreGetRegistry, *pipewire.CoreGetRegistry]{
|
||||
{"sample", samplePWContainer[0][2][1], pipewire.CoreGetRegistry{
|
||||
Version: pipewire.PW_VERSION_REGISTRY,
|
||||
// this ends up as the Id of PW_TYPE_INTERFACE_Registry
|
||||
NewID: 2,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreCreateObject(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreCreateObject, *pipewire.CoreCreateObject]{
|
||||
{"sample", []byte{
|
||||
/* size: rest of data */ 0x80, 0, 0, 0,
|
||||
/* type: Struct */ 0xe, 0, 0, 0,
|
||||
|
||||
/* size: 0x13 bytes */ 0x13, 0, 0, 0,
|
||||
/* type: String */ 8, 0, 0, 0,
|
||||
|
||||
// value: "spa-device-factory\x00"
|
||||
0x73, 0x70, 0x61, 0x2d,
|
||||
0x64, 0x65, 0x76, 0x69,
|
||||
0x63, 0x65, 0x2d, 0x66,
|
||||
0x61, 0x63, 0x74, 0x6f,
|
||||
0x72, 0x79, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
|
||||
/* size: 0x1a bytes */ 0x1a, 0, 0, 0,
|
||||
/* type: String */ 8, 0, 0, 0,
|
||||
|
||||
// value: "PipeWire:Interface:Device\x00"
|
||||
0x50, 0x69, 0x70, 0x65,
|
||||
0x57, 0x69, 0x72, 0x65,
|
||||
0x3a, 0x49, 0x6e, 0x74,
|
||||
0x65, 0x72, 0x66, 0x61,
|
||||
0x63, 0x65, 0x3a, 0x44,
|
||||
0x65, 0x76, 0x69, 0x63,
|
||||
0x65, 0, 0, 0,
|
||||
0, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: 3 */ 3, 0, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
|
||||
/* size */ 0x10, 0, 0, 0,
|
||||
/* type: Struct */ 0xe, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: 0 */ 0, 0, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: 0xbad */ 0xad, 0xb, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
}, pipewire.CoreCreateObject{
|
||||
FactoryName: "spa-device-factory",
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Device,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{},
|
||||
NewID: 0xbad,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestCoreDestroy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.CoreDestroy, *pipewire.CoreDestroy]{
|
||||
{"sample", []byte{
|
||||
/* size: rest of data */ 0x10, 0, 0, 0,
|
||||
/* type: Struct */ 0xe, 0, 0, 0,
|
||||
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: 3 */ 3, 0, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
}, pipewire.CoreDestroy{
|
||||
ID: 3,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestRegistryGlobal(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.RegistryGlobal, *pipewire.RegistryGlobal]{
|
||||
{"sample0", samplePWContainer[1][6][1], pipewire.RegistryGlobal{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Permissions: pipewire.PW_CORE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Core,
|
||||
Version: pipewire.PW_VERSION_CORE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "0"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-0"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample1", samplePWContainer[1][7][1], pipewire.RegistryGlobal{
|
||||
ID: 1,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "1"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-rt"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample2", samplePWContainer[1][8][1], pipewire.RegistryGlobal{
|
||||
ID: 3,
|
||||
Permissions: pipewire.PW_SECURITY_CONTEXT_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_SecurityContext,
|
||||
Version: pipewire.PW_VERSION_SECURITY_CONTEXT,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "3"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample3", samplePWContainer[1][9][1], pipewire.RegistryGlobal{
|
||||
ID: 2,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-protocol-native"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample4", samplePWContainer[1][10][1], pipewire.RegistryGlobal{
|
||||
ID: 5,
|
||||
Permissions: pipewire.PW_PROFILER_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Profiler,
|
||||
Version: pipewire.PW_VERSION_PROFILER,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "5"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample5", samplePWContainer[1][11][1], pipewire.RegistryGlobal{
|
||||
ID: 4,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "4"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-profiler"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample6", samplePWContainer[1][12][1], pipewire.RegistryGlobal{
|
||||
ID: 6,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "6"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-metadata"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample7", samplePWContainer[1][13][1], pipewire.RegistryGlobal{
|
||||
ID: 7,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "7"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "6"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "metadata"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Metadata},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample8", samplePWContainer[1][14][1], pipewire.RegistryGlobal{
|
||||
ID: 8,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "8"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-spa-device-factory"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample9", samplePWContainer[1][15][1], pipewire.RegistryGlobal{
|
||||
ID: 9,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "9"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "8"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "spa-device-factory"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Device},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample10", samplePWContainer[1][16][1], pipewire.RegistryGlobal{
|
||||
ID: 10,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "10"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-spa-node-factory"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample11", samplePWContainer[1][17][1], pipewire.RegistryGlobal{
|
||||
ID: 11,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "11"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "10"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "spa-node-factory"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Node},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample12", samplePWContainer[1][18][1], pipewire.RegistryGlobal{
|
||||
ID: 12,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "12"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-client-node"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample13", samplePWContainer[1][19][1], pipewire.RegistryGlobal{
|
||||
ID: 13,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "13"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "12"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "client-node"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_ClientNode},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "6"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample14", samplePWContainer[1][20][1], pipewire.RegistryGlobal{
|
||||
ID: 14,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "14"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-client-device"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample15", samplePWContainer[1][21][1], pipewire.RegistryGlobal{
|
||||
ID: 15,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "15"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "14"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "client-device"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "Spa:Pointer:Interface:Device"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample16", samplePWContainer[1][22][1], pipewire.RegistryGlobal{
|
||||
ID: 16,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "16"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-portal"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample17", samplePWContainer[1][23][1], pipewire.RegistryGlobal{
|
||||
ID: 17,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "17"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-access"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample18", samplePWContainer[1][24][1], pipewire.RegistryGlobal{
|
||||
ID: 18,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "18"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-adapter"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample19", samplePWContainer[1][25][1], pipewire.RegistryGlobal{
|
||||
ID: 19,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "19"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "18"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "adapter"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Node},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample20", samplePWContainer[1][26][1], pipewire.RegistryGlobal{
|
||||
ID: 20,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "20"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-link-factory"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample21", samplePWContainer[1][27][1], pipewire.RegistryGlobal{
|
||||
ID: 21,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "21"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "20"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "link-factory"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Link},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample22", samplePWContainer[1][28][1], pipewire.RegistryGlobal{
|
||||
ID: 22,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-session-manager"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample23", samplePWContainer[1][29][1], pipewire.RegistryGlobal{
|
||||
ID: 23,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "23"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "client-endpoint"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:ClientEndpoint"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample24", samplePWContainer[1][30][1], pipewire.RegistryGlobal{
|
||||
ID: 24,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "24"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "client-session"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:ClientSession"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample25", samplePWContainer[1][31][1], pipewire.RegistryGlobal{
|
||||
ID: 25,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "25"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "session"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:Session"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample26", samplePWContainer[1][32][1], pipewire.RegistryGlobal{
|
||||
ID: 26,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "26"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "endpoint"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:Endpoint"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample27", samplePWContainer[1][33][1], pipewire.RegistryGlobal{
|
||||
ID: 27,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "27"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "endpoint-stream"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:EndpointStream"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample28", samplePWContainer[1][34][1], pipewire.RegistryGlobal{
|
||||
ID: 28,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "28"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "endpoint-link"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:EndpointLink"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample29", samplePWContainer[1][35][1], pipewire.RegistryGlobal{
|
||||
ID: 29,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "29"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-x11-bell"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample30", samplePWContainer[1][36][1], pipewire.RegistryGlobal{
|
||||
ID: 30,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "30"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-jackdbus-detect"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample31", samplePWContainer[1][37][1], pipewire.RegistryGlobal{
|
||||
ID: 31,
|
||||
Permissions: pipewire.PW_PERM_RWXM, // why is this not PW_NODE_PERM_MASK?
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Node,
|
||||
Version: pipewire.PW_VERSION_NODE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "31"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_ID, Value: "11"},
|
||||
{Key: pipewire.PW_KEY_PRIORITY_DRIVER, Value: "200000"},
|
||||
{Key: pipewire.PW_KEY_NODE_NAME, Value: "Dummy-Driver"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample32", samplePWContainer[1][38][1], pipewire.RegistryGlobal{
|
||||
ID: 32,
|
||||
Permissions: pipewire.PW_PERM_RWXM, // why is this not PW_NODE_PERM_MASK?
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Node,
|
||||
Version: pipewire.PW_VERSION_NODE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "32"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_ID, Value: "11"},
|
||||
{Key: pipewire.PW_KEY_PRIORITY_DRIVER, Value: "190000"},
|
||||
{Key: pipewire.PW_KEY_NODE_NAME, Value: "Freewheel-Driver"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample33", samplePWContainer[1][39][1], pipewire.RegistryGlobal{
|
||||
ID: 33,
|
||||
Permissions: pipewire.PW_METADATA_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Metadata,
|
||||
Version: pipewire.PW_VERSION_METADATA,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "33"},
|
||||
{Key: "metadata.name", Value: "settings"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample34", samplePWContainer[1][40][1], pipewire.RegistryGlobal{
|
||||
ID: 34,
|
||||
Permissions: pipewire.PW_CLIENT_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Client,
|
||||
Version: pipewire.PW_VERSION_CLIENT,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
{Key: pipewire.PW_KEY_ACCESS, Value: "unrestricted"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "pw-container"},
|
||||
},
|
||||
}, nil},
|
||||
|
||||
{"sample35", samplePWContainer[1][42][1], pipewire.RegistryGlobal{
|
||||
ID: 35,
|
||||
Permissions: pipewire.PW_CLIENT_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Client,
|
||||
Version: pipewire.PW_VERSION_CLIENT,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "35"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1447"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
{Key: pipewire.PW_KEY_ACCESS, Value: "unrestricted"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "WirePlumber"},
|
||||
},
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestRegistryGlobalRemove(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.RegistryGlobalRemove, *pipewire.RegistryGlobalRemove]{
|
||||
{"sample", []byte{
|
||||
/* size: rest of data*/ 0x10, 0, 0, 0,
|
||||
/* type: Struct */ 0xe, 0, 0, 0,
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: 0xbad */ 0xad, 0xb, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
}, pipewire.RegistryGlobalRemove{
|
||||
ID: 0xbad,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestRegistryBind(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.RegistryBind, *pipewire.RegistryBind]{
|
||||
{"sample", samplePWContainer[3][0][1], pipewire.RegistryBind{
|
||||
ID: 3,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_SecurityContext,
|
||||
Version: pipewire.PW_VERSION_SECURITY_CONTEXT,
|
||||
NewID: 3, // registry takes up 2
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
|
||||
func TestRegistryDestroy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.RegistryDestroy, *pipewire.RegistryDestroy]{
|
||||
{"sample", []byte{
|
||||
/* size: rest of data*/ 0x10, 0, 0, 0,
|
||||
/* type: Struct */ 0xe, 0, 0, 0,
|
||||
/* size: 4 bytes */ 4, 0, 0, 0,
|
||||
/* type: Int */ 4, 0, 0, 0,
|
||||
/* value: 0xbad */ 0xad, 0xb, 0, 0,
|
||||
/* padding */ 0, 0, 0, 0,
|
||||
}, pipewire.RegistryDestroy{
|
||||
ID: 0xbad,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
73
internal/pipewire/header.go
Normal file
73
internal/pipewire/header.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package pipewire
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
const (
|
||||
// SizeHeader is the fixed size of [Header].
|
||||
SizeHeader = 16
|
||||
// SizeMax is the largest value of [Header.Size] that can be represented in its 3-byte segment.
|
||||
SizeMax = 0x00ffffff
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrSizeRange indicates that the value of [Header.Size] cannot be represented in its 3-byte segment.
|
||||
ErrSizeRange = errors.New("size out of range")
|
||||
// ErrBadHeader indicates that the header slice does not have length [HeaderSize].
|
||||
ErrBadHeader = errors.New("incorrect header size")
|
||||
)
|
||||
|
||||
// A Header is the fixed-size message header described in protocol native.
|
||||
type Header struct {
|
||||
// The message id this is the destination resource/proxy id.
|
||||
ID Int `json:"Id"`
|
||||
// The opcode on the resource/proxy interface.
|
||||
Opcode byte `json:"opcode"`
|
||||
// The size of the payload and optional footer of the message.
|
||||
// Note: this value is only 24 bits long in the format.
|
||||
Size uint32 `json:"size"`
|
||||
// An increasing sequence number for each message.
|
||||
Sequence Int `json:"seq"`
|
||||
// Number of file descriptors in this message.
|
||||
FileCount Int `json:"n_fds"`
|
||||
}
|
||||
|
||||
// append appends the protocol native message header to data.
|
||||
//
|
||||
// Callers must perform bounds check on [Header.Size].
|
||||
func (h *Header) append(data []byte) []byte {
|
||||
data = binary.NativeEndian.AppendUint32(data, Word(h.ID))
|
||||
data = binary.NativeEndian.AppendUint32(data, Word(h.Opcode)<<24|h.Size)
|
||||
data = binary.NativeEndian.AppendUint32(data, Word(h.Sequence))
|
||||
data = binary.NativeEndian.AppendUint32(data, Word(h.FileCount))
|
||||
return data
|
||||
}
|
||||
|
||||
// MarshalBinary encodes the protocol native message header.
|
||||
func (h *Header) MarshalBinary() (data []byte, err error) {
|
||||
if h.Size&^SizeMax != 0 {
|
||||
return nil, ErrSizeRange
|
||||
}
|
||||
return h.append(make([]byte, 0, SizeHeader)), nil
|
||||
}
|
||||
|
||||
// unmarshalBinary decodes the protocol native message header.
|
||||
func (h *Header) unmarshalBinary(data [SizeHeader]byte) {
|
||||
h.ID = Int(binary.NativeEndian.Uint32(data[0:4]))
|
||||
h.Size = binary.NativeEndian.Uint32(data[4:8])
|
||||
h.Opcode = byte(h.Size >> 24)
|
||||
h.Size &= SizeMax
|
||||
h.Sequence = Int(binary.NativeEndian.Uint32(data[8:]))
|
||||
h.FileCount = Int(binary.NativeEndian.Uint32(data[12:]))
|
||||
}
|
||||
|
||||
// UnmarshalBinary decodes the protocol native message header.
|
||||
func (h *Header) UnmarshalBinary(data []byte) error {
|
||||
if len(data) != SizeHeader {
|
||||
return ErrBadHeader
|
||||
}
|
||||
h.unmarshalBinary(([SizeHeader]byte)(data))
|
||||
return nil
|
||||
}
|
||||
407
internal/pipewire/header_test.go
Normal file
407
internal/pipewire/header_test.go
Normal file
@@ -0,0 +1,407 @@
|
||||
package pipewire_test
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/internal/pipewire"
|
||||
)
|
||||
|
||||
func TestHeader(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.Header, *pipewire.Header]{
|
||||
|
||||
/* sendmsg 0 */
|
||||
|
||||
{"PW_CORE_METHOD_HELLO", samplePWContainer[0][0][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_METHOD_HELLO,
|
||||
Size: 0x18, Sequence: 0, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_CLIENT_METHOD_UPDATE_PROPERTIES", samplePWContainer[0][1][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CLIENT,
|
||||
Opcode: pipewire.PW_CLIENT_METHOD_UPDATE_PROPERTIES,
|
||||
Size: 0x600, Sequence: 1, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_CORE_METHOD_GET_REGISTRY", samplePWContainer[0][2][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_METHOD_GET_REGISTRY,
|
||||
Size: 0x28, Sequence: 2, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_CORE_METHOD_SYNC 0", samplePWContainer[0][3][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_METHOD_SYNC,
|
||||
Size: 0x28, Sequence: 3, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
/* recvmsg 0 */
|
||||
|
||||
{"PW_CORE_EVENT_INFO", samplePWContainer[1][0][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_EVENT_INFO,
|
||||
Size: 0x6b8, Sequence: 0, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_CORE_EVENT_BOUND_PROPS 0", samplePWContainer[1][1][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_EVENT_BOUND_PROPS,
|
||||
Size: 0x198, Sequence: 1, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_CLIENT_EVENT_INFO 0", samplePWContainer[1][2][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CLIENT,
|
||||
Opcode: pipewire.PW_CLIENT_EVENT_INFO,
|
||||
Size: 0x1f0, Sequence: 2, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_CLIENT_EVENT_INFO 1", samplePWContainer[1][3][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CLIENT,
|
||||
Opcode: pipewire.PW_CLIENT_EVENT_INFO,
|
||||
Size: 0x7a0, Sequence: 3, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_CLIENT_EVENT_INFO 2", samplePWContainer[1][4][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CLIENT,
|
||||
Opcode: pipewire.PW_CLIENT_EVENT_INFO,
|
||||
Size: 0x7d0, Sequence: 4, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_CORE_EVENT_DONE 0", samplePWContainer[1][5][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_EVENT_DONE,
|
||||
Size: 0x58, Sequence: 5, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 0", samplePWContainer[1][6][0], pipewire.Header{
|
||||
ID: 2, // this is specified by Core::GetRegistry in samplePWContainer[0][2][1]
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xc8, Sequence: 6, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 1", samplePWContainer[1][7][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xd8, Sequence: 7, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 2", samplePWContainer[1][8][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xa8, Sequence: 8, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 3", samplePWContainer[1][9][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe8, Sequence: 9, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 4", samplePWContainer[1][10][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xa0, Sequence: 10, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 5", samplePWContainer[1][11][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe0, Sequence: 11, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 6", samplePWContainer[1][12][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe0, Sequence: 12, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 7", samplePWContainer[1][13][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x170, Sequence: 13, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 8", samplePWContainer[1][14][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe8, Sequence: 14, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 9", samplePWContainer[1][15][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x178, Sequence: 15, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 10", samplePWContainer[1][16][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe8, Sequence: 16, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 11", samplePWContainer[1][17][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x170, Sequence: 17, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 12", samplePWContainer[1][18][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe0, Sequence: 18, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 13", samplePWContainer[1][19][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x170, Sequence: 19, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 14", samplePWContainer[1][20][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe8, Sequence: 20, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 15", samplePWContainer[1][21][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x170, Sequence: 21, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 16", samplePWContainer[1][22][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe0, Sequence: 22, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 17", samplePWContainer[1][23][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe0, Sequence: 23, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 18", samplePWContainer[1][24][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe0, Sequence: 24, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 19", samplePWContainer[1][25][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x160, Sequence: 25, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 20", samplePWContainer[1][26][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe0, Sequence: 26, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 21", samplePWContainer[1][27][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x168, Sequence: 27, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 22", samplePWContainer[1][28][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe8, Sequence: 28, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 23", samplePWContainer[1][29][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x178, Sequence: 29, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 24", samplePWContainer[1][30][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x178, Sequence: 30, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 25", samplePWContainer[1][31][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x168, Sequence: 31, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 26", samplePWContainer[1][32][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x170, Sequence: 32, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 27", samplePWContainer[1][33][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x178, Sequence: 33, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 28", samplePWContainer[1][34][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x170, Sequence: 34, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 29", samplePWContainer[1][35][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe0, Sequence: 35, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 30", samplePWContainer[1][36][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xe8, Sequence: 36, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 31", samplePWContainer[1][37][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x118, Sequence: 37, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 32", samplePWContainer[1][38][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x120, Sequence: 38, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 33", samplePWContainer[1][39][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0xd0, Sequence: 39, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 34", samplePWContainer[1][40][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x238, Sequence: 40, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_CORE_EVENT_DONE 1", samplePWContainer[1][41][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_EVENT_DONE,
|
||||
Size: 0x28, Sequence: 41, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
{"PW_REGISTRY_EVENT_GLOBAL 35", samplePWContainer[1][42][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_EVENT_GLOBAL,
|
||||
Size: 0x268, Sequence: 42, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
/* sendmsg 1 */
|
||||
|
||||
{"PW_REGISTRY_METHOD_BIND", samplePWContainer[3][0][0], pipewire.Header{
|
||||
ID: 2,
|
||||
Opcode: pipewire.PW_REGISTRY_METHOD_BIND,
|
||||
Size: 0x98, Sequence: 4, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
/* recvmsg 1 */
|
||||
|
||||
{"PW_CORE_EVENT_BOUND_PROPS 1", samplePWContainer[4][0][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_EVENT_BOUND_PROPS,
|
||||
Size: 0x68, Sequence: 43, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
/* sendmsg 2 */
|
||||
|
||||
{"PW_SECURITY_CONTEXT_METHOD_CREATE", samplePWContainer[6][0][0], pipewire.Header{
|
||||
ID: 3,
|
||||
Opcode: pipewire.PW_SECURITY_CONTEXT_METHOD_CREATE,
|
||||
Size: 0xd8, Sequence: 5, FileCount: 2,
|
||||
}, nil},
|
||||
|
||||
{"PW_CORE_METHOD_SYNC 1", samplePWContainer[6][1][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_METHOD_SYNC,
|
||||
Size: 0x28, Sequence: 6, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
/* recvmsg 2 */
|
||||
|
||||
{"PW_CORE_EVENT_DONE 2", samplePWContainer[7][0][0], pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_EVENT_DONE,
|
||||
Size: 0x28, Sequence: 44, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
/* excerpts */
|
||||
|
||||
{"PW_CORE_EVENT_ERROR", []byte{
|
||||
/* Id: */ 0, 0, 0, 0,
|
||||
/* size: */ 0x60, 0, 0,
|
||||
/* opcode: */ 3,
|
||||
/* seq: */ 0xf5, 0, 0, 0,
|
||||
/* n_fds: */ 0, 0, 0, 0,
|
||||
}, pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_EVENT_ERROR,
|
||||
Size: 0x60, Sequence: 0xf5, FileCount: 0,
|
||||
}, nil},
|
||||
|
||||
/* handmade samples */
|
||||
|
||||
{"PW_CORE_EVENT_PING", []byte{
|
||||
/* Id: */ 0, 0, 0, 0,
|
||||
/* size: */ 0xed, 0xb, 0,
|
||||
/* opcode: */ 2,
|
||||
/* seq: */ 0xff, 0xff, 0, 0,
|
||||
/* n_fds: */ 0xfe, 0xca, 0, 0,
|
||||
}, pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_EVENT_PING,
|
||||
Size: 0xbed, Sequence: 0xffff, FileCount: 0xcafe,
|
||||
}, nil},
|
||||
|
||||
{"PW_CORE_METHOD_PONG", []byte{
|
||||
/* Id: */ 0, 0, 0, 0,
|
||||
/* size: */ 0xed, 0xb, 0,
|
||||
/* opcode: */ 3,
|
||||
/* seq: */ 0xff, 0xff, 0, 0,
|
||||
/* n_fds: */ 0xfe, 0xca, 0, 0,
|
||||
}, pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_METHOD_PONG,
|
||||
Size: 0xbed, Sequence: 0xffff, FileCount: 0xcafe,
|
||||
}, nil},
|
||||
|
||||
{"PW_CORE_METHOD_ERROR", []byte{
|
||||
/* Id: */ 0, 0, 0, 0,
|
||||
/* size: */ 0xad, 0xb, 0,
|
||||
/* opcode: */ 4,
|
||||
/* seq: */ 0xfe, 0xfe, 0, 0,
|
||||
/* n_fds: */ 0xfe, 0xca, 0, 0,
|
||||
}, pipewire.Header{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Opcode: pipewire.PW_CORE_METHOD_ERROR,
|
||||
Size: 0xbad, Sequence: 0xfefe, FileCount: 0xcafe,
|
||||
}, nil},
|
||||
}.run(t)
|
||||
|
||||
t.Run("size range", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if _, err := (&pipewire.Header{Size: 0xff000000}).MarshalBinary(); !reflect.DeepEqual(err, pipewire.ErrSizeRange) {
|
||||
t.Errorf("UnmarshalBinary: error = %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("header size", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if err := (*pipewire.Header)(nil).UnmarshalBinary(nil); !reflect.DeepEqual(err, pipewire.ErrBadHeader) {
|
||||
t.Errorf("UnmarshalBinary: error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
1024
internal/pipewire/pipewire.go
Normal file
1024
internal/pipewire/pipewire.go
Normal file
File diff suppressed because it is too large
Load Diff
899
internal/pipewire/pipewire_test.go
Normal file
899
internal/pipewire/pipewire_test.go
Normal file
@@ -0,0 +1,899 @@
|
||||
package pipewire_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
. "syscall"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hakurei.app/container/stub"
|
||||
"hakurei.app/internal/pipewire"
|
||||
)
|
||||
|
||||
func TestContext(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var (
|
||||
// Underlying connection stub holding test data.
|
||||
conn = stubUnixConn{samples: []stubUnixConnSample{
|
||||
{SYS_SENDMSG, samplePWContainer00, MSG_DONTWAIT | MSG_NOSIGNAL, nil, 0},
|
||||
{SYS_RECVMSG, samplePWContainer01, MSG_DONTWAIT | MSG_CMSG_CLOEXEC, nil, 0},
|
||||
{SYS_RECVMSG, "", MSG_DONTWAIT | MSG_CMSG_CLOEXEC, nil, EAGAIN},
|
||||
{SYS_SENDMSG, samplePWContainer03, MSG_DONTWAIT | MSG_NOSIGNAL, nil, 0},
|
||||
{SYS_RECVMSG, samplePWContainer04, MSG_DONTWAIT | MSG_CMSG_CLOEXEC, nil, 0},
|
||||
{SYS_RECVMSG, "", MSG_DONTWAIT | MSG_CMSG_CLOEXEC, nil, EAGAIN},
|
||||
{SYS_SENDMSG, samplePWContainer06, MSG_DONTWAIT | MSG_NOSIGNAL, []int{20, 21}, 0},
|
||||
{SYS_RECVMSG, samplePWContainer07, MSG_DONTWAIT | MSG_CMSG_CLOEXEC, nil, 0},
|
||||
{SYS_RECVMSG, "", MSG_DONTWAIT | MSG_CMSG_CLOEXEC, nil, EAGAIN},
|
||||
}}
|
||||
|
||||
// Context instance under testing.
|
||||
ctx = pipewire.MustNew(&conn, pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_REMOTE_INTENTION, Value: "manager"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_BINARY, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_LANGUAGE, Value: "en_US.UTF-8"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_ID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_USER, Value: "alice"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_HOST, Value: "nixos"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_SESSION_ID, Value: "1"},
|
||||
{Key: pipewire.PW_KEY_WINDOW_X11_DISPLAY, Value: ":0"},
|
||||
{Key: "cpu.vm.name", Value: "qemu"},
|
||||
{Key: "log.level", Value: "0"},
|
||||
{Key: pipewire.PW_KEY_CPU_MAX_ALIGN, Value: "32"},
|
||||
{Key: "default.clock.rate", Value: "48000"},
|
||||
{Key: "default.clock.quantum", Value: "1024"},
|
||||
{Key: "default.clock.min-quantum", Value: "32"},
|
||||
{Key: "default.clock.max-quantum", Value: "2048"},
|
||||
{Key: "default.clock.quantum-limit", Value: "8192"},
|
||||
{Key: "default.clock.quantum-floor", Value: "4"},
|
||||
{Key: "default.video.width", Value: "640"},
|
||||
{Key: "default.video.height", Value: "480"},
|
||||
{Key: "default.video.rate.num", Value: "25"},
|
||||
{Key: "default.video.rate.denom", Value: "1"},
|
||||
{Key: "clock.power-of-two-quantum", Value: "true"},
|
||||
{Key: "link.max-buffers", Value: "64"},
|
||||
{Key: "mem.warn-mlock", Value: "false"},
|
||||
{Key: "mem.allow-mlock", Value: "true"},
|
||||
{Key: "settings.check-quantum", Value: "false"},
|
||||
{Key: "settings.check-rate", Value: "false"},
|
||||
{Key: pipewire.PW_KEY_CORE_VERSION, Value: "1.4.7"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-alice-1443"},
|
||||
})
|
||||
)
|
||||
|
||||
var registry *pipewire.Registry
|
||||
const wantRegistryId = 2
|
||||
if r, err := ctx.GetRegistry(); err != nil {
|
||||
t.Fatalf("GetRegistry: error = %v", err)
|
||||
} else {
|
||||
if r.ID != wantRegistryId {
|
||||
t.Fatalf("GetRegistry: ID = %d, want %d", r.ID, wantRegistryId)
|
||||
}
|
||||
registry = r
|
||||
}
|
||||
if err := ctx.GetCore().Sync(); err != nil {
|
||||
t.Fatalf("Sync: error = %v", err)
|
||||
}
|
||||
|
||||
wantCoreInfo0 := pipewire.CoreInfo{
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Cookie: -2069267610,
|
||||
UserName: "alice",
|
||||
HostName: "nixos",
|
||||
Version: "1.4.7",
|
||||
Name: "pipewire-0",
|
||||
ChangeMask: pipewire.PW_CORE_CHANGE_MASK_PROPS,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_CONFIG_NAME, Value: "pipewire.conf"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "pipewire"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_BINARY, Value: "pipewire"},
|
||||
{Key: pipewire.PW_KEY_APP_LANGUAGE, Value: "en_US.UTF-8"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_ID, Value: "1446"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_USER, Value: "alice"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_HOST, Value: "nixos"},
|
||||
{Key: pipewire.PW_KEY_WINDOW_X11_DISPLAY, Value: ":0"},
|
||||
{Key: "cpu.vm.name", Value: "qemu"},
|
||||
{Key: "link.max-buffers", Value: "16"},
|
||||
{Key: pipewire.PW_KEY_CORE_DAEMON, Value: "true"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-0"},
|
||||
{Key: "default.clock.min-quantum", Value: "1024"},
|
||||
{Key: pipewire.PW_KEY_CPU_MAX_ALIGN, Value: "32"},
|
||||
{Key: "default.clock.rate", Value: "48000"},
|
||||
{Key: "default.clock.quantum", Value: "1024"},
|
||||
{Key: "default.clock.max-quantum", Value: "2048"},
|
||||
{Key: "default.clock.quantum-limit", Value: "8192"},
|
||||
{Key: "default.clock.quantum-floor", Value: "4"},
|
||||
{Key: "default.video.width", Value: "640"},
|
||||
{Key: "default.video.height", Value: "480"},
|
||||
{Key: "default.video.rate.num", Value: "25"},
|
||||
{Key: "default.video.rate.denom", Value: "1"},
|
||||
{Key: "log.level", Value: "2"},
|
||||
{Key: "clock.power-of-two-quantum", Value: "true"},
|
||||
{Key: "mem.warn-mlock", Value: "false"},
|
||||
{Key: "mem.allow-mlock", Value: "true"},
|
||||
{Key: "settings.check-quantum", Value: "false"},
|
||||
{Key: "settings.check-rate", Value: "false"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_ID, Value: "0"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "0"},
|
||||
},
|
||||
}
|
||||
|
||||
wantClient0 := pipewire.Client{
|
||||
Info: &pipewire.ClientInfo{
|
||||
ID: 34,
|
||||
ChangeMask: pipewire.PW_CLIENT_CHANGE_MASK_PROPS,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-alice-1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_ID, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_REMOTE_INTENTION, Value: "manager"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_BINARY, Value: "pw-container"},
|
||||
{Key: pipewire.PW_KEY_APP_LANGUAGE, Value: "en_US.UTF-8"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_ID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_USER, Value: "alice"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_HOST, Value: "nixos"},
|
||||
{Key: pipewire.PW_KEY_APP_PROCESS_SESSION_ID, Value: "1"},
|
||||
{Key: pipewire.PW_KEY_WINDOW_X11_DISPLAY, Value: ":0"},
|
||||
{Key: "cpu.vm.name", Value: "qemu"},
|
||||
{Key: "log.level", Value: "0"},
|
||||
{Key: pipewire.PW_KEY_CPU_MAX_ALIGN, Value: "32"},
|
||||
{Key: "default.clock.rate", Value: "48000"},
|
||||
{Key: "default.clock.quantum", Value: "1024"},
|
||||
{Key: "default.clock.min-quantum", Value: "32"},
|
||||
{Key: "default.clock.max-quantum", Value: "2048"},
|
||||
{Key: "default.clock.quantum-limit", Value: "8192"},
|
||||
{Key: "default.clock.quantum-floor", Value: "4"},
|
||||
{Key: "default.video.width", Value: "640"},
|
||||
{Key: "default.video.height", Value: "480"},
|
||||
{Key: "default.video.rate.num", Value: "25"},
|
||||
{Key: "default.video.rate.denom", Value: "1"},
|
||||
{Key: "clock.power-of-two-quantum", Value: "true"},
|
||||
{Key: "link.max-buffers", Value: "64"},
|
||||
{Key: "mem.warn-mlock", Value: "false"},
|
||||
{Key: "mem.allow-mlock", Value: "true"},
|
||||
{Key: "settings.check-quantum", Value: "false"},
|
||||
{Key: "settings.check-rate", Value: "false"},
|
||||
{Key: pipewire.PW_KEY_CORE_VERSION, Value: "1.4.7"},
|
||||
{Key: pipewire.PW_KEY_ACCESS, Value: "unrestricted"},
|
||||
},
|
||||
},
|
||||
Properties: pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
},
|
||||
}
|
||||
|
||||
wantRegistry0 := pipewire.Registry{
|
||||
ID: wantRegistryId,
|
||||
Objects: map[pipewire.Int]pipewire.RegistryGlobal{
|
||||
pipewire.PW_ID_CORE: {
|
||||
ID: pipewire.PW_ID_CORE,
|
||||
Permissions: pipewire.PW_CORE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Core,
|
||||
Version: pipewire.PW_VERSION_CORE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "0"},
|
||||
{Key: pipewire.PW_KEY_CORE_NAME, Value: "pipewire-0"},
|
||||
},
|
||||
},
|
||||
|
||||
1: {
|
||||
ID: 1,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "1"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-rt"},
|
||||
},
|
||||
},
|
||||
|
||||
3: {
|
||||
ID: 3,
|
||||
Permissions: pipewire.PW_SECURITY_CONTEXT_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_SecurityContext,
|
||||
Version: pipewire.PW_VERSION_SECURITY_CONTEXT,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "3"},
|
||||
},
|
||||
},
|
||||
|
||||
2: {
|
||||
ID: 2,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-protocol-native"},
|
||||
},
|
||||
},
|
||||
|
||||
5: {
|
||||
ID: 5,
|
||||
Permissions: pipewire.PW_PROFILER_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Profiler,
|
||||
Version: pipewire.PW_VERSION_PROFILER,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "5"},
|
||||
},
|
||||
},
|
||||
|
||||
4: {
|
||||
ID: 4,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "4"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-profiler"},
|
||||
},
|
||||
},
|
||||
|
||||
6: {
|
||||
ID: 6,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "6"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-metadata"},
|
||||
},
|
||||
},
|
||||
|
||||
7: {
|
||||
ID: 7,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "7"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "6"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "metadata"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Metadata},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
},
|
||||
|
||||
8: {
|
||||
ID: 8,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "8"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-spa-device-factory"},
|
||||
},
|
||||
},
|
||||
|
||||
9: {
|
||||
ID: 9,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "9"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "8"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "spa-device-factory"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Device},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
},
|
||||
|
||||
10: {
|
||||
ID: 10,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "10"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-spa-node-factory"},
|
||||
},
|
||||
},
|
||||
|
||||
11: {
|
||||
ID: 11,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "11"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "10"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "spa-node-factory"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Node},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
},
|
||||
|
||||
12: {
|
||||
ID: 12,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "12"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-client-node"},
|
||||
},
|
||||
},
|
||||
|
||||
13: {
|
||||
ID: 13,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "13"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "12"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "client-node"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_ClientNode},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "6"},
|
||||
},
|
||||
},
|
||||
|
||||
14: {
|
||||
ID: 14,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "14"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-client-device"},
|
||||
},
|
||||
},
|
||||
|
||||
15: {
|
||||
ID: 15,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "15"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "14"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "client-device"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "Spa:Pointer:Interface:Device"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
},
|
||||
|
||||
16: {
|
||||
ID: 16,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "16"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-portal"},
|
||||
},
|
||||
},
|
||||
|
||||
17: {
|
||||
ID: 17,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "17"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-access"},
|
||||
},
|
||||
},
|
||||
|
||||
18: {
|
||||
ID: 18,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "18"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-adapter"},
|
||||
},
|
||||
},
|
||||
|
||||
19: {
|
||||
ID: 19,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "19"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "18"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "adapter"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Node},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
},
|
||||
|
||||
20: {
|
||||
ID: 20,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "20"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-link-factory"},
|
||||
},
|
||||
},
|
||||
|
||||
21: {
|
||||
ID: 21,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "21"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "20"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "link-factory"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: pipewire.PW_TYPE_INTERFACE_Link},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "3"},
|
||||
},
|
||||
},
|
||||
|
||||
22: {
|
||||
ID: 22,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-session-manager"},
|
||||
},
|
||||
},
|
||||
|
||||
23: {
|
||||
ID: 23,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "23"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "client-endpoint"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:ClientEndpoint"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
},
|
||||
|
||||
24: {
|
||||
ID: 24,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "24"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "client-session"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:ClientSession"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
},
|
||||
|
||||
25: {
|
||||
ID: 25,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "25"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "session"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:Session"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
},
|
||||
|
||||
26: {
|
||||
ID: 26,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "26"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "endpoint"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:Endpoint"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
},
|
||||
|
||||
27: {
|
||||
ID: 27,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "27"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "endpoint-stream"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:EndpointStream"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
},
|
||||
|
||||
28: {
|
||||
ID: 28,
|
||||
Permissions: pipewire.PW_FACTORY_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Factory,
|
||||
Version: pipewire.PW_VERSION_FACTORY,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "28"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "22"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_NAME, Value: "endpoint-link"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_NAME, Value: "PipeWire:Interface:EndpointLink"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_TYPE_VERSION, Value: "0"},
|
||||
},
|
||||
},
|
||||
|
||||
29: {
|
||||
ID: 29,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "29"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-x11-bell"},
|
||||
},
|
||||
},
|
||||
|
||||
30: {
|
||||
ID: 30,
|
||||
Permissions: pipewire.PW_MODULE_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Module,
|
||||
Version: pipewire.PW_VERSION_MODULE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "30"},
|
||||
{Key: pipewire.PW_KEY_MODULE_NAME, Value: pipewire.PIPEWIRE_MODULE_PREFIX + "module-jackdbus-detect"},
|
||||
},
|
||||
},
|
||||
|
||||
31: {
|
||||
ID: 31,
|
||||
Permissions: pipewire.PW_PERM_RWXM, // why is this not PW_NODE_PERM_MASK?
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Node,
|
||||
Version: pipewire.PW_VERSION_NODE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "31"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_ID, Value: "11"},
|
||||
{Key: pipewire.PW_KEY_PRIORITY_DRIVER, Value: "200000"},
|
||||
{Key: pipewire.PW_KEY_NODE_NAME, Value: "Dummy-Driver"},
|
||||
},
|
||||
},
|
||||
|
||||
32: {
|
||||
ID: 32,
|
||||
Permissions: pipewire.PW_PERM_RWXM, // why is this not PW_NODE_PERM_MASK?
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Node,
|
||||
Version: pipewire.PW_VERSION_NODE,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "32"},
|
||||
{Key: pipewire.PW_KEY_FACTORY_ID, Value: "11"},
|
||||
{Key: pipewire.PW_KEY_PRIORITY_DRIVER, Value: "190000"},
|
||||
{Key: pipewire.PW_KEY_NODE_NAME, Value: "Freewheel-Driver"},
|
||||
},
|
||||
},
|
||||
|
||||
33: {
|
||||
ID: 33,
|
||||
Permissions: pipewire.PW_METADATA_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Metadata,
|
||||
Version: pipewire.PW_VERSION_METADATA,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "33"},
|
||||
{Key: "metadata.name", Value: "settings"},
|
||||
},
|
||||
},
|
||||
|
||||
34: {
|
||||
ID: 34,
|
||||
Permissions: pipewire.PW_CLIENT_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Client,
|
||||
Version: pipewire.PW_VERSION_CLIENT,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "34"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1443"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
{Key: pipewire.PW_KEY_ACCESS, Value: "unrestricted"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "pw-container"},
|
||||
},
|
||||
},
|
||||
|
||||
35: {
|
||||
ID: 35,
|
||||
Permissions: pipewire.PW_CLIENT_PERM_MASK,
|
||||
Type: pipewire.PW_TYPE_INTERFACE_Client,
|
||||
Version: pipewire.PW_VERSION_CLIENT,
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_OBJECT_SERIAL, Value: "35"},
|
||||
{Key: pipewire.PW_KEY_MODULE_ID, Value: "2"},
|
||||
{Key: pipewire.PW_KEY_PROTOCOL, Value: "protocol-native"},
|
||||
{Key: pipewire.PW_KEY_SEC_PID, Value: "1447"},
|
||||
{Key: pipewire.PW_KEY_SEC_UID, Value: "1000"},
|
||||
{Key: pipewire.PW_KEY_SEC_GID, Value: "100"},
|
||||
{Key: pipewire.PW_KEY_SEC_SOCKET, Value: "pipewire-0-manager"},
|
||||
{Key: pipewire.PW_KEY_ACCESS, Value: "unrestricted"},
|
||||
{Key: pipewire.PW_KEY_APP_NAME, Value: "WirePlumber"},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
if coreInfo := ctx.GetCore().Info; !reflect.DeepEqual(coreInfo, &wantCoreInfo0) {
|
||||
t.Fatalf("New: CoreInfo = %s, want %s", mustMarshalJSON(coreInfo), mustMarshalJSON(&wantCoreInfo0))
|
||||
}
|
||||
if client := ctx.GetClient(); !reflect.DeepEqual(client, &wantClient0) {
|
||||
t.Fatalf("New: Client = %s, want %s", mustMarshalJSON(client), mustMarshalJSON(&wantClient0))
|
||||
}
|
||||
if registry.ID != wantRegistry0.ID {
|
||||
t.Fatalf("GetRegistry: ID = %d, want %d", registry.ID, wantRegistry0.ID)
|
||||
}
|
||||
if !reflect.DeepEqual(registry.Objects, wantRegistry0.Objects) {
|
||||
t.Fatalf("GetRegistry: Objects = %s, want %s", mustMarshalJSON(registry.Objects), mustMarshalJSON(wantRegistry0.Objects))
|
||||
}
|
||||
|
||||
var securityContext *pipewire.SecurityContext
|
||||
const wantSecurityContextId = 3
|
||||
if c, err := registry.GetSecurityContext(); err != nil {
|
||||
t.Fatalf("GetSecurityContext: error = %v", err)
|
||||
} else {
|
||||
if c.ID != wantSecurityContextId {
|
||||
t.Fatalf("GetSecurityContext: ID = %d, want %d", c.ID, wantSecurityContextId)
|
||||
}
|
||||
securityContext = c
|
||||
}
|
||||
if err := ctx.Roundtrip(); err != nil {
|
||||
t.Fatalf("Roundtrip: error = %v", err)
|
||||
}
|
||||
|
||||
// none of these should change
|
||||
if coreInfo := ctx.GetCore().Info; !reflect.DeepEqual(coreInfo, &wantCoreInfo0) {
|
||||
t.Fatalf("Roundtrip: CoreInfo = %s, want %s", mustMarshalJSON(coreInfo), mustMarshalJSON(&wantCoreInfo0))
|
||||
}
|
||||
if client := ctx.GetClient(); !reflect.DeepEqual(client, &wantClient0) {
|
||||
t.Fatalf("Roundtrip: Client = %s, want %s", mustMarshalJSON(client), mustMarshalJSON(&wantClient0))
|
||||
}
|
||||
if registry.ID != wantRegistry0.ID {
|
||||
t.Fatalf("Roundtrip: ID = %d, want %d", registry.ID, wantRegistry0.ID)
|
||||
}
|
||||
if !reflect.DeepEqual(registry.Objects, wantRegistry0.Objects) {
|
||||
t.Fatalf("Roundtrip: Objects = %s, want %s", mustMarshalJSON(registry.Objects), mustMarshalJSON(wantRegistry0.Objects))
|
||||
}
|
||||
|
||||
if err := securityContext.Create(21, 20, pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_SEC_ENGINE, Value: "org.flatpak"},
|
||||
{Key: pipewire.PW_KEY_ACCESS, Value: "restricted"},
|
||||
}); err != nil {
|
||||
t.Fatalf("SecurityContext.Create: error = %v", err)
|
||||
}
|
||||
|
||||
// none of these should change
|
||||
if coreInfo := ctx.GetCore().Info; !reflect.DeepEqual(coreInfo, &wantCoreInfo0) {
|
||||
t.Fatalf("Roundtrip: CoreInfo = %s, want %s", mustMarshalJSON(coreInfo), mustMarshalJSON(&wantCoreInfo0))
|
||||
}
|
||||
if client := ctx.GetClient(); !reflect.DeepEqual(client, &wantClient0) {
|
||||
t.Fatalf("Roundtrip: Client = %s, want %s", mustMarshalJSON(client), mustMarshalJSON(&wantClient0))
|
||||
}
|
||||
if registry.ID != wantRegistry0.ID {
|
||||
t.Fatalf("Roundtrip: ID = %d, want %d", registry.ID, wantRegistry0.ID)
|
||||
}
|
||||
if !reflect.DeepEqual(registry.Objects, wantRegistry0.Objects) {
|
||||
t.Fatalf("Roundtrip: Objects = %s, want %s", mustMarshalJSON(registry.Objects), mustMarshalJSON(wantRegistry0.Objects))
|
||||
}
|
||||
|
||||
if err := ctx.Close(); err != nil {
|
||||
t.Fatalf("Close: error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// stubUnixConnSample is sample data held by stubUnixConn.
|
||||
type stubUnixConnSample struct {
|
||||
nr uintptr
|
||||
iovec string
|
||||
flags int
|
||||
files []int
|
||||
errno Errno
|
||||
}
|
||||
|
||||
// stubUnixConn implements [pipewire.Conn] and checks the behaviour of [pipewire.Context].
|
||||
type stubUnixConn struct {
|
||||
samples []stubUnixConnSample
|
||||
current int
|
||||
}
|
||||
|
||||
func (conn *stubUnixConn) MightBlock(timeout time.Duration) {
|
||||
if timeout != 5*time.Second {
|
||||
panic("unexpected timeout " + timeout.String())
|
||||
}
|
||||
if conn.current == 0 ||
|
||||
(conn.samples[conn.current-1].nr == SYS_RECVMSG && conn.samples[conn.current-1].errno == EAGAIN && conn.samples[conn.current].nr == SYS_SENDMSG) ||
|
||||
(conn.samples[conn.current-1].nr == SYS_SENDMSG && conn.samples[conn.current].nr == SYS_RECVMSG) {
|
||||
return
|
||||
}
|
||||
panic("unexpected blocking hint before sample " + strconv.Itoa(conn.current))
|
||||
}
|
||||
|
||||
// nextSample returns the current sample and increments the counter.
|
||||
func (conn *stubUnixConn) nextSample(nr uintptr) (sample *stubUnixConnSample, wantOOB []byte, err error) {
|
||||
sample = &conn.samples[conn.current]
|
||||
conn.current++
|
||||
if sample.nr != nr {
|
||||
err = fmt.Errorf("unexpected syscall %d", SYS_SENDMSG)
|
||||
return
|
||||
}
|
||||
if len(sample.files) > 0 {
|
||||
wantOOB = UnixRights(sample.files...)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (conn *stubUnixConn) Recvmsg(p, oob []byte, flags int) (n, oobn, recvflags int, err error) {
|
||||
var (
|
||||
sample *stubUnixConnSample
|
||||
wantOOB []byte
|
||||
)
|
||||
sample, wantOOB, err = conn.nextSample(SYS_RECVMSG)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if n = copy(p, sample.iovec); n != len(sample.iovec) {
|
||||
err = fmt.Errorf("insufficient iovec size %d, want at least %d", len(p), len(sample.iovec))
|
||||
return
|
||||
}
|
||||
if oobn = copy(oob, wantOOB); oobn != len(wantOOB) {
|
||||
err = fmt.Errorf("insufficient oob size %d, want at least %d", len(oob), len(wantOOB))
|
||||
return
|
||||
}
|
||||
if flags != sample.flags {
|
||||
err = fmt.Errorf("flags = %#x, want %#x", flags, sample.flags)
|
||||
return
|
||||
}
|
||||
|
||||
recvflags = MSG_CMSG_CLOEXEC
|
||||
if sample.errno != 0 {
|
||||
err = sample.errno
|
||||
if n != 0 {
|
||||
panic("invalid recvmsg: n = " + strconv.Itoa(n))
|
||||
}
|
||||
n = -1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (conn *stubUnixConn) Sendmsg(p, oob []byte, flags int) (n int, err error) {
|
||||
var (
|
||||
sample *stubUnixConnSample
|
||||
wantOOB []byte
|
||||
)
|
||||
sample, wantOOB, err = conn.nextSample(SYS_SENDMSG)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if string(p) != sample.iovec {
|
||||
err = fmt.Errorf("iovec: %#v, want %#v", p, []byte(sample.iovec))
|
||||
return
|
||||
}
|
||||
if string(oob[:len(wantOOB)]) != string(wantOOB) {
|
||||
err = fmt.Errorf("oob: %#v, want %#v", oob[:len(wantOOB)], wantOOB)
|
||||
return
|
||||
}
|
||||
if flags != sample.flags {
|
||||
err = fmt.Errorf("flags = %#x, want %#x", flags, sample.flags)
|
||||
return
|
||||
}
|
||||
|
||||
n = len(sample.iovec)
|
||||
if sample.errno != 0 {
|
||||
err = sample.errno
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (conn *stubUnixConn) Close() error {
|
||||
if conn.current != len(conn.samples) {
|
||||
return fmt.Errorf("consumed %d samples, want %d", conn.current, len(conn.samples))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestContextErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{"ProxyConsumeError invalid", pipewire.ProxyConsumeError{}, "invalid proxy consume error"},
|
||||
{"ProxyConsumeError single", pipewire.ProxyConsumeError{
|
||||
stub.UniqueError(0),
|
||||
}, "unique error 0 injected by the test suite"},
|
||||
{"ProxyConsumeError multiple", pipewire.ProxyConsumeError{
|
||||
stub.UniqueError(1),
|
||||
stub.UniqueError(2),
|
||||
stub.UniqueError(3),
|
||||
stub.UniqueError(4),
|
||||
stub.UniqueError(5),
|
||||
stub.UniqueError(6),
|
||||
stub.UniqueError(7),
|
||||
}, "unique error 1 injected by the test suite; 7 additional proxy errors occurred after this point"},
|
||||
|
||||
{"ProxyFatalError", &pipewire.ProxyFatalError{
|
||||
Err: stub.UniqueError(8),
|
||||
}, "unique error 8 injected by the test suite"},
|
||||
{"ProxyFatalError proxy errors", &pipewire.ProxyFatalError{
|
||||
Err: stub.UniqueError(9),
|
||||
ProxyErrs: make([]error, 1<<4),
|
||||
}, "unique error 9 injected by the test suite; 16 additional proxy errors occurred before this point"},
|
||||
|
||||
{"UnexpectedFileCountError", &pipewire.UnexpectedFileCountError{0, -1}, "received -1 files instead of the expected 0"},
|
||||
{"UnacknowledgedProxyError", make(pipewire.UnacknowledgedProxyError, 1<<4), "server did not acknowledge 16 proxies"},
|
||||
{"UnacknowledgedProxyDestructionError", make(pipewire.UnacknowledgedProxyDestructionError, 1<<4), "server did not acknowledge 16 proxy destructions"},
|
||||
{"DanglingFilesError", make(pipewire.DanglingFilesError, 1<<4), "received 16 dangling files"},
|
||||
{"UnexpectedFilesError", pipewire.UnexpectedFilesError(1 << 4), "server message headers claim to have sent more files than actually received"},
|
||||
{"UnexpectedSequenceError", pipewire.UnexpectedSequenceError(1 << 4), "unexpected seq 16"},
|
||||
{"UnsupportedFooterOpcodeError", pipewire.UnsupportedFooterOpcodeError(1 << 4), "unsupported footer opcode 16"},
|
||||
|
||||
{"RoundtripUnexpectedEOFError ErrRoundtripEOFHeader", pipewire.ErrRoundtripEOFHeader, "unexpected EOF decoding message header"},
|
||||
{"RoundtripUnexpectedEOFError ErrRoundtripEOFBody", pipewire.ErrRoundtripEOFBody, "unexpected EOF establishing message body bounds"},
|
||||
{"RoundtripUnexpectedEOFError ErrRoundtripEOFFooter", pipewire.ErrRoundtripEOFFooter, "unexpected EOF establishing message footer bounds"},
|
||||
{"RoundtripUnexpectedEOFError ErrRoundtripEOFFooterOpcode", pipewire.ErrRoundtripEOFFooterOpcode, "unexpected EOF decoding message footer opcode"},
|
||||
{"RoundtripUnexpectedEOFError invalid", pipewire.RoundtripUnexpectedEOFError(0xbad), "unexpected EOF"},
|
||||
{"InconsistentFilesError", &pipewire.InconsistentFilesError{0, 2}, "queued 0 files instead of the expected 2"},
|
||||
|
||||
{"UnsupportedOpcodeError", &pipewire.UnsupportedOpcodeError{
|
||||
Opcode: 0xff,
|
||||
Interface: pipewire.PW_TYPE_INFO_INTERFACE_BASE + "Invalid",
|
||||
}, "unsupported PipeWire:Interface:Invalid opcode 255"},
|
||||
|
||||
{"UnknownIdError", &pipewire.UnknownIdError{
|
||||
Id: -1,
|
||||
Data: "\x00",
|
||||
}, "unknown proxy id -1"},
|
||||
|
||||
{"InvalidPingError", &pipewire.InvalidPingError{
|
||||
ID: 0xbad,
|
||||
Sequence: 0xcafe,
|
||||
}, "received Core::Ping seq 51966 targeting unknown proxy id 2989"},
|
||||
|
||||
{"GlobalIDCollisionError", &pipewire.GlobalIDCollisionError{
|
||||
ID: 0xbad,
|
||||
Previous: &pipewire.RegistryGlobal{Type: "PipeWire:Interface:Invalid"},
|
||||
Current: &pipewire.RegistryGlobal{Type: "PipeWire:Interface:NewInvalid"},
|
||||
}, "new Registry::Global event for PipeWire:Interface:NewInvalid stepping on previous id 2989 for PipeWire:Interface:Invalid"},
|
||||
|
||||
{"UnknownGlobalIDRemoveError", pipewire.UnknownGlobalIDRemoveError(0xbad), "Registry::GlobalRemove event targets unknown id 2989"},
|
||||
|
||||
{"PermissionError", &pipewire.PermissionError{
|
||||
ID: 2,
|
||||
Message: "no permission to destroy 0",
|
||||
}, "no permission to destroy 0"},
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
641
internal/pipewire/pod.go
Normal file
641
internal/pipewire/pod.go
Normal file
@@ -0,0 +1,641 @@
|
||||
package pipewire
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"math"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type (
|
||||
// A Word is a 32-bit unsigned integer.
|
||||
//
|
||||
// Values internal to a message appear to always be aligned to 32-bit boundary.
|
||||
Word = uint32
|
||||
|
||||
// A Bool is a boolean value representing SPA_TYPE_Bool.
|
||||
Bool = bool
|
||||
// An Id is an enumerated value representing SPA_TYPE_Id.
|
||||
Id = Word
|
||||
// An Int is a signed integer value representing SPA_TYPE_Int.
|
||||
Int = int32
|
||||
// A Long is a signed integer value representing SPA_TYPE_Long.
|
||||
Long = int64
|
||||
// A Float is a floating point value representing SPA_TYPE_Float.
|
||||
Float = float32
|
||||
// A Double is a floating point value representing SPA_TYPE_Double.
|
||||
Double = float64
|
||||
// A String is a string value representing SPA_TYPE_String.
|
||||
String = string
|
||||
// Bytes is a byte slice representing SPA_TYPE_Bytes.
|
||||
Bytes = []byte
|
||||
|
||||
// A Fd is a signed integer value representing SPA_TYPE_Fd.
|
||||
Fd Long
|
||||
)
|
||||
|
||||
const (
|
||||
// SizeAlign is the boundary which POD starts are always aligned to.
|
||||
SizeAlign = 8
|
||||
|
||||
// SizeSPrefix is the fixed, unpadded size of the fixed-size prefix encoding POD wire size.
|
||||
SizeSPrefix = 4
|
||||
// SizeTPrefix is the fixed, unpadded size of the fixed-size prefix encoding POD value type.
|
||||
SizeTPrefix = 4
|
||||
// SizePrefix is the fixed, unpadded size of the fixed-size POD prefix.
|
||||
SizePrefix = SizeSPrefix + SizeTPrefix
|
||||
|
||||
// SizeId is the fixed, unpadded size of a [SPA_TYPE_Id] value.
|
||||
SizeId Word = 4
|
||||
// SizeInt is the fixed, unpadded size of a [SPA_TYPE_Int] value.
|
||||
SizeInt Word = 4
|
||||
// SizeLong is the fixed, unpadded size of a [SPA_TYPE_Long] value.
|
||||
SizeLong Word = 8
|
||||
|
||||
// SizeFd is the fixed, unpadded size of a [SPA_TYPE_Fd] value.
|
||||
SizeFd = SizeLong
|
||||
)
|
||||
|
||||
// A KnownSize value has known POD encoded size before serialisation.
|
||||
type KnownSize interface {
|
||||
// Size returns the POD encoded size of the receiver.
|
||||
Size() Word
|
||||
}
|
||||
|
||||
// PaddingSize returns the padding size corresponding to a wire size.
|
||||
func PaddingSize[W Word | int](wireSize W) W { return (SizeAlign - (wireSize)%SizeAlign) % SizeAlign }
|
||||
|
||||
// PaddedSize returns the padded size corresponding to a wire size.
|
||||
func PaddedSize[W Word | int](wireSize W) W { return wireSize + PaddingSize(wireSize) }
|
||||
|
||||
// Size returns prefixed and padded size corresponding to a wire size.
|
||||
func Size[W Word | int](wireSize W) W { return SizePrefix + PaddedSize(wireSize) }
|
||||
|
||||
// SizeString returns prefixed and padded size corresponding to a string.
|
||||
func SizeString[W Word | int](s string) W { return Size(W(len(s)) + 1) }
|
||||
|
||||
// PODMarshaler is the interface implemented by an object that can
|
||||
// marshal itself into PipeWire POD encoding.
|
||||
type PODMarshaler interface {
|
||||
// MarshalPOD encodes the receiver into PipeWire POD encoding,
|
||||
// appends it to data, and returns the result.
|
||||
MarshalPOD(data []byte) ([]byte, error)
|
||||
}
|
||||
|
||||
// An UnsupportedTypeError is returned by [Marshal] when attempting
|
||||
// to encode an unsupported value type.
|
||||
type UnsupportedTypeError struct{ Type reflect.Type }
|
||||
|
||||
func (e *UnsupportedTypeError) Error() string { return "unsupported type " + e.Type.String() }
|
||||
|
||||
// An UnsupportedSizeError is returned by [Marshal] when attempting
|
||||
// to encode a value with its encoded size exceeding what could be
|
||||
// represented by the format.
|
||||
type UnsupportedSizeError int
|
||||
|
||||
func (e UnsupportedSizeError) Error() string { return "size " + strconv.Itoa(int(e)) + " out of range" }
|
||||
|
||||
// Marshal returns the PipeWire POD encoding of v.
|
||||
func Marshal(v any) ([]byte, error) {
|
||||
var data []byte
|
||||
if s, ok := v.(KnownSize); ok {
|
||||
data = make([]byte, 0, s.Size())
|
||||
}
|
||||
return MarshalAppend(data, v)
|
||||
}
|
||||
|
||||
// MarshalAppend appends the PipeWire POD encoding of v to data.
|
||||
func MarshalAppend(data []byte, v any) ([]byte, error) {
|
||||
return marshalValueAppend(data, reflect.ValueOf(v))
|
||||
}
|
||||
|
||||
// appendInner calls f and handles size prefix and padding around the appended data.
|
||||
// f must only append to data.
|
||||
func appendInner(data []byte, f func(data []byte) ([]byte, error)) ([]byte, error) {
|
||||
data = append(data, make([]byte, SizeSPrefix)...)
|
||||
|
||||
rData, err := f(data)
|
||||
if err != nil {
|
||||
return data, err
|
||||
}
|
||||
|
||||
size := len(rData) - len(data) + SizeSPrefix
|
||||
// compensated for size and type prefix
|
||||
wireSize := size - SizePrefix
|
||||
if wireSize > math.MaxUint32 {
|
||||
return data, UnsupportedSizeError(wireSize)
|
||||
}
|
||||
binary.NativeEndian.PutUint32(rData[len(data)-SizeSPrefix:len(data)], Word(wireSize))
|
||||
rData = append(rData, make([]byte, PaddingSize(size))...)
|
||||
|
||||
return rData, nil
|
||||
}
|
||||
|
||||
// marshalValueAppendRaw implements [MarshalAppend] on [reflect.Value].
|
||||
func marshalValueAppend(data []byte, v reflect.Value) ([]byte, error) {
|
||||
if v.CanInterface() && (v.Kind() != reflect.Pointer || !v.IsNil()) {
|
||||
if m, ok := v.Interface().(PODMarshaler); ok {
|
||||
var err error
|
||||
data, err = m.MarshalPOD(data)
|
||||
return data, err
|
||||
}
|
||||
}
|
||||
|
||||
return appendInner(data, func(data []byte) ([]byte, error) { return marshalValueAppendRaw(data, v) })
|
||||
}
|
||||
|
||||
// marshalValueAppendRaw implements [MarshalAppend] on [reflect.Value] without the size prefix.
|
||||
func marshalValueAppendRaw(data []byte, v reflect.Value) ([]byte, error) {
|
||||
if v.CanInterface() {
|
||||
switch c := v.Interface().(type) {
|
||||
case Fd:
|
||||
data = SPA_TYPE_Fd.append(data)
|
||||
data = binary.NativeEndian.AppendUint64(data, uint64(c))
|
||||
return data, nil
|
||||
}
|
||||
}
|
||||
|
||||
switch v.Kind() {
|
||||
case reflect.Uint32:
|
||||
data = SPA_TYPE_Id.append(data)
|
||||
data = binary.NativeEndian.AppendUint32(data, Word(v.Uint()))
|
||||
return data, nil
|
||||
|
||||
case reflect.Int32:
|
||||
data = SPA_TYPE_Int.append(data)
|
||||
data = binary.NativeEndian.AppendUint32(data, Word(v.Int()))
|
||||
return data, nil
|
||||
|
||||
case reflect.Int64:
|
||||
data = SPA_TYPE_Long.append(data)
|
||||
data = binary.NativeEndian.AppendUint64(data, uint64(v.Int()))
|
||||
return data, nil
|
||||
|
||||
case reflect.Struct:
|
||||
data = SPA_TYPE_Struct.append(data)
|
||||
var err error
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
data, err = marshalValueAppend(data, v.Field(i))
|
||||
if err != nil {
|
||||
return data, err
|
||||
}
|
||||
}
|
||||
return data, nil
|
||||
|
||||
case reflect.Pointer:
|
||||
if v.IsNil() {
|
||||
data = SPA_TYPE_None.append(data)
|
||||
return data, nil
|
||||
}
|
||||
return marshalValueAppendRaw(data, v.Elem())
|
||||
|
||||
case reflect.String:
|
||||
data = SPA_TYPE_String.append(data)
|
||||
data = append(data, []byte(v.String())...)
|
||||
data = append(data, 0)
|
||||
return data, nil
|
||||
|
||||
default:
|
||||
return data, &UnsupportedTypeError{v.Type()}
|
||||
}
|
||||
}
|
||||
|
||||
// PODUnmarshaler is the interface implemented by an object that can
|
||||
// unmarshal a PipeWire POD encoding representation of itself.
|
||||
type PODUnmarshaler interface {
|
||||
// UnmarshalPOD must be able to decode the form generated by MarshalPOD.
|
||||
// UnmarshalPOD must copy the data if it wishes to retain the data
|
||||
// after returning.
|
||||
UnmarshalPOD(data []byte) (Word, error)
|
||||
}
|
||||
|
||||
// An InvalidUnmarshalError describes an invalid argument passed to [Unmarshal].
|
||||
// (The argument to [Unmarshal] must be a non-nil pointer.)
|
||||
type InvalidUnmarshalError struct{ Type reflect.Type }
|
||||
|
||||
func (e *InvalidUnmarshalError) Error() string {
|
||||
if e.Type == nil {
|
||||
return "attempting to unmarshal to nil"
|
||||
}
|
||||
|
||||
if e.Type.Kind() != reflect.Pointer {
|
||||
return "attempting to unmarshal to non-pointer type " + e.Type.String()
|
||||
}
|
||||
return "attempting to unmarshal to nil " + e.Type.String()
|
||||
}
|
||||
|
||||
// UnexpectedEOFError describes an unexpected EOF encountered in the middle of decoding POD data.
|
||||
type UnexpectedEOFError uintptr
|
||||
|
||||
const (
|
||||
// ErrEOFPrefix is returned when unexpectedly encountering EOF
|
||||
// decoding the fixed-size POD prefix.
|
||||
ErrEOFPrefix UnexpectedEOFError = iota
|
||||
// ErrEOFData is returned when unexpectedly encountering EOF
|
||||
// establishing POD data bounds.
|
||||
ErrEOFData
|
||||
// ErrEOFDataString is returned when unexpectedly encountering EOF
|
||||
// establishing POD [String] bounds.
|
||||
ErrEOFDataString
|
||||
)
|
||||
|
||||
func (UnexpectedEOFError) Unwrap() error { return io.ErrUnexpectedEOF }
|
||||
func (e UnexpectedEOFError) Error() string {
|
||||
var suffix string
|
||||
switch e {
|
||||
case ErrEOFPrefix:
|
||||
suffix = "decoding fixed-size POD prefix"
|
||||
case ErrEOFData:
|
||||
suffix = "establishing POD data bounds"
|
||||
case ErrEOFDataString:
|
||||
suffix = "establishing POD String bounds"
|
||||
|
||||
default:
|
||||
return "unexpected EOF"
|
||||
}
|
||||
|
||||
return "unexpected EOF " + suffix
|
||||
}
|
||||
|
||||
// Unmarshal parses the PipeWire POD encoded data and stores the result
|
||||
// in the value pointed to by v. If v is nil or not a pointer,
|
||||
// Unmarshal returns an [InvalidUnmarshalError].
|
||||
func Unmarshal(data []byte, v any) error {
|
||||
if n, err := UnmarshalNext(data, v); err != nil {
|
||||
return err
|
||||
} else if len(data) > int(n) {
|
||||
return TrailingGarbageError(data[int(n):])
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// UnmarshalNext implements [Unmarshal] but returns the size of message decoded
|
||||
// and skips the final trailing garbage check.
|
||||
func UnmarshalNext(data []byte, v any) (size Word, err error) {
|
||||
rv := reflect.ValueOf(v)
|
||||
if rv.Kind() != reflect.Pointer || rv.IsNil() {
|
||||
return 0, &InvalidUnmarshalError{reflect.TypeOf(v)}
|
||||
}
|
||||
err = unmarshalValue(data, rv.Elem(), &size)
|
||||
// prefix and padding size
|
||||
size = Size(size)
|
||||
return
|
||||
}
|
||||
|
||||
// UnmarshalSetError describes a value that cannot be set during [Unmarshal].
|
||||
// This is likely an unexported struct field.
|
||||
type UnmarshalSetError struct{ Type reflect.Type }
|
||||
|
||||
func (u *UnmarshalSetError) Error() string { return "cannot set " + u.Type.String() }
|
||||
|
||||
// A TrailingGarbageError describes extra bytes after decoding
|
||||
// has completed during [Unmarshal].
|
||||
type TrailingGarbageError []byte
|
||||
|
||||
func (e TrailingGarbageError) Error() string {
|
||||
if len(e) < SizePrefix {
|
||||
return "got " + strconv.Itoa(len(e)) + " bytes of trailing garbage"
|
||||
}
|
||||
return "data has extra values starting with " + SPAKind(binary.NativeEndian.Uint32(e[SizeSPrefix:])).String()
|
||||
}
|
||||
|
||||
// A StringTerminationError describes an incorrectly terminated string
|
||||
// encountered during [Unmarshal].
|
||||
type StringTerminationError byte
|
||||
|
||||
func (e StringTerminationError) Error() string {
|
||||
return "got byte " + strconv.Itoa(int(e)) + " instead of NUL"
|
||||
}
|
||||
|
||||
// unmarshalValue implements [Unmarshal] on [reflect.Value] without compensating for prefix and padding size.
|
||||
func unmarshalValue(data []byte, v reflect.Value, wireSizeP *Word) error {
|
||||
if !v.CanSet() {
|
||||
return &UnmarshalSetError{v.Type()}
|
||||
}
|
||||
|
||||
if v.CanInterface() {
|
||||
if v.Kind() == reflect.Pointer {
|
||||
v.Set(reflect.New(v.Type().Elem()))
|
||||
}
|
||||
|
||||
if u, ok := v.Interface().(PODUnmarshaler); ok {
|
||||
var err error
|
||||
*wireSizeP, err = u.UnmarshalPOD(data)
|
||||
return err
|
||||
}
|
||||
|
||||
switch v.Interface().(type) {
|
||||
case Fd:
|
||||
*wireSizeP = SizeFd
|
||||
if err := unmarshalCheckTypeBounds(&data, SPA_TYPE_Fd, wireSizeP); err != nil {
|
||||
return err
|
||||
}
|
||||
v.SetInt(int64(binary.NativeEndian.Uint64(data)))
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
switch v.Kind() {
|
||||
case reflect.Uint32:
|
||||
*wireSizeP = SizeId
|
||||
if err := unmarshalCheckTypeBounds(&data, SPA_TYPE_Id, wireSizeP); err != nil {
|
||||
return err
|
||||
}
|
||||
v.SetUint(uint64(binary.NativeEndian.Uint32(data)))
|
||||
return nil
|
||||
|
||||
case reflect.Int32:
|
||||
*wireSizeP = SizeInt
|
||||
if err := unmarshalCheckTypeBounds(&data, SPA_TYPE_Int, wireSizeP); err != nil {
|
||||
return err
|
||||
}
|
||||
v.SetInt(int64(binary.NativeEndian.Uint32(data)))
|
||||
return nil
|
||||
|
||||
case reflect.Int64:
|
||||
*wireSizeP = SizeLong
|
||||
if err := unmarshalCheckTypeBounds(&data, SPA_TYPE_Long, wireSizeP); err != nil {
|
||||
return err
|
||||
}
|
||||
v.SetInt(int64(binary.NativeEndian.Uint64(data)))
|
||||
return nil
|
||||
|
||||
case reflect.Struct:
|
||||
*wireSizeP = 0
|
||||
if err := unmarshalCheckTypeBounds(&data, SPA_TYPE_Struct, wireSizeP); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var fieldWireSize Word
|
||||
for i := 0; i < v.NumField(); i++ {
|
||||
if err := unmarshalValue(data, v.Field(i), &fieldWireSize); err != nil {
|
||||
return err
|
||||
}
|
||||
// bounds check completed in successful call to unmarshalValue
|
||||
data = data[Size(fieldWireSize):]
|
||||
}
|
||||
|
||||
if len(data) != 0 {
|
||||
return TrailingGarbageError(data)
|
||||
}
|
||||
return nil
|
||||
|
||||
case reflect.Pointer:
|
||||
if ok, err := unmarshalHandleNone(&data, wireSizeP); err != nil {
|
||||
return err
|
||||
} else if ok {
|
||||
v.SetZero()
|
||||
return nil
|
||||
}
|
||||
|
||||
v.Set(reflect.New(v.Type().Elem()))
|
||||
return unmarshalValue(data, v.Elem(), wireSizeP)
|
||||
|
||||
case reflect.String:
|
||||
*wireSizeP = 0
|
||||
if err := unmarshalCheckTypeBounds(&data, SPA_TYPE_String, wireSizeP); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// string size, one extra NUL byte
|
||||
size := int(*wireSizeP)
|
||||
if len(data) < size {
|
||||
return ErrEOFDataString
|
||||
}
|
||||
|
||||
// the serialised strings still include NUL termination
|
||||
if data[size-1] != 0 {
|
||||
return StringTerminationError(data[size-1])
|
||||
}
|
||||
|
||||
v.SetString(string(data[:size-1]))
|
||||
return nil
|
||||
|
||||
default:
|
||||
return &UnsupportedTypeError{v.Type()}
|
||||
}
|
||||
}
|
||||
|
||||
// unmarshalHandleNone establishes prefix bounds and, for a value of type [SPA_TYPE_None],
|
||||
// validates its size and skips the header. This is for unmarshalling values that can be nil.
|
||||
func unmarshalHandleNone(data *[]byte, wireSizeP *Word) (bool, error) {
|
||||
if len(*data) < SizePrefix {
|
||||
return false, ErrEOFPrefix
|
||||
}
|
||||
|
||||
if SPAKind(binary.NativeEndian.Uint32((*data)[SizeSPrefix:])) != SPA_TYPE_None {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
*wireSizeP = 0
|
||||
if err := unmarshalCheckTypeBounds(data, SPA_TYPE_None, wireSizeP); err != nil {
|
||||
return true, err
|
||||
}
|
||||
|
||||
if len(*data) != 0 {
|
||||
return true, TrailingGarbageError(*data)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// An InconsistentSizeError describes an inconsistent size prefix encountered
|
||||
// in data passed to [Unmarshal].
|
||||
type InconsistentSizeError struct{ Prefix, Expect Word }
|
||||
|
||||
func (e InconsistentSizeError) Error() string {
|
||||
return "prefix claims size " + strconv.Itoa(int(e.Prefix)) +
|
||||
" for a " + strconv.Itoa(int(e.Expect)) + "-byte long segment"
|
||||
}
|
||||
|
||||
// An UnexpectedTypeError describes an unexpected type encountered
|
||||
// in data passed to [Unmarshal].
|
||||
type UnexpectedTypeError struct{ Type, Expect SPAKind }
|
||||
|
||||
func (e UnexpectedTypeError) Error() string {
|
||||
return "received " + e.Type.String() + " for a value of type " + e.Expect.String()
|
||||
}
|
||||
|
||||
// unmarshalCheckTypeBounds performs bounds checks on data and validates the type and size prefixes.
|
||||
// An expected size of zero skips further bounds checks.
|
||||
func unmarshalCheckTypeBounds(data *[]byte, t SPAKind, sizeP *Word) error {
|
||||
if len(*data) < SizePrefix {
|
||||
return ErrEOFPrefix
|
||||
}
|
||||
|
||||
wantSize := *sizeP
|
||||
gotSize := binary.NativeEndian.Uint32(*data)
|
||||
*sizeP = gotSize
|
||||
|
||||
if wantSize != 0 && gotSize != wantSize {
|
||||
return InconsistentSizeError{gotSize, wantSize}
|
||||
}
|
||||
if len(*data)-SizePrefix < int(gotSize) {
|
||||
return ErrEOFData
|
||||
}
|
||||
|
||||
gotType := SPAKind(binary.NativeEndian.Uint32((*data)[SizeSPrefix:]))
|
||||
if gotType != t {
|
||||
return UnexpectedTypeError{gotType, t}
|
||||
}
|
||||
|
||||
*data = (*data)[SizePrefix : gotSize+SizePrefix]
|
||||
return nil
|
||||
}
|
||||
|
||||
// The Footer contains additional messages, not directed to
|
||||
// the destination object defined by the Id field.
|
||||
type Footer[P KnownSize] struct {
|
||||
// The footer opcode.
|
||||
Opcode Id `json:"opcode"`
|
||||
// The footer payload struct.
|
||||
Payload P `json:"payload"`
|
||||
}
|
||||
|
||||
// Size satisfies [KnownSize] with a usually compile-time known value.
|
||||
func (f *Footer[P]) Size() Word {
|
||||
return SizePrefix +
|
||||
Size(SizeId) +
|
||||
f.Payload.Size()
|
||||
}
|
||||
|
||||
// MarshalBinary satisfies [encoding.BinaryMarshaler] via [Marshal].
|
||||
func (f *Footer[T]) MarshalBinary() ([]byte, error) { return Marshal(f) }
|
||||
|
||||
// UnmarshalBinary satisfies [encoding.BinaryUnmarshaler] via [Unmarshal].
|
||||
func (f *Footer[T]) UnmarshalBinary(data []byte) error { return Unmarshal(data, f) }
|
||||
|
||||
// SPADictItem represents spa_dict_item.
|
||||
type SPADictItem struct {
|
||||
// Dot-separated string.
|
||||
Key string `json:"key"`
|
||||
// Arbitrary string.
|
||||
//
|
||||
// Integer values are represented in base 10,
|
||||
// boolean values are represented as "true" or "false".
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
// SPADict represents spa_dict.
|
||||
type SPADict []SPADictItem
|
||||
|
||||
// Size satisfies [KnownSize] with a value computed at runtime.
|
||||
func (d *SPADict) Size() Word {
|
||||
if d == nil {
|
||||
return 0
|
||||
}
|
||||
|
||||
// struct prefix, NItems value
|
||||
size := SizePrefix + int(Size(SizeInt))
|
||||
for i := range *d {
|
||||
size += SizeString[int]((*d)[i].Key)
|
||||
size += SizeString[int]((*d)[i].Value)
|
||||
}
|
||||
return Word(size)
|
||||
}
|
||||
|
||||
// MarshalPOD satisfies [PODMarshaler] as [SPADict] violates the POD type system.
|
||||
func (d *SPADict) MarshalPOD(data []byte) ([]byte, error) {
|
||||
return appendInner(data, func(dataPrefix []byte) (data []byte, err error) {
|
||||
data = SPA_TYPE_Struct.append(dataPrefix)
|
||||
if data, err = MarshalAppend(data, Int(len(*d))); err != nil {
|
||||
return
|
||||
}
|
||||
for i := range *d {
|
||||
if data, err = MarshalAppend(data, (*d)[i].Key); err != nil {
|
||||
return
|
||||
}
|
||||
if data, err = MarshalAppend(data, (*d)[i].Value); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
})
|
||||
}
|
||||
|
||||
// UnmarshalPOD satisfies [PODUnmarshaler] as [SPADict] violates the POD type system.
|
||||
func (d *SPADict) UnmarshalPOD(data []byte) (Word, error) {
|
||||
var wireSize Word
|
||||
if err := unmarshalCheckTypeBounds(&data, SPA_TYPE_Struct, &wireSize); err != nil {
|
||||
return wireSize, err
|
||||
}
|
||||
// bounds check completed in successful call to unmarshalCheckTypeBounds
|
||||
data = data[:wireSize]
|
||||
|
||||
var count Int
|
||||
if size, err := UnmarshalNext(data, &count); err != nil {
|
||||
return wireSize, err
|
||||
} else {
|
||||
// bounds check completed in successful call to Unmarshal
|
||||
data = data[size:]
|
||||
}
|
||||
|
||||
*d = make([]SPADictItem, count)
|
||||
for i := range *d {
|
||||
if size, err := UnmarshalNext(data, &(*d)[i].Key); err != nil {
|
||||
return wireSize, err
|
||||
} else {
|
||||
// bounds check completed in successful call to Unmarshal
|
||||
data = data[size:]
|
||||
}
|
||||
if size, err := UnmarshalNext(data, &(*d)[i].Value); err != nil {
|
||||
return wireSize, err
|
||||
} else {
|
||||
// bounds check completed in successful call to Unmarshal
|
||||
data = data[size:]
|
||||
}
|
||||
}
|
||||
|
||||
if len(data) != 0 {
|
||||
return wireSize, TrailingGarbageError(data)
|
||||
}
|
||||
return wireSize, nil
|
||||
}
|
||||
|
||||
// A Message is a value that can be transmitted as a message over PipeWire protocol native.
|
||||
type Message interface {
|
||||
// Opcode returns the opcode of this message.
|
||||
Opcode() byte
|
||||
// FileCount returns the number of files associated with this message.
|
||||
FileCount() Int
|
||||
|
||||
KnownSize
|
||||
}
|
||||
|
||||
// A MessageEncoder provides methods for encoding a [Message].
|
||||
type MessageEncoder struct{ Message }
|
||||
|
||||
// SizeMessage returns the size of Message transmitted over protocol native.
|
||||
func (m MessageEncoder) SizeMessage(footer KnownSize) (size Word) {
|
||||
size = SizeHeader + m.Message.Size()
|
||||
if footer != nil {
|
||||
size += footer.Size()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// AppendMessage appends the protocol native encoding of Message to dst and returns the appended slice.
|
||||
func (m MessageEncoder) AppendMessage(dst []byte, Id, sequence Int, footer KnownSize) (data []byte, err error) {
|
||||
size := m.SizeMessage(footer)
|
||||
if size&^SizeMax != 0 {
|
||||
return dst, ErrSizeRange
|
||||
}
|
||||
|
||||
data = slices.Grow(dst, int(size))
|
||||
data = (&Header{
|
||||
ID: Id,
|
||||
Opcode: m.Message.Opcode(),
|
||||
Size: size - SizeHeader,
|
||||
Sequence: sequence,
|
||||
FileCount: m.Message.FileCount(),
|
||||
}).append(data)
|
||||
data, err = MarshalAppend(data, m.Message)
|
||||
if err == nil && footer != nil {
|
||||
data, err = MarshalAppend(data, footer)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
226
internal/pipewire/pod_test.go
Normal file
226
internal/pipewire/pod_test.go
Normal file
@@ -0,0 +1,226 @@
|
||||
package pipewire_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding"
|
||||
"encoding/gob"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/internal/pipewire"
|
||||
)
|
||||
|
||||
type encodingTestCases[V any, S interface {
|
||||
encoding.BinaryMarshaler
|
||||
encoding.BinaryUnmarshaler
|
||||
|
||||
*V
|
||||
}] []struct {
|
||||
// Uninterpreted name of subtest.
|
||||
name string
|
||||
// Encoded data.
|
||||
wantData []byte
|
||||
// Value corresponding to wantData.
|
||||
value V
|
||||
// Expected decoding error. Skips encoding check if non-nil.
|
||||
wantErr error
|
||||
}
|
||||
|
||||
// run runs all test cases as subtests of [testing.T].
|
||||
func (testCases encodingTestCases[V, S]) run(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("decode", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var value V
|
||||
if err := S(&value).UnmarshalBinary(tc.wantData); err != nil {
|
||||
t.Fatalf("UnmarshalBinary: error = %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(&value, &tc.value) {
|
||||
t.Fatalf("UnmarshalBinary:\n%s\nwant\n%s", mustMarshalJSON(value), mustMarshalJSON(tc.value))
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("encode", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if gotData, err := S(&tc.value).MarshalBinary(); err != nil {
|
||||
t.Fatalf("MarshalBinary: error = %v", err)
|
||||
} else if string(gotData) != string(tc.wantData) {
|
||||
t.Fatalf("MarshalBinary: %#v, want %#v", gotData, tc.wantData)
|
||||
}
|
||||
})
|
||||
|
||||
if s, ok := any(&tc.value).(pipewire.KnownSize); ok {
|
||||
t.Run("size", func(t *testing.T) {
|
||||
if got := int(s.Size()); got != len(tc.wantData) {
|
||||
t.Errorf("Size: %d, want %d", got, len(tc.wantData))
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPODErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
err error
|
||||
want string
|
||||
}{
|
||||
{"UnsupportedTypeError", &pipewire.UnsupportedTypeError{
|
||||
Type: reflect.TypeFor[any](),
|
||||
}, "unsupported type interface {}"},
|
||||
|
||||
{"UnsupportedSizeError", pipewire.UnsupportedSizeError(pipewire.SizeMax + 1), "size 16777216 out of range"},
|
||||
|
||||
{"InvalidUnmarshalError untyped nil", new(pipewire.InvalidUnmarshalError), "attempting to unmarshal to nil"},
|
||||
{"InvalidUnmarshalError non-pointer", &pipewire.InvalidUnmarshalError{
|
||||
Type: reflect.TypeFor[uintptr](),
|
||||
}, "attempting to unmarshal to non-pointer type uintptr"},
|
||||
{"InvalidUnmarshalError nil", &pipewire.InvalidUnmarshalError{
|
||||
Type: reflect.TypeFor[*uintptr](),
|
||||
}, "attempting to unmarshal to nil *uintptr"},
|
||||
|
||||
{"UnexpectedEOFError ErrEOFPrefix", pipewire.ErrEOFPrefix, "unexpected EOF decoding fixed-size POD prefix"},
|
||||
{"UnexpectedEOFError ErrEOFData", pipewire.ErrEOFData, "unexpected EOF establishing POD data bounds"},
|
||||
{"UnexpectedEOFError ErrEOFDataString", pipewire.ErrEOFDataString, "unexpected EOF establishing POD String bounds"},
|
||||
{"UnexpectedEOFError invalid", pipewire.UnexpectedEOFError(0xbad), "unexpected EOF"},
|
||||
|
||||
{"UnmarshalSetError", &pipewire.UnmarshalSetError{
|
||||
Type: reflect.TypeFor[*uintptr](),
|
||||
}, "cannot set *uintptr"},
|
||||
|
||||
{"TrailingGarbageError short", make(pipewire.TrailingGarbageError, 1<<3-1), "got 7 bytes of trailing garbage"},
|
||||
{"TrailingGarbageError String", pipewire.TrailingGarbageError{
|
||||
/* size: */ 0, 0, 0, 0,
|
||||
/* type: */ byte(pipewire.SPA_TYPE_String), 0, 0, 0,
|
||||
}, "data has extra values starting with String"},
|
||||
{"TrailingGarbageError invalid", pipewire.TrailingGarbageError{
|
||||
/* size: */ 0, 0, 0, 0,
|
||||
/* type: */ 0xff, 0xff, 0xff, 0xff,
|
||||
/* garbage: */ 0,
|
||||
}, "data has extra values starting with invalid type field 0xffffffff"},
|
||||
|
||||
{"StringTerminationError", pipewire.StringTerminationError(0xff), "got byte 255 instead of NUL"},
|
||||
|
||||
{"InconsistentSizeError", pipewire.InconsistentSizeError{
|
||||
Prefix: 0xbad,
|
||||
Expect: 0xff,
|
||||
}, "prefix claims size 2989 for a 255-byte long segment"},
|
||||
|
||||
{"UnexpectedTypeError zero", pipewire.UnexpectedTypeError{}, "received invalid type field 0x0 for a value of type invalid type field 0x0"},
|
||||
{"UnexpectedTypeError", pipewire.UnexpectedTypeError{
|
||||
Type: pipewire.SPA_TYPE_String,
|
||||
Expect: pipewire.SPA_TYPE_Array,
|
||||
}, "received String for a value of type Array"},
|
||||
{"UnexpectedTypeError invalid", pipewire.UnexpectedTypeError{
|
||||
Type: 0xdeadbeef,
|
||||
Expect: pipewire.SPA_TYPE_Long,
|
||||
}, "received invalid type field 0xdeadbeef for a value of type Long"},
|
||||
}
|
||||
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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
var benchmarkSample = func() (sample pipewire.CoreInfo) {
|
||||
if err := sample.UnmarshalBinary(samplePWContainer[1][0][1]); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return
|
||||
}()
|
||||
|
||||
func BenchmarkMarshal(b *testing.B) {
|
||||
for b.Loop() {
|
||||
if _, err := benchmarkSample.MarshalBinary(); err != nil {
|
||||
b.Fatalf("MarshalBinary: error = %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkMarshalJSON(b *testing.B) {
|
||||
for b.Loop() {
|
||||
if _, err := json.Marshal(benchmarkSample); err != nil {
|
||||
b.Fatalf("json.Marshal: error = %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGobEncode(b *testing.B) {
|
||||
e := gob.NewEncoder(io.Discard)
|
||||
type sampleRaw pipewire.CoreInfo
|
||||
|
||||
for b.Loop() {
|
||||
if err := e.Encode((*sampleRaw)(&benchmarkSample)); err != nil {
|
||||
b.Fatalf("(*gob.Encoder).Encode: error = %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkUnmarshal(b *testing.B) {
|
||||
var got pipewire.CoreInfo
|
||||
|
||||
for b.Loop() {
|
||||
if err := got.UnmarshalBinary(samplePWContainer[1][0][1]); err != nil {
|
||||
b.Fatalf("UnmarshalBinary: error = %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkUnmarshalJSON(b *testing.B) {
|
||||
var got pipewire.CoreInfo
|
||||
data, err := json.Marshal(benchmarkSample)
|
||||
if err != nil {
|
||||
b.Fatalf("json.Marshal: error = %v", err)
|
||||
}
|
||||
|
||||
for b.Loop() {
|
||||
if err = json.Unmarshal(data, &got); err != nil {
|
||||
b.Fatalf("json.Unmarshal: error = %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGobDecode(b *testing.B) {
|
||||
type sampleRaw pipewire.CoreInfo
|
||||
var buf bytes.Buffer
|
||||
e := gob.NewEncoder(&buf)
|
||||
d := gob.NewDecoder(&buf)
|
||||
|
||||
for b.Loop() {
|
||||
b.StopTimer()
|
||||
if err := e.Encode((*sampleRaw)(&benchmarkSample)); err != nil {
|
||||
b.Fatalf("(*gob.Encoder).Encode: error = %v", err)
|
||||
}
|
||||
b.StartTimer()
|
||||
|
||||
if err := d.Decode(new(sampleRaw)); err != nil {
|
||||
b.Fatalf("(*gob.Encoder).Decode: error = %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// mustMarshalJSON calls [json.Marshal] and returns the result.
|
||||
func mustMarshalJSON(v any) string {
|
||||
if data, err := json.Marshal(v); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
return string(data)
|
||||
}
|
||||
}
|
||||
247
internal/pipewire/securitycontext.go
Normal file
247
internal/pipewire/securitycontext.go
Normal file
@@ -0,0 +1,247 @@
|
||||
package pipewire
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"runtime"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
/* pipewire/extensions/security-context.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_SecurityContext = PW_TYPE_INFO_INTERFACE_BASE + "SecurityContext"
|
||||
PW_SECURITY_CONTEXT_PERM_MASK = PW_PERM_RWX
|
||||
PW_VERSION_SECURITY_CONTEXT = 3
|
||||
|
||||
PW_EXTENSION_MODULE_SECURITY_CONTEXT = PIPEWIRE_MODULE_PREFIX + "module-security-context"
|
||||
)
|
||||
|
||||
const (
|
||||
PW_SECURITY_CONTEXT_EVENT_NUM = iota
|
||||
|
||||
PW_VERSION_SECURITY_CONTEXT_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_SECURITY_CONTEXT_METHOD_ADD_LISTENER = iota
|
||||
|
||||
PW_SECURITY_CONTEXT_METHOD_CREATE
|
||||
|
||||
PW_SECURITY_CONTEXT_METHOD_NUM
|
||||
PW_VERSION_SECURITY_CONTEXT_METHODS = 0
|
||||
)
|
||||
|
||||
// SecurityContextCreate is sent to create a new security context.
|
||||
//
|
||||
// Creates a new security context with a socket listening FD.
|
||||
// PipeWire will accept new client connections on listen_fd.
|
||||
//
|
||||
// listen_fd must be ready to accept new connections when this
|
||||
// request is sent by the client. In other words, the client must
|
||||
// call bind(2) and listen(2) before sending the FD.
|
||||
//
|
||||
// close_fd is a FD closed by the client when PipeWire should stop
|
||||
// accepting new connections on listen_fd.
|
||||
//
|
||||
// PipeWire must continue to accept connections on listen_fd when
|
||||
// the client which created the security context disconnects.
|
||||
//
|
||||
// After sending this request, closing listen_fd and close_fd
|
||||
// remains the only valid operation on them.
|
||||
type SecurityContextCreate struct {
|
||||
// The offset in the SCM_RIGHTS msg_control message to
|
||||
// the fd to listen on for new connections.
|
||||
ListenFd Fd
|
||||
// The offset in the SCM_RIGHTS msg_control message to
|
||||
// the fd used to stop listening.
|
||||
CloseFd Fd
|
||||
|
||||
// Extra properties. These will be copied on the client
|
||||
// that connects through this context.
|
||||
Properties *SPADict `json:"props"`
|
||||
}
|
||||
|
||||
// Opcode satisfies [Message] with a constant value.
|
||||
func (c *SecurityContextCreate) Opcode() byte { return PW_SECURITY_CONTEXT_METHOD_CREATE }
|
||||
|
||||
// FileCount satisfies [Message] with a constant value.
|
||||
func (c *SecurityContextCreate) FileCount() Int { return 2 }
|
||||
|
||||
// Size satisfies [KnownSize] with a value computed at runtime.
|
||||
func (c *SecurityContextCreate) Size() Word {
|
||||
return SizePrefix +
|
||||
Size(SizeFd) +
|
||||
Size(SizeFd) +
|
||||
c.Properties.Size()
|
||||
}
|
||||
|
||||
// MarshalBinary satisfies [encoding.BinaryMarshaler] via [Marshal].
|
||||
func (c *SecurityContextCreate) MarshalBinary() ([]byte, error) { return Marshal(c) }
|
||||
|
||||
// UnmarshalBinary satisfies [encoding.BinaryUnmarshaler] via [Unmarshal].
|
||||
func (c *SecurityContextCreate) UnmarshalBinary(data []byte) error { return Unmarshal(data, c) }
|
||||
|
||||
// SecurityContext holds state of [PW_TYPE_INTERFACE_SecurityContext].
|
||||
type SecurityContext struct {
|
||||
// Proxy id as tracked by [Context].
|
||||
ID Int `json:"proxy_id"`
|
||||
// Global id as tracked by [Registry].
|
||||
GlobalID Int `json:"id"`
|
||||
|
||||
ctx *Context
|
||||
|
||||
destructible
|
||||
}
|
||||
|
||||
// GetSecurityContext queues a [RegistryBind] message for the PipeWire server
|
||||
// and returns the address of the newly allocated [SecurityContext].
|
||||
func (registry *Registry) GetSecurityContext() (securityContext *SecurityContext, err error) {
|
||||
securityContext = &SecurityContext{ctx: registry.ctx}
|
||||
for globalId, object := range registry.Objects {
|
||||
if object.Type == securityContext.String() {
|
||||
securityContext.GlobalID = globalId
|
||||
securityContext.ID, err = registry.bind(securityContext, securityContext.GlobalID, PW_VERSION_SECURITY_CONTEXT)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return nil, UnsupportedObjectTypeError(securityContext.String())
|
||||
}
|
||||
|
||||
// Create queues a [SecurityContextCreate] message for the PipeWire server.
|
||||
func (securityContext *SecurityContext) Create(listenFd, closeFd int, props SPADict) (err error) {
|
||||
if err = securityContext.checkDestroy(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
asCoreError := securityContext.ctx.expectsCoreError(securityContext.ID, &err)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// queued in reverse based on upstream behaviour, unsure why
|
||||
offset := securityContext.ctx.queueFiles(closeFd, listenFd)
|
||||
if err = securityContext.ctx.writeMessage(
|
||||
securityContext.ID,
|
||||
&SecurityContextCreate{ListenFd: offset + 1, CloseFd: offset + 0, Properties: &props},
|
||||
); err != nil {
|
||||
return
|
||||
}
|
||||
if err = securityContext.ctx.GetCore().Sync(); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if coreError := asCoreError(); coreError == nil {
|
||||
return
|
||||
} else {
|
||||
switch syscall.Errno(-coreError.Result) {
|
||||
case syscall.EPERM:
|
||||
return &PermissionError{securityContext.ID, coreError.Message}
|
||||
|
||||
default:
|
||||
return coreError
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// securityContextCloser holds onto resources associated to the security context.
|
||||
type securityContextCloser struct {
|
||||
// Pipe with its write end passed to [SecurityContextCreate.CloseFd].
|
||||
closeFds [2]int
|
||||
// Pathname the socket was bound to.
|
||||
pathname string
|
||||
}
|
||||
|
||||
// Close closes both ends of the pipe.
|
||||
func (scc *securityContextCloser) Close() (err error) {
|
||||
err = errors.Join(
|
||||
syscall.Close(scc.closeFds[1]),
|
||||
syscall.Close(scc.closeFds[0]),
|
||||
// there is still technically a TOCTOU here but this is internal
|
||||
// and has access to the privileged pipewire socket, so it only
|
||||
// receives trusted input (e.g. from cmd/hakurei) anyway
|
||||
os.Remove(scc.pathname),
|
||||
)
|
||||
|
||||
// no need for a finalizer anymore
|
||||
runtime.SetFinalizer(scc, nil)
|
||||
return
|
||||
}
|
||||
|
||||
// BindAndCreate binds a new socket to the specified pathname and pass it to Create.
|
||||
// It returns an [io.Closer] corresponding to [SecurityContextCreate.CloseFd].
|
||||
func (securityContext *SecurityContext) BindAndCreate(pathname string, props SPADict) (io.Closer, error) {
|
||||
if err := securityContext.checkDestroy(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var scc securityContextCloser
|
||||
|
||||
// ensure pathname is available
|
||||
if f, err := os.Create(pathname); err != nil {
|
||||
return nil, err
|
||||
} else if err = f.Close(); err != nil {
|
||||
_ = os.Remove(pathname)
|
||||
return nil, err
|
||||
} else if err = os.Remove(pathname); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
scc.pathname = pathname
|
||||
|
||||
var listenFd int
|
||||
if fd, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC, 0); err != nil {
|
||||
return nil, os.NewSyscallError("socket", err)
|
||||
} else {
|
||||
securityContext.ctx.cleanup(func() error { return syscall.Close(fd) })
|
||||
listenFd = fd
|
||||
}
|
||||
if err := syscall.Bind(listenFd, &syscall.SockaddrUnix{Name: pathname}); err != nil {
|
||||
return nil, os.NewSyscallError("bind", err)
|
||||
} else if err = syscall.Listen(listenFd, 0); err != nil {
|
||||
_ = os.Remove(pathname)
|
||||
return nil, os.NewSyscallError("listen", err)
|
||||
}
|
||||
|
||||
if err := syscall.Pipe2(scc.closeFds[0:], syscall.O_CLOEXEC); err != nil {
|
||||
_ = os.Remove(pathname)
|
||||
return nil, err
|
||||
}
|
||||
runtime.SetFinalizer(&scc, (*securityContextCloser).Close)
|
||||
|
||||
if err := securityContext.Create(listenFd, scc.closeFds[1], props); err != nil {
|
||||
_ = scc.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &scc, nil
|
||||
}
|
||||
|
||||
func (securityContext *SecurityContext) consume(opcode byte, files []int, _ func(v any)) error {
|
||||
securityContext.mustCheckDestroy()
|
||||
closeReceivedFiles(files...)
|
||||
switch opcode {
|
||||
// SecurityContext does not receive any events
|
||||
|
||||
default:
|
||||
panic(&UnsupportedOpcodeError{opcode, securityContext.String()})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (securityContext *SecurityContext) setBoundProps(event *CoreBoundProps) error {
|
||||
securityContext.mustCheckDestroy()
|
||||
if securityContext.ID != event.ID {
|
||||
return &InconsistentIdError{Proxy: securityContext, ID: securityContext.ID, ServerID: event.ID}
|
||||
}
|
||||
if securityContext.GlobalID != event.GlobalID {
|
||||
return &InconsistentIdError{Global: true, Proxy: securityContext, ID: securityContext.GlobalID, ServerID: event.GlobalID}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Destroy destroys this [SecurityContext] proxy.
|
||||
func (securityContext *SecurityContext) Destroy() error {
|
||||
return securityContext.destroy(securityContext.ctx, securityContext.ID)
|
||||
}
|
||||
|
||||
func (securityContext *SecurityContext) String() string { return PW_TYPE_INTERFACE_SecurityContext }
|
||||
21
internal/pipewire/securitycontext_test.go
Normal file
21
internal/pipewire/securitycontext_test.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package pipewire_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"hakurei.app/internal/pipewire"
|
||||
)
|
||||
|
||||
func TestSecurityContextCreate(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
encodingTestCases[pipewire.SecurityContextCreate, *pipewire.SecurityContextCreate]{
|
||||
{"sample", samplePWContainer[6][0][1], pipewire.SecurityContextCreate{
|
||||
ListenFd: 1 /* 21: duplicated from listen_fd */, CloseFd: 0, /* 20: duplicated from close_fd */
|
||||
Properties: &pipewire.SPADict{
|
||||
{Key: pipewire.PW_KEY_SEC_ENGINE, Value: "org.flatpak"},
|
||||
{Key: pipewire.PW_KEY_ACCESS, Value: "restricted"},
|
||||
},
|
||||
}, nil},
|
||||
}.run(t)
|
||||
}
|
||||
837
internal/pipewire/spa.go
Normal file
837
internal/pipewire/spa.go
Normal file
@@ -0,0 +1,837 @@
|
||||
package pipewire
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// A SPAKind describes the kind of data being encoded right after it.
|
||||
//
|
||||
// These do not always follow the same rules, and encoding/decoding
|
||||
// is very much context-dependent. Callers should therefore not
|
||||
// attempt to use these values directly and rely on [Marshal] and
|
||||
// [Unmarshal] and their variants instead.
|
||||
type SPAKind Word
|
||||
|
||||
/* Basic types */
|
||||
const (
|
||||
/* POD's can contain a number of basic SPA types: */
|
||||
|
||||
SPA_TYPE_START SPAKind = 0x00000 + iota
|
||||
|
||||
SPA_TYPE_None // No value or a NULL pointer.
|
||||
SPA_TYPE_Bool // A boolean value.
|
||||
SPA_TYPE_Id // An enumerated value.
|
||||
SPA_TYPE_Int // An integer value, 32-bit.
|
||||
SPA_TYPE_Long // An integer value, 64-bit.
|
||||
SPA_TYPE_Float // A floating point value, 32-bit.
|
||||
SPA_TYPE_Double // A floating point value, 64-bit.
|
||||
SPA_TYPE_String // A string.
|
||||
SPA_TYPE_Bytes // A byte array.
|
||||
SPA_TYPE_Rectangle // A rectangle with width and height.
|
||||
SPA_TYPE_Fraction // A fraction with numerator and denominator.
|
||||
SPA_TYPE_Bitmap // An array of bits.
|
||||
|
||||
/* POD's can be grouped together in these container types: */
|
||||
|
||||
SPA_TYPE_Array // An array of equal sized objects.
|
||||
SPA_TYPE_Struct // A collection of types and objects.
|
||||
SPA_TYPE_Object // An object with properties.
|
||||
SPA_TYPE_Sequence // A timed sequence of POD's.
|
||||
|
||||
/* POD's can also contain some extra types: */
|
||||
|
||||
SPA_TYPE_Pointer // A typed pointer in memory.
|
||||
SPA_TYPE_Fd // A file descriptor.
|
||||
SPA_TYPE_Choice // A choice of values.
|
||||
SPA_TYPE_Pod // A generic type for the POD itself.
|
||||
|
||||
_SPA_TYPE_LAST // not part of ABI
|
||||
)
|
||||
|
||||
// append appends the representation of [SPAKind] to data and returns the appended slice.
|
||||
func (kind SPAKind) append(data []byte) []byte {
|
||||
return binary.NativeEndian.AppendUint32(data, Word(kind))
|
||||
}
|
||||
|
||||
// String returns the name of the [SPAKind] for basic types.
|
||||
func (kind SPAKind) String() string {
|
||||
switch kind {
|
||||
case SPA_TYPE_None:
|
||||
return "None"
|
||||
case SPA_TYPE_Bool:
|
||||
return "Bool"
|
||||
case SPA_TYPE_Id:
|
||||
return "Id"
|
||||
case SPA_TYPE_Int:
|
||||
return "Int"
|
||||
case SPA_TYPE_Long:
|
||||
return "Long"
|
||||
case SPA_TYPE_Float:
|
||||
return "Float"
|
||||
case SPA_TYPE_Double:
|
||||
return "Double"
|
||||
case SPA_TYPE_String:
|
||||
return "String"
|
||||
case SPA_TYPE_Bytes:
|
||||
return "Bytes"
|
||||
case SPA_TYPE_Rectangle:
|
||||
return "Rectangle"
|
||||
case SPA_TYPE_Fraction:
|
||||
return "Fraction"
|
||||
case SPA_TYPE_Bitmap:
|
||||
return "Bitmap"
|
||||
case SPA_TYPE_Array:
|
||||
return "Array"
|
||||
case SPA_TYPE_Struct:
|
||||
return "Struct"
|
||||
case SPA_TYPE_Object:
|
||||
return "Object"
|
||||
case SPA_TYPE_Sequence:
|
||||
return "Sequence"
|
||||
case SPA_TYPE_Pointer:
|
||||
return "Pointer"
|
||||
case SPA_TYPE_Fd:
|
||||
return "Fd"
|
||||
case SPA_TYPE_Choice:
|
||||
return "Choice"
|
||||
case SPA_TYPE_Pod:
|
||||
return "Pod"
|
||||
|
||||
default:
|
||||
return fmt.Sprintf("invalid type field %#x", Word(kind))
|
||||
}
|
||||
}
|
||||
|
||||
/* Pointers */
|
||||
const (
|
||||
SPA_TYPE_POINTER_START = 0x10000 + iota
|
||||
SPA_TYPE_POINTER_Buffer
|
||||
SPA_TYPE_POINTER_Meta
|
||||
SPA_TYPE_POINTER_Dict
|
||||
|
||||
_SPA_TYPE_POINTER_LAST // not part of ABI
|
||||
)
|
||||
|
||||
/* Events */
|
||||
const (
|
||||
SPA_TYPE_EVENT_START = 0x20000 + iota
|
||||
SPA_TYPE_EVENT_Device
|
||||
SPA_TYPE_EVENT_Node
|
||||
|
||||
_SPA_TYPE_EVENT_LAST // not part of ABI
|
||||
)
|
||||
|
||||
/* Commands */
|
||||
const (
|
||||
SPA_TYPE_COMMAND_START = 0x30000 + iota
|
||||
SPA_TYPE_COMMAND_Device
|
||||
SPA_TYPE_COMMAND_Node
|
||||
|
||||
_SPA_TYPE_COMMAND_LAST // not part of ABI
|
||||
)
|
||||
|
||||
/* Objects */
|
||||
const (
|
||||
SPA_TYPE_OBJECT_START = 0x40000 + iota
|
||||
SPA_TYPE_OBJECT_PropInfo
|
||||
SPA_TYPE_OBJECT_Props
|
||||
SPA_TYPE_OBJECT_Format
|
||||
SPA_TYPE_OBJECT_ParamBuffers
|
||||
SPA_TYPE_OBJECT_ParamMeta
|
||||
SPA_TYPE_OBJECT_ParamIO
|
||||
SPA_TYPE_OBJECT_ParamProfile
|
||||
SPA_TYPE_OBJECT_ParamPortConfig
|
||||
SPA_TYPE_OBJECT_ParamRoute
|
||||
SPA_TYPE_OBJECT_Profiler
|
||||
SPA_TYPE_OBJECT_ParamLatency
|
||||
SPA_TYPE_OBJECT_ParamProcessLatency
|
||||
SPA_TYPE_OBJECT_ParamTag
|
||||
_SPA_TYPE_OBJECT_LAST // not part of ABI
|
||||
)
|
||||
|
||||
/* vendor extensions */
|
||||
const (
|
||||
SPA_TYPE_VENDOR_PipeWire = 0x02000000
|
||||
|
||||
SPA_TYPE_VENDOR_Other = 0x7f000000
|
||||
)
|
||||
|
||||
/* spa/include/spa/utils/type.h */
|
||||
|
||||
const (
|
||||
SPA_TYPE_INFO_BASE = "Spa:"
|
||||
|
||||
SPA_TYPE_INFO_Flags = SPA_TYPE_INFO_BASE + "Flags"
|
||||
SPA_TYPE_INFO_FLAGS_BASE = SPA_TYPE_INFO_Flags + ":"
|
||||
|
||||
SPA_TYPE_INFO_Enum = SPA_TYPE_INFO_BASE + "Enum"
|
||||
SPA_TYPE_INFO_ENUM_BASE = SPA_TYPE_INFO_Enum + ":"
|
||||
|
||||
SPA_TYPE_INFO_Pod = SPA_TYPE_INFO_BASE + "Pod"
|
||||
SPA_TYPE_INFO_POD_BASE = SPA_TYPE_INFO_Pod + ":"
|
||||
|
||||
SPA_TYPE_INFO_Struct = SPA_TYPE_INFO_POD_BASE + "Struct"
|
||||
SPA_TYPE_INFO_STRUCT_BASE = SPA_TYPE_INFO_Struct + ":"
|
||||
|
||||
SPA_TYPE_INFO_Object = SPA_TYPE_INFO_POD_BASE + "Object"
|
||||
SPA_TYPE_INFO_OBJECT_BASE = SPA_TYPE_INFO_Object + ":"
|
||||
|
||||
SPA_TYPE_INFO_Pointer = SPA_TYPE_INFO_BASE + "Pointer"
|
||||
SPA_TYPE_INFO_POINTER_BASE = SPA_TYPE_INFO_Pointer + ":"
|
||||
|
||||
SPA_TYPE_INFO_Interface = SPA_TYPE_INFO_POINTER_BASE + "Interface"
|
||||
SPA_TYPE_INFO_INTERFACE_BASE = SPA_TYPE_INFO_Interface + ":"
|
||||
|
||||
SPA_TYPE_INFO_Event = SPA_TYPE_INFO_OBJECT_BASE + "Event"
|
||||
SPA_TYPE_INFO_EVENT_BASE = SPA_TYPE_INFO_Event + ":"
|
||||
|
||||
SPA_TYPE_INFO_Command = SPA_TYPE_INFO_OBJECT_BASE + "Command"
|
||||
SPA_TYPE_INFO_COMMAND_BASE = SPA_TYPE_INFO_Command + ":"
|
||||
)
|
||||
|
||||
/* pipewire/device.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_Device = PW_TYPE_INFO_INTERFACE_BASE + "Device"
|
||||
PW_DEVICE_PERM_MASK = PW_PERM_RWXM
|
||||
PW_VERSION_DEVICE = 3
|
||||
)
|
||||
|
||||
const (
|
||||
PW_DEVICE_CHANGE_MASK_PROPS = 1 << iota
|
||||
PW_DEVICE_CHANGE_MASK_PARAMS
|
||||
|
||||
PW_DEVICE_CHANGE_MASK_ALL = 1<<iota - 1
|
||||
)
|
||||
|
||||
const (
|
||||
PW_DEVICE_EVENT_INFO = iota
|
||||
PW_DEVICE_EVENT_PARAM
|
||||
PW_DEVICE_EVENT_NUM
|
||||
|
||||
PW_VERSION_DEVICE_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_DEVICE_METHOD_ADD_LISTENER = iota
|
||||
PW_DEVICE_METHOD_SUBSCRIBE_PARAMS
|
||||
PW_DEVICE_METHOD_ENUM_PARAMS
|
||||
PW_DEVICE_METHOD_SET_PARAM
|
||||
PW_DEVICE_METHOD_NUM
|
||||
|
||||
PW_VERSION_DEVICE_METHODS = 0
|
||||
)
|
||||
|
||||
/* pipewire/factory.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_Factory = PW_TYPE_INFO_INTERFACE_BASE + "Factory"
|
||||
PW_FACTORY_PERM_MASK = PW_PERM_R | PW_PERM_M
|
||||
PW_VERSION_FACTORY = 3
|
||||
)
|
||||
|
||||
const (
|
||||
PW_FACTORY_CHANGE_MASK_PROPS = 1 << iota
|
||||
|
||||
PW_FACTORY_CHANGE_MASK_ALL = 1<<iota - 1
|
||||
)
|
||||
|
||||
const (
|
||||
PW_FACTORY_EVENT_INFO = iota
|
||||
PW_FACTORY_EVENT_NUM
|
||||
|
||||
PW_VERSION_FACTORY_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_FACTORY_METHOD_ADD_LISTENER = iota
|
||||
PW_FACTORY_METHOD_NUM
|
||||
|
||||
PW_VERSION_FACTORY_METHODS = 0
|
||||
)
|
||||
|
||||
/* pipewire/link.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_Link = PW_TYPE_INFO_INTERFACE_BASE + "Link"
|
||||
PW_LINK_PERM_MASK = PW_PERM_R | PW_PERM_X
|
||||
PW_VERSION_LINK = 3
|
||||
)
|
||||
|
||||
const (
|
||||
PW_LINK_STATE_ERROR = iota - 2 // the link is in error
|
||||
PW_LINK_STATE_UNLINKED // the link is unlinked
|
||||
PW_LINK_STATE_INIT // the link is initialized
|
||||
PW_LINK_STATE_NEGOTIATING // the link is negotiating formats
|
||||
PW_LINK_STATE_ALLOCATING // the link is allocating buffers
|
||||
PW_LINK_STATE_PAUSED // the link is paused
|
||||
PW_LINK_STATE_ACTIVE // the link is active
|
||||
)
|
||||
|
||||
const (
|
||||
PW_LINK_CHANGE_MASK_STATE = (1 << iota)
|
||||
PW_LINK_CHANGE_MASK_FORMAT
|
||||
PW_LINK_CHANGE_MASK_PROPS
|
||||
|
||||
PW_LINK_CHANGE_MASK_ALL = 1<<iota - 1
|
||||
)
|
||||
|
||||
const (
|
||||
PW_LINK_EVENT_INFO = iota
|
||||
PW_LINK_EVENT_NUM
|
||||
|
||||
PW_VERSION_LINK_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_LINK_METHOD_ADD_LISTENER = iota
|
||||
PW_LINK_METHOD_NUM
|
||||
|
||||
PW_VERSION_LINK_METHODS = 0
|
||||
)
|
||||
|
||||
/* pipewire/module.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_Module = PW_TYPE_INFO_INTERFACE_BASE + "Module"
|
||||
PW_MODULE_PERM_MASK = PW_PERM_R | PW_PERM_M
|
||||
PW_VERSION_MODULE = 3
|
||||
)
|
||||
|
||||
const (
|
||||
PW_MODULE_CHANGE_MASK_PROPS = 1 << iota
|
||||
|
||||
PW_MODULE_CHANGE_MASK_ALL = 1<<iota - 1
|
||||
)
|
||||
|
||||
const (
|
||||
PW_MODULE_EVENT_INFO = iota
|
||||
PW_MODULE_EVENT_NUM
|
||||
|
||||
PW_VERSION_MODULE_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_MODULE_METHOD_ADD_LISTENER = iota
|
||||
PW_MODULE_METHOD_NUM
|
||||
|
||||
PW_VERSION_MODULE_METHODS = 0
|
||||
)
|
||||
|
||||
/* pipewire/impl-module.h */
|
||||
|
||||
const (
|
||||
PIPEWIRE_SYMBOL_MODULE_INIT = "pipewire__module_init"
|
||||
PIPEWIRE_MODULE_PREFIX = "libpipewire-"
|
||||
|
||||
PW_VERSION_IMPL_MODULE_EVENTS = 0
|
||||
)
|
||||
|
||||
/* pipewire/node.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_Node = PW_TYPE_INFO_INTERFACE_BASE + "Node"
|
||||
PW_NODE_PERM_MASK = PW_PERM_RWXML
|
||||
PW_VERSION_NODE = 3
|
||||
)
|
||||
|
||||
const (
|
||||
PW_NODE_STATE_ERROR = iota - 1 // error state
|
||||
PW_NODE_STATE_CREATING // the node is being created
|
||||
PW_NODE_STATE_SUSPENDED // the node is suspended, the device might be closed
|
||||
PW_NODE_STATE_IDLE // the node is running but there is no active port
|
||||
PW_NODE_STATE_RUNNING // the node is running
|
||||
)
|
||||
|
||||
const (
|
||||
PW_NODE_CHANGE_MASK_INPUT_PORTS = 1 << iota
|
||||
PW_NODE_CHANGE_MASK_OUTPUT_PORTS
|
||||
PW_NODE_CHANGE_MASK_STATE
|
||||
PW_NODE_CHANGE_MASK_PROPS
|
||||
PW_NODE_CHANGE_MASK_PARAMS
|
||||
|
||||
PW_NODE_CHANGE_MASK_ALL = 1<<iota - 1
|
||||
)
|
||||
|
||||
const (
|
||||
PW_NODE_EVENT_INFO = iota
|
||||
PW_NODE_EVENT_PARAM
|
||||
PW_NODE_EVENT_NUM
|
||||
|
||||
PW_VERSION_NODE_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_NODE_METHOD_ADD_LISTENER = iota
|
||||
PW_NODE_METHOD_SUBSCRIBE_PARAMS
|
||||
PW_NODE_METHOD_ENUM_PARAMS
|
||||
PW_NODE_METHOD_SET_PARAM
|
||||
PW_NODE_METHOD_SEND_COMMAND
|
||||
PW_NODE_METHOD_NUM
|
||||
|
||||
PW_VERSION_NODE_METHODS = 0
|
||||
)
|
||||
|
||||
/* pipewire/permission.h */
|
||||
|
||||
const (
|
||||
PW_PERM_R = 0400 // object can be seen and events can be received
|
||||
PW_PERM_W = 0200 // methods can be called that modify the object
|
||||
PW_PERM_X = 0100 // methods can be called on the object. The W flag must be present in order to call methods that modify the object.
|
||||
PW_PERM_M = 0010 // metadata can be set on object, Since 0.3.9
|
||||
PW_PERM_L = 0020 // a link can be made between a node that doesn't have permission to see the other node, Since 0.3.77
|
||||
|
||||
PW_PERM_RW = PW_PERM_R | PW_PERM_W
|
||||
PW_PERM_RWX = PW_PERM_RW | PW_PERM_X
|
||||
PW_PERM_RWXM = PW_PERM_RWX | PW_PERM_M
|
||||
PW_PERM_RWXML = PW_PERM_RWXM | PW_PERM_L
|
||||
|
||||
PW_PERM_ALL = PW_PERM_RWXM
|
||||
PW_PERM_INVALID Word = 0xffffffff
|
||||
)
|
||||
|
||||
/* pipewire/port.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_Port = PW_TYPE_INFO_INTERFACE_BASE + "Port"
|
||||
PW_PORT_PERM_MASK = PW_PERM_R | PW_PERM_X | PW_PERM_M
|
||||
PW_VERSION_PORT = 3
|
||||
)
|
||||
|
||||
const (
|
||||
PW_PORT_CHANGE_MASK_PROPS = 1 << iota
|
||||
PW_PORT_CHANGE_MASK_PARAMS
|
||||
|
||||
PW_PORT_CHANGE_MASK_ALL = 1<<iota - 1
|
||||
)
|
||||
|
||||
const (
|
||||
PW_PORT_EVENT_INFO = iota
|
||||
PW_PORT_EVENT_PARAM
|
||||
PW_PORT_EVENT_NUM
|
||||
|
||||
PW_VERSION_PORT_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_PORT_METHOD_ADD_LISTENER = iota
|
||||
PW_PORT_METHOD_SUBSCRIBE_PARAMS
|
||||
PW_PORT_METHOD_ENUM_PARAMS
|
||||
PW_PORT_METHOD_NUM
|
||||
|
||||
PW_VERSION_PORT_METHODS = 0
|
||||
)
|
||||
|
||||
/* pipewire/extensions/client-node.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_ClientNode = PW_TYPE_INFO_INTERFACE_BASE + "ClientNode"
|
||||
PW_VERSION_CLIENT_NODE = 6
|
||||
|
||||
PW_EXTENSION_MODULE_CLIENT_NODE = PIPEWIRE_MODULE_PREFIX + "module-client-node"
|
||||
)
|
||||
|
||||
const (
|
||||
PW_CLIENT_NODE_EVENT_TRANSPORT = iota
|
||||
PW_CLIENT_NODE_EVENT_SET_PARAM
|
||||
PW_CLIENT_NODE_EVENT_SET_IO
|
||||
PW_CLIENT_NODE_EVENT_EVENT
|
||||
PW_CLIENT_NODE_EVENT_COMMAND
|
||||
PW_CLIENT_NODE_EVENT_ADD_PORT
|
||||
PW_CLIENT_NODE_EVENT_REMOVE_PORT
|
||||
PW_CLIENT_NODE_EVENT_PORT_SET_PARAM
|
||||
PW_CLIENT_NODE_EVENT_PORT_USE_BUFFERS
|
||||
PW_CLIENT_NODE_EVENT_PORT_SET_IO
|
||||
PW_CLIENT_NODE_EVENT_SET_ACTIVATION
|
||||
PW_CLIENT_NODE_EVENT_PORT_SET_MIX_INFO
|
||||
PW_CLIENT_NODE_EVENT_NUM
|
||||
|
||||
PW_VERSION_CLIENT_NODE_EVENTS = 1
|
||||
)
|
||||
|
||||
const (
|
||||
PW_CLIENT_NODE_METHOD_ADD_LISTENER = iota
|
||||
PW_CLIENT_NODE_METHOD_GET_NODE
|
||||
PW_CLIENT_NODE_METHOD_UPDATE
|
||||
PW_CLIENT_NODE_METHOD_PORT_UPDATE
|
||||
PW_CLIENT_NODE_METHOD_SET_ACTIVE
|
||||
PW_CLIENT_NODE_METHOD_EVENT
|
||||
PW_CLIENT_NODE_METHOD_PORT_BUFFERS
|
||||
PW_CLIENT_NODE_METHOD_NUM
|
||||
|
||||
PW_VERSION_CLIENT_NODE_METHODS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_CLIENT_NODE_UPDATE_PARAMS = 1 << iota
|
||||
PW_CLIENT_NODE_UPDATE_INFO
|
||||
)
|
||||
|
||||
const (
|
||||
PW_CLIENT_NODE_PORT_UPDATE_PARAMS = 1 << iota
|
||||
PW_CLIENT_NODE_PORT_UPDATE_INFO
|
||||
)
|
||||
|
||||
/* pipewire/extensions/metadata.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_Metadata = PW_TYPE_INFO_INTERFACE_BASE + "Metadata"
|
||||
PW_METADATA_PERM_MASK = PW_PERM_RWX
|
||||
PW_VERSION_METADATA = 3
|
||||
|
||||
PW_EXTENSION_MODULE_METADATA = PIPEWIRE_MODULE_PREFIX + "module-metadata"
|
||||
)
|
||||
|
||||
const (
|
||||
PW_METADATA_EVENT_PROPERTY = iota
|
||||
PW_METADATA_EVENT_NUM
|
||||
|
||||
PW_VERSION_METADATA_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_METADATA_METHOD_ADD_LISTENER = iota
|
||||
PW_METADATA_METHOD_SET_PROPERTY
|
||||
PW_METADATA_METHOD_CLEAR
|
||||
PW_METADATA_METHOD_NUM
|
||||
|
||||
PW_VERSION_METADATA_METHODS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_KEY_METADATA_NAME = "metadata.name"
|
||||
PW_KEY_METADATA_VALUES = "metadata.values"
|
||||
)
|
||||
|
||||
/* pipewire/extensions/profiler.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INTERFACE_Profiler = PW_TYPE_INFO_INTERFACE_BASE + "Profiler"
|
||||
PW_VERSION_PROFILER = 3
|
||||
PW_PROFILER_PERM_MASK = PW_PERM_R
|
||||
|
||||
PW_EXTENSION_MODULE_PROFILER = PIPEWIRE_MODULE_PREFIX + "module-profiler"
|
||||
)
|
||||
|
||||
const (
|
||||
PW_PROFILER_EVENT_PROFILE = iota
|
||||
PW_PROFILER_EVENT_NUM
|
||||
|
||||
PW_VERSION_PROFILER_EVENTS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_PROFILER_METHOD_ADD_LISTENER = iota
|
||||
PW_PROFILER_METHOD_NUM
|
||||
|
||||
PW_VERSION_PROFILER_METHODS = 0
|
||||
)
|
||||
|
||||
const (
|
||||
PW_KEY_PROFILER_NAME = "profiler.name"
|
||||
)
|
||||
|
||||
/* pipewire/type.h */
|
||||
|
||||
const (
|
||||
PW_TYPE_INFO_BASE = "PipeWire:"
|
||||
|
||||
PW_TYPE_INFO_Object = PW_TYPE_INFO_BASE + "Object"
|
||||
PW_TYPE_INFO_OBJECT_BASE = PW_TYPE_INFO_Object + ":"
|
||||
|
||||
PW_TYPE_INFO_Interface = PW_TYPE_INFO_BASE + "Interface"
|
||||
PW_TYPE_INFO_INTERFACE_BASE = PW_TYPE_INFO_Interface + ":"
|
||||
)
|
||||
|
||||
/* pipewire/keys.h */
|
||||
|
||||
/**
|
||||
* Key Names
|
||||
*
|
||||
* A collection of keys that are used to add extra information on objects.
|
||||
*
|
||||
* Keys that start with "pipewire." are in general set-once and then
|
||||
* read-only. They are usually used for security sensitive information that
|
||||
* needs to be fixed.
|
||||
*
|
||||
* Properties from other objects can also appear. This usually suggests some
|
||||
* sort of parent/child or owner/owned relationship.
|
||||
*
|
||||
*/
|
||||
|
||||
const (
|
||||
PW_KEY_PROTOCOL = "pipewire.protocol" /* protocol used for connection */
|
||||
PW_KEY_ACCESS = "pipewire.access" /* how the client access is controlled */
|
||||
PW_KEY_CLIENT_ACCESS = "pipewire.client.access" /* how the client wants to be access controlled */
|
||||
|
||||
/** Various keys related to the identity of a client process and its security.
|
||||
* Must be obtained from trusted sources by the protocol and placed as
|
||||
* read-only properties. */
|
||||
|
||||
PW_KEY_SEC_PID = "pipewire.sec.pid" /* Client pid, set by protocol */
|
||||
PW_KEY_SEC_UID = "pipewire.sec.uid" /* Client uid, set by protocol*/
|
||||
PW_KEY_SEC_GID = "pipewire.sec.gid" /* client gid, set by protocol*/
|
||||
PW_KEY_SEC_LABEL = "pipewire.sec.label" /* client security label, set by protocol*/
|
||||
|
||||
PW_KEY_SEC_SOCKET = "pipewire.sec.socket" /* client socket name, set by protocol */
|
||||
|
||||
PW_KEY_SEC_ENGINE = "pipewire.sec.engine" /* client secure context engine, set by protocol. This can also be set by a client when making a new security context. */
|
||||
PW_KEY_SEC_APP_ID = "pipewire.sec.app-id" /* client secure application id */
|
||||
PW_KEY_SEC_INSTANCE_ID = "pipewire.sec.instance-id" /* client secure instance id */
|
||||
|
||||
PW_KEY_LIBRARY_NAME_SYSTEM = "library.name.system" /* name of the system library to use */
|
||||
PW_KEY_LIBRARY_NAME_LOOP = "library.name.loop" /* name of the loop library to use */
|
||||
PW_KEY_LIBRARY_NAME_DBUS = "library.name.dbus" /* name of the dbus library to use */
|
||||
|
||||
/** object properties */
|
||||
|
||||
PW_KEY_OBJECT_PATH = "object.path" /* unique path to construct the object */
|
||||
PW_KEY_OBJECT_ID = "object.id" /* a global object id */
|
||||
PW_KEY_OBJECT_SERIAL = "object.serial" /* a 64 bit object serial number. This is a number incremented for each object that is created. The lower 32 bits are guaranteed to never be SPA_ID_INVALID. */
|
||||
PW_KEY_OBJECT_LINGER = "object.linger" /* the object lives on even after the client that created it has been destroyed */
|
||||
PW_KEY_OBJECT_REGISTER = "object.register" /* If the object should be registered. */
|
||||
PW_KEY_OBJECT_EXPORT = "object.export" /* If the object should be exported, since 0.3.72 */
|
||||
|
||||
/* config */
|
||||
|
||||
PW_KEY_CONFIG_PREFIX = "config.prefix" /* a config prefix directory */
|
||||
PW_KEY_CONFIG_NAME = "config.name" /* a config file name */
|
||||
PW_KEY_CONFIG_OVERRIDE_PREFIX = "config.override.prefix" /* a config override prefix directory */
|
||||
PW_KEY_CONFIG_OVERRIDE_NAME = "config.override.name" /* a config override file name */
|
||||
|
||||
/* loop */
|
||||
|
||||
PW_KEY_LOOP_NAME = "loop.name" /* the name of a loop */
|
||||
PW_KEY_LOOP_CLASS = "loop.class" /* the classes this loop handles, array of strings */
|
||||
PW_KEY_LOOP_RT_PRIO = "loop.rt-prio" /* realtime priority of the loop */
|
||||
PW_KEY_LOOP_CANCEL = "loop.cancel" /* if the loop can be canceled */
|
||||
|
||||
/* context */
|
||||
|
||||
PW_KEY_CONTEXT_PROFILE_MODULES = "context.profile.modules" /* a context profile for modules, deprecated */
|
||||
PW_KEY_USER_NAME = "context.user-name" /* The user name that runs pipewire */
|
||||
PW_KEY_HOST_NAME = "context.host-name" /* The host name of the machine */
|
||||
|
||||
/* core */
|
||||
|
||||
PW_KEY_CORE_NAME = "core.name" /* The name of the core. Default is `pipewire-<username>-<pid>`, overwritten by env(PIPEWIRE_CORE) */
|
||||
PW_KEY_CORE_VERSION = "core.version" /* The version of the core. */
|
||||
PW_KEY_CORE_DAEMON = "core.daemon" /* If the core is listening for connections. */
|
||||
|
||||
PW_KEY_CORE_ID = "core.id" /* the core id */
|
||||
PW_KEY_CORE_MONITORS = "core.monitors" /* the apis monitored by core. */
|
||||
|
||||
/* cpu */
|
||||
|
||||
PW_KEY_CPU_MAX_ALIGN = "cpu.max-align" /* maximum alignment needed to support all CPU optimizations */
|
||||
PW_KEY_CPU_CORES = "cpu.cores" /* number of cores */
|
||||
|
||||
/* priorities */
|
||||
|
||||
PW_KEY_PRIORITY_SESSION = "priority.session" /* priority in session manager */
|
||||
PW_KEY_PRIORITY_DRIVER = "priority.driver" /* priority to be a driver */
|
||||
|
||||
/* remote keys */
|
||||
|
||||
PW_KEY_REMOTE_NAME = "remote.name" /* The name of the remote to connect to, default pipewire-0, overwritten by env(PIPEWIRE_REMOTE). May also be a SPA-JSON array of sockets, to be tried in order. The "internal" remote name and "generic" intention connects to the local PipeWire instance. */
|
||||
PW_KEY_REMOTE_INTENTION = "remote.intention" /* The intention of the remote connection, "generic", "screencast", "manager" */
|
||||
|
||||
/** application keys */
|
||||
|
||||
PW_KEY_APP_NAME = "application.name" /* application name. Ex: "Totem Music Player" */
|
||||
PW_KEY_APP_ID = "application.id" /* a textual id for identifying an application logically. Ex: "org.gnome.Totem" */
|
||||
PW_KEY_APP_VERSION = "application.version" /* application version. Ex: "1.2.0" */
|
||||
PW_KEY_APP_ICON = "application.icon" /* aa base64 blob with PNG image data */
|
||||
PW_KEY_APP_ICON_NAME = "application.icon-name" /* an XDG icon name for the application. Ex: "totem" */
|
||||
PW_KEY_APP_LANGUAGE = "application.language" /* application language if applicable, in standard POSIX format. Ex: "en_GB" */
|
||||
|
||||
PW_KEY_APP_PROCESS_ID = "application.process.id" /* process id (pid)*/
|
||||
PW_KEY_APP_PROCESS_BINARY = "application.process.binary" /* binary name */
|
||||
PW_KEY_APP_PROCESS_USER = "application.process.user" /* user name */
|
||||
PW_KEY_APP_PROCESS_HOST = "application.process.host" /* host name */
|
||||
PW_KEY_APP_PROCESS_MACHINE_ID = "application.process.machine-id" /* the D-Bus host id the application runs on */
|
||||
PW_KEY_APP_PROCESS_SESSION_ID = "application.process.session-id" /* login session of the application, on Unix the value of $XDG_SESSION_ID. */
|
||||
|
||||
/** window system */
|
||||
|
||||
PW_KEY_WINDOW_X11_DISPLAY = "window.x11.display" /* the X11 display string. Ex. ":0.0" */
|
||||
|
||||
/** Client properties */
|
||||
|
||||
PW_KEY_CLIENT_ID = "client.id" /* a client id */
|
||||
PW_KEY_CLIENT_NAME = "client.name" /* the client name */
|
||||
PW_KEY_CLIENT_API = "client.api" /* the client api used to access PipeWire */
|
||||
|
||||
/** Node keys */
|
||||
|
||||
PW_KEY_NODE_ID = "node.id" /* node id */
|
||||
PW_KEY_NODE_NAME = "node.name" /* node name */
|
||||
PW_KEY_NODE_NICK = "node.nick" /* short node name */
|
||||
PW_KEY_NODE_DESCRIPTION = "node.description" /* localized human readable node one-line description. Ex. "Foobar USB Headset" */
|
||||
PW_KEY_NODE_PLUGGED = "node.plugged" /* when the node was created. As a uint64 in nanoseconds. */
|
||||
|
||||
PW_KEY_NODE_SESSION = "node.session" /* the session id this node is part of */
|
||||
PW_KEY_NODE_GROUP = "node.group" /* the group id this node is part of. Nodes in the same group are always scheduled with the same driver. Can be an array of group names. */
|
||||
PW_KEY_NODE_SYNC_GROUP = "node.sync-group" /* the sync group this node is part of. Nodes in the same sync group are always scheduled together with the same driver when the sync is active. Can be an array of sync names. */
|
||||
PW_KEY_NODE_SYNC = "node.sync" /* if the sync-group is active or not */
|
||||
PW_KEY_NODE_TRANSPORT = "node.transport" /* if the transport is active or not */
|
||||
PW_KEY_NODE_EXCLUSIVE = "node.exclusive" /* node wants exclusive access to resources */
|
||||
PW_KEY_NODE_AUTOCONNECT = "node.autoconnect" /* node wants to be automatically connected to a compatible node */
|
||||
PW_KEY_NODE_LATENCY = "node.latency" /* the requested latency of the node as a fraction. Ex: 128/48000 */
|
||||
PW_KEY_NODE_MAX_LATENCY = "node.max-latency" /* the maximum supported latency of the node as a fraction. Ex: 1024/48000 */
|
||||
PW_KEY_NODE_LOCK_QUANTUM = "node.lock-quantum" /* don't change quantum when this node is active */
|
||||
PW_KEY_NODE_FORCE_QUANTUM = "node.force-quantum" /* force a quantum while the node is active */
|
||||
PW_KEY_NODE_RATE = "node.rate" /* the requested rate of the graph as a fraction. Ex: 1/48000 */
|
||||
PW_KEY_NODE_LOCK_RATE = "node.lock-rate" /* don't change rate when this node is active */
|
||||
PW_KEY_NODE_FORCE_RATE = "node.force-rate" /* force a rate while the node is active. A value of 0 takes the denominator of node.rate */
|
||||
|
||||
PW_KEY_NODE_DONT_RECONNECT = "node.dont-reconnect" /* don't reconnect this node. The node is initially linked to target.object or the default node. If the target is removed, the node is destroyed */
|
||||
PW_KEY_NODE_ALWAYS_PROCESS = "node.always-process" /* process even when unlinked */
|
||||
PW_KEY_NODE_WANT_DRIVER = "node.want-driver" /* the node wants to be grouped with a driver node in order to schedule the graph. */
|
||||
PW_KEY_NODE_PAUSE_ON_IDLE = "node.pause-on-idle" /* pause the node when idle */
|
||||
PW_KEY_NODE_SUSPEND_ON_IDLE = "node.suspend-on-idle" /* suspend the node when idle */
|
||||
PW_KEY_NODE_CACHE_PARAMS = "node.cache-params" /* cache the node params */
|
||||
PW_KEY_NODE_TRANSPORT_SYNC = "node.transport.sync" /* the node handles transport sync */
|
||||
PW_KEY_NODE_DRIVER = "node.driver" /* node can drive the graph. When the node is selected as the driver, it needs to start the graph periodically. */
|
||||
PW_KEY_NODE_SUPPORTS_LAZY = "node.supports-lazy" /* the node can be a lazy driver. It will listen to RequestProcess commands and take them into account when deciding to start the graph. A value of 0 disables support, a value of > 0 enables with increasing preference. */
|
||||
PW_KEY_NODE_SUPPORTS_REQUEST = "node.supports-request" /* The node supports emiting RequestProcess events when it wants the graph to be scheduled. A value of 0 disables support, a value of > 0 enables with increasing preference. */
|
||||
PW_KEY_NODE_DRIVER_ID = "node.driver-id" /* the node id of the node assigned as driver for this node */
|
||||
PW_KEY_NODE_ASYNC = "node.async" /* the node wants async scheduling */
|
||||
PW_KEY_NODE_LOOP_NAME = "node.loop.name" /* the loop name fnmatch pattern to run in */
|
||||
PW_KEY_NODE_LOOP_CLASS = "node.loop.class" /* the loop class fnmatch pattern to run in */
|
||||
PW_KEY_NODE_STREAM = "node.stream" /* node is a stream, the server side should add a converter */
|
||||
PW_KEY_NODE_VIRTUAL = "node.virtual" /* the node is some sort of virtual object */
|
||||
PW_KEY_NODE_PASSIVE = "node.passive" /* indicate that a node wants passive links on output/input/all ports when the value is "out"/"in"/"true" respectively */
|
||||
PW_KEY_NODE_LINK_GROUP = "node.link-group" /* the node is internally linked to nodes with the same link-group. Can be an array of group names. */
|
||||
PW_KEY_NODE_NETWORK = "node.network" /* the node is on a network */
|
||||
PW_KEY_NODE_TRIGGER = "node.trigger" /* the node is not scheduled automatically based on the dependencies in the graph but it will be triggered explicitly. */
|
||||
PW_KEY_NODE_CHANNELNAMES = "node.channel-names" /* names of node's channels (unrelated to positions) */
|
||||
PW_KEY_NODE_DEVICE_PORT_NAME_PREFIX = "node.device-port-name-prefix" /* override port name prefix for device ports, like capture and playback or disable the prefix completely if an empty string is provided */
|
||||
PW_KEY_NODE_PHYSICAL = "node.physical" /* ports from the node are physical */
|
||||
PW_KEY_NODE_TERMINAL = "node.terminal" /* ports from the node are terminal */
|
||||
|
||||
PW_KEY_NODE_RELIABLE = "node.reliable" /* node uses reliable transport 1.6.0 */
|
||||
|
||||
/** Port keys */
|
||||
|
||||
PW_KEY_PORT_ID = "port.id" /* port id */
|
||||
PW_KEY_PORT_NAME = "port.name" /* port name */
|
||||
PW_KEY_PORT_DIRECTION = "port.direction" /* the port direction, one of "in" or "out" or "control" and "notify" for control ports */
|
||||
PW_KEY_PORT_ALIAS = "port.alias" /* port alias */
|
||||
PW_KEY_PORT_PHYSICAL = "port.physical" /* if this is a physical port */
|
||||
PW_KEY_PORT_TERMINAL = "port.terminal" /* if this port consumes the data */
|
||||
PW_KEY_PORT_CONTROL = "port.control" /* if this port is a control port */
|
||||
PW_KEY_PORT_MONITOR = "port.monitor" /* if this port is a monitor port */
|
||||
PW_KEY_PORT_CACHE_PARAMS = "port.cache-params" /* cache the node port params */
|
||||
PW_KEY_PORT_EXTRA = "port.extra" /* api specific extra port info, API name should be prefixed. "jack:flags:56" */
|
||||
PW_KEY_PORT_PASSIVE = "port.passive" /* the ports wants passive links, since 0.3.67 */
|
||||
PW_KEY_PORT_IGNORE_LATENCY = "port.ignore-latency" /* latency ignored by peers, since 0.3.71 */
|
||||
PW_KEY_PORT_GROUP = "port.group" /* the port group of the port 1.2.0 */
|
||||
PW_KEY_PORT_EXCLUSIVE = "port.exclusive" /* link port only once 1.6.0 */
|
||||
PW_KEY_PORT_RELIABLE = "port.reliable" /* port uses reliable transport 1.6.0 */
|
||||
|
||||
/** link properties */
|
||||
|
||||
PW_KEY_LINK_ID = "link.id" /* a link id */
|
||||
PW_KEY_LINK_INPUT_NODE = "link.input.node" /* input node id of a link */
|
||||
PW_KEY_LINK_INPUT_PORT = "link.input.port" /* input port id of a link */
|
||||
PW_KEY_LINK_OUTPUT_NODE = "link.output.node" /* output node id of a link */
|
||||
PW_KEY_LINK_OUTPUT_PORT = "link.output.port" /* output port id of a link */
|
||||
PW_KEY_LINK_PASSIVE = "link.passive" /* indicate that a link is passive and does not cause the graph to be runnable. */
|
||||
PW_KEY_LINK_FEEDBACK = "link.feedback" /* indicate that a link is a feedback link and the target will receive data in the next cycle */
|
||||
PW_KEY_LINK_ASYNC = "link.async" /* the link is using async io */
|
||||
|
||||
/** device properties */
|
||||
|
||||
PW_KEY_DEVICE_ID = "device.id" /* device id */
|
||||
PW_KEY_DEVICE_NAME = "device.name" /* device name */
|
||||
PW_KEY_DEVICE_PLUGGED = "device.plugged" /* when the device was created. As a uint64 in nanoseconds. */
|
||||
PW_KEY_DEVICE_NICK = "device.nick" /* a short device nickname */
|
||||
PW_KEY_DEVICE_STRING = "device.string" /* device string in the underlying layer's format. Ex. "surround51:0" */
|
||||
PW_KEY_DEVICE_API = "device.api" /* API this device is accessed with. Ex. "alsa", "v4l2" */
|
||||
PW_KEY_DEVICE_DESCRIPTION = "device.description" /* localized human readable device one-line description. Ex. "Foobar USB Headset" */
|
||||
PW_KEY_DEVICE_BUS_PATH = "device.bus-path" /* bus path to the device in the OS' format. Ex. "pci-0000:00:14.0-usb-0:3.2:1.0" */
|
||||
PW_KEY_DEVICE_SERIAL = "device.serial" /* Serial number if applicable */
|
||||
PW_KEY_DEVICE_VENDOR_ID = "device.vendor.id" /* vendor ID if applicable */
|
||||
PW_KEY_DEVICE_VENDOR_NAME = "device.vendor.name" /* vendor name if applicable */
|
||||
PW_KEY_DEVICE_PRODUCT_ID = "device.product.id" /* product ID if applicable */
|
||||
PW_KEY_DEVICE_PRODUCT_NAME = "device.product.name" /* product name if applicable */
|
||||
PW_KEY_DEVICE_CLASS = "device.class" /* device class */
|
||||
PW_KEY_DEVICE_FORM_FACTOR = "device.form-factor" /* form factor if applicable. One of "internal", "speaker", "handset", "tv", "webcam", "microphone", "headset", "headphone", "hands-free", "car", "hifi", "computer", "portable" */
|
||||
PW_KEY_DEVICE_BUS = "device.bus" /* bus of the device if applicable. One of "isa", "pci", "usb", "firewire", "bluetooth" */
|
||||
PW_KEY_DEVICE_SUBSYSTEM = "device.subsystem" /* device subsystem */
|
||||
PW_KEY_DEVICE_SYSFS_PATH = "device.sysfs.path" /* device sysfs path */
|
||||
PW_KEY_DEVICE_ICON = "device.icon" /* icon for the device. A base64 blob containing PNG image data */
|
||||
PW_KEY_DEVICE_ICON_NAME = "device.icon-name" /* an XDG icon name for the device. Ex. "sound-card-speakers-usb" */
|
||||
PW_KEY_DEVICE_INTENDED_ROLES = "device.intended-roles" /* intended use. A space separated list of roles (see PW_KEY_MEDIA_ROLE) this device is particularly well suited for, due to latency, quality or form factor. */
|
||||
PW_KEY_DEVICE_CACHE_PARAMS = "device.cache-params" /* cache the device spa params */
|
||||
|
||||
/** module properties */
|
||||
|
||||
PW_KEY_MODULE_ID = "module.id" /* the module id */
|
||||
PW_KEY_MODULE_NAME = "module.name" /* the name of the module */
|
||||
PW_KEY_MODULE_AUTHOR = "module.author" /* the author's name */
|
||||
PW_KEY_MODULE_DESCRIPTION = "module.description" /* a human readable one-line description of the module's purpose.*/
|
||||
PW_KEY_MODULE_USAGE = "module.usage" /* a human readable usage description of the module's arguments. */
|
||||
PW_KEY_MODULE_VERSION = "module.version" /* a version string for the module. */
|
||||
PW_KEY_MODULE_DEPRECATED = "module.deprecated" /* the module is deprecated with this message */
|
||||
|
||||
/** Factory properties */
|
||||
|
||||
PW_KEY_FACTORY_ID = "factory.id" /* the factory id */
|
||||
PW_KEY_FACTORY_NAME = "factory.name" /* the name of the factory */
|
||||
PW_KEY_FACTORY_USAGE = "factory.usage" /* the usage of the factory */
|
||||
PW_KEY_FACTORY_TYPE_NAME = "factory.type.name" /* the name of the type created by a factory */
|
||||
PW_KEY_FACTORY_TYPE_VERSION = "factory.type.version" /* the version of the type created by a factory */
|
||||
|
||||
/** Stream properties */
|
||||
|
||||
PW_KEY_STREAM_IS_LIVE = "stream.is-live" /* Indicates that the stream is live. */
|
||||
PW_KEY_STREAM_LATENCY_MIN = "stream.latency.min" /* The minimum latency of the stream. */
|
||||
PW_KEY_STREAM_LATENCY_MAX = "stream.latency.max" /* The maximum latency of the stream */
|
||||
PW_KEY_STREAM_MONITOR = "stream.monitor" /* Indicates that the stream is monitoring and might select a less accurate but faster conversion algorithm. Monitor streams are also ignored when calculating the latency of their peer ports (since 0.3.71).
|
||||
*/
|
||||
PW_KEY_STREAM_DONT_REMIX = "stream.dont-remix" /* don't remix channels */
|
||||
PW_KEY_STREAM_CAPTURE_SINK = "stream.capture.sink" /* Try to capture the sink output instead of source output */
|
||||
|
||||
/** Media */
|
||||
|
||||
PW_KEY_MEDIA_TYPE = "media.type" /* Media type, one of Audio, Video, Midi */
|
||||
PW_KEY_MEDIA_CATEGORY = "media.category" /* Media Category: Playback, Capture, Duplex, Monitor, Manager */
|
||||
PW_KEY_MEDIA_ROLE = "media.role" /* Role: Movie, Music, Camera, Screen, Communication, Game, Notification, DSP, Production, Accessibility, Test */
|
||||
PW_KEY_MEDIA_CLASS = "media.class" /* class Ex: "Video/Source" */
|
||||
PW_KEY_MEDIA_NAME = "media.name" /* media name. Ex: "Pink Floyd: Time" */
|
||||
PW_KEY_MEDIA_TITLE = "media.title" /* title. Ex: "Time" */
|
||||
PW_KEY_MEDIA_ARTIST = "media.artist" /* artist. Ex: "Pink Floyd" */
|
||||
PW_KEY_MEDIA_ALBUM = "media.album" /* album. Ex: "Dark Side of the Moon" */
|
||||
PW_KEY_MEDIA_COPYRIGHT = "media.copyright" /* copyright string */
|
||||
PW_KEY_MEDIA_SOFTWARE = "media.software" /* generator software */
|
||||
PW_KEY_MEDIA_LANGUAGE = "media.language" /* language in POSIX format. Ex: en_GB */
|
||||
PW_KEY_MEDIA_FILENAME = "media.filename" /* filename */
|
||||
PW_KEY_MEDIA_ICON = "media.icon" /* icon for the media, a base64 blob with PNG image data */
|
||||
PW_KEY_MEDIA_ICON_NAME = "media.icon-name" /* an XDG icon name for the media. Ex: "audio-x-mp3" */
|
||||
PW_KEY_MEDIA_COMMENT = "media.comment" /* extra comment */
|
||||
PW_KEY_MEDIA_DATE = "media.date" /* date of the media */
|
||||
PW_KEY_MEDIA_FORMAT = "media.format" /* format of the media */
|
||||
|
||||
/** format related properties */
|
||||
|
||||
PW_KEY_FORMAT_DSP = "format.dsp" /* a dsp format. Ex: "32 bit float mono audio" */
|
||||
|
||||
/** audio related properties */
|
||||
|
||||
PW_KEY_AUDIO_CHANNEL = "audio.channel" /* an audio channel. Ex: "FL" */
|
||||
PW_KEY_AUDIO_RATE = "audio.rate" /* an audio samplerate */
|
||||
PW_KEY_AUDIO_CHANNELS = "audio.channels" /* number of audio channels */
|
||||
PW_KEY_AUDIO_FORMAT = "audio.format" /* an audio format. Ex: "S16LE" */
|
||||
PW_KEY_AUDIO_ALLOWED_RATES = "audio.allowed-rates" /* a list of allowed samplerates ex. "[ 44100 48000 ]" */
|
||||
|
||||
/** video related properties */
|
||||
|
||||
PW_KEY_VIDEO_RATE = "video.framerate" /* a video framerate */
|
||||
PW_KEY_VIDEO_FORMAT = "video.format" /* a video format */
|
||||
PW_KEY_VIDEO_SIZE = "video.size" /* a video size as "<width>x<height" */
|
||||
|
||||
PW_KEY_TARGET_OBJECT = "target.object" /* a target object to link to. This can be and object name or object.serial */
|
||||
)
|
||||
81
internal/pipewire/spa_test.go
Normal file
81
internal/pipewire/spa_test.go
Normal file
@@ -0,0 +1,81 @@
|
||||
package pipewire_test
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/binary"
|
||||
"testing"
|
||||
|
||||
"hakurei.app/internal/pipewire"
|
||||
)
|
||||
|
||||
func TestSPAKind(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
v pipewire.SPAKind
|
||||
want string
|
||||
}{
|
||||
{"invalid", 0xdeadbeef, "invalid type field 0xdeadbeef"},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
if got := tc.v.String(); got != tc.want {
|
||||
t.Errorf("String: %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// splitMessages splits concatenated messages into groups of
|
||||
// header, payload, footer of each individual message.
|
||||
// splitMessages panics on any decoding error.
|
||||
func splitMessages(iovec string) (messages [][3][]byte) {
|
||||
data := []byte(iovec)
|
||||
messages = make([][3][]byte, 0, 1<<7)
|
||||
|
||||
var header pipewire.Header
|
||||
for len(data) != 0 {
|
||||
if err := header.UnmarshalBinary(data[:pipewire.SizeHeader]); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
size := pipewire.SizePrefix + binary.NativeEndian.Uint32(data[pipewire.SizeHeader:])
|
||||
messages = append(messages, [3][]byte{
|
||||
data[:pipewire.SizeHeader],
|
||||
data[pipewire.SizeHeader : pipewire.SizeHeader+size],
|
||||
data[pipewire.SizeHeader+size : pipewire.SizeHeader+header.Size],
|
||||
})
|
||||
data = data[pipewire.SizeHeader+header.Size:]
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
//go:embed testdata/pw-container-00-sendmsg
|
||||
samplePWContainer00 string
|
||||
//go:embed testdata/pw-container-01-recvmsg
|
||||
samplePWContainer01 string
|
||||
//go:embed testdata/pw-container-03-sendmsg
|
||||
samplePWContainer03 string
|
||||
//go:embed testdata/pw-container-04-recvmsg
|
||||
samplePWContainer04 string
|
||||
//go:embed testdata/pw-container-06-sendmsg
|
||||
samplePWContainer06 string
|
||||
//go:embed testdata/pw-container-07-recvmsg
|
||||
samplePWContainer07 string
|
||||
|
||||
// samplePWContainer is a collection of messages from the pw-container sample.
|
||||
samplePWContainer = [...][][3][]byte{
|
||||
splitMessages(samplePWContainer00),
|
||||
splitMessages(samplePWContainer01),
|
||||
nil,
|
||||
splitMessages(samplePWContainer03),
|
||||
splitMessages(samplePWContainer04),
|
||||
nil,
|
||||
splitMessages(samplePWContainer06),
|
||||
splitMessages(samplePWContainer07),
|
||||
nil,
|
||||
}
|
||||
)
|
||||
BIN
internal/pipewire/testdata/pw-container-00-sendmsg
vendored
Normal file
BIN
internal/pipewire/testdata/pw-container-00-sendmsg
vendored
Normal file
Binary file not shown.
BIN
internal/pipewire/testdata/pw-container-01-recvmsg
vendored
Normal file
BIN
internal/pipewire/testdata/pw-container-01-recvmsg
vendored
Normal file
Binary file not shown.
BIN
internal/pipewire/testdata/pw-container-03-sendmsg
vendored
Normal file
BIN
internal/pipewire/testdata/pw-container-03-sendmsg
vendored
Normal file
Binary file not shown.
BIN
internal/pipewire/testdata/pw-container-04-recvmsg
vendored
Normal file
BIN
internal/pipewire/testdata/pw-container-04-recvmsg
vendored
Normal file
Binary file not shown.
BIN
internal/pipewire/testdata/pw-container-06-sendmsg
vendored
Normal file
BIN
internal/pipewire/testdata/pw-container-06-sendmsg
vendored
Normal file
Binary file not shown.
BIN
internal/pipewire/testdata/pw-container-07-recvmsg
vendored
Normal file
BIN
internal/pipewire/testdata/pw-container-07-recvmsg
vendored
Normal file
Binary file not shown.
211
internal/pkg/dir.go
Normal file
211
internal/pkg/dir.go
Normal file
@@ -0,0 +1,211 @@
|
||||
package pkg
|
||||
|
||||
import (
|
||||
"crypto/sha512"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
|
||||
"hakurei.app/container/check"
|
||||
)
|
||||
|
||||
// FlatEntry is a directory entry to be encoded for [Flatten].
|
||||
type FlatEntry struct {
|
||||
Mode fs.FileMode // file mode bits
|
||||
Path string // pathname of the file
|
||||
Data []byte // file content or symlink destination
|
||||
}
|
||||
|
||||
/*
|
||||
| mode uint32 | path_sz uint32 |
|
||||
| data_sz uint64 |
|
||||
| path string |
|
||||
| data []byte |
|
||||
*/
|
||||
|
||||
// wordSize is the boundary which binary segments are always aligned to.
|
||||
const wordSize = 8
|
||||
|
||||
// alignSize returns the padded size for aligning sz.
|
||||
func alignSize(sz int) int {
|
||||
return sz + (wordSize-(sz)%wordSize)%wordSize
|
||||
}
|
||||
|
||||
// Encode encodes the entry for transmission or hashing.
|
||||
func (ent *FlatEntry) Encode(w io.Writer) (n int, err error) {
|
||||
pPathSize := alignSize(len(ent.Path))
|
||||
if pPathSize > math.MaxUint32 {
|
||||
return 0, syscall.E2BIG
|
||||
}
|
||||
pDataSize := alignSize(len(ent.Data))
|
||||
|
||||
payload := make([]byte, wordSize*2+pPathSize+pDataSize)
|
||||
binary.LittleEndian.PutUint32(payload, uint32(ent.Mode))
|
||||
binary.LittleEndian.PutUint32(payload[wordSize/2:], uint32(len(ent.Path)))
|
||||
binary.LittleEndian.PutUint64(payload[wordSize:], uint64(len(ent.Data)))
|
||||
copy(payload[wordSize*2:], ent.Path)
|
||||
copy(payload[wordSize*2+pPathSize:], ent.Data)
|
||||
return w.Write(payload)
|
||||
}
|
||||
|
||||
// ErrInsecurePath is returned by [FlatEntry.Decode] if validation is requested
|
||||
// and a nonlocal path is encountered in the stream.
|
||||
var ErrInsecurePath = errors.New("insecure file path")
|
||||
|
||||
// Decode decodes the entry from its representation produced by Encode.
|
||||
func (ent *FlatEntry) Decode(r io.Reader, validate bool) (n int, err error) {
|
||||
var nr int
|
||||
|
||||
header := make([]byte, wordSize*2)
|
||||
nr, err = r.Read(header)
|
||||
n += nr
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) && n != 0 {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
ent.Mode = fs.FileMode(binary.LittleEndian.Uint32(header))
|
||||
pathSize := int(binary.LittleEndian.Uint32(header[wordSize/2:]))
|
||||
pPathSize := alignSize(pathSize)
|
||||
dataSize := int(binary.LittleEndian.Uint64(header[wordSize:]))
|
||||
pDataSize := alignSize(dataSize)
|
||||
|
||||
buf := make([]byte, pPathSize+pDataSize)
|
||||
nr, err = r.Read(buf)
|
||||
n += nr
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
if nr != len(buf) {
|
||||
err = io.ErrUnexpectedEOF
|
||||
return
|
||||
}
|
||||
} else {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ent.Path = string(buf[:pathSize])
|
||||
if ent.Mode.IsDir() {
|
||||
ent.Data = nil
|
||||
} else {
|
||||
ent.Data = buf[pPathSize : pPathSize+dataSize]
|
||||
}
|
||||
|
||||
if validate && !filepath.IsLocal(ent.Path) {
|
||||
err = ErrInsecurePath
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// DirScanner provides an efficient interface for reading a stream of encoded
|
||||
// [FlatEntry]. Successive calls to the Scan method will step through the
|
||||
// entries in the stream.
|
||||
type DirScanner struct {
|
||||
// Underlying reader to scan [FlatEntry] representations from.
|
||||
r io.Reader
|
||||
|
||||
// First non-EOF I/O error, returned by the Err method.
|
||||
err error
|
||||
|
||||
// Entry to store results in. Its address is returned by the Entry method
|
||||
// and is updated on every call to Scan.
|
||||
ent FlatEntry
|
||||
|
||||
// Validate pathnames during decoding.
|
||||
validate bool
|
||||
}
|
||||
|
||||
// NewDirScanner returns the address of a new instance of [DirScanner] reading
|
||||
// from r. The caller must no longer read from r after this function returns.
|
||||
func NewDirScanner(r io.Reader, validate bool) *DirScanner {
|
||||
return &DirScanner{r: r, validate: validate}
|
||||
}
|
||||
|
||||
// Err returns the first non-EOF I/O error.
|
||||
func (s *DirScanner) Err() error {
|
||||
if errors.Is(s.err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
return s.err
|
||||
}
|
||||
|
||||
// Entry returns the address to the [FlatEntry] value storing the last result.
|
||||
func (s *DirScanner) Entry() *FlatEntry { return &s.ent }
|
||||
|
||||
// Scan advances to the next [FlatEntry].
|
||||
func (s *DirScanner) Scan() bool {
|
||||
if s.err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
var n int
|
||||
n, s.err = s.ent.Decode(s.r, s.validate)
|
||||
if errors.Is(s.err, io.EOF) {
|
||||
return n != 0
|
||||
}
|
||||
return s.err == nil
|
||||
}
|
||||
|
||||
// Flatten writes a deterministic representation of the contents of fsys to w.
|
||||
// The resulting data can be hashed to produce a deterministic checksum for the
|
||||
// directory.
|
||||
func Flatten(fsys fs.FS, root string, w io.Writer) (n int, err error) {
|
||||
var nr int
|
||||
err = fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var fi fs.FileInfo
|
||||
fi, err = d.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ent := FlatEntry{
|
||||
Path: path,
|
||||
Mode: fi.Mode(),
|
||||
}
|
||||
if ent.Mode.IsRegular() {
|
||||
if ent.Data, err = fs.ReadFile(fsys, path); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if ent.Mode&fs.ModeSymlink != 0 {
|
||||
var newpath string
|
||||
if newpath, err = fs.ReadLink(fsys, path); err != nil {
|
||||
return err
|
||||
}
|
||||
ent.Data = []byte(newpath)
|
||||
} else if !ent.Mode.IsDir() {
|
||||
return InvalidFileModeError(ent.Mode)
|
||||
}
|
||||
|
||||
nr, err = ent.Encode(w)
|
||||
n += nr
|
||||
return err
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// HashFS returns a checksum produced by hashing the result of [Flatten].
|
||||
func HashFS(buf *Checksum, fsys fs.FS, root string) error {
|
||||
h := sha512.New384()
|
||||
if _, err := Flatten(fsys, root, h); err != nil {
|
||||
return err
|
||||
}
|
||||
h.Sum(buf[:0])
|
||||
return nil
|
||||
}
|
||||
|
||||
// HashDir returns a checksum produced by hashing the result of [Flatten].
|
||||
func HashDir(buf *Checksum, pathname *check.Absolute) error {
|
||||
return HashFS(buf, os.DirFS(pathname.String()), ".")
|
||||
}
|
||||
570
internal/pkg/dir_test.go
Normal file
570
internal/pkg/dir_test.go
Normal file
@@ -0,0 +1,570 @@
|
||||
package pkg_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/fs"
|
||||
"reflect"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
"hakurei.app/internal/pkg"
|
||||
)
|
||||
|
||||
func TestFlatten(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
fsys fs.FS
|
||||
entries []pkg.FlatEntry
|
||||
sum pkg.Checksum
|
||||
err error
|
||||
}{
|
||||
{"bad type", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
"invalid": {Mode: fs.ModeCharDevice | 0400},
|
||||
}, nil, pkg.Checksum{}, pkg.InvalidFileModeError(
|
||||
fs.ModeCharDevice | 0400,
|
||||
)},
|
||||
|
||||
{"empty", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("E4vEZKhCcL2gPZ2Tt59FS3lDng-d_2SKa2i5G_RbDfwGn6EemptFaGLPUDiOa94C"), nil},
|
||||
|
||||
{"sample cache file", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX": {Mode: 0400, Data: []byte{0}},
|
||||
"checksum/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq": {Mode: 0400, Data: []byte{0, 0, 0, 0, 0xad, 0xb, 0, 4, 0xfe, 0xfe, 0, 0, 0xfe, 0xca, 0, 0}},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX")},
|
||||
"identifier/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq")},
|
||||
"identifier/cafebabecafebabecafebabecafebabecafebabecafebabecafebabecafebabe": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq")},
|
||||
"identifier/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq")},
|
||||
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: 0400, Path: "checksum/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq", Data: []byte{0, 0, 0, 0, 0xad, 0xb, 0, 4, 0xfe, 0xfe, 0, 0, 0xfe, 0xca, 0, 0}},
|
||||
{Mode: 0400, Path: "checksum/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX", Data: []byte{0}},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq", Data: []byte("../checksum/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/cafebabecafebabecafebabecafebabecafebabecafebabecafebabecafebabe", Data: []byte("../checksum/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef", Data: []byte("../checksum/0bSFPu5Tnd-2Jj0Mv6co23PW2t3BmHc7eLFj9TgY3eIBg8zislo7xZYNBqovVLcq")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX", Data: []byte("../checksum/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("St9rlE-mGZ5gXwiv_hzQ_B8bZP-UUvSNmf4nHUZzCMOumb6hKnheZSe0dmnuc4Q2"), nil},
|
||||
|
||||
{"sample http get cure", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/fLYGIMHgN1louE-JzITJZJo2SDniPu-IHBXubtvQWFO-hXnDVKNuscV7-zlyr5fU": {Mode: 0400, Data: []byte("\x7f\xe1\x69\xa2\xdd\x63\x96\x26\x83\x79\x61\x8b\xf0\x3f\xd5\x16\x9a\x39\x3a\xdb\xcf\xb1\xbc\x8d\x33\xff\x75\xee\x62\x56\xa9\xf0\x27\xac\x13\x94\x69")},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/NqVORkT6L9HX6Za7kT2zcibY10qFqBaxEjPiYFrBQX-ZFr3yxCzJxbKOP0zVjeWb": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/fLYGIMHgN1louE-JzITJZJo2SDniPu-IHBXubtvQWFO-hXnDVKNuscV7-zlyr5fU")},
|
||||
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: 0400, Path: "checksum/fLYGIMHgN1louE-JzITJZJo2SDniPu-IHBXubtvQWFO-hXnDVKNuscV7-zlyr5fU", Data: []byte("\x7f\xe1\x69\xa2\xdd\x63\x96\x26\x83\x79\x61\x8b\xf0\x3f\xd5\x16\x9a\x39\x3a\xdb\xcf\xb1\xbc\x8d\x33\xff\x75\xee\x62\x56\xa9\xf0\x27\xac\x13\x94\x69")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/NqVORkT6L9HX6Za7kT2zcibY10qFqBaxEjPiYFrBQX-ZFr3yxCzJxbKOP0zVjeWb", Data: []byte("../checksum/fLYGIMHgN1louE-JzITJZJo2SDniPu-IHBXubtvQWFO-hXnDVKNuscV7-zlyr5fU")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("bqtn69RkV5E7V7GhhgCFjcvbxmaqrO8DywamM4Tyjf10F6EJBHjXiIa_tFRtF4iN"), nil},
|
||||
|
||||
{"sample directory step simple", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"check": {Mode: 0400, Data: []byte{0, 0}},
|
||||
|
||||
"lib": {Mode: fs.ModeDir | 0700},
|
||||
"lib/libedac.so": {Mode: fs.ModeSymlink | 0777, Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
|
||||
"lib/pkgconfig": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0500, Path: "."},
|
||||
|
||||
{Mode: 0400, Path: "check", Data: []byte{0, 0}},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "lib"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "lib/libedac.so", Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "lib/pkgconfig"},
|
||||
}, pkg.MustDecode("qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b"), nil},
|
||||
|
||||
{"sample directory step garbage", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"lib": {Mode: fs.ModeDir | 0500},
|
||||
"lib/check": {Mode: 0400, Data: []byte{}},
|
||||
|
||||
"lib/pkgconfig": {Mode: fs.ModeDir | 0500},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0500, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0500, Path: "lib"},
|
||||
{Mode: 0400, Path: "lib/check", Data: []byte{}},
|
||||
|
||||
{Mode: fs.ModeDir | 0500, Path: "lib/pkgconfig"},
|
||||
}, pkg.MustDecode("CUx-3hSbTWPsbMfDhgalG4Ni_GmR9TnVX8F99tY_P5GtkYvczg9RrF5zO0jX9XYT"), nil},
|
||||
|
||||
{"sample directory", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b/check": {Mode: 0400, Data: []byte{0, 0}},
|
||||
"checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b/lib": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b/lib/pkgconfig": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b/lib/libedac.so": {Mode: fs.ModeSymlink | 0777, Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/HnySzeLQvSBZuTUcvfmLEX_OmH4yJWWH788NxuLuv7kVn8_uPM6Ks4rqFWM2NZJY": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b")},
|
||||
"identifier/Zx5ZG9BAwegNT3zQwCySuI2ktCXxNgxirkGLFjW4FW06PtojYVaCdtEw8yuntPLa": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b")},
|
||||
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b"},
|
||||
{Mode: 0400, Path: "checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b/check", Data: []byte{0, 0}},
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b/lib"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b/lib/libedac.so", Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b/lib/pkgconfig"},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/HnySzeLQvSBZuTUcvfmLEX_OmH4yJWWH788NxuLuv7kVn8_uPM6Ks4rqFWM2NZJY", Data: []byte("../checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/Zx5ZG9BAwegNT3zQwCySuI2ktCXxNgxirkGLFjW4FW06PtojYVaCdtEw8yuntPLa", Data: []byte("../checksum/qRN6in76LndiiOZJheHkwyW8UT1N5-f-bXvHfDvwrMw2fSkOoZdh8pWE1qhLk65b")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("WVpvsVqVKg9Nsh744x57h51AuWUoUR2nnh8Md-EYBQpk6ziyTuUn6PLtF2e0Eu_d"), nil},
|
||||
|
||||
{"sample tar step unpack", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/check": {Mode: 0400, Data: []byte{0, 0}},
|
||||
"checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib/pkgconfig": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib/libedac.so": {Mode: fs.ModeSymlink | 0777, Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0500},
|
||||
"identifier/HnySzeLQvSBZuTUcvfmLEX_OmH4yJWWH788NxuLuv7kVn8_uPM6Ks4rqFWM2NZJY": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP")},
|
||||
"identifier/Zx5ZG9BAwegNT3zQwCySuI2ktCXxNgxirkGLFjW4FW06PtojYVaCdtEw8yuntPLa": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP")},
|
||||
|
||||
"work": {Mode: fs.ModeDir | 0500},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0500, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP"},
|
||||
{Mode: 0400, Path: "checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/check", Data: []byte{0, 0}},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib/libedac.so", Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib/pkgconfig"},
|
||||
|
||||
{Mode: fs.ModeDir | 0500, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/HnySzeLQvSBZuTUcvfmLEX_OmH4yJWWH788NxuLuv7kVn8_uPM6Ks4rqFWM2NZJY", Data: []byte("../checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/Zx5ZG9BAwegNT3zQwCySuI2ktCXxNgxirkGLFjW4FW06PtojYVaCdtEw8yuntPLa", Data: []byte("../checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP")},
|
||||
|
||||
{Mode: fs.ModeDir | 0500, Path: "work"},
|
||||
}, pkg.MustDecode("cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM"), nil},
|
||||
|
||||
{"sample tar", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/check": {Mode: 0400, Data: []byte{0, 0}},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib/libedac.so": {Mode: fs.ModeSymlink | 0777, Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib/pkgconfig": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/identifier": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/identifier/HnySzeLQvSBZuTUcvfmLEX_OmH4yJWWH788NxuLuv7kVn8_uPM6Ks4rqFWM2NZJY": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP")},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/identifier/Zx5ZG9BAwegNT3zQwCySuI2ktCXxNgxirkGLFjW4FW06PtojYVaCdtEw8yuntPLa": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP")},
|
||||
"checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/work": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/-P_1iw6yVq_letMHncqcExSE0bYcDhYI5OdY6b1wKASf-Corufvj__XTBUq2Qd2a": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM")},
|
||||
"identifier/0_rRxIqbX9LK9L_KDbuafotFz6HFkonNgO9gXhK1asM_Y1Pxn0amg756vRTo6m74": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM")},
|
||||
|
||||
"temp": {Mode: fs.ModeDir | 0700},
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP"},
|
||||
{Mode: 0400, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/check", Data: []byte{0, 0}},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib/libedac.so", Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP/lib/pkgconfig"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/identifier/HnySzeLQvSBZuTUcvfmLEX_OmH4yJWWH788NxuLuv7kVn8_uPM6Ks4rqFWM2NZJY", Data: []byte("../checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/identifier/Zx5ZG9BAwegNT3zQwCySuI2ktCXxNgxirkGLFjW4FW06PtojYVaCdtEw8yuntPLa", Data: []byte("../checksum/1TL00Qb8dcqayX7wTO8WNaraHvY6b-KCsctLDTrb64QBCmxj_-byK1HdIUwMaFEP")},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM/work"},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/-P_1iw6yVq_letMHncqcExSE0bYcDhYI5OdY6b1wKASf-Corufvj__XTBUq2Qd2a", Data: []byte("../checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/0_rRxIqbX9LK9L_KDbuafotFz6HFkonNgO9gXhK1asM_Y1Pxn0amg756vRTo6m74", Data: []byte("../checksum/cTw0h3AmYe7XudSoyEMByduYXqGi-N5ZkTZ0t9K5elsu3i_jNIVF5T08KR1roBFM")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "temp"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("sxbgyX-bPoezbha214n2lbQhiVfTUBkhZ0EX6zI7mmkMdrCdwuMwhMBJphLQsy94"), nil},
|
||||
|
||||
{"sample tar expand step unpack", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"libedac.so": {Mode: fs.ModeSymlink | 0777, Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0500, Path: "."},
|
||||
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "libedac.so", Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
}, pkg.MustDecode("CH3AiUrCCcVOjOYLaMKKK1Da78989JtfHeIsxMzWOQFiN4mrCLDYpoDxLWqJWCUN"), nil},
|
||||
|
||||
{"sample tar expand", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/CH3AiUrCCcVOjOYLaMKKK1Da78989JtfHeIsxMzWOQFiN4mrCLDYpoDxLWqJWCUN": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/CH3AiUrCCcVOjOYLaMKKK1Da78989JtfHeIsxMzWOQFiN4mrCLDYpoDxLWqJWCUN/libedac.so": {Mode: fs.ModeSymlink | 0777, Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/-P_1iw6yVq_letMHncqcExSE0bYcDhYI5OdY6b1wKASf-Corufvj__XTBUq2Qd2a": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/CH3AiUrCCcVOjOYLaMKKK1Da78989JtfHeIsxMzWOQFiN4mrCLDYpoDxLWqJWCUN")},
|
||||
"identifier/0_rRxIqbX9LK9L_KDbuafotFz6HFkonNgO9gXhK1asM_Y1Pxn0amg756vRTo6m74": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/CH3AiUrCCcVOjOYLaMKKK1Da78989JtfHeIsxMzWOQFiN4mrCLDYpoDxLWqJWCUN")},
|
||||
|
||||
"temp": {Mode: fs.ModeDir | 0700},
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/CH3AiUrCCcVOjOYLaMKKK1Da78989JtfHeIsxMzWOQFiN4mrCLDYpoDxLWqJWCUN"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "checksum/CH3AiUrCCcVOjOYLaMKKK1Da78989JtfHeIsxMzWOQFiN4mrCLDYpoDxLWqJWCUN/libedac.so", Data: []byte("/proc/nonexistent/libedac.so")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/-P_1iw6yVq_letMHncqcExSE0bYcDhYI5OdY6b1wKASf-Corufvj__XTBUq2Qd2a", Data: []byte("../checksum/CH3AiUrCCcVOjOYLaMKKK1Da78989JtfHeIsxMzWOQFiN4mrCLDYpoDxLWqJWCUN")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/0_rRxIqbX9LK9L_KDbuafotFz6HFkonNgO9gXhK1asM_Y1Pxn0amg756vRTo6m74", Data: []byte("../checksum/CH3AiUrCCcVOjOYLaMKKK1Da78989JtfHeIsxMzWOQFiN4mrCLDYpoDxLWqJWCUN")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "temp"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("4I8wx_h7NSJTlG5lbuz-GGEXrOg0GYC3M_503LYEBhv5XGWXfNIdIY9Q3eVSYldX"), nil},
|
||||
|
||||
{"testtool", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"check": {Mode: 0400, Data: []byte{0}},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0500, Path: "."},
|
||||
|
||||
{Mode: 0400, Path: "check", Data: []byte{0}},
|
||||
}, pkg.MustDecode("GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9"), nil},
|
||||
|
||||
{"sample exec container", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check": {Mode: 0400, Data: []byte{0}},
|
||||
"checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb": {Mode: 0400, Data: []byte{}},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/U2cbgVgEtjfRuvHfE1cQnZ3t8yoexULQyo_VLgvxAVJSsobMcNaFIsuDWtmt7kzK": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
"identifier/_gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb")},
|
||||
"identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
"temp": {Mode: fs.ModeDir | 0700},
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9"},
|
||||
{Mode: 0400, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check", Data: []byte{0}},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU"},
|
||||
{Mode: 0400, Path: "checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb", Data: []byte{}},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/U2cbgVgEtjfRuvHfE1cQnZ3t8yoexULQyo_VLgvxAVJSsobMcNaFIsuDWtmt7kzK", Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/_gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", Data: []byte("../checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA", Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "temp"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("UiV6kMz7KrTsc_yphiyQzFLqjRanHxUOwrBMtkKuWo4mOO6WgPFAcoUEeSp7eVIW"), nil},
|
||||
|
||||
{"testtool net", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"check": {Mode: 0400, Data: []byte("net")},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0500, Path: "."},
|
||||
|
||||
{Mode: 0400, Path: "check", Data: []byte("net")},
|
||||
}, pkg.MustDecode("a1F_i9PVQI4qMcoHgTQkORuyWLkC1GLIxOhDt2JpU1NGAxWc5VJzdlfRK-PYBh3W"), nil},
|
||||
|
||||
{"sample exec net container", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb": {Mode: 0400, Data: []byte{}},
|
||||
"checksum/a1F_i9PVQI4qMcoHgTQkORuyWLkC1GLIxOhDt2JpU1NGAxWc5VJzdlfRK-PYBh3W": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/a1F_i9PVQI4qMcoHgTQkORuyWLkC1GLIxOhDt2JpU1NGAxWc5VJzdlfRK-PYBh3W/check": {Mode: 0400, Data: []byte("net")},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/_gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb")},
|
||||
"identifier/QdsJhGgnk5N2xdUNGcndXQxFKifxf1V_2t9X8CQ-pDcg24x6mGJC_BiLfGbs6Qml": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/a1F_i9PVQI4qMcoHgTQkORuyWLkC1GLIxOhDt2JpU1NGAxWc5VJzdlfRK-PYBh3W")},
|
||||
"identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
"temp": {Mode: fs.ModeDir | 0700},
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU"},
|
||||
{Mode: 0400, Path: "checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb", Data: []byte{}},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/a1F_i9PVQI4qMcoHgTQkORuyWLkC1GLIxOhDt2JpU1NGAxWc5VJzdlfRK-PYBh3W"},
|
||||
{Mode: 0400, Path: "checksum/a1F_i9PVQI4qMcoHgTQkORuyWLkC1GLIxOhDt2JpU1NGAxWc5VJzdlfRK-PYBh3W/check", Data: []byte("net")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/QdsJhGgnk5N2xdUNGcndXQxFKifxf1V_2t9X8CQ-pDcg24x6mGJC_BiLfGbs6Qml", Data: []byte("../checksum/a1F_i9PVQI4qMcoHgTQkORuyWLkC1GLIxOhDt2JpU1NGAxWc5VJzdlfRK-PYBh3W")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/_gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", Data: []byte("../checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA", Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "temp"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("ek4K-0d4iRSArkY2TCs3WK34DbiYeOmhE_4vsJTSu_6roY4ZF3YG6eKRooal-i1o"), nil},
|
||||
|
||||
{"sample exec container overlay root", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check": {Mode: 0400, Data: []byte{0}},
|
||||
"checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/5ey2wpmMpj483YYa7ZZQciYLA2cx3_l167JCqWW4Pd-5DVp81dj9EsBtVTwYptF6": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
"identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
"temp": {Mode: fs.ModeDir | 0700},
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9"},
|
||||
{Mode: 0400, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check", Data: []byte{0}},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU"},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/5ey2wpmMpj483YYa7ZZQciYLA2cx3_l167JCqWW4Pd-5DVp81dj9EsBtVTwYptF6", Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA", Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "temp"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("VIqqpf0ip9jcyw63i6E8lCMGUcLivQBe4Bevt3WusNac-1MSy5bzB647qGUBzl-W"), nil},
|
||||
|
||||
{"sample exec container overlay work", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check": {Mode: 0400, Data: []byte{0}},
|
||||
"checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/acaDzHZv40dZaz4cGAXayqbRMgbEOuiuiUijZL8IgDQvyeCNMFE3onBMYfny-kXA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
"identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
"temp": {Mode: fs.ModeDir | 0700},
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9"},
|
||||
{Mode: 0400, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check", Data: []byte{0}},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU"},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/acaDzHZv40dZaz4cGAXayqbRMgbEOuiuiUijZL8IgDQvyeCNMFE3onBMYfny-kXA", Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA", Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "temp"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("q8x2zQg4YZbKpPqKlEBj_uxXD9vOBaZ852qOuIsl9QdO73I_UMNpuUoPLtunxUYl"), nil},
|
||||
|
||||
{"sample exec container multiple layers", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check": {Mode: 0400, Data: []byte{0}},
|
||||
"checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb": {Mode: 0400, Data: []byte{}},
|
||||
"checksum/nY_CUdiaUM1OL4cPr5TS92FCJ3rCRV7Hm5oVTzAvMXwC03_QnTRfQ5PPs7mOU9fK": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/nY_CUdiaUM1OL4cPr5TS92FCJ3rCRV7Hm5oVTzAvMXwC03_QnTRfQ5PPs7mOU9fK/check": {Mode: 0400, Data: []byte("layers")},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/_gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb")},
|
||||
"identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
"identifier/rXLKjjYfGSyoWmuvEJooHkvGJIZaC0IAWnKGvtPZkM15gBxAgW7mIXcxRVNOXAr4": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/nY_CUdiaUM1OL4cPr5TS92FCJ3rCRV7Hm5oVTzAvMXwC03_QnTRfQ5PPs7mOU9fK")},
|
||||
"identifier/tfjrsVuBuFgzWgwz-yPppFtylYuC1VFWnKhyBiHbWTGkyz8lt7Ee9QXWaIHPXs4x": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
|
||||
"temp": {Mode: fs.ModeDir | 0700},
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9"},
|
||||
{Mode: 0400, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check", Data: []byte{0}},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU"},
|
||||
{Mode: 0400, Path: "checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb", Data: []byte{}},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/nY_CUdiaUM1OL4cPr5TS92FCJ3rCRV7Hm5oVTzAvMXwC03_QnTRfQ5PPs7mOU9fK"},
|
||||
{Mode: 0400, Path: "checksum/nY_CUdiaUM1OL4cPr5TS92FCJ3rCRV7Hm5oVTzAvMXwC03_QnTRfQ5PPs7mOU9fK/check", Data: []byte("layers")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/_gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", Data: []byte("../checksum/OLBgp1GsljhM2TJ-sbHjaiH9txEUvgdDTAzHv2P24donTt6_529l-9Ua0vFImLlb")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA", Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/rXLKjjYfGSyoWmuvEJooHkvGJIZaC0IAWnKGvtPZkM15gBxAgW7mIXcxRVNOXAr4", Data: []byte("../checksum/nY_CUdiaUM1OL4cPr5TS92FCJ3rCRV7Hm5oVTzAvMXwC03_QnTRfQ5PPs7mOU9fK")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/tfjrsVuBuFgzWgwz-yPppFtylYuC1VFWnKhyBiHbWTGkyz8lt7Ee9QXWaIHPXs4x", Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "temp"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("SITnQ6PTV12PAQQjIuLUxkvsXQiC9Gq_HJQlcb4BPL5YnRHnx8lsW7PRM9YMLBsx"), nil},
|
||||
|
||||
{"sample exec container layer promotion", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9": {Mode: fs.ModeDir | 0500},
|
||||
"checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check": {Mode: 0400, Data: []byte{0}},
|
||||
"checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU": {Mode: fs.ModeDir | 0500},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/1tQZOGmVk_JkpyiG84AKW_BXmlK_MvHUbh5WtMuthGbHUq7i7nL1bvdF-LoJbqNh": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
"identifier/O-6VjlIUxc4PYLf5v35uhIeL8kkYCbHYklqlmDjFPXe0m4j6GkUDg5qwTzBRESnf": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
"identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
"temp": {Mode: fs.ModeDir | 0700},
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9"},
|
||||
{Mode: 0400, Path: "checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9/check", Data: []byte{0}},
|
||||
{Mode: fs.ModeDir | 0500, Path: "checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU"},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/1tQZOGmVk_JkpyiG84AKW_BXmlK_MvHUbh5WtMuthGbHUq7i7nL1bvdF-LoJbqNh", Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/O-6VjlIUxc4PYLf5v35uhIeL8kkYCbHYklqlmDjFPXe0m4j6GkUDg5qwTzBRESnf", Data: []byte("../checksum/GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9")},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/nfeISfLeFDr1k-g3hpE1oZ440kTqDdfF8TDpoLdbTPqaMMIl95oiqcvqjRkMjubA", Data: []byte("../checksum/MGWmEfjut2QE2xPJwTsmUzpff4BN_FEnQ7T0j7gvUCCiugJQNwqt9m151fm9D1yU")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "temp"},
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("fuC20BhMKr86TYzNPP2A-9P7mGLvdcOiG10exlhRvZm8ySI7csf0LhW3im_26l1N"), nil},
|
||||
|
||||
{"sample file short", fstest.MapFS{
|
||||
".": {Mode: fs.ModeDir | 0700},
|
||||
|
||||
"checksum": {Mode: fs.ModeDir | 0700},
|
||||
"checksum/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX": {Mode: 0400, Data: []byte{0}},
|
||||
|
||||
"identifier": {Mode: fs.ModeDir | 0700},
|
||||
"identifier/lIx_W4M7tVOcQ8jh08EJOfXf4brRmkEEjvUa7c17vVUzlmtUxlhhrgqmc9aZhjbn": {Mode: fs.ModeSymlink | 0777, Data: []byte("../checksum/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX")},
|
||||
|
||||
"work": {Mode: fs.ModeDir | 0700},
|
||||
}, []pkg.FlatEntry{
|
||||
{Mode: fs.ModeDir | 0700, Path: "."},
|
||||
{Mode: fs.ModeDir | 0700, Path: "checksum"},
|
||||
{Mode: 0400, Path: "checksum/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX", Data: []byte{0}},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "identifier"},
|
||||
{Mode: fs.ModeSymlink | 0777, Path: "identifier/lIx_W4M7tVOcQ8jh08EJOfXf4brRmkEEjvUa7c17vVUzlmtUxlhhrgqmc9aZhjbn", Data: []byte("../checksum/vsAhtPNo4waRNOASwrQwcIPTqb3SBuJOXw2G4T1mNmVZM-wrQTRllmgXqcIIoRcX")},
|
||||
|
||||
{Mode: fs.ModeDir | 0700, Path: "work"},
|
||||
}, pkg.MustDecode("hnrfmJtivNKcgtETsKnU9gP_OwPgpNY3DSUJnmxnmeOODSO-YBvEBiTgieY4AAd7"), nil},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
t.Run("roundtrip", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var buf bytes.Buffer
|
||||
if _, err := pkg.Flatten(
|
||||
tc.fsys,
|
||||
".",
|
||||
&buf,
|
||||
); !reflect.DeepEqual(err, tc.err) {
|
||||
t.Fatalf("Flatten: error = %v, want %v", err, tc.err)
|
||||
} else if tc.err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
s := pkg.NewDirScanner(bytes.NewReader(buf.Bytes()), true)
|
||||
var got []pkg.FlatEntry
|
||||
for s.Scan() {
|
||||
got = append(got, *s.Entry())
|
||||
}
|
||||
if err := s.Err(); err != nil {
|
||||
t.Fatalf("Err: error = %v", err)
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(got, tc.entries) {
|
||||
t.Fatalf("Scan: %#v, want %#v", got, tc.entries)
|
||||
}
|
||||
})
|
||||
|
||||
if tc.err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
t.Run("hash", func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
var got pkg.Checksum
|
||||
if err := pkg.HashFS(&got, tc.fsys, "."); err != nil {
|
||||
t.Fatalf("HashFS: error = %v", err)
|
||||
} else if got != tc.sum {
|
||||
t.Fatalf("HashFS: %v", &pkg.ChecksumMismatchError{
|
||||
Got: got,
|
||||
Want: tc.sum,
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
411
internal/pkg/exec.go
Normal file
411
internal/pkg/exec.go
Normal file
@@ -0,0 +1,411 @@
|
||||
package pkg
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path"
|
||||
"slices"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
"unique"
|
||||
|
||||
"hakurei.app/container"
|
||||
"hakurei.app/container/check"
|
||||
"hakurei.app/container/fhs"
|
||||
"hakurei.app/container/std"
|
||||
"hakurei.app/message"
|
||||
)
|
||||
|
||||
// AbsWork is the container pathname [CureContext.GetWorkDir] is mounted on.
|
||||
var AbsWork = fhs.AbsRoot.Append("work/")
|
||||
|
||||
// ExecPath is a slice of [Artifact] and the [check.Absolute] pathname to make
|
||||
// it available at under in the container.
|
||||
type ExecPath struct {
|
||||
// Pathname in the container mount namespace.
|
||||
P *check.Absolute
|
||||
// Artifacts to mount on the pathname, must contain at least one [Artifact].
|
||||
// If there are multiple entries or W is true, P is set up as an overlay
|
||||
// mount, and entries of A must not implement [FileArtifact].
|
||||
A []Artifact
|
||||
// Whether to make the mount point writable via the temp directory.
|
||||
W bool
|
||||
}
|
||||
|
||||
// layers returns pathnames collected from A deduplicated by checksum.
|
||||
func (p *ExecPath) layers(f *FContext) []*check.Absolute {
|
||||
msg := f.GetMessage()
|
||||
|
||||
layers := make([]*check.Absolute, 0, len(p.A))
|
||||
checksums := make(map[unique.Handle[Checksum]]struct{}, len(p.A))
|
||||
for i := range p.A {
|
||||
d := p.A[len(p.A)-1-i]
|
||||
pathname, checksum := f.GetArtifact(d)
|
||||
if _, ok := checksums[checksum]; ok {
|
||||
if msg.IsVerbose() {
|
||||
msg.Verbosef(
|
||||
"promoted layer %d as %s",
|
||||
len(p.A)-1-i, reportName(d, f.cache.Ident(d)),
|
||||
)
|
||||
}
|
||||
continue
|
||||
}
|
||||
checksums[checksum] = struct{}{}
|
||||
layers = append(layers, pathname)
|
||||
}
|
||||
slices.Reverse(layers)
|
||||
return layers
|
||||
}
|
||||
|
||||
// Path returns a populated [ExecPath].
|
||||
func Path(pathname *check.Absolute, writable bool, a ...Artifact) ExecPath {
|
||||
return ExecPath{pathname, a, writable}
|
||||
}
|
||||
|
||||
// MustPath is like [Path], but takes a string pathname via [check.MustAbs].
|
||||
func MustPath(pathname string, writable bool, a ...Artifact) ExecPath {
|
||||
return ExecPath{check.MustAbs(pathname), a, writable}
|
||||
}
|
||||
|
||||
const (
|
||||
// ExecTimeoutDefault replaces out of range [NewExec] timeout values.
|
||||
ExecTimeoutDefault = 15 * time.Minute
|
||||
// ExecTimeoutMax is the arbitrary upper bound of [NewExec] timeout.
|
||||
ExecTimeoutMax = 48 * time.Hour
|
||||
)
|
||||
|
||||
// An execArtifact is an [Artifact] that produces output by running a program
|
||||
// part of another [Artifact] in a [container] to produce its output.
|
||||
//
|
||||
// Methods of execArtifact does not modify any struct field or underlying arrays
|
||||
// referred to by slices.
|
||||
type execArtifact struct {
|
||||
// Caller-supplied user-facing reporting name, guaranteed to be nonzero
|
||||
// during initialisation.
|
||||
name string
|
||||
// Caller-supplied inner mount points.
|
||||
paths []ExecPath
|
||||
|
||||
// Passed through to [container.Params].
|
||||
dir *check.Absolute
|
||||
// Passed through to [container.Params].
|
||||
env []string
|
||||
// Passed through to [container.Params].
|
||||
path *check.Absolute
|
||||
// Passed through to [container.Params].
|
||||
args []string
|
||||
|
||||
// Duration the initial process is allowed to run. The zero value is
|
||||
// equivalent to execTimeoutDefault. This value is never encoded in Params
|
||||
// because it cannot affect outcome.
|
||||
timeout time.Duration
|
||||
|
||||
// Caller-supplied exclusivity value, returned as is by IsExclusive.
|
||||
exclusive bool
|
||||
}
|
||||
|
||||
var _ fmt.Stringer = new(execArtifact)
|
||||
|
||||
// execNetArtifact is like execArtifact but implements [KnownChecksum] and has
|
||||
// its resulting container keep the host net namespace.
|
||||
type execNetArtifact struct {
|
||||
checksum Checksum
|
||||
|
||||
execArtifact
|
||||
}
|
||||
|
||||
var _ KnownChecksum = new(execNetArtifact)
|
||||
|
||||
// Checksum returns the caller-supplied checksum.
|
||||
func (a *execNetArtifact) Checksum() Checksum { return a.checksum }
|
||||
|
||||
// Kind returns the hardcoded [Kind] constant.
|
||||
func (*execNetArtifact) Kind() Kind { return KindExecNet }
|
||||
|
||||
// Params is [Checksum] concatenated with [KindExec] params.
|
||||
func (a *execNetArtifact) Params(ctx *IContext) {
|
||||
ctx.GetHash().Write(a.checksum[:])
|
||||
a.execArtifact.Params(ctx)
|
||||
}
|
||||
|
||||
// Cure cures the [Artifact] in the container described by the caller. The
|
||||
// container retains host networking.
|
||||
func (a *execNetArtifact) Cure(f *FContext) error {
|
||||
return a.cure(f, true)
|
||||
}
|
||||
|
||||
// NewExec returns a new [Artifact] that executes the program path in a
|
||||
// container with specified paths bind mounted read-only in order. A private
|
||||
// instance of /proc and /dev is made available to the container.
|
||||
//
|
||||
// The working and temporary directories are both created and mounted writable
|
||||
// on [AbsWork] and [fhs.AbsTmp] respectively. If one or more paths target
|
||||
// [AbsWork], the final entry is set up as a writable overlay mount on /work for
|
||||
// which the upperdir is the host side work directory. In this configuration,
|
||||
// the W field is ignored, and the program must avoid causing whiteout files to
|
||||
// be created. Cure fails if upperdir ends up with entries other than directory,
|
||||
// regular or symlink.
|
||||
//
|
||||
// If checksum is non-nil, the resulting [Artifact] implements [KnownChecksum]
|
||||
// and its container runs in the host net namespace.
|
||||
//
|
||||
// The container is allowed to run for the specified duration before the initial
|
||||
// process and all processes originating from it is terminated. A zero or
|
||||
// negative timeout value is equivalent tp [ExecTimeoutDefault], a timeout value
|
||||
// greater than [ExecTimeoutMax] is equivalent to [ExecTimeoutMax].
|
||||
//
|
||||
// The user-facing name and exclusivity value are not accessible from the
|
||||
// container and does not affect curing outcome. Because of this, it is omitted
|
||||
// from parameter data for computing identifier.
|
||||
func NewExec(
|
||||
name string,
|
||||
checksum *Checksum,
|
||||
timeout time.Duration,
|
||||
exclusive bool,
|
||||
|
||||
dir *check.Absolute,
|
||||
env []string,
|
||||
pathname *check.Absolute,
|
||||
args []string,
|
||||
|
||||
paths ...ExecPath,
|
||||
) Artifact {
|
||||
if name == "" {
|
||||
name = "exec-" + path.Base(pathname.String())
|
||||
}
|
||||
if timeout <= 0 {
|
||||
timeout = ExecTimeoutDefault
|
||||
}
|
||||
if timeout > ExecTimeoutMax {
|
||||
timeout = ExecTimeoutMax
|
||||
}
|
||||
a := execArtifact{name, paths, dir, env, pathname, args, timeout, exclusive}
|
||||
if checksum == nil {
|
||||
return &a
|
||||
}
|
||||
return &execNetArtifact{*checksum, a}
|
||||
}
|
||||
|
||||
// Kind returns the hardcoded [Kind] constant.
|
||||
func (*execArtifact) Kind() Kind { return KindExec }
|
||||
|
||||
// Params writes paths, executable pathname and args.
|
||||
func (a *execArtifact) Params(ctx *IContext) {
|
||||
h := ctx.GetHash()
|
||||
|
||||
_0, _1 := []byte{0}, []byte{1}
|
||||
for _, p := range a.paths {
|
||||
if p.W {
|
||||
h.Write(_1)
|
||||
} else {
|
||||
h.Write(_0)
|
||||
}
|
||||
if p.P != nil {
|
||||
h.Write([]byte(p.P.String()))
|
||||
} else {
|
||||
h.Write([]byte("invalid P\x00"))
|
||||
}
|
||||
h.Write(_0)
|
||||
for _, d := range p.A {
|
||||
ctx.WriteIdent(d)
|
||||
}
|
||||
h.Write(_0)
|
||||
}
|
||||
h.Write(_0)
|
||||
h.Write([]byte(a.dir.String()))
|
||||
h.Write(_0)
|
||||
for _, e := range a.env {
|
||||
h.Write([]byte(e))
|
||||
}
|
||||
h.Write(_0)
|
||||
h.Write([]byte(a.path.String()))
|
||||
h.Write(_0)
|
||||
for _, arg := range a.args {
|
||||
h.Write([]byte(arg))
|
||||
}
|
||||
}
|
||||
|
||||
// Dependencies returns a slice of all artifacts collected from caller-supplied
|
||||
// [ExecPath].
|
||||
func (a *execArtifact) Dependencies() []Artifact {
|
||||
artifacts := make([][]Artifact, 0, len(a.paths))
|
||||
for _, p := range a.paths {
|
||||
artifacts = append(artifacts, p.A)
|
||||
}
|
||||
return slices.Concat(artifacts...)
|
||||
}
|
||||
|
||||
// IsExclusive returns the caller-supplied exclusivity value.
|
||||
func (a *execArtifact) IsExclusive() bool { return a.exclusive }
|
||||
|
||||
// String returns the caller-supplied reporting name.
|
||||
func (a *execArtifact) String() string { return a.name }
|
||||
|
||||
// Cure cures the [Artifact] in the container described by the caller.
|
||||
func (a *execArtifact) Cure(f *FContext) (err error) {
|
||||
return a.cure(f, false)
|
||||
}
|
||||
|
||||
const (
|
||||
// execWaitDelay is passed through to [container.Params].
|
||||
execWaitDelay = time.Nanosecond
|
||||
)
|
||||
|
||||
// scanVerbose prefixes program output for a verbose [message.Msg].
|
||||
func scanVerbose(
|
||||
msg message.Msg,
|
||||
done chan<- struct{},
|
||||
prefix string,
|
||||
r io.Reader,
|
||||
) {
|
||||
defer close(done)
|
||||
s := bufio.NewScanner(r)
|
||||
s.Buffer(
|
||||
make([]byte, bufio.MaxScanTokenSize),
|
||||
bufio.MaxScanTokenSize<<12,
|
||||
)
|
||||
for s.Scan() {
|
||||
msg.Verbose(prefix, s.Text())
|
||||
}
|
||||
if err := s.Err(); err != nil && !errors.Is(err, os.ErrClosed) {
|
||||
msg.Verbose("*"+prefix, err)
|
||||
}
|
||||
}
|
||||
|
||||
// cure is like Cure but allows optional host net namespace. This is used for
|
||||
// the [KnownChecksum] variant where networking is allowed.
|
||||
func (a *execArtifact) cure(f *FContext, hostNet bool) (err error) {
|
||||
overlayWorkIndex := -1
|
||||
for i, p := range a.paths {
|
||||
if p.P == nil || len(p.A) == 0 {
|
||||
return os.ErrInvalid
|
||||
}
|
||||
if p.P.Is(AbsWork) {
|
||||
overlayWorkIndex = i
|
||||
}
|
||||
}
|
||||
|
||||
var artifactCount int
|
||||
for _, p := range a.paths {
|
||||
artifactCount += len(p.A)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(f.Unwrap(), a.timeout)
|
||||
defer cancel()
|
||||
|
||||
z := container.New(ctx, f.GetMessage())
|
||||
z.WaitDelay = execWaitDelay
|
||||
z.SeccompPresets |= std.PresetStrict & ^std.PresetDenyNS
|
||||
z.ParentPerm = 0700
|
||||
z.HostNet = hostNet
|
||||
z.Hostname = "cure"
|
||||
if z.HostNet {
|
||||
z.Hostname = "cure-net"
|
||||
}
|
||||
z.Uid, z.Gid = (1<<10)-1, (1<<10)-1
|
||||
if msg := f.GetMessage(); msg.IsVerbose() {
|
||||
var stdout, stderr io.ReadCloser
|
||||
if stdout, err = z.StdoutPipe(); err != nil {
|
||||
return
|
||||
}
|
||||
if stderr, err = z.StderrPipe(); err != nil {
|
||||
_ = stdout.Close()
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err != nil && !errors.As(err, new(*exec.ExitError)) {
|
||||
_ = stdout.Close()
|
||||
_ = stderr.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
stdoutDone, stderrDone := make(chan struct{}), make(chan struct{})
|
||||
go scanVerbose(msg, stdoutDone, "("+a.name+":1)", stdout)
|
||||
go scanVerbose(msg, stderrDone, "("+a.name+":2)", stderr)
|
||||
defer func() { <-stdoutDone; <-stderrDone }()
|
||||
}
|
||||
|
||||
z.Dir, z.Env, z.Path, z.Args = a.dir, a.env, a.path, a.args
|
||||
z.Grow(len(a.paths) + 4)
|
||||
|
||||
temp, work := f.GetTempDir(), f.GetWorkDir()
|
||||
for i, b := range a.paths {
|
||||
if i == overlayWorkIndex {
|
||||
if err = os.MkdirAll(work.String(), 0700); err != nil {
|
||||
return
|
||||
}
|
||||
tempWork := temp.Append(".work")
|
||||
if err = os.MkdirAll(tempWork.String(), 0700); err != nil {
|
||||
return
|
||||
}
|
||||
z.Overlay(
|
||||
AbsWork,
|
||||
work,
|
||||
tempWork,
|
||||
b.layers(f)...,
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
if a.paths[i].W {
|
||||
tempUpper, tempWork := temp.Append(
|
||||
".upper", strconv.Itoa(i),
|
||||
), temp.Append(
|
||||
".work", strconv.Itoa(i),
|
||||
)
|
||||
if err = os.MkdirAll(tempUpper.String(), 0700); err != nil {
|
||||
return
|
||||
}
|
||||
if err = os.MkdirAll(tempWork.String(), 0700); err != nil {
|
||||
return
|
||||
}
|
||||
z.Overlay(b.P, tempUpper, tempWork, b.layers(f)...)
|
||||
} else if len(b.A) == 1 {
|
||||
pathname, _ := f.GetArtifact(b.A[0])
|
||||
z.Bind(pathname, b.P, 0)
|
||||
} else {
|
||||
z.OverlayReadonly(b.P, b.layers(f)...)
|
||||
}
|
||||
}
|
||||
if overlayWorkIndex < 0 {
|
||||
z.Bind(
|
||||
work,
|
||||
AbsWork,
|
||||
std.BindWritable|std.BindEnsure,
|
||||
)
|
||||
}
|
||||
z.Bind(
|
||||
f.GetTempDir(),
|
||||
fhs.AbsTmp,
|
||||
std.BindWritable|std.BindEnsure,
|
||||
)
|
||||
z.Proc(fhs.AbsProc).Dev(fhs.AbsDev, true)
|
||||
|
||||
if err = z.Start(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = z.Serve(); err != nil {
|
||||
return
|
||||
}
|
||||
if err = z.Wait(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
// do not allow empty directories to succeed
|
||||
for {
|
||||
err = syscall.Rmdir(work.String())
|
||||
if err != syscall.EINTR {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err != nil && errors.Is(err, syscall.ENOTEMPTY) {
|
||||
err = nil
|
||||
}
|
||||
return
|
||||
}
|
||||
339
internal/pkg/exec_test.go
Normal file
339
internal/pkg/exec_test.go
Normal file
@@ -0,0 +1,339 @@
|
||||
package pkg_test
|
||||
|
||||
//go:generate env CGO_ENABLED=0 go build -tags testtool -o testdata/testtool ./testdata
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/gob"
|
||||
"errors"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"testing"
|
||||
"unique"
|
||||
|
||||
"hakurei.app/container/check"
|
||||
"hakurei.app/container/stub"
|
||||
"hakurei.app/hst"
|
||||
"hakurei.app/internal/pkg"
|
||||
)
|
||||
|
||||
// testtoolBin is the container test tool binary made available to the
|
||||
// execArtifact for testing its curing environment.
|
||||
//
|
||||
//go:embed testdata/testtool
|
||||
var testtoolBin []byte
|
||||
|
||||
func TestExec(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
wantChecksumOffline := pkg.MustDecode(
|
||||
"GPa4aBakdSJd7Tz7LYj_VJFoojzyZinmVcG3k6M5xI6CZ821J5sXLhLDDuS47gi9",
|
||||
)
|
||||
|
||||
checkWithCache(t, []cacheTestCase{
|
||||
{"offline", nil, func(t *testing.T, base *check.Absolute, c *pkg.Cache) {
|
||||
c.SetStrict(true)
|
||||
testtool, testtoolDestroy := newTesttool()
|
||||
|
||||
cureMany(t, c, []cureStep{
|
||||
{"container", pkg.NewExec(
|
||||
"exec-offline", nil, 0, false,
|
||||
pkg.AbsWork,
|
||||
[]string{"HAKUREI_TEST=1"},
|
||||
check.MustAbs("/opt/bin/testtool"),
|
||||
[]string{"testtool"},
|
||||
|
||||
pkg.MustPath("/file", false, newStubFile(
|
||||
pkg.KindHTTPGet,
|
||||
pkg.ID{0xfe, 0},
|
||||
nil,
|
||||
nil, nil,
|
||||
)),
|
||||
pkg.MustPath("/.hakurei", false, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("empty directory"),
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return os.MkdirAll(t.GetWorkDir().String(), 0700)
|
||||
},
|
||||
}),
|
||||
pkg.MustPath("/opt", false, testtool),
|
||||
), ignorePathname, wantChecksumOffline, nil},
|
||||
|
||||
{"error passthrough", pkg.NewExec(
|
||||
"", nil, 0, true,
|
||||
pkg.AbsWork,
|
||||
[]string{"HAKUREI_TEST=1"},
|
||||
check.MustAbs("/opt/bin/testtool"),
|
||||
[]string{"testtool"},
|
||||
|
||||
pkg.MustPath("/proc/nonexistent", false, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("doomed artifact"),
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return stub.UniqueError(0xcafe)
|
||||
},
|
||||
}),
|
||||
), nil, pkg.Checksum{}, &pkg.DependencyCureError{
|
||||
{
|
||||
Ident: unique.Make(pkg.ID(pkg.MustDecode(
|
||||
"CWEoJqnSBpWf8uryC2qnIe3O1a_FZWUWZGbiVPsQFGW7pvDHiSwoK3QCU9-uxN87",
|
||||
))),
|
||||
Err: stub.UniqueError(0xcafe),
|
||||
},
|
||||
}},
|
||||
|
||||
{"invalid paths", pkg.NewExec(
|
||||
"", nil, 0, false,
|
||||
pkg.AbsWork,
|
||||
[]string{"HAKUREI_TEST=1"},
|
||||
check.MustAbs("/opt/bin/testtool"),
|
||||
[]string{"testtool"},
|
||||
|
||||
pkg.ExecPath{},
|
||||
), nil, pkg.Checksum{}, os.ErrInvalid},
|
||||
})
|
||||
|
||||
// check init failure passthrough
|
||||
var exitError *exec.ExitError
|
||||
if _, _, err := c.Cure(pkg.NewExec(
|
||||
"", nil, 0, false,
|
||||
pkg.AbsWork,
|
||||
nil,
|
||||
check.MustAbs("/opt/bin/testtool"),
|
||||
[]string{"testtool"},
|
||||
)); !errors.As(err, &exitError) ||
|
||||
exitError.ExitCode() != hst.ExitFailure {
|
||||
t.Fatalf("Cure: error = %v, want init exit status 1", err)
|
||||
}
|
||||
|
||||
testtoolDestroy(t, base, c)
|
||||
}, pkg.MustDecode("UiV6kMz7KrTsc_yphiyQzFLqjRanHxUOwrBMtkKuWo4mOO6WgPFAcoUEeSp7eVIW")},
|
||||
|
||||
{"net", nil, func(t *testing.T, base *check.Absolute, c *pkg.Cache) {
|
||||
c.SetStrict(true)
|
||||
testtool, testtoolDestroy := newTesttool()
|
||||
|
||||
wantChecksum := pkg.MustDecode(
|
||||
"a1F_i9PVQI4qMcoHgTQkORuyWLkC1GLIxOhDt2JpU1NGAxWc5VJzdlfRK-PYBh3W",
|
||||
)
|
||||
cureMany(t, c, []cureStep{
|
||||
{"container", pkg.NewExec(
|
||||
"exec-net", &wantChecksum, 0, false,
|
||||
pkg.AbsWork,
|
||||
[]string{"HAKUREI_TEST=1"},
|
||||
check.MustAbs("/opt/bin/testtool"),
|
||||
[]string{"testtool", "net"},
|
||||
|
||||
pkg.MustPath("/file", false, newStubFile(
|
||||
pkg.KindHTTPGet,
|
||||
pkg.ID{0xfe, 0},
|
||||
nil,
|
||||
nil, nil,
|
||||
)),
|
||||
pkg.MustPath("/.hakurei", false, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("empty directory"),
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return os.MkdirAll(t.GetWorkDir().String(), 0700)
|
||||
},
|
||||
}),
|
||||
pkg.MustPath("/opt", false, testtool),
|
||||
), ignorePathname, wantChecksum, nil},
|
||||
})
|
||||
|
||||
testtoolDestroy(t, base, c)
|
||||
}, pkg.MustDecode("ek4K-0d4iRSArkY2TCs3WK34DbiYeOmhE_4vsJTSu_6roY4ZF3YG6eKRooal-i1o")},
|
||||
|
||||
{"overlay root", nil, func(t *testing.T, base *check.Absolute, c *pkg.Cache) {
|
||||
c.SetStrict(true)
|
||||
testtool, testtoolDestroy := newTesttool()
|
||||
|
||||
cureMany(t, c, []cureStep{
|
||||
{"container", pkg.NewExec(
|
||||
"exec-overlay-root", nil, 0, false,
|
||||
pkg.AbsWork,
|
||||
[]string{"HAKUREI_TEST=1", "HAKUREI_ROOT=1"},
|
||||
check.MustAbs("/opt/bin/testtool"),
|
||||
[]string{"testtool"},
|
||||
|
||||
pkg.MustPath("/", true, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("empty directory"),
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return os.MkdirAll(t.GetWorkDir().String(), 0700)
|
||||
},
|
||||
}),
|
||||
pkg.MustPath("/opt", false, testtool),
|
||||
), ignorePathname, wantChecksumOffline, nil},
|
||||
})
|
||||
|
||||
testtoolDestroy(t, base, c)
|
||||
}, pkg.MustDecode("VIqqpf0ip9jcyw63i6E8lCMGUcLivQBe4Bevt3WusNac-1MSy5bzB647qGUBzl-W")},
|
||||
|
||||
{"overlay work", nil, func(t *testing.T, base *check.Absolute, c *pkg.Cache) {
|
||||
c.SetStrict(true)
|
||||
testtool, testtoolDestroy := newTesttool()
|
||||
|
||||
cureMany(t, c, []cureStep{
|
||||
{"container", pkg.NewExec(
|
||||
"exec-overlay-work", nil, 0, false,
|
||||
pkg.AbsWork,
|
||||
[]string{"HAKUREI_TEST=1", "HAKUREI_ROOT=1"},
|
||||
check.MustAbs("/work/bin/testtool"),
|
||||
[]string{"testtool"},
|
||||
|
||||
pkg.MustPath("/", true, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("empty directory"),
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return os.MkdirAll(t.GetWorkDir().String(), 0700)
|
||||
},
|
||||
}), pkg.MustPath("/work/", false, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("empty directory"),
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return os.MkdirAll(t.GetWorkDir().String(), 0700)
|
||||
},
|
||||
}), pkg.Path(pkg.AbsWork, false /* ignored */, testtool),
|
||||
), ignorePathname, wantChecksumOffline, nil},
|
||||
})
|
||||
|
||||
testtoolDestroy(t, base, c)
|
||||
}, pkg.MustDecode("q8x2zQg4YZbKpPqKlEBj_uxXD9vOBaZ852qOuIsl9QdO73I_UMNpuUoPLtunxUYl")},
|
||||
|
||||
{"multiple layers", nil, func(t *testing.T, base *check.Absolute, c *pkg.Cache) {
|
||||
c.SetStrict(true)
|
||||
testtool, testtoolDestroy := newTesttool()
|
||||
|
||||
cureMany(t, c, []cureStep{
|
||||
{"container", pkg.NewExec(
|
||||
"exec-multiple-layers", nil, 0, false,
|
||||
pkg.AbsWork,
|
||||
[]string{"HAKUREI_TEST=1", "HAKUREI_ROOT=1"},
|
||||
check.MustAbs("/opt/bin/testtool"),
|
||||
[]string{"testtool", "layers"},
|
||||
|
||||
pkg.MustPath("/", true, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("empty directory"),
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return os.MkdirAll(t.GetWorkDir().String(), 0700)
|
||||
},
|
||||
}, &stubArtifactF{
|
||||
kind: pkg.KindExec,
|
||||
params: []byte("test sample with dependencies"),
|
||||
|
||||
deps: slices.Repeat([]pkg.Artifact{newStubFile(
|
||||
pkg.KindHTTPGet,
|
||||
pkg.ID{0xfe, 0},
|
||||
nil,
|
||||
nil, nil,
|
||||
), &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("empty directory"),
|
||||
|
||||
// this is queued and might run instead of the other
|
||||
// one so do not leave it as nil
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return os.MkdirAll(t.GetWorkDir().String(), 0700)
|
||||
},
|
||||
}}, 1<<5 /* concurrent cache hits */),
|
||||
|
||||
cure: func(f *pkg.FContext) error {
|
||||
work := f.GetWorkDir()
|
||||
if err := os.MkdirAll(work.String(), 0700); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(work.Append("check").String(), []byte("layers"), 0400)
|
||||
},
|
||||
}),
|
||||
pkg.MustPath("/opt", false, testtool),
|
||||
), ignorePathname, wantChecksumOffline, nil},
|
||||
})
|
||||
|
||||
testtoolDestroy(t, base, c)
|
||||
}, pkg.MustDecode("SITnQ6PTV12PAQQjIuLUxkvsXQiC9Gq_HJQlcb4BPL5YnRHnx8lsW7PRM9YMLBsx")},
|
||||
|
||||
{"overlay layer promotion", nil, func(t *testing.T, base *check.Absolute, c *pkg.Cache) {
|
||||
c.SetStrict(true)
|
||||
testtool, testtoolDestroy := newTesttool()
|
||||
|
||||
cureMany(t, c, []cureStep{
|
||||
{"container", pkg.NewExec(
|
||||
"exec-layer-promotion", nil, 0, true,
|
||||
pkg.AbsWork,
|
||||
[]string{"HAKUREI_TEST=1", "HAKUREI_ROOT=1"},
|
||||
check.MustAbs("/opt/bin/testtool"),
|
||||
[]string{"testtool", "promote"},
|
||||
|
||||
pkg.MustPath("/", true, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("another empty directory"),
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return os.MkdirAll(t.GetWorkDir().String(), 0700)
|
||||
},
|
||||
}, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
params: []byte("empty directory"),
|
||||
cure: func(t *pkg.TContext) error {
|
||||
return os.MkdirAll(t.GetWorkDir().String(), 0700)
|
||||
},
|
||||
}),
|
||||
pkg.MustPath("/opt", false, testtool),
|
||||
), ignorePathname, wantChecksumOffline, nil},
|
||||
})
|
||||
|
||||
testtoolDestroy(t, base, c)
|
||||
}, pkg.MustDecode("fuC20BhMKr86TYzNPP2A-9P7mGLvdcOiG10exlhRvZm8ySI7csf0LhW3im_26l1N")},
|
||||
})
|
||||
}
|
||||
|
||||
// newTesttool returns an [Artifact] that cures into testtoolBin. The returned
|
||||
// function must be called at the end of the test but not deferred.
|
||||
func newTesttool() (
|
||||
testtool pkg.Artifact,
|
||||
testtoolDestroy func(t *testing.T, base *check.Absolute, c *pkg.Cache),
|
||||
) {
|
||||
// testtoolBin is built during go:generate and is not deterministic
|
||||
testtool = overrideIdent{pkg.ID{0xfe, 0xff}, &stubArtifact{
|
||||
kind: pkg.KindTar,
|
||||
cure: func(t *pkg.TContext) error {
|
||||
work := t.GetWorkDir()
|
||||
if err := os.MkdirAll(
|
||||
work.Append("bin").String(),
|
||||
0700,
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if ift, err := net.Interfaces(); err != nil {
|
||||
return err
|
||||
} else {
|
||||
var f *os.File
|
||||
if f, err = os.Create(t.GetWorkDir().Append(
|
||||
"ift",
|
||||
).String()); err != nil {
|
||||
return err
|
||||
} else {
|
||||
err = gob.NewEncoder(f).Encode(ift)
|
||||
closeErr := f.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if closeErr != nil {
|
||||
return closeErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return os.WriteFile(t.GetWorkDir().Append(
|
||||
"bin",
|
||||
"testtool",
|
||||
).String(), testtoolBin, 0500)
|
||||
},
|
||||
}}
|
||||
testtoolDestroy = newDestroyArtifactFunc(testtool)
|
||||
return
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user