dbus

package
v1.3.0-alpha.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 11, 2016 License: BSD-2-Clause, Apache-2.0 Imports: 21 Imported by: 0

README

dbus

dbus is a simple library that implements native Go client bindings for the D-Bus message bus system.

Features

  • Complete native implementation of the D-Bus message protocol
  • Go-like API (channels for signals / asynchronous method calls, Goroutine-safe connections)
  • Subpackages that help with the introspection / property interfaces

Installation

This packages requires Go 1.1. If you installed it and set up your GOPATH, just run:

go get github.com/godbus/dbus

If you want to use the subpackages, you can install them the same way.

Usage

The complete package documentation and some simple examples are available at godoc.org. Also, the _examples directory gives a short overview over the basic usage.

Projects using godbus
  • notify provides desktop notifications over dbus into a library.

Please note that the API is considered unstable for now and may change without further notice.

License

go.dbus is available under the Simplified BSD License; see LICENSE for the full text.

Nearly all of the credit for this library goes to github.com/guelfey/go.dbus.

Documentation

Overview

Package dbus implements bindings to the D-Bus message bus system.

To use the message bus API, you first need to connect to a bus (usually the session or system bus). The acquired connection then can be used to call methods on remote objects and emit or receive signals. Using the Export method, you can arrange D-Bus methods calls to be directly translated to method calls on a Go value.

Conversion Rules

For outgoing messages, Go types are automatically converted to the corresponding D-Bus types. The following types are directly encoded as their respective D-Bus equivalents:

Go type     | D-Bus type
------------+-----------
byte        | BYTE
bool        | BOOLEAN
int16       | INT16
uint16      | UINT16
int32       | INT32
uint32      | UINT32
int64       | INT64
uint64      | UINT64
float64     | DOUBLE
string      | STRING
ObjectPath  | OBJECT_PATH
Signature   | SIGNATURE
Variant     | VARIANT
UnixFDIndex | UNIX_FD

Slices and arrays encode as ARRAYs of their element type.

Maps encode as DICTs, provided that their key type can be used as a key for a DICT.

Structs other than Variant and Signature encode as a STRUCT containing their exported fields. Fields whose tags contain `dbus:"-"` and unexported fields will be skipped.

Pointers encode as the value they're pointed to.

Trying to encode any other type or a slice, map or struct containing an unsupported type will result in an InvalidTypeError.

For incoming messages, the inverse of these rules are used, with the exception of STRUCTs. Incoming STRUCTS are represented as a slice of empty interfaces containing the struct fields in the correct order. The Store function can be used to convert such values to Go structs.

Unix FD passing

Handling Unix file descriptors deserves special mention. To use them, you should first check that they are supported on a connection by calling SupportsUnixFDs. If it returns true, all method of Connection will translate messages containing UnixFD's to messages that are accompanied by the given file descriptors with the UnixFD values being substituted by the correct indices. Similarily, the indices of incoming messages are automatically resolved. It shouldn't be necessary to use UnixFDIndex.

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("dbus: connection closed by user")

ErrClosed is the error returned by calls on a closed connection.

Functions

func Store

func Store(src []interface{}, dest ...interface{}) error

Store copies the values contained in src to dest, which must be a slice of pointers. It converts slices of interfaces from src to corresponding structs in dest. An error is returned if the lengths of src and dest or the types of their elements don't match.

Types

type Auth

type Auth interface {
	// Return the name of the mechnism, the argument to the first AUTH command
	// and the next status.
	FirstData() (name, resp []byte, status AuthStatus)

	// Process the given DATA command, and return the argument to the DATA
	// command and the next status. If len(resp) == 0, no DATA command is sent.
	HandleData(data []byte) (resp []byte, status AuthStatus)
}

Auth defines the behaviour of an authentication mechanism.

func AuthCookieSha1

func AuthCookieSha1(user, home string) Auth

AuthCookieSha1 returns an Auth that authenticates as the given user with the DBUS_COOKIE_SHA1 mechanism. The home parameter should specify the home directory of the user.

func AuthExternal

func AuthExternal(user string) Auth

AuthExternal returns an Auth that authenticates as the given user with the EXTERNAL mechanism.

type AuthStatus

type AuthStatus byte

AuthStatus represents the Status of an authentication mechanism.

