Documentation
¶
Overview ¶
Package zerobus is a small D-Bus client that does not allocate in steady state. It speaks the D-Bus wire protocol over a Unix socket and decodes messages in place, so strings and arrays point into the receive buffer and stay valid only until the next read.
DialContext, SessionBusContext and SystemBusContext bound socket connection, authentication and Hello with a context. Cancellation does not affect a successfully returned Conn. Dial, SessionBus and SystemBus use a background context and impose no setup timeout.
Concurrent clients ¶
Dispatcher owns a Conn and runs one reader goroutine for concurrent, context-cancellable Call, asynchronous Go, and bounded Subscribe streams. NewCall or NewSignal locks the encoder: follow it with Call, Go or Send on the same goroutine, with no intervening Dispatcher methods. Delivered Msgs own their storage and remain valid across reads. Close each Msg to release untaken descriptors; abandoning a Pending with a delivered reply can leak descriptors. Signals never carry descriptors. A warm successful Call costs four allocations, while unwanted messages are not detached.
Match.Sender must be empty or a unique name starting with ':'. Resolve well-known names with org.freedesktop.DBus.GetNameOwner and pass the unique name; local sender filtering isolates overlapping subscriptions. Subscribe checks cancellation before AddMatch and, if cancellation races its reply, attempts RemoveMatch with a fresh one-second context before returning.
Clients and servers ¶
A Conn has one encoder and one receive buffer. A client may block in Call, which sends a method call and waits for its reply, and may set Handle to see the messages that arrive meanwhile.
A server loop uses only Send and ReadMessage, never Call or Handle. It answers a method call with NewReply or NewError, emits NewSignal or the directed NewSignalTo, and sends its own requests with NewMethodCall, which returns the serial. The reply comes back later through ReadMessage as a message whose ReplySerial is that serial. Decode a message completely before the next Send is built and the next read: both reuse the same buffers.
Unix file descriptors ¶
On Linux, UnixFDs reports negotiated descriptor support. Encoder.UnixFD borrows an outgoing descriptor until Send or Call returns. Message.TakeFD takes ownership of a received descriptor indexed by Reader.UnixFD; the caller must close it. Untaken descriptors are closed on the next read, Call or Close. Other platforms do not negotiate descriptor support.
Polling ¶
A loop that also waits for other descriptors gets the socket from SyscallConn and waits for it to be readable. ReadMessage reads all the bytes available, so call it while Buffered reports true before waiting again. After the descriptor turns readable, ReadMessage may still block for the rest of a message that has only partly arrived.
Index ¶
- Constants
- Variables
- type ArrayMark
- type Conn
- func (c *Conn) AddMatch(rule string) error
- func (c *Conn) Buffered() bool
- func (c *Conn) Call() (*Message, error)
- func (c *Conn) Close() error
- func (c *Conn) NewCall(dest, path, iface, member, sig string) *Encoder
- func (c *Conn) NewError(m *Message, name, sig string) *Encoder
- func (c *Conn) NewMethodCall(dest, path, iface, member, sig string) (*Encoder, uint32)
- func (c *Conn) NewReply(m *Message, sig string) *Encoder
- func (c *Conn) NewSignal(path, iface, member, sig string) *Encoder
- func (c *Conn) NewSignalTo(dest, path, iface, member, sig string) *Encoder
- func (c *Conn) ReadMessage() (*Message, error)
- func (c *Conn) RemoveMatch(rule string) error
- func (c *Conn) RequestName(name string, flags uint32) (uint32, error)
- func (c *Conn) Send() (uint32, error)
- func (c *Conn) SyscallConn() (syscall.RawConn, error)
- func (c *Conn) UniqueName() string
- func (c *Conn) UnixFDs() bool
- type Dispatcher
- func (d *Dispatcher) Call(ctx context.Context) (*Msg, error)
- func (d *Dispatcher) Close() error
- func (d *Dispatcher) Done() <-chan struct{}
- func (d *Dispatcher) Err() error
- func (d *Dispatcher) Go() (*Pending, error)
- func (d *Dispatcher) NewCall(dest, path, iface, member, sig string) *Encoder
- func (d *Dispatcher) NewSignal(path, iface, member, sig string) *Encoder
- func (d *Dispatcher) Send() (uint32, error)
- func (d *Dispatcher) Subscribe(ctx context.Context, m Match, buf int) (*Subscription, error)
- func (d *Dispatcher) UniqueName() string
- func (d *Dispatcher) UnixFDs() bool
- type Encoder
- func (e *Encoder) BeginArray(elem byte) ArrayMark
- func (e *Encoder) Bool(v bool)
- func (e *Encoder) Byte(v byte)
- func (e *Encoder) ByteArray(b []byte)
- func (e *Encoder) EndArray(a ArrayMark)
- func (e *Encoder) Float64(v float64)
- func (e *Encoder) Int16(v int16)
- func (e *Encoder) Int32(v int32)
- func (e *Encoder) Int64(v int64)
- func (e *Encoder) ObjectPath(p string)
- func (e *Encoder) SetFlags(f Flags)
- func (e *Encoder) Signature(sig string)
- func (e *Encoder) Str(s string)
- func (e *Encoder) Struct()
- func (e *Encoder) Uint16(v uint16)
- func (e *Encoder) Uint32(v uint32)
- func (e *Encoder) Uint64(v uint64)
- func (e *Encoder) UnixFD(fd int)
- func (e *Encoder) Variant(sig string)
- type Error
- type Flags
- type Match
- type Message
- type Msg
- type Pending
- type Reader
- func (r *Reader) Array(elem byte) int
- func (r *Reader) Bool() bool
- func (r *Reader) Byte() byte
- func (r *Reader) ByteArray() []byte
- func (r *Reader) Done() bool
- func (r *Reader) Err() error
- func (r *Reader) Float64() float64
- func (r *Reader) Int16() int16
- func (r *Reader) Int32() int32
- func (r *Reader) Int64() int64
- func (r *Reader) More(end int) bool
- func (r *Reader) ObjectPath() string
- func (r *Reader) Signature() string
- func (r *Reader) Skip(sig string)
- func (r *Reader) SkipTo(end int)
- func (r *Reader) Str() string
- func (r *Reader) Struct()
- func (r *Reader) Uint16() uint16
- func (r *Reader) Uint32() uint32
- func (r *Reader) Uint64() uint64
- func (r *Reader) UnixFD() uint32
- func (r *Reader) Variant() string
- type Subscription
- type Type
Constants ¶
const ( NamePrimaryOwner = 1 NameInQueue = 2 NameExists = 3 NameAlreadyOwner = 4 )
Reply codes of RequestName.
const ( NameFlagAllowReplacement = 0x1 NameFlagReplaceExisting = 0x2 NameFlagDoNotQueue = 0x4 )
Flags of RequestName.
Variables ¶
var ( // ErrClosed reports a read or send on a closed or broken connection. ErrClosed = errors.New("zerobus: connection closed") // ErrNested reports a Call or ReadMessage made from inside Conn.Handle. ErrNested = errors.New("zerobus: Call or ReadMessage inside Handle") )
var ( // ErrMalformed reports bytes that do not follow the D-Bus wire format. ErrMalformed = errors.New("zerobus: malformed message") // ErrTooLarge reports a message or array over the D-Bus size limits. ErrTooLarge = errors.New("zerobus: message too large") // ErrInvalid reports an outgoing value D-Bus does not allow, such as a // string with a NUL byte or a body that does not match its signature. ErrInvalid = errors.New("zerobus: invalid value") )
Functions ¶
This section is empty.
Types ¶
type ArrayMark ¶
type ArrayMark struct {
// contains filtered or unexported fields
}
ArrayMark is an array being written; pass it to EndArray.
type Conn ¶
type Conn struct {
// Handle receives the messages that arrive while Call waits for its
// reply. It may be nil; those messages are then dropped.
//
// Handle may answer or emit messages with NewReply, NewError,
// NewSignal and Send. It may not wait: Call and ReadMessage return
// ErrNested inside it.
Handle func(*Message)
// contains filtered or unexported fields
}
Conn is a connection to a message bus.
A Conn is not safe for concurrent use: read and send from one goroutine, usually an event loop around ReadMessage. Close may be called from any goroutine to stop a blocked read.
func Dial ¶
Dial connects to a bus address such as "unix:path=/run/user/1000/bus", authenticates, and registers with the bus. Only unix:path and unix:abstract addresses are supported; with several addresses separated by ';', the first that connects is used.
func DialContext ¶
DialContext is Dial with cancellation covering connect, authentication (including descriptor negotiation), and Hello. The context does not affect the returned Conn.
func SessionBus ¶
SessionBus connects to the session bus named by DBUS_SESSION_BUS_ADDRESS, or $XDG_RUNTIME_DIR/bus when it is not set.
func SessionBusContext ¶
SessionBusContext is SessionBus with cancellation covering connect, auth and Hello.
func SystemBus ¶
SystemBus connects to the system bus named by DBUS_SYSTEM_BUS_ADDRESS, or the standard socket when it is not set.
func SystemBusContext ¶
SystemBusContext is SystemBus with cancellation covering connect, auth and Hello.
func (*Conn) AddMatch ¶
AddMatch asks the bus to send this connection the messages that match rule, such as "type='signal',interface='org.kde.StatusNotifierItem'".
func (*Conn) Buffered ¶
Buffered reports whether ReadMessage can return without waiting for the socket: a complete message, or a sticky error, is already in the receive buffer. A poll loop must call ReadMessage until Buffered is false before it waits on the descriptor again, because ReadMessage reads everything the socket has and a later poll would not see those bytes.
func (*Conn) Call ¶
Call sends the method call being built and waits for its reply. Messages that arrive meanwhile go to Handle. An error reply returns an *Error. A call flagged FlagNoReplyExpected gets no reply: send it with Send.
The reply is valid until the next read, like ReadMessage's.
func (*Conn) Close ¶
Close closes the connection. A blocked ReadMessage returns ErrClosed.
func (*Conn) NewCall ¶
NewCall starts a method call and returns the encoder for its body, which must match sig. Send it with Send or Call. Empty dest and iface are left out of the header.
The connection has one encoder: send a message before starting another.
func (*Conn) NewError ¶
NewError starts an error reply to the method call m. Write a message string as the body when sig is "s".
func (*Conn) NewMethodCall ¶
NewMethodCall starts a method call like NewCall and also returns its serial. A loop that only uses Send and ReadMessage keeps the serial to recognize the reply later, as Message.ReplySerial, without blocking in Call. The serial is the one Send returns for this message.
func (*Conn) NewReply ¶
NewReply starts the reply to the method call m and returns the encoder for its body.
func (*Conn) NewSignal ¶
NewSignal starts a signal and returns the encoder for its body.
func (*Conn) NewSignalTo ¶
NewSignalTo starts a signal addressed to the single peer dest, a unique name such as ":1.42" or a well-known name, and returns the encoder for its body. Only dest receives it, whatever match rules other peers have. An empty dest makes Send fail: use NewSignal to broadcast.
func (*Conn) ReadMessage ¶
ReadMessage blocks until the next message arrives. The message and its strings are valid until the next call to ReadMessage or Call.
func (*Conn) RemoveMatch ¶
RemoveMatch removes a rule added by AddMatch.
func (*Conn) RequestName ¶
RequestName asks the bus for a well-known name and returns its reply code, such as NamePrimaryOwner.
func (*Conn) Send ¶
Send sends the message built since the last NewCall, NewSignal, NewReply or NewError and returns its serial.
func (*Conn) SyscallConn ¶
SyscallConn returns the raw socket of the connection, for a poll loop that waits for it to become readable together with other file descriptors. Only wait on the descriptor: read, write and close through the Conn.
Bytes already read from the socket are not visible to poll: check Buffered before waiting. After the descriptor turns readable, ReadMessage may still block until the rest of a partially received message arrives.
func (*Conn) UniqueName ¶
UniqueName returns the name the bus gave this connection, such as ":1.42".
type Dispatcher ¶ added in v0.6.0
type Dispatcher struct {
// contains filtered or unexported fields
}
Dispatcher owns a Conn and provides concurrent calls and bounded signal streams using one reader goroutine. Do not use the Conn after handing it off. A NewCall/NewSignal and its following Call/Go/Send form one critical section: they must run on the same goroutine, with no intervening Dispatcher methods.
func DialDispatcher ¶ added in v0.6.0
func DialDispatcher(ctx context.Context, address string) (*Dispatcher, error)
DialDispatcher connects and starts a dispatcher.
func NewDispatcher ¶ added in v0.6.0
func NewDispatcher(c *Conn) *Dispatcher
NewDispatcher takes ownership of c and starts its reader. c.Handle must be nil.
func SessionBusDispatcher ¶ added in v0.6.0
func SessionBusDispatcher(ctx context.Context) (*Dispatcher, error)
SessionBusDispatcher connects to the session bus and starts a dispatcher.
func SystemBusDispatcher ¶ added in v0.6.0
func SystemBusDispatcher(ctx context.Context) (*Dispatcher, error)
SystemBusDispatcher connects to the system bus and starts a dispatcher.
func (*Dispatcher) Call ¶ added in v0.6.0
func (d *Dispatcher) Call(ctx context.Context) (*Msg, error)
Call sends and waits. Cancellation always returns ctx.Err(), never a reply.
func (*Dispatcher) Close ¶ added in v0.6.0
func (d *Dispatcher) Close() error
Close closes the connection and waits for the reader. It is idempotent.
func (*Dispatcher) Done ¶ added in v0.6.0
func (d *Dispatcher) Done() <-chan struct{}
Done closes when the reader exits.
func (*Dispatcher) Err ¶ added in v0.6.0
func (d *Dispatcher) Err() error
Err returns the terminal error after Done closes.
func (*Dispatcher) Go ¶ added in v0.6.0
func (d *Dispatcher) Go() (*Pending, error)
Go sends a method call and returns its pending result.
func (*Dispatcher) NewCall ¶ added in v0.6.0
func (d *Dispatcher) NewCall(dest, path, iface, member, sig string) *Encoder
NewCall starts a call. Exactly one Call, Go or Send must follow.
func (*Dispatcher) NewSignal ¶ added in v0.6.0
func (d *Dispatcher) NewSignal(path, iface, member, sig string) *Encoder
NewSignal starts a signal. Send must follow.
func (*Dispatcher) Send ¶ added in v0.6.0
func (d *Dispatcher) Send() (uint32, error)
Send sends the built message without tracking a reply.
func (*Dispatcher) Subscribe ¶ added in v0.6.0
func (d *Dispatcher) Subscribe(ctx context.Context, m Match, buf int) (*Subscription, error)
Subscribe installs a bus match and a local stream with capacity buf (at least 1). Nonempty Sender must start with ':'; resolve well-known names using org.freedesktop.DBus.GetNameOwner first. If cancellation races AddMatch, Subscribe attempts RemoveMatch with a fresh one-second context before returning.
func (*Dispatcher) UniqueName ¶ added in v0.6.0
func (d *Dispatcher) UniqueName() string
UniqueName returns the bus-assigned name.
func (*Dispatcher) UnixFDs ¶ added in v0.6.0
func (d *Dispatcher) UnixFDs() bool
UnixFDs reports negotiated descriptor support.
type Encoder ¶
type Encoder struct {
// contains filtered or unexported fields
}
Encoder appends D-Bus values to an outgoing message. Get one from Conn.NewCall, Conn.Signal, Conn.Reply or Conn.Error, write the body values in the order of the message signature, then call Conn.Send.
Errors are sticky and reported by Conn.Send.
func (*Encoder) BeginArray ¶
BeginArray starts an ARRAY whose element type starts with the signature byte elem. Write the elements, then call EndArray:
a := e.BeginArray('s')
e.Str("one")
e.Str("two")
e.EndArray(a)
func (*Encoder) ByteArray ¶
ByteArray writes an ARRAY of BYTE (ay).
func (*Encoder) EndArray ¶
EndArray finishes the array started by BeginArray.
func (*Encoder) ObjectPath ¶
ObjectPath writes an OBJECT_PATH (o).
func (*Encoder) SetFlags ¶
SetFlags sets the flags of the message being built.
func (*Encoder) Signature ¶
Signature writes a SIGNATURE (g).
func (*Encoder) Struct ¶
func (e *Encoder) Struct()
Struct aligns the encoder to the start of a STRUCT or DICT_ENTRY. Call it before writing the first field.
func (*Encoder) UnixFD ¶
UnixFD appends a UNIX_FD index and attaches fd to the outgoing message. The caller retains ownership and must keep fd valid until Send or Call returns. Descriptor passing requires successful Linux Unix-FD negotiation.
type Error ¶
type Error struct {
Name string // such as org.freedesktop.DBus.Error.ServiceUnknown
Message string // the first string of the body, if any
}
Error is a D-Bus error reply.
type Flags ¶
type Flags byte
Flags are the header flags of a message.
const ( // FlagNoReplyExpected tells the receiver not to answer a method call. FlagNoReplyExpected Flags = 0x1 // FlagNoAutoStart tells the bus not to start the destination service. FlagNoAutoStart Flags = 0x2 // FlagAllowInteractiveAuth allows the receiver to prompt the user. FlagAllowInteractiveAuth Flags = 0x4 )
Message flags.
type Match ¶ added in v0.6.0
type Match struct{ Sender, Path, Interface, Member string }
Match selects signals. Empty fields match anything. Sender must be empty or a unique name (starting with ':'). Resolve well-known names with org.freedesktop.DBus.GetNameOwner before subscribing.
type Message ¶
type Message struct {
Type Type
Flags Flags
Serial uint32
ReplySerial uint32
Path string
Interface string
Member string
ErrorName string
Destination string
Sender string
Signature string // the signature of the body
// contains filtered or unexported fields
}
Message is a received message.
Its strings point into the connection's receive buffer: they and the message itself are valid only until the next read on the connection.
func (*Message) Body ¶
Body returns a reader at the start of the message body. Each call starts over from the beginning.
func (*Message) NumFDs ¶
NumFDs returns the number of descriptors attached to this message.
type Msg ¶ added in v0.6.0
type Msg struct {
Type Type
Flags Flags
Serial uint32
ReplySerial uint32
Path string
Interface string
Member string
ErrorName string
Destination string
Sender string
Signature string
// contains filtered or unexported fields
}
Msg is a detached message. Its strings and decoded body remain valid across reads. Close it when done to release untaken descriptors. Msg is not safe for concurrent use. Signals never contain descriptors.
func (*Msg) Close ¶ added in v0.6.0
func (m *Msg) Close()
Close releases untaken descriptors. It is idempotent and nil-safe.
func (*Msg) NumFDs ¶ added in v0.6.0
NumFDs returns the number of received descriptor slots, including taken slots.
type Pending ¶ added in v0.6.0
type Pending struct {
// contains filtered or unexported fields
}
Pending is an asynchronous call. Always retrieve its result and close the returned Msg: abandoning a delivered result can leak descriptors. Pending is not safe for concurrent use, except Cancel racing completion.
func (*Pending) Cancel ¶ added in v0.6.0
func (p *Pending) Cancel()
Cancel cancels the call, closing even a reply that raced cancellation.
func (*Pending) Done ¶ added in v0.6.0
func (p *Pending) Done() <-chan struct{}
Done closes on reply, cancellation or connection failure.
func (*Pending) Result ¶ added in v0.6.0
Result returns the result after Done closes.
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
Reader decodes D-Bus values in place.
Strings and byte slices it returns point into the message buffer: they are valid only until the next Conn.ReadMessage. Copy them (strings.Clone, bytes.Clone) to keep them longer.
Read values in the order of the message signature. Errors are sticky: after the first one, every read returns a zero value and Err reports it.
func (*Reader) Array ¶
Array reads the header of an ARRAY whose element type starts with the signature byte elem, and returns the offset where the array ends. Read the elements while More returns true:
end := r.Array('s')
for r.More(end) {
name := r.Str()
}
func (*Reader) ByteArray ¶
ByteArray reads an ARRAY of BYTE (ay). The result points into the message buffer.
func (*Reader) Done ¶
Done reports whether every byte was read without error.
func (*Reader) Err ¶
Err returns the first error the reader met, or nil.
func (*Reader) More ¶
More reports whether the array that ends at end has another element.
func (*Reader) ObjectPath ¶
ObjectPath reads an OBJECT_PATH (o). The result points into the message buffer.
func (*Reader) Signature ¶
Signature reads a SIGNATURE (g). The result points into the message buffer.
func (*Reader) Skip ¶
Skip reads past values of the given signature. Arrays are skipped by their length, without reading their elements.
func (*Reader) SkipTo ¶
SkipTo moves to end, the value returned by Array. Use it to leave an array before its last element.
func (*Reader) Str ¶
Str reads a STRING (s). The result points into the message buffer.
func (*Reader) Struct ¶
func (r *Reader) Struct()
Struct aligns the reader to the start of a STRUCT or DICT_ENTRY. Call it before reading the first field.
func (*Reader) UnixFD ¶
UnixFD reads a UNIX_FD (h): an index into the fds sent with the message. Pass this index to Message.TakeFD to take ownership.
type Subscription ¶ added in v0.6.0
type Subscription struct {
C <-chan *Msg
// contains filtered or unexported fields
}
Subscription is a bounded drop-newest signal stream. Close unregisters it.
func (*Subscription) Close ¶ added in v0.6.0
func (s *Subscription) Close(ctx context.Context) error
Close stops delivery immediately, then best-effort removes the bus match. After dispatcher teardown it returns nil without a bus call.
func (*Subscription) Dropped ¶ added in v0.6.0
func (s *Subscription) Dropped() uint64
Dropped returns the number of signals dropped because the buffer was full.
Source Files
¶
- conn.go
- dispatcher.go
- doc.go
- fd_linux.go
- message.go
- recvmsg_linux.go
- wire.go