[daemon-dev] Start of daemon with kdbus
[platform/upstream/dbus.git] / bus / kdbus-d.c
1 /*
2  * kdbus-d.c
3  *
4  *  Created on: Sep 4, 2013
5  *      Author: r.pajak
6  *
7  *  kdbus add-on to dbus daemon
8  *
9  */
10
11 #include <kdbus-d.h>
12 #include <dbus/kdbus.h>
13 #include <dbus/dbus-connection-internal.h>
14
15 #include <utils.h>
16 #include <stdlib.h>
17 #include <stdio.h>
18 #include <fcntl.h>
19 #include <unistd.h>
20
21 char* make_kdbus_bus(DBusBusType type, DBusError *error)
22 {
23     struct {
24         struct kdbus_cmd_bus_make head;
25         uint64_t n_size;
26         uint64_t n_type;
27         char name[64];
28     } __attribute__ ((__aligned__(8))) bus_make;
29
30     int fdc, ret;
31     char *bus;
32
33     /*TODO Distinguish session and system bus make*/
34     /*TODO Add dbus_set_error(error, DBUS_ERROR_FAILED,  "...") (?)*/
35
36     _dbus_verbose("Opening /dev/kdbus/control\n");
37     fdc = open("/dev/kdbus/control", O_RDWR|O_CLOEXEC);
38     if (fdc < 0)
39     {
40         _dbus_verbose("--- error %d (%m)\n", fdc);
41         return NULL;
42     }
43
44     memset(&bus_make, 0, sizeof(bus_make));
45     bus_make.head.bloom_size = 64;
46     bus_make.head.flags = KDBUS_MAKE_ACCESS_WORLD;
47
48     snprintf(bus_make.name, sizeof(bus_make.name), "%u-kdbus", getuid());
49     bus_make.n_type = KDBUS_MAKE_NAME;
50     bus_make.n_size = KDBUS_PART_HEADER_SIZE + strlen(bus_make.name) + 1;
51     bus_make.head.size = sizeof(struct kdbus_cmd_bus_make) + bus_make.n_size;
52
53     _dbus_verbose("Creating bus '%s'\n", bus_make.name);
54     ret = ioctl(fdc, KDBUS_CMD_BUS_MAKE, &bus_make);
55     if (ret)
56     {
57         _dbus_verbose("--- error %d (%m)\n", ret);
58         return NULL;
59     }
60
61     if (asprintf(&bus, "kdbus:path=/dev/kdbus/%s/bus", bus_make.name) < 0)
62     {
63         BUS_SET_OOM (error);
64         return NULL;
65     }
66
67     _dbus_verbose("Return value '%s'\n", bus);
68         return bus;
69 }
70
71 DBusConnection* daemon_as_client(DBusBusType type, DBusError *error)
72 {
73         DBusConnection* connection;
74
75         connection = dbus_bus_get(type, error);
76         if(connection == NULL)
77                 return NULL;
78
79         if(dbus_bus_request_name(connection, DBUS_SERVICE_DBUS, 0, error) != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
80                 goto failed;
81
82         dbus_bus_add_match(connection, "type='signal', member='NameAcquired'", error);
83         dbus_bus_add_match(connection, "type='signal', member='NameLost'", error);
84         if(dbus_error_is_set(error))
85                 goto failed;
86
87         return connection;
88
89 failed:
90         _dbus_connection_close_possibly_shared (connection);
91         dbus_connection_unref (connection);
92         connection = NULL;
93         return NULL;
94 }