const (
	// AuthOk signals that authentication is finished; the next command
	// from the server should be an OK.
	AuthOk AuthStatus = iota

	// AuthContinue signals that additional data is needed; the next command
	// from the server should be a DATA.
	AuthContinue

	// AuthError signals an error; the server sent invalid data or some
	// other unexpected thing happened and the current authentication
	// process should be aborted.
	AuthError
)

type BusObject added in v1.2.0

type BusObject interface {
	Call(method string, flags Flags, args ...interface{}) *Call
	Go(method string, flags Flags, ch chan *Call, args ...interface{}) *Call
	GetProperty(p string) (Variant, error)
	Destination() string
	Path() ObjectPath
}

BusObject is the interface of a remote object on which methods can be invoked.

type Call

type Call struct {
	Destination string
	Path        ObjectPath
	Method      string
	Args        []interface{}

	// Strobes when the call is complete.
	Done chan *Call

	// After completion, the error status. If this is non-nil, it may be an
	// error message from the peer (with Error as its type) or some other error.
	Err error

	// Holds the response once the call is done.
	Body []interface{}
}

Call represents a pending or completed method call.

func (*Call) Store

func (c *Call) Store(retvalues ...interface{}) error

Store stores the body of the reply into the provided pointers. It returns an error if the signatures of the body and retvalues don't match, or if the error status is not nil.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn represents a connection to a message bus (usually, the system or session bus).

Connections are either shared or private. Shared connections are shared between calls to the functions that return them. As a result, the methods Close, Auth and Hello must not be called on them.

Multiple goroutines may invoke methods on a connection simultaneously.

func Dial

func Dial(address string) (*Conn, error)

Dial establishes a new private connection to the message bus specified by address.

func NewConn

func NewConn(conn io.ReadWriteCloser) (*Conn, error)

NewConn creates a new private *Conn from an already established connection.

func SessionBus

func SessionBus() (conn *Conn, err error)

SessionBus returns a shared connection to the session bus, connecting to it if not already done.

func SessionBusPrivate

func SessionBusPrivate() (*Conn, error)

SessionBusPrivate returns a new private connection to the session bus.

func SystemBus

func SystemBus() (conn *Conn, err error)

SystemBus returns a shared connection to the system bus, connecting to it if not already done.

func SystemBusPrivate

func SystemBusPrivate() (*Conn, error)

SystemBusPrivate returns a new private connection to the system bus.

func (*Conn) Auth

func (conn *Conn) Auth(methods []Auth) error

Auth authenticates the connection, trying the given list of authentication mechanisms (in that order). If nil is passed, the EXTERNAL and DBUS_COOKIE_SHA1 mechanisms are tried for the current user. For private connections, this method must be called before sending any messages to the bus. Auth must not be called on shared connections.

func (*Conn) BusObject

func (conn *Conn) BusObject() BusObject

BusObject returns the object owned by the bus daemon which handles administrative requests.

func (*Conn) Close

func (conn *Conn) Close() error

Close closes the connection. Any blocked operations will return with errors and the channels passed to Eavesdrop and Signal are closed. This method must not be called on shared connections.

func (*Conn) Eavesdrop

func (conn *Conn) Eavesdrop(ch chan<- *Message)

Eavesdrop causes conn to send all incoming messages to the given channel without further processing. Method replies, errors and signals will not be sent to the appropiate channels and method calls will not be handled. If nil is passed, the normal behaviour is restored.

The caller has to make sure that ch is sufficiently buffered; if a message arrives when a write to ch is not possible, the message is discarded.

func (*Conn) Emit

func (conn *Conn) Emit(path ObjectPath, name string, values ...interface{}) error

Emit emits the given signal on the message bus. The name parameter must be formatted as "interface.member", e.g., "org.freedesktop.DBus.NameLost".

func (*Conn) Export

func (conn *Conn) Export(v interface{}, path ObjectPath, iface string) error

Export registers the given value to be exported as an object on the message bus.

If a method call on the given path and interface is received, an exported method with the same name is called with v as the receiver if the parameters match and the last return value is of type *Error. If this *Error is not nil, it is sent back to the caller as an error. Otherwise, a method reply is sent with the other return values as its body.

