chiark / gitweb /
units: properly create prefdm symlink
[elogind.git] / src / dbus-common.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <assert.h>
23 #include <sys/socket.h>
24 #include <errno.h>
25 #include <unistd.h>
26 #include <dbus/dbus.h>
27
28 #include "log.h"
29 #include "dbus-common.h"
30
31 int bus_check_peercred(DBusConnection *c) {
32         int fd;
33         struct ucred ucred;
34         socklen_t l;
35
36         assert(c);
37
38         assert_se(dbus_connection_get_unix_fd(c, &fd));
39
40         l = sizeof(struct ucred);
41         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0) {
42                 log_error("SO_PEERCRED failed: %m");
43                 return -errno;
44         }
45
46         if (l != sizeof(struct ucred)) {
47                 log_error("SO_PEERCRED returned wrong size.");
48                 return -E2BIG;
49         }
50
51         if (ucred.uid != 0)
52                 return -EPERM;
53
54         return 1;
55 }
56
57 int bus_connect(DBusBusType t, DBusConnection **_bus, bool *private, DBusError *error) {
58         DBusConnection *bus;
59
60         assert(_bus);
61
62         /* If we are root, then let's not go via the bus */
63         if (geteuid() == 0 && t == DBUS_BUS_SYSTEM) {
64
65                 if (!(bus = dbus_connection_open("unix:abstract=/org/freedesktop/systemd1/private", error)))
66                         return -EIO;
67
68                 if (bus_check_peercred(bus) < 0) {
69                         dbus_connection_unref(bus);
70
71                         dbus_set_error_const(error, DBUS_ERROR_ACCESS_DENIED, "Failed to verify owner of bus.");
72                         return -EACCES;
73                 }
74
75                 if (private)
76                         *private = true;
77
78         } else {
79                 if (!(bus = dbus_bus_get(t, error)))
80                         return -EIO;
81
82                 if (private)
83                         *private = false;
84         }
85
86         dbus_connection_set_exit_on_disconnect(bus, FALSE);
87
88         *_bus = bus;
89         return 0;
90 }