Monday, February 23, 2009

Driving the D-Bus with Ruby

Having looked at the D-Bus from the client perspective before, its now time to get behind the wheel.

In order to drive the D-Bus, you need to decide on a couple of things:

  • which bus to drive
    you can choose between the system(-wide) bus or the (per-)session bus
  • the service name
    this is the name other clients can find your service, the name has dotted notation, e.g. my.awesome.Service
  • the objects to publish
    each service can provide any number of objects, denoted a slash-separated path name, e.g. /my/awesome/Service/thing
  • the interface name
    methods offered by objects are grouped by interface name. Usually its used to flag object capabilities. Interface names have dotted notation, usually prefixed by the service name, e.g. my.awesome.Service.Greeting
  • the methods
    these are the exported functions of the objects. Methods, also called members in D-Bus speak, have input parameters and a return value.

Obtaining a drivers license

Allowance for driving the D-Bus is controlled by config files below /etc/dbus-1. /etc/dbus-1/system.conf controls the system bus, /etc/dbus-1/session.conf controls the session bus. Both load additional configuration files from sub-directories (/etc/dbus-1/system.d/ resp. /etc/dbus-1/session.d/)

These config files are xml-based busconfig snippets, defining policies on who's allowed to own a service who can use which interfaces of the service.

A typical service configuration looks like this

 <!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN"
   "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
 <busconfig>
   <policy user="root">
     <allow own="my.awesome.Service" />
     <allow send_destination="my.awesome.Service" />
   </policy>
   <policy context="default">
     <allow send_destination="my.awesome.Service"
            send_interface="my.awesome.Service.Greeting" />
     <!-- introspection is allowed -->
     <allow send_destination="my.awesome.Service"
            send_interface="org.freedesktop.DBus.Introspectable" />
   </policy>
 </busconfig>
It gives root the right to own the service my.awesome.Service and to use it as a client. Any other user can only use the my.awesome.Service.Greeting interface of my.awesome.Service and can introspect it.

Convention tells you to name this busconfig file after your service with a .conf extension, e.g my.awesome.Service.conf. Place it below /etc/dbus-1/session.d/ or /etc/dbus-1/system.d/, depending which bus you want to drive.

Coding a D-Bus service

Examples for creating a D-Bus service using C are scarce and scary. Esp. programming in C while avoiding Glib, things become really ugly.

As we will see, using the ruby-dbus extension to Ruby makes creating D-Bus services a breeze.

We start with creating a DBus::Object defining (dbus_)methods under a (dbus_)interface.

#!/usr/bin/env ruby

require 'dbus'

class Awesome < DBus::Object
  # Create an interface.
  dbus_interface "my.awesome.Service.Greeting" do
    dbus_method :hola, "in name:s" do |name|
      puts "Hola #{name}!" 
    end
    dbus_method :hello, "in name:s, out res:s" do |name|
      "hello #{name}!" 
    end
    dbus_method :ahoj, "in name:s, in title:s" do |name,title|
      puts "Ahoj #{title} #{name}!" 
    end
  end
end

The dbus_method call get the method name passed as a symbol, followed by its signature. The signature describes the input ("in") and output ("out") parameters by name (before the colon) and type (after the colon). The parameter names are just syntactic sugar, but the type is essential and enforced by D-Bus. Look at D-Bus type signatures to find out how to specify types.

ruby-dbus uses the method name and signature to automatically generate an XML representation of the interface needed for D-Bus introspection. This allows clients to find out about available interfaces and their methods at runtime.

The following do ... end block contains the method implementation. Every "in" parameter is passed as a value to the block in typical ruby fashion.

Next is connecting to the bus and obtaining the service. You can easily export multiple services if the bus configuration allows that.

# Choose the bus (could also be DBus::session_bus)
bus = DBus::system_bus
# Define the service name
service = bus.request_service("my.awesome.Service")

Then we create the object and export it through the service.

# Set the object path
obj = Awesome.new("/my/awesome/Service/thing")
# Export it!
service.export(obj)

Note that there is no requirement to create and export objects in advance. You can start with a simple object and method, creating additional objects as requested by the client. Hal is a typical example for such a service.

Finally we start the listener and wait for incoming requests.

# Now listen to incoming requests
main = DBus::Main.new
main << bus
main.run

main.run never returns, as you would expect from a service daemon. Either kill(1) it, code a timeout signal or implement a method calling exit.

Running the service

Running the D-Bus service is as easy as running any other Ruby program:

kkaempf> ruby my_service.rb
This, however, will get you a Exception `DBus::Error' at (eval):26 - org.freedesktop.DBus.Error.AccessDenied: Connection ":1.967" is not allowed to own the service "my.awesome.Service" due to security policies in the configuration file

Looking at our busconfig defined above immediately reveals the error. Only user root is allowed to own the service. So we better do a

kkaempf> sudo ruby my_service.rb
to get this running.

Now congrats for passing your drivers exam ! ;-)

2 comments:

Anonymous said...

Thanks for putting this up. I had everything but the DBus::Main loop working, but I could not figure that out.

Thanks!

kkaempf said...

Actually, I was struggling with DBus::Main too ;-)

Btw, I couldn't get 'activation' to work with ruby-dbus yet. Looks like a bug to me