Any parameters with the special type Sender are set to the sender of the dbus message when the method is called. Parameters of this type do not contribute to the dbus signature of the method (i.e. the method is exposed as if the parameters of type Sender were not there).

Similarly, any parameters with the type Message are set to the raw message received on the bus. Again, parameters of this type do not contribute to the dbus signature of the method.

Every method call is executed in a new goroutine, so the method may be called in multiple goroutines at once.

Method calls on the interface org.freedesktop.DBus.Peer will be automatically handled for every object.

Passing nil as the first parameter will cause conn to cease handling calls on the given combination of path and interface.

Export returns an error if path is not a valid path name.

func (*Conn) ExportSubtree added in v1.2.0

func (conn *Conn) ExportSubtree(v interface{}, path ObjectPath, iface string) error

ExportSubtree works exactly like Export but registers the given value for an entire subtree rather under the root path provided.

In order to make this useful, one parameter in each of the value's exported methods should be a Message, in which case it will contain the raw message (allowing one to get access to the path that caused the method to be called).

Note that more specific export paths take precedence over less specific. For example, a method call using the ObjectPath /foo/bar/baz will call a method exported on /foo/bar before a method exported on /foo.

func (*Conn) ExportSubtreeWithMap added in v1.2.0

func (conn *Conn) ExportSubtreeWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error

ExportSubtreeWithMap works exactly like ExportSubtree but provides the ability to remap method names (e.g. export a lower-case method).

The keys in the map are the real method names (exported on the struct), and the values are the method names to be exported on DBus.

func (*Conn) ExportWithMap added in v1.2.0

func (conn *Conn) ExportWithMap(v interface{}, mapping map[string]string, path ObjectPath, iface string) error

ExportWithMap works exactly like Export but provides the ability to remap method names (e.g. export a lower-case method).

The keys in the map are the real method names (exported on the struct), and the values are the method names to be exported on DBus.

func (*Conn) Hello

func (conn *Conn) Hello() error

Hello sends the initial org.freedesktop.DBus.Hello call. This method must be called after authentication, but before sending any other messages to the bus. Hello must not be called for shared connections.

func (*Conn) Names

func (conn *Conn) Names() []string

Names returns the list of all names that are currently owned by this connection. The slice is always at least one element long, the first element being the unique name of the connection.

func (*Conn) Object

func (conn *Conn) Object(dest string, path ObjectPath) BusObject

Object returns the object identified by the given destination name and path.

func (*Conn) ReleaseName

func (conn *Conn) ReleaseName(name string) (ReleaseNameReply, error)

ReleaseName calls org.freedesktop.DBus.ReleaseName and awaits a response.

func (*Conn) RequestName

func (conn *Conn) RequestName(name string, flags RequestNameFlags) (RequestNameReply, error)

RequestName calls org.freedesktop.DBus.RequestName and awaits a response.

func (*Conn) Send

func (conn *Conn) Send(msg *Message, ch chan *Call) *Call

Send sends the given message to the message bus. You usually don't need to use this; use the higher-level equivalents (Call / Go, Emit and Export) instead. If msg is a method call and NoReplyExpected is not set, a non-nil call is returned and the same value is sent to ch (which must be buffered) once the call is complete. Otherwise, ch is ignored and a Call structure is returned of which only the Err member is valid.

func (*Conn) Signal

func (conn *Conn) Signal(ch chan<- *Signal)

Signal registers the given channel to be passed all received signal messages. The caller has to make sure that ch is sufficiently buffered; if a message arrives when a write to c is not possible, it is discarded.

Multiple of these channels can be registered at the same time. Passing a channel that already is registered will remove it from the list of the registered channels.

These channels are "overwritten" by Eavesdrop; i.e., if there currently is a channel for eavesdropped messages, this channel receives all signals, and none of the channels passed to Signal will receive any signals.

func (*Conn) SupportsUnixFDs

func (conn *Conn) SupportsUnixFDs() bool

SupportsUnixFDs returns whether the underlying transport supports passing of unix file descriptors. If this is false, method calls containing unix file descriptors will return an error and emitted signals containing them will not be sent.

type Error

type Error struct {
	Name string
	Body []interface{}
}

Error represents a D-Bus message of type Error.

func NewError added in v1.2.0

