diff options
| author | Ophestra <cat@gensokyo.uk> | 2026-10-27 20:13:13 +0900 |
|---|---|---|
| committer | Ophestra <cat@gensokyo.uk> | 2026-10-27 20:13:13 +0900 |
| commit | ea29e6bad114306b78820cb674863a9bf3041fa5 (patch) | |
| tree | da87b09d5b3b57d6744db90b697124c5d4569e8d /internal/pipewire/pipewire.go | |
| parent | 672cf9abcac6f25abfdd2541cae6455c6da38fc3 (diff) | |
internal/pipewire: re-format for readability
This package was the first somewhat large piece of code that was
primarily written using the built-in display of my laptop. The
experience had been deeply unpleasant due to the awkward 3:2 aspect
ratio not working well with my setup, which almost always involved
having the implementation and tests side-by-side. This experience is
what provoked me to re-instate the 80-column limit that I had long
resented and rejected. This package however predates the formal
re-instating of this limit, and was never updated.
Signed-off-by: Ophestra <cat@gensokyo.uk>
Diffstat (limited to 'internal/pipewire/pipewire.go')
| -rw-r--r-- | internal/pipewire/pipewire.go | 324 |
1 files changed, 212 insertions, 112 deletions
diff --git a/internal/pipewire/pipewire.go b/internal/pipewire/pipewire.go index 3b909336..9357c565 100644 --- a/internal/pipewire/pipewire.go +++ b/internal/pipewire/pipewire.go @@ -1,17 +1,25 @@ -// Package pipewire provides a partial implementation of the PipeWire protocol native. +// Package pipewire provides a partial implementation of the PipeWire protocol +// native and the SecurityContext extension. // -// This implementation is created based on black box analysis and very limited static -// analysis. The PipeWire documentation is vague and mostly nonexistent, and source code -// readability is not great due to frequent macro abuse, confusing and inconsistent naming -// schemes, almost complete absence of comments and the multiple layers of abstractions -// even internal to the library. The convoluted build system and frequent (mis)use of -// dlopen(3) further complicates static analysis efforts. +// This implementation is created based on black box analysis and very limited +// static analysis. The PipeWire documentation is vague and mostly nonexistent, +// and source code readability is not great due to frequent macro abuse, +// confusing and inconsistent naming schemes, almost complete absence of +// comments and the multiple layers of abstractions even internal to the +// library. The convoluted build system and frequent (mis)use of dlopen(3) +// further complicates static analysis efforts. // -// Because of this, extreme care must be taken when reusing any code found in this package. -// While it is extensively tested to be correct for its role within Hakurei, remember that -// work is only done against PipeWire behaviour specific to this use case, and it is nearly -// impossible to guarantee that this interpretation of its behaviour is intended, or correct -// for any other uses of the protocol. +// Because of this, extreme care must be taken when reusing any code found in +// this package. While it is extensively tested to be correct for its role +// within Hakurei, remember that work is only done against PipeWire behaviour +// specific to this use case, and it is nearly impossible to guarantee that this +// interpretation of its behaviour is intended, or correct for any other uses of +// the protocol. +// +// This package does not use the network poller. It directly utilises epoll +// in a way identical to the upstream PipeWire client implementation, validated +// via syscall tracing. This is not necessary, but aims to avoid potential +// upstream PipeWire bugs that happen to not affect their own implementation. package pipewire import ( @@ -46,9 +54,12 @@ type Conn interface { Close() error } -// The kernel constant SCM_MAX_FD defines a limit on the number of file descriptors in the array. -// Attempting to send an array larger than this limit causes sendmsg(2) to fail with the error -// EINVAL. SCM_MAX_FD has the value 253 (or 255 before Linux 2.6.38). +// The kernel constant SCM_MAX_FD defines a limit on the number of file +// descriptors in the array. +// +// Attempting to send an array larger than this limit causes sendmsg(2) to fail +// with the error EINVAL. SCM_MAX_FD has the value 253 (or 255 before Linux +// 2.6.38). const _SCM_MAX_FD = 253 // A Context holds state of a connection to PipeWire. @@ -76,7 +87,8 @@ type Context struct { // Proxy for built-in client events. client Client - // Current server-side [Header.Sequence] value, incremented on every event processed. + // Current server-side [Header.Sequence] value, incremented on every event + // processed. remoteSequence Int // Files from the server. This is discarded on every Roundtrip so eventProxy // implementations must make sure to close them to avoid leaking fds. @@ -84,8 +96,9 @@ type Context struct { // These are not automatically set up as [os.File] because it is impossible // to undo the effects of os.NewFile, which can be inconvenient for some uses. receivedFiles []int - // Non-protocol errors encountered during event handling of the current Roundtrip; - // errors that prevent event processing from continuing must be panicked. + // Non-protocol errors encountered during event handling of the current + // Roundtrip; errors that prevent event processing from continuing must be + // panicked. proxyErrors ProxyConsumeError // Pending footer value for the next outgoing message. // Newer footers appear to simply replace the existing one. @@ -95,8 +108,9 @@ type Context struct { deferredPendingFooter KnownSize // Server side registry generation number. generation Long - // Deferred operations ran after a [Core.Sync] completes or Close is called. Errors - //are reported as part of [ProxyConsumeError] and is not considered fatal unless panicked. + // Deferred operations ran after a [Core.Sync] completes or Close is called. + // Errors are reported as part of [ProxyConsumeError] and is not considered + // fatal unless panicked. syncComplete []func() error // Passed to [Conn.Recvmsg]. Not copied if sufficient for all received messages. @@ -110,7 +124,9 @@ type Context struct { // cleanup arranges for f to be called after the next [CoreDone] event // or when [Context] is closed. -func (ctx *Context) cleanup(f func() error) { ctx.syncComplete = append(ctx.syncComplete, f) } +func (ctx *Context) cleanup(f func() error) { + ctx.syncComplete = append(ctx.syncComplete, f) +} // GetCore returns the address of [Core] held by this [Context]. func (ctx *Context) GetCore() *Core { return &ctx.core } @@ -118,8 +134,11 @@ func (ctx *Context) GetCore() *Core { return &ctx.core } // GetClient returns the address of [Client] held by this [Context]. func (ctx *Context) GetClient() *Client { return &ctx.client } -// New initialises [Context] for an already established connection and returns its address. -// The caller must not call any method of the underlying [Conn] after this function returns. +// New initialises [Context] for an already established connection and returns +// its address. +// +// The caller must not call any method of the underlying [Conn] after this +// function returns. func New(conn Conn, props SPADict) (*Context, error) { ctx := Context{conn: conn} ctx.core.ctx = &ctx @@ -143,14 +162,15 @@ func New(conn Conn, props SPADict) (*Context, error) { return &ctx, nil } -// unixConn is an implementation of the [Conn] interface for connections -// to Unix domain sockets. +// unixConn is an implementation of the [Conn] interface for connections to Unix +// domain sockets. type unixConn struct { fd int // Whether creation of a new epoll instance was attempted. epoll bool // File descriptor referring to the new epoll instance. + // // Valid if epoll is true and epollErr is nil. epollFd int // Error returned by syscall.EpollCreate1. @@ -164,9 +184,15 @@ type unixConn struct { // Dial connects to a Unix domain socket described by name. func Dial(name string) (Conn, error) { - if fd, err := syscall.Socket(syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC|syscall.SOCK_NONBLOCK, 0); err != nil { + if fd, err := syscall.Socket( + syscall.AF_UNIX, syscall.SOCK_STREAM|syscall.SOCK_CLOEXEC|syscall.SOCK_NONBLOCK, + 0, + ); err != nil { return nil, os.NewSyscallError("socket", err) - } else if err = syscall.Connect(fd, &syscall.SockaddrUnix{Name: name}); err != nil { + } else if err = syscall.Connect( + fd, + &syscall.SockaddrUnix{Name: name}, + ); err != nil { _ = syscall.Close(fd) return nil, os.NewSyscallError("connect", err) } else { @@ -174,8 +200,8 @@ func Dial(name string) (Conn, error) { } } -// MightBlock informs the implementation that the next call -// might block for a non-zero timeout. +// MightBlock informs the implementation that the next call might block for a +// non-zero timeout. func (conn *unixConn) MightBlock(timeout time.Duration) { if timeout < 0 { timeout = 0 @@ -189,10 +215,15 @@ func (conn *unixConn) wantsEpoll() error { conn.epoll = true conn.epollFd, conn.epollErr = syscall.EpollCreate1(syscall.EPOLL_CLOEXEC) if conn.epollErr == nil { - if conn.epollErr = syscall.EpollCtl(conn.epollFd, syscall.EPOLL_CTL_ADD, conn.fd, &syscall.EpollEvent{ - Events: syscall.EPOLLERR | syscall.EPOLLHUP, - Fd: int32(conn.fd), - }); conn.epollErr != nil { + if conn.epollErr = syscall.EpollCtl( + conn.epollFd, + syscall.EPOLL_CTL_ADD, + conn.fd, + &syscall.EpollEvent{ + Events: syscall.EPOLLERR | syscall.EPOLLHUP, + Fd: int32(conn.fd), + }, + ); conn.epollErr != nil { _ = syscall.Close(conn.epollFd) } } @@ -209,16 +240,25 @@ func (conn *unixConn) wait(event uint32) (err error) { deadline := time.Now().Add(conn.timeout) conn.timeout = 0 - if err = syscall.EpollCtl(conn.epollFd, syscall.EPOLL_CTL_MOD, conn.fd, &syscall.EpollEvent{ - Events: event | syscall.EPOLLERR | syscall.EPOLLHUP, - Fd: int32(conn.fd), - }); err != nil { + if err = syscall.EpollCtl( + conn.epollFd, + syscall.EPOLL_CTL_MOD, + conn.fd, + &syscall.EpollEvent{ + Events: event | syscall.EPOLLERR | syscall.EPOLLHUP, + Fd: int32(conn.fd), + }, + ); err != nil { return } for timeout := deadline.Sub(time.Now()); timeout > 0; timeout = deadline.Sub(time.Now()) { var n int - if n, err = syscall.EpollWait(conn.epollFd, conn.epollBuf[:], int(timeout/time.Millisecond)); err != nil { + if n, err = syscall.EpollWait( + conn.epollFd, + conn.epollBuf[:], + int(timeout/time.Millisecond), + ); err != nil { return } @@ -245,7 +285,10 @@ func (conn *unixConn) wait(event uint32) (err error) { } // Recvmsg calls syscall.Recvmsg on the underlying socket. -func (conn *unixConn) Recvmsg(p, oob []byte, flags int) (n, oobn, recvflags int, err error) { +func (conn *unixConn) Recvmsg(p, oob []byte, flags int) ( + n, oobn, recvflags int, + err error, +) { if err = conn.wantsEpoll(); err != nil { return } else if err = conn.wait(syscall.EPOLLIN); err != nil { @@ -279,8 +322,8 @@ func (conn *unixConn) Close() (err error) { return conn.epollErr } -// MustNew calls [New](conn, props) and panics on error. -// It is intended for use in tests with hard-coded strings. +// MustNew calls [New](conn, props) and panics on error. It is intended for use +// in tests with hard-coded strings. func MustNew(conn Conn, props SPADict) *Context { if ctx, err := New(conn, props); err != nil { panic(err) @@ -292,20 +335,21 @@ func MustNew(conn Conn, props SPADict) *Context { // free releases the underlying storage of buf. func (ctx *Context) free() { ctx.buf = make([]byte, 0) } -// queueFiles queues some file descriptors to be sent for the next message. -// It returns the offset of their index for the syscall.SCM_RIGHTS message. +// queueFiles queues some file descriptors to be sent for the next message. It +// returns the offset of their index for the syscall.SCM_RIGHTS message. func (ctx *Context) queueFiles(fds ...int) (offset Fd) { offset = Fd(len(ctx.pendingFiles)) ctx.pendingFiles = append(ctx.pendingFiles, fds...) return } -// InconsistentFilesError describes an implementation error where an incorrect amount -// of files is queued between two messages. +// InconsistentFilesError describes an implementation error where an incorrect +// amount of files is queued between two messages. type InconsistentFilesError [2]Int func (e *InconsistentFilesError) Error() string { - return "queued " + strconv.Itoa(int(e[0])) + " files instead of the expected " + strconv.Itoa(int(e[1])) + return "queued " + strconv.Itoa(int(e[0])) + + " files instead of the expected " + strconv.Itoa(int(e[1])) } // writeMessage appends the POD representation of v and an optional footer to buf. @@ -318,7 +362,12 @@ func (ctx *Context) writeMessage(Id Int, v Message) (err error) { ctx.pendingFooter, ctx.deferredPendingFooter = ctx.deferredPendingFooter, nil } - ctx.buf, err = MessageEncoder{v}.AppendMessage(ctx.buf, Id, ctx.sequence, ctx.pendingFooter) + ctx.buf, err = MessageEncoder{v}.AppendMessage( + ctx.buf, + Id, + ctx.sequence, + ctx.pendingFooter, + ) if err == nil { ctx.headerFiles = len(ctx.pendingFiles) ctx.pendingFooter = nil @@ -327,8 +376,8 @@ func (ctx *Context) writeMessage(Id Int, v Message) (err error) { return } -// mustWriteMessage calls writeMessage and panics if a non-nil error is returned. -// This must only be called from eventProxy.consume. +// mustWriteMessage calls writeMessage and panics if a non-nil error is +// returned. This must only be called from eventProxy.consume. func (ctx *Context) mustWriteMessage(Id Int, v Message) { if err := ctx.writeMessage(Id, v); err != nil { panic(err) @@ -352,8 +401,8 @@ increment: return newId } -// closeReceivedFiles closes all receivedFiles. This is only during protocol error -// where [Context] is rendered unusable. +// closeReceivedFiles closes all receivedFiles. This is only during protocol +// error where [Context] is rendered unusable. func (ctx *Context) closeReceivedFiles() { slices.Sort(ctx.receivedFiles) ctx.receivedFiles = slices.Compact(ctx.receivedFiles) @@ -377,7 +426,11 @@ func (ctx *Context) recvmsg(remaining []byte) (payload []byte, err error) { var n, oobn, recvflags int for { - n, oobn, recvflags, err = ctx.conn.Recvmsg(ctx.iovecBuf[len(remaining):], ctx.oobBuf[:], recvmsgFlags) + n, oobn, recvflags, err = ctx.conn.Recvmsg( + ctx.iovecBuf[len(remaining):], + ctx.oobBuf[:], + recvmsgFlags, + ) if oob := ctx.oobBuf[:oobn]; len(oob) > 0 { var oobErr error @@ -412,7 +465,10 @@ func (ctx *Context) recvmsg(remaining []byte) (payload []byte, err error) { } if err != syscall.EAGAIN && err != syscall.EWOULDBLOCK { ctx.closeReceivedFiles() - return nil, &ProxyFatalError{Err: os.NewSyscallError("recvmsg", err), ProxyErrs: ctx.cloneAsProxyErrors()} + return nil, &ProxyFatalError{ + Err: os.NewSyscallError("recvmsg", err), + ProxyErrs: ctx.cloneAsProxyErrors(), + } } } @@ -449,7 +505,10 @@ func (ctx *Context) sendmsg(p []byte, fds ...int) error { } if err != nil && err != syscall.EAGAIN && err != syscall.EWOULDBLOCK { - return &ProxyFatalError{Err: os.NewSyscallError("sendmsg", err), ProxyErrs: ctx.cloneAsProxyErrors()} + return &ProxyFatalError{ + Err: os.NewSyscallError("sendmsg", err), + ProxyErrs: ctx.cloneAsProxyErrors(), + } } return err } @@ -463,7 +522,9 @@ type UnknownIdError struct { Data string } -func (e *UnknownIdError) Error() string { return "unknown proxy id " + strconv.Itoa(int(e.Id)) } +func (e *UnknownIdError) Error() string { + return "unknown proxy id " + strconv.Itoa(int(e.Id)) +} // UnsupportedOpcodeError describes a message with an unsupported opcode. type UnsupportedOpcodeError struct { @@ -484,7 +545,8 @@ func (e UnsupportedFooterOpcodeError) Error() string { return "unsupported footer opcode " + strconv.Itoa(int(e)) } -// A RoundtripUnexpectedEOFError describes an unexpected EOF encountered during [Context.Roundtrip]. +// A RoundtripUnexpectedEOFError describes an unexpected EOF encountered during +// [Context.Roundtrip]. type RoundtripUnexpectedEOFError uintptr const ( @@ -494,11 +556,11 @@ const ( // ErrRoundtripEOFBody is returned when unexpectedly encountering EOF // establishing message body bounds. ErrRoundtripEOFBody - // ErrRoundtripEOFFooter is like [ErrRoundtripEOFBody], but for when establishing - // bounds for the footer instead. + // ErrRoundtripEOFFooter is like [ErrRoundtripEOFBody], but for when + // establishing bounds for the footer instead. ErrRoundtripEOFFooter - // ErrRoundtripEOFFooterOpcode is returned when unexpectedly encountering EOF - // during the footer opcode hack. + // ErrRoundtripEOFFooterOpcode is returned when unexpectedly encountering + // EOF during the footer opcode hack. ErrRoundtripEOFFooterOpcode ) @@ -549,10 +611,10 @@ func (ctx *Context) unmarshal(header *Header, data []byte, v any) error { data = data[n:header.Size] if len(data) > 0 { - /* the footer concrete type is determined by opcode, which cannot be - decoded directly before the type is known, so this hack is required: - skip the struct prefix, then the integer prefix, and the next SizeId - bytes are the encoded opcode value */ + // the footer concrete type is determined by opcode, which cannot be + // decoded directly before the type is known, so this hack is required: + // skip the struct prefix, then the integer prefix, and the next SizeId + // bytes are the encoded opcode value if len(data) < int(SizePrefix*2+SizeId) { return ErrRoundtripEOFFooterOpcode } @@ -565,11 +627,14 @@ func (ctx *Context) unmarshal(header *Header, data []byte, v any) error { if ctx.generation != footer.Payload.RegistryGeneration { var pendingFooter = Footer[FooterClientGeneration]{ FOOTER_CORE_OPCODE_GENERATION, - FooterClientGeneration{ClientGeneration: footer.Payload.RegistryGeneration}, + FooterClientGeneration{ + ClientGeneration: footer.Payload.RegistryGeneration, + }, } - // this emulates upstream behaviour that pending footer updated on the last message - // during a roundtrip is pushed back to the first message of the next roundtrip + // this emulates upstream behaviour that pending footer updated + // on the last message during a roundtrip is pushed back to the + // first message of the next roundtrip if isLastMessage { ctx.deferredPendingFooter = &pendingFooter } else { @@ -592,38 +657,43 @@ func (ctx *Context) unmarshal(header *Header, data []byte, v any) error { // is, in fact, not the message header. type UnexpectedSequenceError Int -func (e UnexpectedSequenceError) Error() string { return "unexpected seq " + strconv.Itoa(int(e)) } +func (e UnexpectedSequenceError) Error() string { + return "unexpected seq " + strconv.Itoa(int(e)) +} -// An UnexpectedFilesError describes an inconsistent state where file count claimed by -// [Header] accumulates to a value greater than the total number of files received. +// An UnexpectedFilesError describes an inconsistent state where file count +// claimed by [Header] accumulates to a value greater than the total number of +// files received. type UnexpectedFilesError int func (e UnexpectedFilesError) Error() string { return "server message headers claim to have sent more files than actually received" } -// A DanglingFilesError holds onto files that were sent by the server but no [Header] -// accounts for. These are closed by their finalizers if discarded. +// A DanglingFilesError holds onto files that were sent by the server but no +// [Header] accounts for. These are closed by their finalizers if discarded. type DanglingFilesError []*os.File func (e DanglingFilesError) Error() string { return "received " + strconv.Itoa(len(e)) + " dangling files" } -// An UnacknowledgedProxyError holds newly allocated proxy ids that the server failed -// to acknowledge after an otherwise successful [Core.Sync]. +// An UnacknowledgedProxyError holds newly allocated proxy ids that the server +// failed to acknowledge after an otherwise successful [Core.Sync]. type UnacknowledgedProxyError []Int func (e UnacknowledgedProxyError) Error() string { - return "server did not acknowledge " + strconv.Itoa(len(e)) + " proxies" + return "server did not acknowledge " + + strconv.Itoa(len(e)) + " proxies" } -// An UnacknowledgedProxyDestructionError holds destroyed proxy ids that the server failed -// to acknowledge after an otherwise successful [Core.Sync]. +// An UnacknowledgedProxyDestructionError holds destroyed proxy ids that the +// server failed to acknowledge after an otherwise successful [Core.Sync]. type UnacknowledgedProxyDestructionError []Int func (e UnacknowledgedProxyDestructionError) Error() string { - return "server did not acknowledge " + strconv.Itoa(len(e)) + " proxy destructions" + return "server did not acknowledge " + + strconv.Itoa(len(e)) + " proxy destructions" } // A ProxyFatalError describes an error that terminates event handling during a @@ -639,14 +709,15 @@ func (e *ProxyFatalError) Unwrap() []error { return append(e.ProxyErrs, e.Err) } func (e *ProxyFatalError) Error() string { s := e.Err.Error() if len(e.ProxyErrs) > 0 { - s += "; " + strconv.Itoa(len(e.ProxyErrs)) + " additional proxy errors occurred before this point" + s += "; " + strconv.Itoa(len(e.ProxyErrs)) + + " additional proxy errors occurred before this point" } return s } -// A ProxyConsumeError is a collection of non-protocol errors returned by proxies -// during event processing. These do not prevent event handling from continuing but -// may be considered fatal to the application. +// A ProxyConsumeError is a collection of non-protocol errors returned by +// proxies during event processing. These do not prevent event handling from +// continuing but may be considered fatal to the application. type ProxyConsumeError []error func (e ProxyConsumeError) Unwrap() []error { return e } @@ -658,7 +729,8 @@ func (e ProxyConsumeError) Error() string { // first error is usually the most relevant one s := e[0].Error() if len(e) > 1 { - s += "; " + strconv.Itoa(len(e)) + " additional proxy errors occurred after this point" + s += "; " + strconv.Itoa(len(e)) + + " additional proxy errors occurred after this point" } return s } @@ -684,14 +756,15 @@ func (ctx *Context) cloneProxyErrors() (err error) { return } -// roundtripSyncID is the id passed to Context.coreSync during a [Context.Roundtrip]. +// roundtripSyncID is the id passed to Context.coreSync during a +// [Context.Roundtrip]. const roundtripSyncID = 0 // Roundtrip sends all pending messages to the server and processes events until // the server has no more messages. // -// For a non-nil error, if the error happens over the network, it has concrete type -// [os.SyscallError]. +// For a non-nil error, if the error happens over the network, it has concrete +// type [os.SyscallError]. func (ctx *Context) Roundtrip() (err error) { err = ctx.roundtrip() if err == nil { @@ -725,10 +798,12 @@ func (ctx *Context) roundtrip() (err error) { danglingFiles = make(DanglingFilesError, 0, len(ctx.receivedFiles)) for _, fd := range ctx.receivedFiles { - // hold these as *os.File so they are closed if this error never reaches the caller, - // or the caller discards or otherwise does not handle this error, to avoid leaking fds + // hold these as *os.File so they are closed if this error never + // reaches the caller, or the caller discards or otherwise does + // not handle this error, to avoid leaking fds danglingFiles = append(danglingFiles, os.NewFile(uintptr(fd), - "dangling fd "+strconv.Itoa(fd)+" received from PipeWire")) + "dangling fd "+strconv.Itoa(fd)+ + " received from PipeWire")) } ctx.receivedFiles = ctx.receivedFiles[:0] } @@ -736,7 +811,10 @@ func (ctx *Context) roundtrip() (err error) { // populated early for finalizers, but does not overwrite existing errors if len(danglingFiles) > 0 && err == nil { ctx.closeReceivedFiles() - err = &ProxyFatalError{Err: danglingFiles, ProxyErrs: ctx.cloneAsProxyErrors()} + err = &ProxyFatalError{ + Err: danglingFiles, + ProxyErrs: ctx.cloneAsProxyErrors(), + } return } }() @@ -754,9 +832,15 @@ func (ctx *Context) roundtrip() (err error) { if len(remaining) == 0 { err = nil } else if len(remaining) < SizeHeader { - err = &ProxyFatalError{Err: ErrRoundtripEOFHeader, ProxyErrs: ctx.cloneAsProxyErrors()} + err = &ProxyFatalError{ + Err: ErrRoundtripEOFHeader, + ProxyErrs: ctx.cloneAsProxyErrors(), + } } else { - err = &ProxyFatalError{Err: ErrRoundtripEOFBody, ProxyErrs: ctx.cloneAsProxyErrors()} + err = &ProxyFatalError{ + Err: ErrRoundtripEOFBody, + ProxyErrs: ctx.cloneAsProxyErrors(), + } } } return @@ -772,7 +856,10 @@ func (ctx *Context) currentSeq() Int { return ctx.sequence - 1 } func (ctx *Context) currentRemoteSeq() Int { return ctx.remoteSequence - 1 } // consume receives messages from the server and processes events. -func (ctx *Context) consume(receiveRemaining []byte) (remaining []byte, err error) { +func (ctx *Context) consume(receiveRemaining []byte) ( + remaining []byte, + err error, +) { defer func() { r := recover() if r == nil { @@ -788,7 +875,10 @@ func (ctx *Context) consume(receiveRemaining []byte) (remaining []byte, err erro panic(&runtime.PanicNilError{}) } - err = &ProxyFatalError{Err: recoveredErr, ProxyErrs: ctx.cloneAsProxyErrors()} + err = &ProxyFatalError{ + Err: recoveredErr, + ProxyErrs: ctx.cloneAsProxyErrors(), + } return }() @@ -816,7 +906,10 @@ func (ctx *Context) consume(receiveRemaining []byte) (remaining []byte, err erro proxy, ok := ctx.proxy[header.ID] if !ok { - return remaining, &UnknownIdError{header.ID, string(remaining[:SizeHeader+header.Size])} + return remaining, &UnknownIdError{ + header.ID, + string(remaining[:SizeHeader+header.Size]), + } } fileCount := int(header.FileCount) @@ -828,7 +921,11 @@ func (ctx *Context) consume(receiveRemaining []byte) (remaining []byte, err erro remaining = remaining[SizeHeader:] proxyErr := proxy.consume(header.Opcode, files, func(v any) { - if unmarshalErr := ctx.unmarshal(&header, remaining, v); unmarshalErr != nil { + if unmarshalErr := ctx.unmarshal( + &header, + remaining, + v, + ); unmarshalErr != nil { panic(unmarshalErr) } }) @@ -840,16 +937,17 @@ func (ctx *Context) consume(receiveRemaining []byte) (remaining []byte, err erro return } -// An UnexpectedFileCountError is returned as part of a [ProxyFatalError] for an event -// that received an unexpected number of files. +// An UnexpectedFileCountError is returned as part of a [ProxyFatalError] for an +// event that received an unexpected number of files. type UnexpectedFileCountError [2]int func (e *UnexpectedFileCountError) Error() string { return "received " + strconv.Itoa(e[1]) + " files instead of the expected " + strconv.Itoa(e[0]) } -// closeReceivedFiles closes all received files and panics with [UnexpectedFileCountError] -// if one or more files are passed. This is used with events that do not expect files. +// closeReceivedFiles closes all received files and panics with +// [UnexpectedFileCountError] if one or more files are passed. This is used with +// events that do not expect files. func closeReceivedFiles(fds ...int) { for _, fd := range fds { _ = syscall.Close(fd) @@ -859,8 +957,9 @@ func closeReceivedFiles(fds ...int) { } } -// doSyncComplete calls syncComplete functions and collects their errors alongside errors -// cloned from proxyErrors. A panic is translated into ProxyFatalError. +// doSyncComplete calls syncComplete functions and collects their errors +// alongside errors cloned from proxyErrors. A panic is translated into +// ProxyFatalError. func (ctx *Context) doSyncComplete() (err error) { proxyErrors := ctx.cloneAsProxyErrors() defer func() { @@ -914,17 +1013,17 @@ func (ctx *Context) Close() (err error) { } } -// expectsCoreError returns a function that inspects an error value and -// returns the address of a [CoreError] if it is the only error present -// and targets the specified proxy and sequence. +// expectsCoreError returns a function that inspects an error value and returns +// the address of a [CoreError] if it is the only error present and targets the +// specified proxy and sequence. // -// The behaviour of expectsCoreError is only correct for an empty buf -// prior to calling. If buf is not empty, [Core.Sync] is called, with -// its return value stored to the value pointed to by errP if not nil, -// and the function is not populated. +// The behaviour of expectsCoreError is only correct for an empty buf prior to +// calling. If buf is not empty, [Core.Sync] is called, with its return value +// stored to the value pointed to by errP if not nil, and the function is not +// populated. // -// The caller must queue a message and call [Core.Sync] immediately -// after calling expectsCoreError. +// The caller must queue a message and call [Core.Sync] immediately after +// calling expectsCoreError. func (ctx *Context) expectsCoreError(id Int, errP *error) (asCoreError func() (coreError *CoreError)) { if len(ctx.buf) > 0 { if err := ctx.GetCore().Sync(); err != nil { @@ -967,7 +1066,8 @@ const Remote = "PIPEWIRE_REMOTE" const DEFAULT_SYSTEM_RUNTIME_DIR = "/run/pipewire" -// connectName connects to a PipeWire remote by name and returns the resulting [Conn]. +// connectName connects to a PipeWire remote by name and returns the resulting +// [Conn]. func connectName(name string, manager bool) (conn Conn, err error) { if manager && !strings.HasSuffix(name, "-manager") { return connectName(name+"-manager", false) |
