aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/system/wayland.go
blob: 9394aaabb2a87e149634504a981a51d8c6c2412a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package system

import (
	"errors"
	"fmt"
	"os"

	"git.ophivana.moe/security/fortify/acl"
	"git.ophivana.moe/security/fortify/internal/fmsg"
	"git.ophivana.moe/security/fortify/wl"
)

// Wayland sets up a wayland socket with a security context attached.
func (sys *I) Wayland(dst, src, appID, instanceID string) *I {
	sys.lock.Lock()
	defer sys.lock.Unlock()

	sys.ops = append(sys.ops, Wayland{[2]string{dst, src}, new(wl.Conn), appID, instanceID})

	return sys
}

type Wayland struct {
	pair [2]string
	conn *wl.Conn

	appID, instanceID string
}

func (w Wayland) Type() Enablement {
	return Process
}

func (w Wayland) apply(sys *I) error {
	// the Wayland op is not repeatable
	if sys.sp != nil {
		return errors.New("attempted to attach multiple wayland sockets")
	}

	if err := w.conn.Attach(w.pair[1]); err != nil {
		return fmsg.WrapErrorSuffix(err,
			fmt.Sprintf("cannot attach to wayland on %q:", w.pair[1]))
	} else {
		fmsg.VPrintf("wayland attached on %q", w.pair[1])
	}

	if sp, err := w.conn.Bind(w.pair[0], w.appID, w.instanceID); err != nil {
		return fmsg.WrapErrorSuffix(err,
			fmt.Sprintf("cannot bind to socket on %q:", w.pair[0]))
	} else {
		sys.sp = sp
		fmsg.VPrintf("wayland listening on %q", w.pair[0])
		return fmsg.WrapErrorSuffix(errors.Join(os.Chmod(w.pair[0], 0), acl.UpdatePerm(w.pair[0], sys.uid, acl.Read, acl.Write, acl.Execute)),
			fmt.Sprintf("cannot chmod socket on %q:", w.pair[0]))
	}
}

func (w Wayland) revert(_ *I, ec *Criteria) error {
	if ec.hasType(w) {
		fmsg.VPrintf("removing wayland socket on %q", w.pair[0])
		if err := os.Remove(w.pair[0]); err != nil && !errors.Is(err, os.ErrNotExist) {
			return err
		}

		fmsg.VPrintf("detaching from wayland on %q", w.pair[1])
		return fmsg.WrapErrorSuffix(w.conn.Close(),
			fmt.Sprintf("cannot detach from wayland on %q:", w.pair[1]))
	} else {
		fmsg.VPrintf("skipping wayland cleanup on %q", w.pair[0])
		return nil
	}
}

func (w Wayland) Is(o Op) bool {
	w0, ok := o.(Wayland)
	return ok && w.pair == w0.pair
}

func (w Wayland) Path() string {
	return w.pair[0]
}

func (w Wayland) String() string {
	return fmt.Sprintf("wayland socket at %q", w.pair[0])
}