System services
pipewire
pipewire is a ScreenCast video producer: a client-node exported over PipeWire's native protocol, in Go, without libpipewire. The producer drives its own graph; a cycle runs when the source has a frame, stamped with header, transform and damage metas.
package main
import (
"log"
"github.com/stubbedev/lys/lib/pipewire"
)
type gray struct{}
func (gray) Fill(dst []byte) ([]pipewire.Rect, bool) {
for i := range dst {
dst[i] = 0x80
}
return nil, true
}
func main() {
p, err := pipewire.Start(pipewire.Config{
Application: "example",
Name: "example-screen",
Width: 640,
Height: 480,
Stride: 640 * 4,
Format: pipewire.VideoBGRx,
FPS: 30,
Source: gray{},
})
if err != nil {
log.Fatal(err)
}
defer p.Close()
log.Printf("node %d", p.NodeID())
<-p.Done()
if err := p.Err(); err != nil {
log.Fatal(err)
}
}Start returns once the server registered the node, so a consumer can link to NodeID.
Config:
| Field | Effect |
|---|---|
Application | Client application.name. Required |
Name | Node name consumers link to. Required |
Width, Height, Stride, Format | Frame geometry and VideoFormat |
FPS | Maximum frame rate, advertised and paced; frames go out when the source has one. Required |
Transform | Constant spa_meta_videotransform value (the output's transform; 0 for a window) |
Source | Fills frames |
Cursor | Optional; carries the pointer as SPA_META_Cursor metadata instead of in the frame |
A Source.Fill copies one frame and returns the damage (nil is the whole frame); returning false skips the cycle. Optional interfaces:
| Interface | Effect |
|---|---|
DmabufSource | Fills GPU buffers in place. Its modifier's format is offered first; consumers of the plain format get shared memory through Fill |
DmabufPreparer | Starts filling the next cycle's dmabuf early (PrepareDmabuf) |
FrameNotifier | Signals when a GPU frame is ready instead of being polled |
Resizable | Frames change size; the producer renegotiates and holds frames until the consumer follows |
Restarter | Told when the consumer's buffers are replaced, so the next fill produces a frame |
eis
eis is an EIS server, the receiving end of libei. A portal's ConnectToEIS hands the app one end of a socket pair.
Pairmakes the pair, serves aHandleron one end and returns the client's end.Serveruns on an existing connection.- Both advertise a named seat with a pointer and a keyboard, plus an absolute pointer and a touchscreen over the given
Regions, and replay emulated input onto theHandler. NewReceiverserves a libei receiver context instead: the client binds a keyboard and pointer, and the caller emulates input on them.
dbusx
dbusx is shared D-Bus plumbing on the patched godbus. Import that copy, not upstream: dbusx takes its Conn.
package main
import (
"log"
dbus "github.com/stubbedev/lys/lib/third_party/godbus"
"github.com/stubbedev/lys/lib/dbusx"
)
type greeter struct{}
func (greeter) Hello(name string) (string, *dbus.Error) {
if name == "" {
return "", dbusx.InvalidArgs("name is empty")
}
return "hello " + name, nil
}
func main() {
conn, err := dbus.ConnectSessionBus()
if err != nil {
log.Fatal(err)
}
defer conn.Close()
release, err := dbusx.Serve(conn, dbusx.Service{
Name: "org.example.Greeter",
Path: "/org/example/Greeter",
Interface: "org.example.Greeter",
Methods: greeter{},
Properties: dbusx.Getters{
"Version": func() any { return uint32(1) },
},
})
if err != nil {
log.Fatal(err)
}
defer release()
select {}
}| Need | Use |
|---|---|
| One interface under a well-known name | Serve with a Service |
| Several interfaces at one path, all or nothing | Export with Interfaces |
| A well-known name alone | Own; ErrNameTaken if owned |
| Computed and writable properties | Getters, Setters |
| A signal declared once | NewSignal; Signal[T] declares, emits and decodes it |
| A signal whose arguments are not read | NewSignal with a T without fields: it decodes whatever the signal carries |
| Methods run one at a time in arrival order | Interface.Ordered |
| Following a service that starts or restarts | WatchOwner, NameOwner |
| One peer's signals, decoded | WatchSignals with an On route per signal, from FromOwner(name) or FromBus() |
| That peer's name changing owner, in order with its signals | an OnOwnerChange route in the same watch |
| Every name changing owner, or those in a namespace | OnNameOwnerChanged, narrowed by WithArg0 or WithArg0Namespace |
| A name losing its owner: a peer leaving the bus | OnNameLost |
| A signal from every object in a path namespace | OnUnder |
| An object's properties changing, an object manager's objects coming and going | PropertiesChanged, InterfacesAdded, InterfacesRemoved |
| Every other signal of an interface, to fail on what a contract does not define | an OnOthers route, listed last |
| A signal channel of your own, taken off the connection | RemoveSignal: it closes the descriptors of what nobody read |
| Proving a descriptor sent over the bus was closed by everyone it reached | dbustest.NewPipe, Pipe.RequireEveryCopyClosed |
| Ordering a signal against a call's reply | the dbus.Sequence every On handler and WatchOwner's appeared get, against dbus.Call.ResponseSequence |
| The system or session bus, without hanging on a silent one | DialSystem, DialSession with a timeout |
A D-Bus method is an exported method whose last result is *dbus.Error; Failed and InvalidArgs build common errors. Introspection is generated on demand.
A Signal[T] decodes a body that starts with its arguments: a missing or mistyped one is an error, and arguments after them are not read, since an interface grows by appending arguments and a daemon may send more than an older client, or its own introspection data, declares (polkitd 126's Changed gained one). A T without fields therefore decodes any body. A package-level NewSignal runs no code at import; its T is read on first use, which is where a T that is no struct panics.
WatchSignals runs each route's handler in arrival order on one goroutine and tells failed of a signal that does not decode. It takes signals only from its sender; one from any other peer is dropped. FromOwner(name) is whoever owns the well-known name as each signal arrives: the watch follows the name from owner to owner, so a service that restarts keeps being heard, and it starts while nobody owns the name yet, as before a bus-activated service's first call. A signal carrying descriptors reaches every watch of a connection with duplicates of its own, so several watches may route the same signal: the handler that gets it owns them, and the watch closes those of every signal no handler gets and of the signals still unread when it ends (dbus.Signal.CloseFDs, on the patched godbus). The watch holds one match rule for the routes of each interface of each object, narrowed to the member when they are of one signal and to the first argument when they all name the same one, and removes them when its context ends, Watch.Stop is called, or the connection closes (ErrDisconnected). Route.WithArg0 narrows a route to one first argument, as for PropertiesChanged of one interface, and Route.WithArg0Namespace to a first argument in a namespace, as the match rule's arg0namespace says: org.mpris.MediaPlayer2 takes org.mpris.MediaPlayer2.vlc, not org.mpris.MediaPlayer2x. OnUnder(s, namespace, …) is On for the object at namespace and every object below it (path_namespace), its handler told which object sent the signal. ObjectManagerInterface's InterfacesAdded (AddedInterfaces) and InterfacesRemoved (RemovedInterfaces) are declared beside PropertiesChanged, so an object manager's client routes them with On. A PropertiesChanged or InterfacesAdded handler only borrows the values it is handed: the descriptors among them are closed once it returns, whether it read them or not, so a handler that keeps one duplicates it. OnOwnerChange(name, …) is the bus's announcement that a name changed owner, taken from the bus whoever the watch's sender is: a watch following FromOwner(name) learns there, between the old owner's signals and the new one's, that the owner came, went or was replaced. OnNameOwnerChanged is that announcement for every name, an OwnerChange each, and OnNameLost only a name left without an owner: a released well-known name or a peer that left the bus. OnOthers(iface, path, …) takes every signal of an interface that no route before it does, undecoded. Dispatch is the watch without the bus: it routes one signal, for a caller that reads its own signal channel, and closes the descriptors of a signal it hands to no handler. Such a caller takes its channel off the connection with RemoveSignal, which closes the descriptors of the signals still unread on it.
pulse/native
pulse/native is a pure-Go client for PulseAudio's native protocol, served by PulseAudio and by pipewire-pulse: server, card, sink and source introspection, volume and mute, subscriptions, record streams, the sample cache, and playback streams. A playback Write blocks until the server asks for audio, never allocates, and Cork pauses it; each stream gets its own sync group. Close returns once the connection's reader and event goroutines have ended, an OnSubscribe handler still running included; requests fail with ErrClosed from the moment it starts, so a handler querying the connection returns promptly. Called from an OnSubscribe or record data handler, Close does not wait for the goroutine it runs on.
pulse/pulsetest is a fake server speaking the same protocol. Like a real one it drops a client's record and playback streams when the client disconnects: they leave the stream listings and subscribers are told of the removals.
logind
logind is the one client for org.freedesktop.login1. Every call is bounded by the caller's context and by CallTimeout, and its error names the method and the object. Dial, which connects to the system bus, is bounded the same way.
| Need | Use |
|---|---|
| The caller's session | NewManager(conn).GetSession(ctx, logind.AutoSession) |
| The session of a process | Manager.GetSessionByPID |
| Suspend, reboot, power off | Manager.Power with a PowerAction |
| Delay or block sleep, idle, shutdown, lid | Manager.Inhibit with an InhibitWhat set and an InhibitMode |
| Lock state | Session.Lock, LockedHint, SetLockedHint, WaitLocked, which fails on a property change it cannot read rather than wait on |
| Device access for a compositor | Session.TakeControl, TakeDevice, PauseDeviceComplete, ReleaseDevice |
| Backlight through logind | Session.SetBrightness |
| Sleep, lock, device and property signals | Session.Watch, which takes signals only from logind's owner, across a restart of logind; each watch owns the descriptor of a device it is told resumed |
logind/logindtest is a fake logind on a private bus that records every call. The methods that have it announce something (SetLockedHint, Lock, PrepareForSleep, …) report a failure with t.Errorf and return false, so they are safe on any goroutine of the test, an OnLock hook included; the fake waits for hooks still running before its connection closes. AnnounceProperty sends a PropertiesChanged carrying any value, for what a client must refuse.
polkit
polkit is the one client for polkitd's Authority (org.freedesktop.PolicyKit1). Every call but CheckAuthorization is bounded by the caller's context and by CallTimeout; a check may wait for a person to authenticate, so its context alone bounds it. Errors name the action and the subject.
func mayApply(ctx context.Context, conn *net.UnixConn) (polkit.Verdict, error) {
pidfd, err := peercred.PIDFDOf(conn)
if err != nil {
return 0, err
}
defer pidfd.Close()
subject, err := polkit.ProcessOfPIDFD(pidfd)
if err != nil {
return 0, err
}
system, err := polkit.Dial(ctx)
if err != nil {
return 0, err
}
defer system.Close()
r, err := polkit.NewAuthority(system).CheckAuthorization(ctx, subject, "org.example.apply", polkit.AllowUserInteraction)
return r.Verdict(), err
}| Need | Use |
|---|---|
| The subject for a socket peer | ProcessOfPIDFD with its peercred.PIDFD; ProcessOf with its peercred.Credentials where the kernel has no SO_PEERPIDFD |
| The subject for a logind session | UnixSession |
| Whether a subject may do something | Authority.CheckAuthorization, then AuthorizationResult.Verdict: Authorized, Denied, Dismissed or Challenge |
| An authentication agent's registration | Authority.RegisterAuthenticationAgent, UnregisterAuthenticationAgent, with AgentInterface |
| The registered actions | Authority.EnumerateActions |
| Retained authorizations | Authority.EnumerateTemporaryAuthorizations, RevokeTemporaryAuthorizations, RevokeTemporaryAuthorizationByID |
polkitd's Changed signal, with or without the argument polkitd 126 added | Changed, ChangedMatch |
A UnixProcess always carries pid, start time and uid; with a pidfd, polkit 124 and later decide about that very process, and an older polkitd ignores it. ProcessOfPIDFD reads the start time and then checks that the process is still running, so the start time cannot be a later process's with the same pid. When a check's context ends first, the check is cancelled at polkitd (CancelCheckAuthorization), which takes the dialog down.
polkit/polkittest is a fake Authority: it answers checks with the result the test sets, or holds them until they are cancelled, and records registrations, checks (with the process a pidfd names) and cancels. It sends Changed as polkitd 127 does, with one uint16; EmitChangedAs(ChangedBare) sends it as polkitd up to 125 did, without arguments.
busauth
busauth is how a service on the system bus names who calls it and asks polkit whether they may. Run reads the caller's credentials from the bus (GetConnectionCredentials) and runs the call for that Caller; Polkit is the Authorizer that checks an action for it, letting it authenticate; Reply answers a polkit refusal with the service's own not-authorized error and any other failure with Failed, and Answer is all three within AuthTimeout. lys-power and lys-users use it.
Where the bus offers the caller's ProcessFD (dbus-broker, dbus-daemon 1.15 and later), polkit is told about the caller by that pidfd, so polkit 124 and later decide about that very process; it is closed when the call returns. Where the bus offers none, the caller is named by its pid and start time. Errors say which of the two was used.
portaldialogs
portaldialogs is the dev.stubbe.lys.PortalDialogs1 contract: native dialogs lys-shell shows for the desktop-portal backend (Access, Account, AppChooser, DynamicLauncher, GlobalShortcuts, Usb, Wallpaper preview), plus the password prompt and administrator authentication.
| Type | Role |
|---|---|
Host | Implemented by a shell; each call blocks until the user answers or the request is dismissed |
Daemon | Serves a Host: NewDaemon, then Export |
Client | Calls the service, bounded only by its ctx; WatchAuthentication follows an authentication through a dbusx watch: it hears only the host owning the name, fails when that host loses the name or signals what the contract does not define, and leaves the connection's match rules as they were |
Emitter | Sends the authentication signals |
Caller, Choice | The request context every dialog receives |
wmipc
wmipc is the wire contract of lys-wm's IPC socket: the socket variable, request and event names, and the small types both sides share. Output, Workspace and Window are the views clients decode, a subset of what the compositor sends. lys-wm's tests hold those views to its own JSON.
pam
pam binds libpam through purego.
Start(service, user, confdir, converse)opens aTxn.confdir, if set, reads the service from that directory (pam_start_confdir) instead of/etc/pam.d.- A
Conversefunction answers each batch ofMessages withReplys or a PAM error code. TxnwrapsAuthenticate,AcctMgmt,Chauthtok,Setcred,OpenSession,CloseSession,Putenv,Getenvlist,StrerrorandEnd.Authtokreturns a copy ofPAM_AUTHTOK.CheckLibraryreports whether libpam and libc load.
userdb
userdb resolves users and groups through systemd's io.systemd.UserDatabase Varlink interface on the multiplexer socket (SocketPath, /run/systemd/userdb/io.systemd.Multiplexer), so every source systemd-userdbd knows answers: the NSS bridge (and with it every nsswitch.conf source), drop-in records and systemd-homed. It speaks Varlink in pure Go.
Dial(ctx, path)opens aConn;UserByName,UserByUID,GroupByNameandMemberships(the groups besides the primary one, in the database's order) are its calls, andLookupUIDis one lookup on a connection of its own.- Every call is bounded by
CallTimeout(10 seconds) whatever the caller's context allows, and a reply is at mostMaxMessagebytes. - A missing socket is an error naming it, never a fallback to
/etc/passwd. A Varlink error carries its name, soerrors.Is(err, userdb.NoRecordFound)tells an unknown user from a failed call. userdbtestserves a fake database on a socket of the test's own.
shacrypt
shacrypt is SHA-512 crypt(3), the $6$ hash /etc/shadow takes, in pure Go and held to the reference vectors of Ulrich Drepper's specification.
Hash(password)hashes withNewSetting(): a 16-character salt fromcrypto/randand the default 5000 rounds.ParseSettingreads$6$, an optionalrounds=N$(clamped to 1000–999999999, as glibc does) and the salt, cut at 16 characters, from a setting or a stored hash. Anything else isErrPrefix,ErrRoundsorErrSalt.Setting.Hashhashes with that setting;Verifychecks a password against a stored hash in constant time.CheckHashaccepts only a whole hash asSetting.Hashwrites it, so a value written to/etc/shadowcannot carry another field or line; anything else is one of the setting's errors orErrDigest, and never quoted.
appearance, portalsettings
appearance holds the color scheme, accent and contrast as values. portalsettings.Monitor follows them, the icon theme and the fonts over the xdg-desktop-portal Settings interface. Without a session bus every value reads unknown. Bus and portal restarts reconnect with backoff. Only the owner of the portal's name is heard (a dbusx watch), so another peer's SettingChanged changes nothing, and a monitor on a shared connection (NewOn) removes its match rules when closed.
icons, icontheme
icons is the freedesktop icon theme spec in pure Go: index.theme inheritance, directory lookup with hicolor fallback, a raster cache per name, size and scale, and bundled Lucide icons as the last tier. A cache's first lookup lists every directory of the theme chain, sixteen at a time, since a slow mount answers them in parallel; later lookups list nothing until a reset. icontheme is its narrow form for programs that only rasterize named icons, such as a compositor.
i18n
i18n reads GNU .mo and .po catalogs with plural forms and message contexts, and resolves locales from the environment.
glibclocale
glibclocale reads glibc's compiled locale data, the locale-archive and per-locale LC_* directories, without libc. System(env) searches where glibc does (LOCPATH, NixOS's LOCALE_ARCHIVE, /usr/lib/locale); List replaces locale -a, and Numeric, Monetary and Time decode a locale's categories, with Time.Format covering the strftime conversions glibc's own formats use. A missing locale or category is an error naming where it looked, never C. musl has no compiled data, so only C and POSIX exist there. glibclocaletest holds real localedef output for tests.
Small helpers
| Package | Purpose |
|---|---|
clib | Open dlopens the first loadable candidate, joining all failures. SystemCandidates lists a soname's usual paths, including the NixOS system profile. GoString copies a C string |
intconv | Integer conversion without silent wraparound: Exact errors, Must panics, Clamp saturates, Duration scales a count. Uint32Bits, Uint64Bits, Int32Bits, Int64Bits reinterpret two's-complement bits |
atomicfile | Write, WriteFile, WriteSeekable replace a file whole: synced temporary, then rename. WriteFileDurable also syncs the directory. WriteFileOwned is a durable write that gives the replacement the owner, group, mode and SELinux label OwnershipOf read from an open file, as root replaces /etc/shadow |
fileuri | Path decodes a local file URI (file:/p, file:///p, file://localhost/p; a remote host is no local path), PathOf takes a file URI or a plain path, FromPath writes a path's URI as glib does, and Encode, Decode and DecodeString percent-encode, keeping a stray % |
assetfile | Open opens an asset without blocking and rejects anything but a regular file within a size limit; Read reads one whole and Map maps one read-only, as fonts are |
xdg | Env resolves base directories (ConfigHome, StateDir, …), an app's directory under each, the system directories (DataDirs, ConfigDirs), the search paths files are looked up along (DataSearchPath, ConfigSearchPath: the home directory, then the system ones, relative entries ignored), and user-dirs.dirs via UserDir. xdg.OS reads the process environment |
peercred | Who is at a Unix socket's other end: Of reads its Credentials (uid, gid, pid, from SO_PEERCRED), PIDFDOf opens a PIDFD of that process (SO_PEERPIDFD), which keeps naming it after its pid is reused and tells whether it has Exited; OfFD and PIDFDOfFD do the same for a raw connected socket descriptor. Adopt takes over a pidfd handed over by other means, such as a bus's ProcessFD. A kernel before Linux 6.5 has none: ErrNoPIDFD |
procstat | A process's /proc/<pid>/stat: Of(pid) and Read(path) return its command name, state, CPU ticks (user plus system) and start time, parsing the command name by its last ) so a name holding one stays whole |
debug | Log traces only in builds with the lysdebug tag; otherwise it compiles out with its arguments. LYS_DEBUG selects categories: unset, empty or * for all, a comma-separated list for those, -name to exclude one |
logutil | The injectable *slog.Logger the libraries emit through; a discarding sink, made when first asked for, until Set |
wallclock | SystemClock is the time a clock on screen shows: Now in the zone set now, which it follows through changes to the zone file (LocaltimePath) unless TZ is set, and Arm, which runs a callback at a wall-clock time, or at once when the clock is set or the zone changes |
testbuild | Race, AllocBudgetsHold, SkipAllocBudget and GoroutineID, for tests that depend on how the binary was built or which goroutine runs; RequireNoInit fails the test of a package that runs code when imported (an init function, or a package-level variable the compiler cannot lay out statically), read from the test binary's own init trace; Allocated, AllocatedAfter and Mallocs count what a function allocates (objects and bytes) on one P after waiting goroutines ran, AllocatedAfter running the caller's warm-up uncounted on that same P so per-P caches start warm; measurements take turns. Allocation gates go through these: a lint rule refuses reading MemStats allocation counters in tests |