2005-01-28 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / doc / dbus-tutorial.xml
1 <?xml version="1.0" standalone="no"?>
2 <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
3 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd"
4 [
5 ]>
6
7 <article id="index">
8   <articleinfo>
9     <title>D-BUS Tutorial</title>
10     <releaseinfo>Version 0.3</releaseinfo>
11     <date>18 January 2005</date>
12     <authorgroup>
13       <author>
14         <firstname>Havoc</firstname>
15         <surname>Pennington</surname>
16         <affiliation>
17           <orgname>Red Hat, Inc.</orgname>
18           <address>
19             <email>hp@pobox.com</email>
20           </address>
21         </affiliation>
22       </author>
23       <author>
24         <firstname>David</firstname>
25         <surname>Wheeler</surname>
26       </author>
27     </authorgroup>
28   </articleinfo>
29
30   <sect1 id="whatis">
31     <title>What is D-BUS?</title>
32     <para>
33       D-BUS is a system for <firstterm>interprocess communication</firstterm>
34       (IPC). Architecturally, it has several layers:
35
36       <itemizedlist>
37         <listitem>
38           <para>
39             A library, <firstterm>libdbus</firstterm>, that allows two
40             applications to connect to each other and exchange messages.
41           </para>
42         </listitem>
43         <listitem>
44           <para>
45             A <firstterm>message bus daemon</firstterm> executable, built on
46             libdbus, that multiple applications can connect to. The daemon can
47             route messages from one application to zero or more other
48             applications.
49           </para>
50         </listitem>
51         <listitem>
52           <para>
53             <firstterm>Wrapper libraries</firstterm> based on particular
54             application frameworks.  For example, libdbus-glib and
55             libdbus-qt. There are also bindings to languages such as
56             Python. These wrapper libraries are the API most people should use,
57             as they simplify the details of D-BUS programming. libdbus is 
58             intended to be a low-level backend for the higher level bindings.
59             Much of the libdbus API is only useful for binding implementation.
60           </para>
61         </listitem>
62       </itemizedlist>
63     </para>
64
65     <para>
66       If you just want to use D-BUS and don't care how it works, jump directly
67       to <xref linkend="concepts"/>.
68       Otherwise, read on.
69     </para>
70
71     <para>
72       libdbus only supports one-to-one connections, just like a raw network
73       socket. However, rather than sending byte streams over the connection, you
74       send <firstterm>messages</firstterm>. Messages have a header identifying
75       the kind of message, and a body containing a data payload. libdbus also
76       abstracts the exact transport used (sockets vs. whatever else), and
77       handles details such as authentication.
78     </para>
79
80     <para>
81       The message bus daemon forms the hub of a wheel. Each spoke of the wheel
82       is a one-to-one connection to an application using libdbus.  An
83       application sends a message to the bus daemon over its spoke, and the bus
84       daemon forwards the message to other connected applications as
85       appropriate. Think of the daemon as a router.
86     </para>
87
88     <para>
89       The bus daemon has multiple instances on a typical computer.  The
90       first instance is a machine-global singleton, that is, a system daemon
91       similar to sendmail or Apache. This instance has heavy security
92       restrictions on what messages it will accept, and is used for systemwide
93       communication. The other instances are created one per user login session.
94       These instances allow applications in the user's session to communicate 
95       with one another.
96     </para>
97
98     <para>
99       The systemwide and per-user daemons are separate.  Normal within-session
100       IPC does not involve the systemwide message bus process and vice versa.
101     </para>
102
103     <sect2 id="uses">
104       <title>D-BUS applications</title>
105       <para>
106         There are many, many technologies in the world that have "Inter-process
107         communication" or "networking" in their stated purpose: <ulink
108         url="http://www.omg.org">CORBA</ulink>, <ulink
109         url="http://www.opengroup.org/dce/">DCE</ulink>, <ulink
110         url="http://www.microsoft.com/com/">DCOM</ulink>, <ulink
111         url="http://developer.kde.org/documentation/library/kdeqt/dcop.html">DCOP</ulink>, <ulink
112         url="http://www.xmlrpc.com">XML-RPC</ulink>, <ulink
113         url="http://www.w3.org/TR/SOAP/">SOAP</ulink>, <ulink
114         url="http://www.mbus.org/">MBUS</ulink>, <ulink
115         url="http://www.zeroc.com/ice.html">Internet Communications Engine (ICE)</ulink>,
116         and probably hundreds more.
117         Each of these is tailored for particular kinds of application.
118         D-BUS is designed for two specific cases:
119         <itemizedlist>
120           <listitem>
121             <para>
122               Communication between desktop applications in the same desktop
123               session; to allow integration of the desktop session as a whole,
124               and address issues of process lifecycle (when do desktop components 
125               start and stop running).
126             </para>
127           </listitem>
128           <listitem>
129             <para>
130               Communication between the desktop session and the operating system, 
131               where the operating system would typically include the kernel 
132               and any system daemons or processes.
133             </para>
134           </listitem>
135         </itemizedlist>
136       </para>
137       <para>
138         For the within-desktop-session use case, the GNOME and KDE desktops 
139         have significant previous experience with different IPC solutions
140         such as CORBA and DCOP. D-BUS is built on that experience and 
141         carefully tailored to meet the needs of these desktop projects 
142         in particular. D-BUS may or may not be appropriate for other 
143         applications; the FAQ has some comparisons to other IPC systems.
144       </para>
145       <para>
146         The problem solved by the systemwide or communication-with-the-OS case 
147         is explained well by the following text from the Linux Hotplug project:
148         <blockquote>
149           <para>
150            A gap in current Linux support is that policies with any sort of
151            dynamic "interact with user" component aren't currently
152            supported. For example, that's often needed the first time a network
153            adapter or printer is connected, and to determine appropriate places
154            to mount disk drives. It would seem that such actions could be
155            supported for any case where a responsible human can be identified:
156            single user workstations, or any system which is remotely
157            administered.
158           </para>
159
160           <para>
161             This is a classic "remote sysadmin" problem, where in this case
162             hotplugging needs to deliver an event from one security domain
163             (operating system kernel, in this case) to another (desktop for
164             logged-in user, or remote sysadmin). Any effective response must go
165             the other way: the remote domain taking some action that lets the
166             kernel expose the desired device capabilities. (The action can often
167             be taken asynchronously, for example letting new hardware be idle
168             until a meeting finishes.) At this writing, Linux doesn't have
169             widely adopted solutions to such problems. However, the new D-Bus
170             work may begin to solve that problem.
171           </para>
172         </blockquote>
173       </para>
174       <para>
175         D-BUS may happen to be useful for purposes other than the one it was
176         designed for. Its general properties that distinguish it from 
177         other forms of IPC are:
178         <itemizedlist>
179           <listitem>
180             <para>
181               Binary protocol designed to be used asynchronously 
182               (similar in spirit to the X Window System protocol).
183             </para>
184           </listitem>
185           <listitem>
186             <para>
187               Stateful, reliable connections held open over time.
188             </para>
189           </listitem>
190           <listitem>
191             <para>
192               The message bus is a daemon, not a "swarm" or 
193               distributed architecture.
194             </para>
195           </listitem>
196           <listitem>
197             <para>
198               Many implementation and deployment issues are specified rather
199               than left ambiguous.
200             </para>
201           </listitem>
202           <listitem>
203             <para>
204               Semantics are similar to the existing DCOP system, allowing 
205               KDE to adopt it more easily.
206             </para>
207           </listitem>
208           <listitem>
209             <para>
210               Security features to support the systemwide mode of the 
211               message bus.
212             </para>
213           </listitem>
214         </itemizedlist>
215       </para>
216     </sect2>
217   </sect1>
218   <sect1 id="concepts">
219     <title>Concepts</title>
220     <para>
221       Some basic concepts apply no matter what application framework you're
222       using to write a D-BUS application. The exact code you write will be
223       different for GLib vs. Qt vs. Python applications, however.
224     </para>
225     
226     <para>
227       Here is a diagram (<ulink url="diagram.png">png</ulink> <ulink
228       url="diagram.svg">svg</ulink>) that may help you visualize the concepts
229       that follow.
230     </para>
231
232     <sect2 id="objects">
233       <title>Objects and Object Paths</title>
234       <para>
235         Each application using D-BUS contains <firstterm>objects</firstterm>,
236         which generally map to GObject, QObject, C++ objects, or Python objects
237         (but need not).  An object is an <emphasis>instance</emphasis> rather
238         than a type.  When messages are received over a D-BUS connection, they
239         are sent to a specific object, not to the application as a whole.
240       </para>
241       <para>
242         To allow messages to specify their destination object, there has to be a
243         way to refer to an object. In your favorite programming language, this
244         is normally called a <firstterm>pointer</firstterm> or
245         <firstterm>reference</firstterm>. However, these references are
246         implemented as memory addresses relative to the address space of your
247         application, and thus can't be passed from one application to another.
248       </para>
249       <para>
250         To solve this, D-BUS introduces a name for each object. The name 
251         looks like a filesystem path, for example an object could be 
252         named <literal>/org/kde/kspread/sheets/3/cells/4/5</literal>. 
253         Human-readable paths are nice, but you are free to create an 
254         object named <literal>/com/mycompany/c5yo817y0c1y1c5b</literal> 
255         if it makes sense for your application.
256       </para>
257       <para>
258         Namespacing object paths is smart, by starting them with the components
259         of a domain name you own (e.g. <literal>/org/kde</literal>). This 
260         keeps different code modules in the same process from stepping 
261         on one another's toes.
262       </para>
263     </sect2>    
264
265     <sect2 id="interfaces">
266       <title>Interfaces</title>
267       <para>
268         Each object supports one or more <firstterm>interfaces</firstterm>.
269         Think of an interface as a named group of methods and signals, 
270         just as it is in GLib or Qt or Java. Interfaces define the 
271         <emphasis>type</emphasis> of an object instance.
272       </para>
273     </sect2>
274       
275     <sect2 id="messages">
276       <title>Message Types</title>
277       <para>
278         Messages are not all the same; in particular, D-BUS has 
279         4 built-in message types:
280         <itemizedlist>
281           <listitem>
282             <para>
283               Method call messages ask to invoke a method 
284               on an object.
285             </para>
286           </listitem>
287           <listitem>
288             <para>
289               Method return messages return the results 
290               of invoking a method.
291             </para>
292           </listitem>
293           <listitem>
294             <para>
295               Error messages return an exception caused by 
296               invoking a method.
297             </para>
298           </listitem>
299           <listitem>
300             <para>
301               Signal messages are notifications that a given signal 
302               has been emitted (that an event has occurred). 
303               You could also think of these as "event" messages.
304             </para>
305           </listitem>
306         </itemizedlist>
307       </para>
308       <para>
309         A method call maps very simply to messages, then: you send a method call
310         message, and receive either a method return message or an error message
311         in reply.
312       </para>
313     </sect2>
314
315     <sect2 id="bus-names">
316       <title>Bus Names</title>
317       
318       <para>
319         Object paths, interfaces, and messages exist on the level of 
320         libdbus and the D-BUS protocol; they are used even in the 
321         1-to-1 case with no message bus involved.
322       </para>
323
324       <para>
325         Bus names, on the other hand, are a property of the message bus daemon.
326         The bus maintains a mapping from names to message bus connections.
327         These names are used to specify the origin and destination
328         of messages passing through the message bus. When a name is mapped 
329         to a particular application's connection, that application is said to 
330         <firstterm>own</firstterm> that name.
331       </para>
332
333       <para>
334         On connecting to the bus daemon, each application immediately owns a
335         special name called the <firstterm>unique connection name</firstterm>.
336         A unique name begins with a ':' (colon) character; no other names are
337         allowed to begin with that character. Unique names are special because
338         they are created dynamically, and are never re-used during the lifetime
339         of the same bus daemon. You know that a given unique name will have the
340         same owner at all times.  An example of a unique name might be
341         <literal>:34-907</literal>. The numbers after the colon have 
342         no meaning other than their uniqueness.
343       </para>
344
345       <para>
346         Applications may ask to own additional <firstterm>well-known
347         names</firstterm>. For example, you could write a specification to
348         define a name called <literal>com.mycompany.TextEditor</literal>.
349         Your definition could specify that to own this name, an application
350         should have an object at the path
351         <literal>/com/mycompany/TextFileManager</literal> supporting the
352         interface <literal>org.freedesktop.FileHandler</literal>.        
353       </para>
354       
355       <para>
356         Applications could then send messages to this bus name, 
357         object, and interface to execute method calls.
358       </para>
359
360       <para>
361         You could think of the unique names as IP addresses, and the
362         well-known names as domain names. So
363         <literal>com.mycompany.TextEditor</literal> might map to something like
364         <literal>:34-907</literal> just as <literal>mycompany.com</literal> maps
365         to something like <literal>192.168.0.5</literal>.
366       </para>
367       
368       <para>
369         Names have a second important use, other than routing messages.  They
370         are used to track lifecycle. When an application exits (or crashes), its
371         connection to the message bus will be closed by the operating system
372         kernel. The message bus then sends out notification messages telling
373         remaining applications that the application's names have lost their
374         owner. By tracking these notifications, your application can reliably
375         monitor the lifetime of other applications.
376       </para>
377
378     </sect2>
379
380     <sect2 id="addresses">
381       <title>Addresses</title>
382
383       <para>
384         Applications using D-BUS are either servers or clients.  A server
385         listens for incoming connections; a client connects to a server. Once
386         the connection is established, it is a symmetric flow of messages; the
387         client-server distinction only matters when setting up the 
388         connection.
389       </para>
390
391       <para>
392         A D-BUS <firstterm>address</firstterm> specifies where a server will
393         listen, and where a client will connect.  For example, the address
394         <literal>unix:path=/tmp/abcdef</literal> specifies that the server will
395         listen on a UNIX domain socket at the path
396         <literal>/tmp/abcdef</literal> and the client will connect to that
397         socket. An address can also specify TCP/IP sockets, or any other
398         transport defined in future iterations of the D-BUS specification.
399       </para>
400
401       <para>
402         When using D-BUS with a message bus, the bus daemon is a server 
403         and all other applications are clients of the bus daemon.
404         libdbus automatically discovers the address of the per-session bus 
405         daemon by reading an environment variable. It discovers the 
406         systemwide bus daemon by checking a well-known UNIX domain socket path
407         (though you can override this address with an environment variable).
408       </para>
409
410       <para>
411         If you're using D-BUS without a bus daemon, it's up to you to 
412         define which application will be the server and which will be 
413         the client, and specify a mechanism for them to agree on 
414         the server's address.
415       </para>
416
417     </sect2>
418
419     <sect2 id="bigpicture">
420       <title>Big Conceptual Picture</title>
421
422       <para>
423         Pulling all these concepts together, to specify a particular 
424         method call on a particular object instance, a number of 
425         nested components have to be named:
426         <programlisting>
427           Address -&gt; [Bus Name] -&gt; Path -&gt; Interface -&gt; Method
428         </programlisting>
429         The bus name is in brackets to indicate that it's optional -- you only
430         provide a name to route the method call to the right application
431         when using the bus daemon. If you have a direct connection to another
432         application, bus names aren't used; there's no bus daemon.
433       </para>
434
435       <para>
436         The interface is also optional, primarily for historical 
437         reasons; DCOP does not require specifying the interface, 
438         instead simply forbidding duplicate method names 
439         on the same object instance. D-BUS will thus let you 
440         omit the interface, but if your method name is ambiguous 
441         it is undefined which method will be invoked.
442       </para>
443       
444     </sect2>
445
446   </sect1>
447
448   <sect1 id="glib-client">
449     <title>GLib API: Using Remote Objects</title>
450
451     <para>
452       
453       The GLib binding is defined in the header file
454       &lt;dbus/dbus-glib.h&gt;. The API is very small, in sharp contrast to the
455       low-level &lt;dbus/dbus.h&gt;.
456
457     </para>
458
459     <para>
460       The GLib bindings are incomplete, see the TODO file and comments in the
461       source code.
462     </para>
463
464     <para>
465 Here is a D-BUS program using the GLib bindings.
466 <programlisting>      
467 int
468 main (int argc, char **argv)
469 {
470   DBusGConnection *connection;
471   GError *error;
472   DBusGProxy *proxy;
473   DBusGPendingCall *call;
474   char **name_list;
475   int name_list_len;
476   int i;
477   
478   g_type_init ();
479
480   error = NULL;
481   connection = dbus_g_bus_get (DBUS_BUS_SESSION,
482                                &amp;error);
483   if (connection == NULL)
484     {
485       g_printerr ("Failed to open connection to bus: %s\n",
486                   error-&gt;message);
487       g_error_free (error);
488       exit (1);
489     }
490
491   /* Create a proxy object for the "bus driver" (name "org.freedesktop.DBus") */
492   
493   proxy = dbus_g_proxy_new_for_name (connection,
494                                      DBUS_SERVICE_ORG_FREEDESKTOP_DBUS,
495                                      DBUS_PATH_ORG_FREEDESKTOP_DBUS,
496                                      DBUS_INTERFACE_ORG_FREEDESKTOP_DBUS);
497
498   /* Call ListNames method */
499   
500   call = dbus_g_proxy_begin_call (proxy, "ListNames", DBUS_TYPE_INVALID);
501
502   error = NULL;
503   if (!dbus_g_proxy_end_call (proxy, call, &amp;error,
504                               DBUS_TYPE_ARRAY, DBUS_TYPE_STRING,
505                               &amp;name_list, &amp;name_list_len,
506                               DBUS_TYPE_INVALID))
507     {
508       g_printerr ("Failed to complete ListNames call: %s\n",
509                   error-&gt;message);
510       g_error_free (error);
511       exit (1);
512     }
513
514   /* Print the results */
515  
516   g_print ("Names on the message bus:\n");
517   i = 0;
518   while (i &lt; name_list_len)
519     {
520       g_assert (name_list[i] != NULL);
521       g_print ("  %s\n", name_list[i]);
522       ++i;
523     }
524   g_assert (name_list[i] == NULL);
525
526   g_strfreev (name_list);
527
528   return 0;
529 }
530 </programlisting>
531     </para>
532
533     <para>
534
535       DBusGProxy represents a remote object. dbus_g_proxy_begin_call() sends 
536       a method call to the remote object, and dbus_g_proxy_end_call() retrieves 
537       any return values or exceptions resulting from the method call. 
538       There are also DBusGProxy functions to connect and disconnect signals, 
539       not shown in the code example.
540
541     </para>
542
543     <para>
544       
545       dbus_g_bus_get() assumes that the application will use GMainLoop. The
546       created connection will be associated with the main loop such that
547       messages will be sent and received when the main loop runs.  However, in
548       the above code example the main loop never runs; D-BUS will not run the
549       loop implicitly. Instead, dbus_g_proxy_end_call() will block until the
550       method call has been sent and the reply received. A more complex GUI
551       application might run the main loop while waiting for the method call
552       reply.  (DBusGPendingCall is currently missing the "notify me when the
553       call is complete" functionality found in DBusPendingCall, but it should be
554       added.)
555
556     </para>
557
558     <para>
559       
560       Future plans (see doc/TODO) are to use G_TYPE_STRING in place of
561       DBUS_TYPE_STRING and so forth. In fact the above code is slightly
562       incorrect at the moment, since it uses g_strfreev() to free a string array
563       that was not allocated with g_malloc(). dbus_free_string_array() should
564       really be used. However, once the GLib bindings are complete the returned
565       data from dbus_g_proxy_end_call() will be allocated with g_malloc().
566
567     </para>
568
569   </sect1>
570
571   <sect1 id="glib-server">
572     <title>GLib API: Implementing Objects</title>
573
574     <para>
575       
576       The GLib binding is defined in the header file
577       &lt;dbus/dbus-glib.h&gt;. To implement an object, it's also necessary
578       to use the dbus-glib-tool command line tool.
579
580     </para>
581
582     <para>
583       The GLib bindings are incomplete.  Implementing an object is not yet
584       possible, see the TODO file and comments in the source code for details
585       on what work needs doing.
586     </para>
587       
588   </sect1>
589
590   <sect1 id="qt-client">
591     <title>Qt API: Using Remote Objects</title>
592     <para>
593       
594       The Qt bindings are not yet documented.
595
596     </para>
597   </sect1>
598
599   <sect1 id="qt-server">
600     <title>Qt API: Implementing Objects</title>
601     <para>
602       The Qt bindings are not yet documented.
603     </para>
604   </sect1>
605
606
607   <sect1 id="python-client">
608     <title>Python API: Using Remote Objects</title>
609     <para>
610       The Python bindings are not yet documented, but the 
611       bindings themselves are in good shape.
612     </para>
613   </sect1>
614
615   <sect1 id="python-server">
616     <title>Python API: Implementing Objects</title>
617     <para>
618       The Python bindings are not yet documented, but the 
619       bindings themselves are in good shape.
620     </para>
621   </sect1>
622
623 </article>