aboutsummaryrefslogtreecommitdiffhomepage
path: root/internal/pipewire/securitycontext.go
blob: ec19a64a6b50a31bc1da65e391c684fe82d8ae71 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
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 }