Native Go bindings for D-Bus

Build Status

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.7. 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.
  • go-bluetooth provides a bluetooth client over bluez dbus API.
  • playerbm a bookmark utility for media players.
  • iwd go bindings for the internet wireless daemon "iwd".

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.

Comments
  • Fix signal related contentions and bugs

    Fix signal related contentions and bugs

    This PR is to fix issue #8.

    First commit adds a bunch of tests for testing contentions. Also, while working on this issue I noticed that Signal function does not behave as it should, so I added tests for it as well.

    Second commit should fix the contentions.

    Third commit should fix the signal watchers adding and removing, so all the tests I've added in first commit pass.

    Fourth commit is there, because "appropriate" is hard to type. :)

    Fifth commit fixes some confusing docs.

  • Error emitting signal: dbus: connection closed by user

    Error emitting signal: dbus: connection closed by user

    Hi,

    I am trying to wrap a library to expose it over DBus. The library provides functionality to query and set Ikea Trådfri light bulbs, and also provides a channel over which notifications are sent when devices are changed through other means (such as a smartphone app or the remote control) so that any user of the library can update its state accordingly.

    In my code, I spawn a goroutine which reads from this channel. For every received message I would then like to emit a notification, with the received message as value. The DBus daemon works in that I can query and set light bulbs through e.g. DFeet, but when I press any button on my remote in order to test the signal delivery I get Error emitting signal: dbus: connection closed by user. The provided channel works appropriately in a command line tool accompanying the library. I've been stuck on this for a while and cannot find a clue as to why this is happening, hence this issue.

    The relevant code is as follows:

            ...
    
    	err = d.conn.Export(DBusClient{*d.client}, objectRoot, nameRoot)
    	if err != nil {
    		return fmt.Errorf("Cannot export Trådfri interface: %s\n", err)
    	}
    
    	// Request name after exporting interfaces to ensure that the interfaces aren't called before they
    	// are exported.
    	reply, err := d.conn.RequestName(nameRoot, dbus.NameFlagDoNotQueue)
    	if err != nil {
    		return fmt.Errorf("Cannot associate name \"%s\": %s\n", nameRoot, err)
    	}
    	if reply != dbus.RequestNameReplyPrimaryOwner {
    		return fmt.Errorf("Name \"%s\" already taken", nameRoot)
    	}
    
            ...
    
            go d.handleDeviceUpdates()
    

    Where handleDeviceUpdates is:

    func (d *DBusDaemon) handleDeviceUpdates() {
    	for msg := range d.client.DeviceEvents() {
    		err := d.conn.Emit(objectRoot, nameRoot+".DeviceChanged", msg)
    		if err != nil {
    			fmt.Printf("Error emitting signal: %s\n", err)
    		} else {
    			fmt.Printf("Emitted signal %s.%s\n", nameRoot+".DeviceChanged", msg.ID)
    		}
            }
    }
    

    The full code is here. Any comments or pointers are appreciated!

  • d-feet errors out with an Exception

    d-feet errors out with an Exception

    com.github.guelfey.Demo : g-io-error-quark: GDBus.Error:org.freedesktop.DBus.Error.NoSuchObject: No such object (36)
    

    When running server.go

    Thanks for your work!

  • Cannot get godbus to connect to private instance of system bus.

    Cannot get godbus to connect to private instance of system bus.

    Hi Folks, I have created an instance of DBus messagebus configured like the system bus. and started it using: "dbus-daemon --config-file=/etc/dbusalt/system.conf" with an open minimalist configuration.

    <!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
     "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
    <!-- Completely open test configuration!  Do not overwrite real DBus
     configuration. Copy to /etc/dbusalt -->
    
    <busconfig>
      <!-- If we fork, keep the user's original umask to avoid affecting
           the behavior of child processes. -->
      <keep_umask/>
    
      <!-- <type>system</type> -->
    
      <!-- Run as special user -->
      <user>messagebus</user>
    
      <!-- Fork into daemon mode -->
      <fork/>
    
      <!-- <standard_session_servicedirs /> -->
      
      <!-- Write a pid file -->
      <pidfile>/var/run/dbusalt/pid</pidfile>
    
      <!-- Only listen on a local socket. (abstract=/path/to/socket 
           means use abstract namespace, don't really create filesystem 
           file; only Linux supports this. Use path=/whatever on other 
           systems.) -->
      <listen>unix:path=/var/run/dbusalt/system_bus_socket</listen>
    
      <auth>ANONYMOUS</auth>
      <allow_anonymous/>
    
      <policy context="default">
        <!-- Allow anyone to own anything -->
        <allow own="*"/>
        <!-- Allow anyone to connect -->
        <allow user="*"/>
        <!-- Allow everything to be sent -->
        <allow send_destination="*" eavesdrop="true"/>
        <!-- Allow everything to be received -->
        <allow eavesdrop="true"/>
      </policy>
    
    
      <!-- raise the service start timeout to 40 seconds as it can timeout
           on the live cd on slow machines -->
      <limit name="service_start_timeout">60000</limit>
    
      <!-- the memory limits are 1G instead of say 4G because they can't exceed 32-bit signed int max -->
      <limit name="max_incoming_bytes">1000000000</limit>
      <limit name="max_outgoing_bytes">1000000000</limit>
      <limit name="max_message_size">1000000000</limit>
      <limit name="service_start_timeout">120000</limit>  
      <limit name="auth_timeout">240000</limit>
      <limit name="max_completed_connections">100000</limit>  
      <limit name="max_incomplete_connections">10000</limit>
      <limit name="max_connections_per_user">100000</limit>
      <limit name="max_pending_service_starts">10000</limit>
      <limit name="max_names_per_connection">50000</limit>
      <limit name="max_match_rules_per_connection">50000</limit>
      <limit name="max_replies_per_connection">50000</limit>
      <limit name="reply_timeout">300000</limit>
    
    </busconfig>
    

    The problem is that connection object returned by either ...

    			os.Setenv("DBUS_SYSTEM_BUS_ADDRESS", "unix:path/var/run/dbusalt/system_bus_socket")
    			fmt.Println("address:", os.Getenv("DBUS_SYSTEM_BUS_ADDRESS"))
    			conn, err = dbus.SystemBus()
    

    or

    			newSocket := "unix:path=/var/run/dbusalt/system_bus_socket"
    			conn, err = dbus.Dial(newSocket)
    

    silently fails to connect to the messagebus I have created, usually fails to throw an error, instead hangs forever. (Please Note that if I set "os.Setenv("DBUS_SYSTEM_BUS_ADDRESS", "unix:path/var/run/dbusalt/system_bus_socket")" I get "no such file or directory", but if I set "os.Setenv("DBUS_SYSTEM_BUS_ADDRESS", "/var/run/dbusalt/system_bus_socket")" it will hang forever when it gets to "conn.Hello()" or any other interactive call to the messagebus. "dbus-monitor" pointed at my instance never detects any activity.

    Is there something that I have misconfigured? Or is it possible that godbus cannot handle private DBus instances (I find this hard to believe)? Please note that I can connect to the private messagebus using d-feet and dbus-send.

  • prop.Set(...) returns nil error value that causes panic when printing panic

    prop.Set(...) returns nil error value that causes panic when printing panic

    Set() returns a *dbus.Error that is nil. As soon as it is returned to the caller's caller, err != nil "become true", and panicking at this point with panic(err) causes a crash hard to debug.

    func (b *Bus) UpdateComDevice(comDevice string) error {
    	err := b.props.Set(b.Interface(), "ComDevice", dbus.MakeVariant(comDevice))
    	fmt.Println(err == nil)  // true
    	return err
    }
    ...
    	if err := b.UpdateComDevice(cec.ComDevice()); err != nil {
    		fmt.Printf("\n          %t\n", err)
    	fmt.Println(err == nil)  // false
    		panic(err)
    	}
    

    See first answer here: https://stackoverflow.com/questions/54368951/panic-when-printing-a-nil-error-in-a-struct . I have to type-assert in order to bypass this bug.

  • Errors with a new connection if previous was closed

    Errors with a new connection if previous was closed

    In my code I use the following pattern

    conn, err := dbus.SystemBus()
    if err != nil {
    	return nil, err
    }
    defer conn.Close()
    

    And in the first function it works great, but the second function fails with error "dbus: connection closed by user". If I remove defer conn.Close() the both functions work great.

  • Allow exposing methods without error return type

    Allow exposing methods without error return type

    Currently only methods of an object that return the dbus.Error can be exposed directly on the bus. Other methods need a wrapper method to do so. This patch eliminates the need for the wrapper. This has been achieved by checking if the last output parameter of the method implements the error interface. If so the value returned by the function call is used as an error, else the method is assumed to not return any error.

  • Refactor connection implementation details

    Refactor connection implementation details

    This refactor allows for all the details of connection message handling to be overridden. The previously inline handlers for signals and messages are now implemented as an instance of the interfaces.

    This is useful for substituting the default object model for another model allowing full customization of object and method lookup. This allows for higher level abstractions to be built without breaking compatibility with the current library.

    All '*Conn' Export and Signal registration will only work with these default handlers. It is expected that implementations wishing to override the behavior of method lookup and signal delivery will implement similar mechanisms. The details of what can be exported or how a signal should be delivered are up to the implementation of the interface and thus should not be part of the interface definition.

  • Add ExportSubtree functions for subtree support.

    Add ExportSubtree functions for subtree support.

    This PR resolves #34 by adding ExportSubtree functions to support exporting on a subtree. It also adds support for obtaining the raw message with or without subtree exports, without changing API. Finally, it adds several tests for the new functionality.

  • Add a context to connections

    Add a context to connections

    This PR attaches a context to D-Bus connections. It adds a WithContext(ctx) option to the connection constructor to set a parent context for the connection (overriding a default of context.Background()), and adds a Conn.Context method to retrieve the connection's context. The connection's context will be done when either the parent context is done, or a disconnect is detected. In either case, the connection is closed when the context is done.

    The use cases for this are:

    1. by setting a parent context for a connection, it can automatically be cleaned up with related code.

    2. by monitoring the context of the shared SessionBus or SystemBus connections, it is possible to have a daemon exit cleanly when the bus exits (e.g. on user session shutdown).

    3. while it isn't implemented in this PR, the context could be used to derive one passed to server methods.

  • Enable exporting a table of function closures

    Enable exporting a table of function closures

    Allow a table of function closures to be substituted for a native object during export. This allows exporting generated code onto dbus more easily. This is especially handy when interfacing with some generic service that wishes to expose dbus methods based on some definition language.

    This refactor also cleans up the logic for the override table a bit. The exported objects are now stored as a table of method name to reflect.Value where the reflect.Value has been filtered to only be valid dbus methods. This is done at export time instead of doing the lookup dynamically at call time.

  • Non-static property values

    Non-static property values

    I'm trying to implement a property which value is not static and must be evaluated dynamically for each call. Is there a way to update the value dynamically on read after exporting them & without making the property writable to clients?

  • auth: Do not send UID with external auth

    auth: Do not send UID with external auth

    Due to mismatch between UID in a user-namespace and out-of-band credential acquired by server on another user-namespace refrain from sending UID with authentication message

    https://github.com/godbus/dbus/issues/345

  • External authentication fails between user-namespaces

    External authentication fails between user-namespaces

    It is not possible to connect to dbus bus running on host from within a user-namespace, a typical containers setup. The "EXTERNAL authentication" mechansim fails to verify the UID credential passing via the message against the out-of-band credential, due mismatch in user-id crossing user-namespace.

    Frameworks like sd-bus, gdbus has already switched to sending empty value instead of UID in DATA payload to fix the issue. https://gitlab.gnome.org/GNOME/glib/-/merge_requests/2832

    https://github.com/systemd/systemd/commit/1ed4723d38cd0d1423c8fe650f90fa86007ddf55

  • Protect object map from concurrent access

    Protect object map from concurrent access

    In situations with many concurrent dbus requests and at the same time new objects are registered it is possible to end up in a situation where the object map is write and read accessed from different go routines resulting in a panic.

    The patch is working in our setup but I've not run any test other than 'go test'

  • Unable to set up new connection: Failed to read an SELinux context from connection

    Unable to set up new connection: Failed to read an SELinux context from connection

    Observed one below test case failure on both architectures i.e. Intel and Power for v5.1.0. === RUN TestTcpNonceConnection dbus-daemon[1407687]: [session uid=0 pid=1407687] Unable to set up new connection: Failed to read an SELinux context from connection transport_nonce_tcp_test.go:31: read tcp [::1]:51214->[::1]:44621: read: connection reset by peer --- FAIL: TestTcpNonceConnection (0.02s)

    I am trying to build this package on RHEL-8.4, it will be helpful if you provide any input on this test failure. Thanks.

Related tags
Go simple async message bus
Go simple async message bus

?? message-bus Go simple async message bus. ?? ABOUT Contributors: Rafał Lorenz Want to contribute ? Feel free to send pull requests! Have problems, b

Dec 29, 2022
Gin best practices, gin development scaffolding, too late to explain, get on the bus.

Table of Contents generated with DocToc gin_scaffold 现在开始 文件分层 log / redis / mysql / http.client 常用方法 swagger文档生成 gin_scaffold Gin best practices, gin

Dec 27, 2022
Easy to use distributed event bus similar to Kafka
Easy to use distributed event bus similar to Kafka

chukcha Easy to use distributed event bus similar to Kafka. The event bus is designed to be used as a persistent intermediate storage buffer for any k

Dec 30, 2022
Govent is an event bus framework for DDD event source implement

Govent is an event bus framework for DDD event source implement. Govent can also solve the package circular dependency problem.

Jan 28, 2022
Messagebus - Simple Message Bus Written in Golang

MessageBus Simple Message Bus Written in Golang How to Use go get gopkg.io/Usada

Apr 21, 2022
Go (golang) bindings for the 0mq (zmq, zeromq) C API

NOTE: These gozmq bindings are in maintenance mode. Only critical bugs will be fixed. Henceforth I would suggest using @pebbe's actively maintained bi

Dec 9, 2022
Package htmltopdf implements wkhtmltopdf Go bindings.

htmltopdf Package htmltopdf implements wkhtmltopdf Go bindings. It can be used to convert HTML documents to PDF files. The package does not use the wk

Sep 19, 2022
Golang client for NATS, the cloud native messaging system.

NATS - Go Client A Go client for the NATS messaging system. Installation # Go client go get github.com/nats-io/nats.go/ # Server go get github.com/na

Jan 5, 2023
High-Performance server for NATS, the cloud native messaging system.
High-Performance server for NATS, the cloud native messaging system.

NATS is a simple, secure and performant communications system for digital systems, services and devices. NATS is part of the Cloud Native Computing Fo

Jan 2, 2023
Kafka implemented in Golang with built-in coordination (No ZooKeeper, single binary install, Cloud Native)

Jocko Distributed commit log service in Go that is wire compatible with Kafka. Created by @travisjeffery, continued by nash. Goals: Protocol compatibl

Aug 9, 2021
KubeMQ is a Kubernetes native message queue broker

KubeMQ Community is the open-source version of KubeMQ, the Kubernetes native message broker. More about KubeMQ

Nov 20, 2021
Tool for collect statistics from AMQP (RabbitMQ) broker. Good for cloud native service calculation.

amqp-statisticator Tool for collect statistics around your AMQP broker. For example RabbitMQ expose a lot information trought the management API, but

Dec 13, 2021
Native Go bindings for D-Bus

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

Nov 20, 2022
Go bindings for D-Bus

Documentation Look at the API on GoPkgDoc. Installation goinstall github.com/norisatir/go-dbus Usage Methods Methods is obtained with meth, err := co

Oct 20, 2019
Go bindings to systemd socket activation, journal, D-Bus, and unit files

go-systemd Go bindings to systemd. The project has several packages: activation - for writing and using socket activation from Go daemon - for notifyi

Dec 30, 2022
🔊Minimalist message bus implementation for internal communication

?? Bus Bus is a minimalist event/message bus implementation for internal communication. It is heavily inspired from my event_bus package for Elixir la

Jan 3, 2023
Go simple async message bus
Go simple async message bus

?? message-bus Go simple async message bus. ?? ABOUT Contributors: Rafał Lorenz Want to contribute ? Feel free to send pull requests! Have problems, b

Dec 29, 2022
A lightweight transactional message bus on top of RabbitMQ

grabbit A lightweight transactional message bus on top of RabbitMQ supporting: Supported Messaging Styles One Way (Fire and forget) Publish/Subscribe

Dec 22, 2022
Gin best practices, gin development scaffolding, too late to explain, get on the bus.

Table of Contents generated with DocToc gin_scaffold 现在开始 文件分层 log / redis / mysql / http.client 常用方法 swagger文档生成 gin_scaffold Gin best practices, gin

Dec 27, 2022
Easy to use distributed event bus similar to Kafka
Easy to use distributed event bus similar to Kafka

chukcha Easy to use distributed event bus similar to Kafka. The event bus is designed to be used as a persistent intermediate storage buffer for any k

Dec 30, 2022