func NewError(name string, body []interface{}) *Error

func (Error) Error

func (e Error) Error() string

type Flags

type Flags byte

Flags represents the possible flags of a D-Bus message.

const (
	// FlagNoReplyExpected signals that the message is not expected to generate
	// a reply. If this flag is set on outgoing messages, any possible reply
	// will be discarded.
	FlagNoReplyExpected Flags = 1 << iota
	// FlagNoAutoStart signals that the message bus should not automatically
	// start an application when handling this message.
	FlagNoAutoStart
)

type FormatError

type FormatError string

A FormatError is an error in the wire format.

func (FormatError) Error

func (e FormatError) Error() string

type HeaderField

type HeaderField byte

HeaderField represents the possible byte codes for the headers of a D-Bus message.

const (
	FieldPath HeaderField = 1 + iota
	FieldInterface
	FieldMember
	FieldErrorName
	FieldReplySerial
	FieldDestination
	FieldSender
	FieldSignature
	FieldUnixFDs
)

type InvalidMessageError

type InvalidMessageError string

An InvalidMessageError describes the reason why a D-Bus message is regarded as invalid.

func (InvalidMessageError) Error

func (e InvalidMessageError) Error() string

type InvalidTypeError

type InvalidTypeError struct {
	Type reflect.Type
}

An InvalidTypeError signals that a value which cannot be represented in the D-Bus wire format was passed to a function.

func (InvalidTypeError) Error

func (e InvalidTypeError) Error() string

type Message

type Message struct {
	Type
	Flags
	Headers map[HeaderField]Variant
	Body    []interface{}
	// contains filtered or unexported fields
}

Message represents a single D-Bus message.

func DecodeMessage

func DecodeMessage(rd io.Reader) (msg *Message, err error)

DecodeMessage tries to decode a single message in the D-Bus wire format from the given reader. The byte order is figured out from the first byte. The possibly returned error can be an error of the underlying reader, an InvalidMessageError or a FormatError.

func (*Message) EncodeTo

func (msg *Message) EncodeTo(out io.Writer, order binary.ByteOrder) error

EncodeTo encodes and sends a message to the given writer. The byte order must be either binary.LittleEndian or binary.BigEndian. If the message is not valid or an error occurs when writing, an error is returned.

func (*Message) IsValid

func (msg *Message) IsValid() error

IsValid checks whether msg is a valid message and returns an InvalidMessageError if it is not.

func (*Message) Serial

func (msg *Message) Serial() uint32

Serial returns the message's serial number. The returned value is only valid for messages received by eavesdropping.

func (*Message) String

func (msg *Message) String() string

String returns a string representation of a message similar to the format of dbus-monitor.

type Object

type Object struct {
	// contains filtered or unexported fields
}

Object represents a remote object on which methods can be invoked.

func (*Object) Call

func (o *Object) Call(method string, flags Flags, args ...interface{}) *Call

Call calls a method with (*Object).Go and waits for its reply.

func (*Object) Destination

func (o *Object) Destination() string

Destination returns the destination that calls on o are sent to.

func (*Object) GetProperty

func (o *Object) GetProperty(p string) (Variant, error)

GetProperty calls org.freedesktop.DBus.Properties.GetProperty on the given object. The property name must be given in interface.member notation.

func (*Object) Go

func (o *Object) Go(method string, flags Flags, ch chan *Call, args ...interface{}) *Call

Go calls a method with the given arguments asynchronously. It returns a Call structure representing this method call. The passed channel will return the same value once the call is done. If ch is nil, a new channel will be allocated. Otherwise, ch has to be buffered or Go will panic.

If the flags include FlagNoReplyExpected, ch is ignored and a Call structure is returned of which only the Err member is valid.

If the method parameter contains a dot ('.'), the part before the last dot specifies the interface on which the method is called.

func (*Object) Path

func (o *Object) Path() ObjectPath

Path returns the path that calls on o are sent to.

type ObjectPath

type ObjectPath string

An ObjectPath is an object path as defined by the D-Bus spec.

func (ObjectPath) IsValid

func (o ObjectPath) IsValid() bool

IsValid returns whether the object path is valid.

type ReleaseNameReply

type ReleaseNameReply uint32

ReleaseNameReply is the reply to a ReleaseName call.

const (
	ReleaseNameReplyReleased ReleaseNameReply = 1 + iota
	ReleaseNameReplyNonExistent
	ReleaseNameReplyNotOwner
)

type RequestNameFlags

type RequestNameFlags uint32

RequestNameFlags represents the possible flags for a RequestName call.

const (
	NameFlagAllowReplacement RequestNameFlags = 1 << iota
	NameFlagReplaceExisting
	NameFlagDoNotQueue
)

type RequestNameReply

type RequestNameReply uint32

RequestNameReply is the reply to a RequestName call.

const (
	RequestNameReplyPrimaryOwner RequestNameReply = 1 + iota
	RequestNameReplyInQueue
	RequestNameReplyExists
	RequestNameReplyAlreadyOwner
)

type Sender

type Sender string

Sender is a type which can be used in exported methods to receive the message sender.

type Signal

type Signal struct {
	Sender string
	Path   ObjectPath
	Name   string
	Body   []interface{}
}

Signal represents a D-Bus message of type Signal. The name member is given in "interface.member" notation, e.g. org.freedesktop.D-Bus.NameLost.

type Signature

type Signature struct {
	// contains filtered or unexported fields
}

Signature represents a correct type signature as specified by the D-Bus specification. The zero value represents the empty signature, "".

func ParseSignature

func ParseSignature(s string) (sig Signature, err error)

ParseSignature returns the signature represented by this string, or a SignatureError if the string is not a valid signature.

func ParseSignatureMust

func ParseSignatureMust(s string) Signature

ParseSignatureMust behaves like ParseSignature, except that it panics if s is not valid.

func SignatureOf

func SignatureOf(vs ...interface{}) Signature

SignatureOf returns the concatenation of all the signatures of the given values. It panics if one of them is not representable in D-Bus.

func SignatureOfType

func SignatureOfType(t reflect.Type) Signature

SignatureOfType returns the signature of the given type. It panics if the type is not representable in D-Bus.

func (Signature) Empty

func (s Signature) Empty() bool

Empty retruns whether the signature is the empty signature.

func (Signature) Single

func (s Signature) Single() bool

Single returns whether the signature represents a single, complete type.

func (Signature) String

func (s Signature) String() string

String returns the signature's string representation.

type SignatureError

type SignatureError struct {
	Sig    string
	Reason string
}

A SignatureError indicates that a signature passed to a function or received on a connection is not a valid signature.

func (SignatureError) Error

func (e SignatureError) Error() string

type Type

type Type byte

Type represents the possible types of a D-Bus message.

const (
	TypeMethodCall Type = 1 + iota
	TypeMethodReply
	TypeError
	TypeSignal
)

func (Type) String

func (t Type) String() string

type UnixFD

type UnixFD int32

A UnixFD is a Unix file descriptor sent over the wire. See the package-level documentation for more information about Unix file descriptor passsing.

type UnixFDIndex

type UnixFDIndex uint32

A UnixFDIndex is the representation of a Unix file descriptor in a message.

type Variant

type Variant struct {
	// contains filtered or unexported fields
}

Variant represents the D-Bus variant type.

func MakeVariant

func MakeVariant(v interface{}) Variant

MakeVariant converts the given value to a Variant. It panics if v cannot be represented as a D-Bus type.

func ParseVariant

func ParseVariant(s string, sig Signature) (Variant, error)

ParseVariant parses the given string as a variant as described at https://developer.gnome.org/glib/unstable/gvariant-text.html. If sig is not empty, it is taken to be the expected signature for the variant.

func (Variant) Signature

func (v Variant) Signature() Signature

Signature returns the D-Bus signature of the underlying value of v.

func (Variant) String

func (v Variant) String() string

String returns the string representation of the underlying value of v as described at https://developer.gnome.org/glib/unstable/gvariant-text.html.

func (Variant) Value

func (v Variant) Value() interface{}

Value returns the underlying value of v.

Directories

Path Synopsis
Package introspect provides some utilities for dealing with the DBus introspection format.
Package introspect provides some utilities for dealing with the DBus introspection format.
Package prop provides the Properties struct which can be used to implement org.freedesktop.DBus.Properties.
Package prop provides the Properties struct which can be used to implement org.freedesktop.DBus.Properties.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL