tizen 2.4 release
[external/systemd.git] / src / core / dbus.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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 Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 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   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <sys/epoll.h>
23 #include <sys/timerfd.h>
24 #include <errno.h>
25 #include <unistd.h>
26
27 #include "sd-bus.h"
28 #include "log.h"
29 #include "strv.h"
30 #include "mkdir.h"
31 #include "missing.h"
32 #include "dbus-unit.h"
33 #include "dbus-job.h"
34 #include "dbus-manager.h"
35 #include "dbus-execute.h"
36 #include "dbus-kill.h"
37 #include "dbus-cgroup.h"
38 #include "special.h"
39 #include "dbus.h"
40 #include "bus-util.h"
41 #include "bus-error.h"
42 #include "bus-errors.h"
43 #include "strxcpyx.h"
44 #include "bus-internal.h"
45 #include "selinux-access.h"
46
47 #define CONNECTIONS_MAX 512
48
49 static void destroy_bus(Manager *m, sd_bus **bus);
50
51 int bus_send_queued_message(Manager *m) {
52         int r;
53
54         assert(m);
55
56         if (!m->queued_message)
57                 return 0;
58
59         assert(m->queued_message_bus);
60
61         /* If we cannot get rid of this message we won't dispatch any
62          * D-Bus messages, so that we won't end up wanting to queue
63          * another message. */
64
65         r = sd_bus_send(m->queued_message_bus, m->queued_message, NULL);
66         if (r < 0)
67                 log_warning("Failed to send queued message: %s", strerror(-r));
68
69         m->queued_message = sd_bus_message_unref(m->queued_message);
70         m->queued_message_bus = sd_bus_unref(m->queued_message_bus);
71
72         return 0;
73 }
74
75 static int signal_agent_released(sd_bus *bus, sd_bus_message *message, void *userdata, sd_bus_error *error) {
76         Manager *m = userdata;
77         const char *cgroup;
78         int r;
79
80         assert(bus);
81         assert(message);
82         assert(m);
83
84         r = sd_bus_message_read(message, "s", &cgroup);
85         if (r < 0) {
86                 bus_log_parse_error(r);
87                 return 0;
88         }
89
90         manager_notify_cgroup_empty(m, cgroup);
91
92         if (m->running_as == SYSTEMD_SYSTEM && m->system_bus) {
93                 /* If we are running as system manager, forward the
94                  * message to the system bus */
95
96                 r = sd_bus_send(m->system_bus, message, NULL);
97                 if (r < 0)
98                         log_warning("Failed to forward Released message: %s", strerror(-r));
99         }
100
101         return 0;
102 }
103
104 static int signal_disconnected(sd_bus *bus, sd_bus_message *message, void *userdata, sd_bus_error *error) {
105         Manager *m = userdata;
106
107         assert(bus);
108         assert(message);
109         assert(m);
110
111         if (bus == m->api_bus)
112                 destroy_bus(m, &m->api_bus);
113         if (bus == m->system_bus)
114                 destroy_bus(m, &m->system_bus);
115         if (set_remove(m->private_buses, bus)) {
116                 log_debug("Got disconnect on private connection.");
117                 destroy_bus(m, &bus);
118         }
119
120         return 0;
121 }
122
123 static int signal_name_owner_changed(sd_bus *bus, sd_bus_message *message, void *userdata, sd_bus_error *error) {
124         const char *name, *old_owner, *new_owner;
125         Manager *m = userdata;
126         int r;
127
128         assert(bus);
129         assert(message);
130         assert(m);
131
132         r = sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner);
133         if (r < 0) {
134                 bus_log_parse_error(r);
135                 return 0;
136         }
137
138         manager_dispatch_bus_name_owner_changed(
139                         m, name,
140                         isempty(old_owner) ? NULL : old_owner,
141                         isempty(new_owner) ? NULL : new_owner);
142
143         return 0;
144 }
145
146 static int signal_activation_request(sd_bus *bus, sd_bus_message *message, void *userdata, sd_bus_error *ret_error) {
147         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
148         _cleanup_bus_message_unref_ sd_bus_message *reply = NULL;
149         Manager *m = userdata;
150         const char *name;
151         Unit *u;
152         int r;
153
154         assert(bus);
155         assert(message);
156         assert(m);
157
158         r = sd_bus_message_read(message, "s", &name);
159         if (r < 0) {
160                 bus_log_parse_error(r);
161                 return 0;
162         }
163
164         /* In Tizen 2.4 with kdbus enabled this check not only makes no sense, it will break activation because dbus.socket is always inactive. */
165         if (m->kdbus_fd < 0 &&
166             (manager_unit_inactive_or_pending(m, SPECIAL_DBUS_SERVICE) ||
167             manager_unit_inactive_or_pending(m, SPECIAL_DBUS_SOCKET))) {
168                 r = sd_bus_error_setf(&error, BUS_ERROR_SHUTTING_DOWN, "Refusing activation, D-Bus is shutting down.");
169                 goto failed;
170         }
171
172         r = manager_load_unit(m, name, NULL, &error, &u);
173         if (r < 0)
174                 goto failed;
175
176         if (u->refuse_manual_start) {
177                 r = sd_bus_error_setf(&error, BUS_ERROR_ONLY_BY_DEPENDENCY, "Operation refused, %s may be requested by dependency only.", u->id);
178                 goto failed;
179         }
180
181         r = manager_add_job(m, JOB_START, u, JOB_REPLACE, true, &error, NULL);
182         if (r < 0)
183                 goto failed;
184
185         /* Successfully queued, that's it for us */
186         return 0;
187
188 failed:
189         if (!sd_bus_error_is_set(&error))
190                 sd_bus_error_set_errno(&error, r);
191
192         log_debug("D-Bus activation failed for %s: %s", name, bus_error_message(&error, r));
193
194         r = sd_bus_message_new_signal(bus, &reply, "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Activator", "ActivationFailure");
195         if (r < 0) {
196                 bus_log_create_error(r);
197                 return 0;
198         }
199
200         r = sd_bus_message_append(reply, "sss", name, error.name, error.message);
201         if (r < 0) {
202                 bus_log_create_error(r);
203                 return 0;
204         }
205
206         r = sd_bus_send_to(bus, reply, "org.freedesktop.DBus", NULL);
207         if (r < 0) {
208                 log_error("Failed to respond with to bus activation request: %s", strerror(-r));
209                 return r;
210         }
211
212         return 0;
213 }
214
215 #ifdef HAVE_SELINUX
216 static int selinux_filter(sd_bus *bus, sd_bus_message *message, void *userdata, sd_bus_error *error) {
217         Manager *m = userdata;
218         const char *verb, *path;
219         Unit *u = NULL;
220         Job *j;
221         int r;
222
223         assert(bus);
224         assert(message);
225
226         /* Our own method calls are all protected individually with
227          * selinux checks, but the built-in interfaces need to be
228          * protected too. */
229
230         if (sd_bus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Set"))
231                 verb = "reload";
232         else if (sd_bus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", NULL) ||
233                  sd_bus_message_is_method_call(message, "org.freedesktop.DBus.Properties", NULL) ||
234                  sd_bus_message_is_method_call(message, "org.freedesktop.DBus.ObjectManager", NULL) ||
235                  sd_bus_message_is_method_call(message, "org.freedesktop.DBus.Peer", NULL))
236                 verb = "status";
237         else
238                 return 0;
239
240         path = sd_bus_message_get_path(message);
241
242         if (object_path_startswith("/org/freedesktop/systemd1", path)) {
243
244                 r = selinux_access_check(message, verb, error);
245                 if (r < 0)
246                         return r;
247
248                 return 0;
249         }
250
251         if (streq_ptr(path, "/org/freedesktop/systemd1/unit/self")) {
252                 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
253                 pid_t pid;
254
255                 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_PID, &creds);
256                 if (r < 0)
257                         return 0;
258
259                 r = sd_bus_creds_get_pid(creds, &pid);
260                 if (r < 0)
261                         return 0;
262
263                 u = manager_get_unit_by_pid(m, pid);
264         } else {
265                 r = manager_get_job_from_dbus_path(m, path, &j);
266                 if (r >= 0)
267                         u = j->unit;
268                 else
269                         manager_load_unit_from_dbus_path(m, path, NULL, &u);
270         }
271
272         if (!u)
273                 return 0;
274
275         r = selinux_unit_access_check(u, message, verb, error);
276         if (r < 0)
277                 return r;
278
279         return 0;
280 }
281 #endif
282
283 static int bus_job_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
284         Manager *m = userdata;
285         Job *j;
286         int r;
287
288         assert(bus);
289         assert(path);
290         assert(interface);
291         assert(found);
292         assert(m);
293
294         r = manager_get_job_from_dbus_path(m, path, &j);
295         if (r < 0)
296                 return 0;
297
298         *found = j;
299         return 1;
300 }
301
302 static int find_unit(Manager *m, sd_bus *bus, const char *path, Unit **unit, sd_bus_error *error) {
303         Unit *u;
304         int r;
305
306         assert(m);
307         assert(bus);
308         assert(path);
309
310         if (streq_ptr(path, "/org/freedesktop/systemd1/unit/self")) {
311                 _cleanup_bus_creds_unref_ sd_bus_creds *creds = NULL;
312                 sd_bus_message *message;
313                 pid_t pid;
314
315                 message = sd_bus_get_current_message(bus);
316                 if (!message)
317                         return 0;
318
319                 r = sd_bus_query_sender_creds(message, SD_BUS_CREDS_PID, &creds);
320                 if (r < 0)
321                         return r;
322
323                 r = sd_bus_creds_get_pid(creds, &pid);
324                 if (r < 0)
325                         return r;
326
327                 u = manager_get_unit_by_pid(m, pid);
328         } else {
329                 r = manager_load_unit_from_dbus_path(m, path, error, &u);
330                 if (r < 0)
331                         return 0;
332         }
333
334         if (!u)
335                 return 0;
336
337         *unit = u;
338         return 1;
339 }
340
341 static int bus_unit_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
342         Manager *m = userdata;
343
344         assert(bus);
345         assert(path);
346         assert(interface);
347         assert(found);
348         assert(m);
349
350         return find_unit(m, bus, path, (Unit**) found, error);
351 }
352
353 static int bus_unit_interface_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
354         Manager *m = userdata;
355         Unit *u;
356         int r;
357
358         assert(bus);
359         assert(path);
360         assert(interface);
361         assert(found);
362         assert(m);
363
364         r = find_unit(m, bus, path, &u, error);
365         if (r <= 0)
366                 return r;
367
368         if (!streq_ptr(interface, UNIT_VTABLE(u)->bus_interface))
369                 return 0;
370
371         *found = u;
372         return 1;
373 }
374
375 static int bus_unit_cgroup_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
376         Manager *m = userdata;
377         Unit *u;
378         int r;
379
380         assert(bus);
381         assert(path);
382         assert(interface);
383         assert(found);
384         assert(m);
385
386         r = find_unit(m, bus, path, &u, error);
387         if (r <= 0)
388                 return r;
389
390         if (!streq_ptr(interface, UNIT_VTABLE(u)->bus_interface))
391                 return 0;
392
393         if (!unit_get_cgroup_context(u))
394                 return 0;
395
396         *found = u;
397         return 1;
398 }
399
400 static int bus_cgroup_context_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
401         Manager *m = userdata;
402         CGroupContext *c;
403         Unit *u;
404         int r;
405
406         assert(bus);
407         assert(path);
408         assert(interface);
409         assert(found);
410         assert(m);
411
412         r = find_unit(m, bus, path, &u, error);
413         if (r <= 0)
414                 return r;
415
416         if (!streq_ptr(interface, UNIT_VTABLE(u)->bus_interface))
417                 return 0;
418
419         c = unit_get_cgroup_context(u);
420         if (!c)
421                 return 0;
422
423         *found = c;
424         return 1;
425 }
426
427 static int bus_exec_context_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
428         Manager *m = userdata;
429         ExecContext *c;
430         Unit *u;
431         int r;
432
433         assert(bus);
434         assert(path);
435         assert(interface);
436         assert(found);
437         assert(m);
438
439         r = find_unit(m, bus, path, &u, error);
440         if (r <= 0)
441                 return r;
442
443         if (!streq_ptr(interface, UNIT_VTABLE(u)->bus_interface))
444                 return 0;
445
446         c = unit_get_exec_context(u);
447         if (!c)
448                 return 0;
449
450         *found = c;
451         return 1;
452 }
453
454 static int bus_kill_context_find(sd_bus *bus, const char *path, const char *interface, void *userdata, void **found, sd_bus_error *error) {
455         Manager *m = userdata;
456         KillContext *c;
457         Unit *u;
458         int r;
459
460         assert(bus);
461         assert(path);
462         assert(interface);
463         assert(found);
464         assert(m);
465
466         r = find_unit(m, bus, path, &u, error);
467         if (r <= 0)
468                 return r;
469
470         if (!streq_ptr(interface, UNIT_VTABLE(u)->bus_interface))
471                 return 0;
472
473         c = unit_get_kill_context(u);
474         if (!c)
475                 return 0;
476
477         *found = c;
478         return 1;
479 }
480
481 static int bus_job_enumerate(sd_bus *bus, const char *path, void *userdata, char ***nodes, sd_bus_error *error) {
482         _cleanup_free_ char **l = NULL;
483         Manager *m = userdata;
484         unsigned k = 0;
485         Iterator i;
486         Job *j;
487
488         l = new0(char*, hashmap_size(m->jobs)+1);
489         if (!l)
490                 return -ENOMEM;
491
492         HASHMAP_FOREACH(j, m->jobs, i) {
493                 l[k] = job_dbus_path(j);
494                 if (!l[k])
495                         return -ENOMEM;
496
497                 k++;
498         }
499
500         assert(hashmap_size(m->jobs) == k);
501
502         *nodes = l;
503         l = NULL;
504
505         return k;
506 }
507
508 static int bus_unit_enumerate(sd_bus *bus, const char *path, void *userdata, char ***nodes, sd_bus_error *error) {
509         _cleanup_free_ char **l = NULL;
510         Manager *m = userdata;
511         unsigned k = 0;
512         Iterator i;
513         Unit *u;
514
515         l = new0(char*, hashmap_size(m->units)+1);
516         if (!l)
517                 return -ENOMEM;
518
519         HASHMAP_FOREACH(u, m->units, i) {
520                 l[k] = unit_dbus_path(u);
521                 if (!l[k])
522                         return -ENOMEM;
523
524                 k++;
525         }
526
527         *nodes = l;
528         l = NULL;
529
530         return k;
531 }
532
533 static int bus_setup_api_vtables(Manager *m, sd_bus *bus) {
534         UnitType t;
535         int r;
536
537         assert(m);
538         assert(bus);
539
540 #ifdef HAVE_SELINUX
541         r = sd_bus_add_filter(bus, NULL, selinux_filter, m);
542         if (r < 0) {
543                 log_error("Failed to add SELinux access filter: %s", strerror(-r));
544                 return r;
545         }
546 #endif
547
548         r = sd_bus_add_object_vtable(bus, NULL, "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", bus_manager_vtable, m);
549         if (r < 0) {
550                 log_error("Failed to register Manager vtable: %s", strerror(-r));
551                 return r;
552         }
553
554         r = sd_bus_add_fallback_vtable(bus, NULL, "/org/freedesktop/systemd1/job", "org.freedesktop.systemd1.Job", bus_job_vtable, bus_job_find, m);
555         if (r < 0) {
556                 log_error("Failed to register Job vtable: %s", strerror(-r));
557                 return r;
558         }
559
560         r = sd_bus_add_node_enumerator(bus, NULL, "/org/freedesktop/systemd1/job", bus_job_enumerate, m);
561         if (r < 0) {
562                 log_error("Failed to add job enumerator: %s", strerror(-r));
563                 return r;
564         }
565
566         r = sd_bus_add_fallback_vtable(bus, NULL, "/org/freedesktop/systemd1/unit", "org.freedesktop.systemd1.Unit", bus_unit_vtable, bus_unit_find, m);
567         if (r < 0) {
568                 log_error("Failed to register Unit vtable: %s", strerror(-r));
569                 return r;
570         }
571
572         r = sd_bus_add_node_enumerator(bus, NULL, "/org/freedesktop/systemd1/unit", bus_unit_enumerate, m);
573         if (r < 0) {
574                 log_error("Failed to add job enumerator: %s", strerror(-r));
575                 return r;
576         }
577
578         for (t = 0; t < _UNIT_TYPE_MAX; t++) {
579                 r = sd_bus_add_fallback_vtable(bus, NULL, "/org/freedesktop/systemd1/unit", unit_vtable[t]->bus_interface, unit_vtable[t]->bus_vtable, bus_unit_interface_find, m);
580                 if (r < 0)  {
581                         log_error("Failed to register type specific vtable for %s: %s", unit_vtable[t]->bus_interface, strerror(-r));
582                         return r;
583                 }
584
585                 if (unit_vtable[t]->cgroup_context_offset > 0) {
586                         r = sd_bus_add_fallback_vtable(bus, NULL, "/org/freedesktop/systemd1/unit", unit_vtable[t]->bus_interface, bus_unit_cgroup_vtable, bus_unit_cgroup_find, m);
587                         if (r < 0) {
588                                 log_error("Failed to register control group unit vtable for %s: %s", unit_vtable[t]->bus_interface, strerror(-r));
589                                 return r;
590                         }
591
592                         r = sd_bus_add_fallback_vtable(bus, NULL, "/org/freedesktop/systemd1/unit", unit_vtable[t]->bus_interface, bus_cgroup_vtable, bus_cgroup_context_find, m);
593                         if (r < 0) {
594                                 log_error("Failed to register control group vtable for %s: %s", unit_vtable[t]->bus_interface, strerror(-r));
595                                 return r;
596                         }
597                 }
598
599                 if (unit_vtable[t]->exec_context_offset > 0) {
600                         r = sd_bus_add_fallback_vtable(bus, NULL, "/org/freedesktop/systemd1/unit", unit_vtable[t]->bus_interface, bus_exec_vtable, bus_exec_context_find, m);
601                         if (r < 0) {
602                                 log_error("Failed to register execute vtable for %s: %s", unit_vtable[t]->bus_interface, strerror(-r));
603                                 return r;
604                         }
605                 }
606
607                 if (unit_vtable[t]->kill_context_offset > 0) {
608                         r = sd_bus_add_fallback_vtable(bus, NULL, "/org/freedesktop/systemd1/unit", unit_vtable[t]->bus_interface, bus_kill_vtable, bus_kill_context_find, m);
609                         if (r < 0) {
610                                 log_error("Failed to register kill vtable for %s: %s", unit_vtable[t]->bus_interface, strerror(-r));
611                                 return r;
612                         }
613                 }
614         }
615
616         return 0;
617 }
618
619 static int bus_setup_disconnected_match(Manager *m, sd_bus *bus) {
620         int r;
621
622         assert(m);
623         assert(bus);
624
625         r = sd_bus_add_match(
626                         bus,
627                         NULL,
628                         "sender='org.freedesktop.DBus.Local',"
629                         "type='signal',"
630                         "path='/org/freedesktop/DBus/Local',"
631                         "interface='org.freedesktop.DBus.Local',"
632                         "member='Disconnected'",
633                         signal_disconnected, m);
634
635         if (r < 0) {
636                 log_error("Failed to register match for Disconnected message: %s", strerror(-r));
637                 return r;
638         }
639
640         return 0;
641 }
642
643 static int bus_on_connection(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
644         _cleanup_bus_unref_ sd_bus *bus = NULL;
645         _cleanup_close_ int nfd = -1;
646         Manager *m = userdata;
647         sd_id128_t id;
648         int r;
649
650         assert(s);
651         assert(m);
652
653         nfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
654         if (nfd < 0) {
655                 log_warning("Failed to accept private connection, ignoring: %m");
656                 return 0;
657         }
658
659         if (set_size(m->private_buses) >= CONNECTIONS_MAX) {
660                 log_warning("Too many concurrent connections, refusing");
661                 return 0;
662         }
663
664         r = set_ensure_allocated(&m->private_buses, trivial_hash_func, trivial_compare_func);
665         if (r < 0) {
666                 log_oom();
667                 return 0;
668         }
669
670         r = sd_bus_new(&bus);
671         if (r < 0) {
672                 log_warning("Failed to allocate new private connection bus: %s", strerror(-r));
673                 return 0;
674         }
675
676         r = sd_bus_set_fd(bus, nfd, nfd);
677         if (r < 0) {
678                 log_warning("Failed to set fd on new connection bus: %s", strerror(-r));
679                 return 0;
680         }
681
682         nfd = -1;
683
684         r = bus_check_peercred(bus);
685         if (r < 0) {
686                 log_warning("Incoming private connection from unprivileged client, refusing: %s", strerror(-r));
687                 return 0;
688         }
689
690         assert_se(sd_id128_randomize(&id) >= 0);
691
692         r = sd_bus_set_server(bus, 1, id);
693         if (r < 0) {
694                 log_warning("Failed to enable server support for new connection bus: %s", strerror(-r));
695                 return 0;
696         }
697
698         r = sd_bus_start(bus);
699         if (r < 0) {
700                 log_warning("Failed to start new connection bus: %s", strerror(-r));
701                 return 0;
702         }
703
704         r = sd_bus_attach_event(bus, m->event, SD_EVENT_PRIORITY_NORMAL);
705         if (r < 0) {
706                 log_warning("Failed to attach new connection bus to event loop: %s", strerror(-r));
707                 return 0;
708         }
709
710         if (m->running_as == SYSTEMD_SYSTEM) {
711                 /* When we run as system instance we get the Released
712                  * signal via a direct connection */
713
714                 r = sd_bus_add_match(
715                                 bus,
716                                 NULL,
717                                 "type='signal',"
718                                 "interface='org.freedesktop.systemd1.Agent',"
719                                 "member='Released',"
720                                 "path='/org/freedesktop/systemd1/agent'",
721                                 signal_agent_released, m);
722
723                 if (r < 0) {
724                         log_warning("Failed to register Released match on new connection bus: %s", strerror(-r));
725                         return 0;
726                 }
727         }
728
729         r = bus_setup_disconnected_match(m, bus);
730         if (r < 0)
731                 return 0;
732
733         r = bus_setup_api_vtables(m, bus);
734         if (r < 0) {
735                 log_warning("Failed to set up API vtables on new connection bus: %s", strerror(-r));
736                 return 0;
737         }
738
739         r = set_put(m->private_buses, bus);
740         if (r < 0) {
741                 log_warning("Failed to add new conenction bus to set: %s", strerror(-r));
742                 return 0;
743         }
744
745         bus = NULL;
746
747         log_debug("Accepted new private connection.");
748
749         return 0;
750 }
751
752 static int bus_list_names(Manager *m, sd_bus *bus) {
753         _cleanup_strv_free_ char **names = NULL;
754         char **i;
755         int r;
756
757         assert(m);
758         assert(bus);
759
760         r = sd_bus_list_names(bus, &names, NULL);
761         if (r < 0) {
762                 log_error("Failed to get initial list of names: %s", strerror(-r));
763                 return r;
764         }
765
766         /* This is a bit hacky, we say the owner of the name is the
767          * name itself, because we don't want the extra traffic to
768          * figure out the real owner. */
769         STRV_FOREACH(i, names)
770                 manager_dispatch_bus_name_owner_changed(m, *i, NULL, *i);
771
772         return 0;
773 }
774
775 static int bus_setup_api(Manager *m, sd_bus *bus) {
776         int r;
777
778         assert(m);
779         assert(bus);
780
781         r = bus_setup_api_vtables(m, bus);
782         if (r < 0)
783                 return r;
784
785         r = sd_bus_add_match(
786                         bus,
787                         NULL,
788                         "type='signal',"
789                         "sender='org.freedesktop.DBus',"
790                         "path='/org/freedesktop/DBus',"
791                         "interface='org.freedesktop.DBus',"
792                         "member='NameOwnerChanged'",
793                         signal_name_owner_changed, m);
794         if (r < 0)
795                 log_warning("Failed to subscribe to NameOwnerChanged signal: %s", strerror(-r));
796
797         r = sd_bus_add_match(
798                         bus,
799                         NULL,
800                         "type='signal',"
801                         "sender='org.freedesktop.DBus',"
802                         "path='/org/freedesktop/DBus',"
803                         "interface='org.freedesktop.systemd1.Activator',"
804                         "member='ActivationRequest'",
805                         signal_activation_request, m);
806         if (r < 0)
807                 log_warning("Failed to subscribe to activation signal: %s", strerror(-r));
808
809         /* Allow replacing of our name, to ease implementation of
810          * reexecution, where we keep the old connection open until
811          * after the new connection is set up and the name installed
812          * to allow clients to synchronously wait for reexecution to
813          * finish */
814         r = sd_bus_request_name(bus,"org.freedesktop.systemd1", SD_BUS_NAME_REPLACE_EXISTING|SD_BUS_NAME_ALLOW_REPLACEMENT);
815         if (r < 0) {
816                 log_error("Failed to register name: %s", strerror(-r));
817                 return r;
818         }
819
820         bus_list_names(m, bus);
821
822         log_debug("Successfully connected to API bus.");
823         return 0;
824 }
825
826 static int bus_init_api(Manager *m) {
827         _cleanup_bus_unref_ sd_bus *bus = NULL;
828         int r;
829
830         if (m->api_bus)
831                 return 0;
832
833         /* The API and system bus is the same if we are running in system mode */
834         if (m->running_as == SYSTEMD_SYSTEM && m->system_bus)
835                 bus = sd_bus_ref(m->system_bus);
836         else {
837                 if (m->running_as == SYSTEMD_SYSTEM)
838                         r = sd_bus_open_system(&bus);
839                 else
840                         r = sd_bus_open_user(&bus);
841
842                 if (r < 0) {
843                         log_debug("Failed to connect to API bus, retrying later...");
844                         return 0;
845                 }
846
847                 r = sd_bus_attach_event(bus, m->event, SD_EVENT_PRIORITY_NORMAL);
848                 if (r < 0) {
849                         log_error("Failed to attach API bus to event loop: %s", strerror(-r));
850                         return 0;
851                 }
852
853                 r = bus_setup_disconnected_match(m, bus);
854                 if (r < 0)
855                         return 0;
856         }
857
858         r = bus_setup_api(m, bus);
859         if (r < 0) {
860                 log_error("Failed to set up API bus: %s", strerror(-r));
861                 return 0;
862         }
863
864         m->api_bus = bus;
865         bus = NULL;
866
867         return 0;
868 }
869
870 static int bus_setup_system(Manager *m, sd_bus *bus) {
871         int r;
872
873         assert(m);
874         assert(bus);
875
876         if (m->running_as == SYSTEMD_SYSTEM)
877                 return 0;
878
879         /* If we are a user instance we get the Released message via
880          * the system bus */
881         r = sd_bus_add_match(
882                         bus,
883                         NULL,
884                         "type='signal',"
885                         "interface='org.freedesktop.systemd1.Agent',"
886                         "member='Released',"
887                         "path='/org/freedesktop/systemd1/agent'",
888                         signal_agent_released, m);
889
890         if (r < 0)
891                 log_warning("Failed to register Released match on system bus: %s", strerror(-r));
892
893         log_debug("Successfully connected to system bus.");
894         return 0;
895 }
896
897 static int bus_init_system(Manager *m) {
898         _cleanup_bus_unref_ sd_bus *bus = NULL;
899         int r;
900
901         if (m->system_bus)
902                 return 0;
903
904         /* The API and system bus is the same if we are running in system mode */
905         if (m->running_as == SYSTEMD_SYSTEM && m->api_bus) {
906                 m->system_bus = sd_bus_ref(m->api_bus);
907                 return 0;
908         }
909
910         r = sd_bus_open_system(&bus);
911         if (r < 0) {
912                 log_debug("Failed to connect to system bus, retrying later...");
913                 return 0;
914         }
915
916         r = bus_setup_disconnected_match(m, bus);
917         if (r < 0)
918                 return 0;
919
920         r = sd_bus_attach_event(bus, m->event, SD_EVENT_PRIORITY_NORMAL);
921         if (r < 0) {
922                 log_error("Failed to attach system bus to event loop: %s", strerror(-r));
923                 return 0;
924         }
925
926         r = bus_setup_system(m, bus);
927         if (r < 0) {
928                 log_error("Failed to set up system bus: %s", strerror(-r));
929                 return 0;
930         }
931
932         m->system_bus = bus;
933         bus = NULL;
934
935         return 0;
936 }
937
938 static int bus_init_private(Manager *m) {
939         _cleanup_close_ int fd = -1;
940         union sockaddr_union sa = {
941                 .un.sun_family = AF_UNIX
942         };
943         sd_event_source *s;
944         socklen_t salen;
945         int r;
946
947         assert(m);
948
949         if (m->private_listen_fd >= 0)
950                 return 0;
951
952         /* We don't need the private socket if we have kdbus */
953         if (m->kdbus_fd >= 0)
954                 return 0;
955
956         if (m->running_as == SYSTEMD_SYSTEM) {
957
958                 /* We want the private bus only when running as init */
959                 if (getpid() != 1)
960                         return 0;
961
962                 strcpy(sa.un.sun_path, "/run/systemd/private");
963                 salen = offsetof(union sockaddr_union, un.sun_path) + strlen("/run/systemd/private");
964         } else {
965                 size_t left = sizeof(sa.un.sun_path);
966                 char *p = sa.un.sun_path;
967                 const char *e;
968
969                 e = secure_getenv("XDG_RUNTIME_DIR");
970                 if (!e) {
971                         log_error("Failed to determine XDG_RUNTIME_DIR");
972                         return -EHOSTDOWN;
973                 }
974
975                 left = strpcpy(&p, left, e);
976                 left = strpcpy(&p, left, "/systemd/private");
977
978                 salen = sizeof(sa.un) - left;
979
980                 mkdir_parents_label(sa.un.sun_path, 0755);
981         }
982
983         unlink(sa.un.sun_path);
984
985         fd = socket(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
986         if (fd < 0) {
987                 log_error("Failed to allocate private socket: %m");
988                 return -errno;
989         }
990
991         r = bind(fd, &sa.sa, salen);
992         if (r < 0) {
993                 log_error("Failed to bind private socket: %m");
994                 return -errno;
995         }
996
997         r = listen(fd, SOMAXCONN);
998         if (r < 0) {
999                 log_error("Failed to make private socket listening: %m");
1000                 return -errno;
1001         }
1002
1003         r = sd_event_add_io(m->event, &s, fd, EPOLLIN, bus_on_connection, m);
1004         if (r < 0) {
1005                 log_error("Failed to allocate event source: %s", strerror(-r));
1006                 return r;
1007         }
1008
1009         m->private_listen_fd = fd;
1010         m->private_listen_event_source = s;
1011         fd = -1;
1012
1013         log_debug("Successfully created private D-Bus server.");
1014
1015         return 0;
1016 }
1017
1018 int bus_init(Manager *m, bool try_bus_connect) {
1019         int r;
1020
1021         if (try_bus_connect) {
1022                 r = bus_init_system(m);
1023                 if (r < 0)
1024                         return r;
1025
1026                 r = bus_init_api(m);
1027                 if (r < 0)
1028                         return r;
1029         }
1030
1031         r = bus_init_private(m);
1032         if (r < 0)
1033                 return r;
1034
1035         return 0;
1036 }
1037
1038 static void destroy_bus(Manager *m, sd_bus **bus) {
1039         Iterator i;
1040         Job *j;
1041
1042         assert(m);
1043         assert(bus);
1044
1045         if (!*bus)
1046                 return;
1047
1048         /* Get rid of tracked clients on this bus */
1049         if (m->subscribed && sd_bus_track_get_bus(m->subscribed) == *bus)
1050                 m->subscribed = sd_bus_track_unref(m->subscribed);
1051
1052         HASHMAP_FOREACH(j, m->jobs, i)
1053                 if (j->clients && sd_bus_track_get_bus(j->clients) == *bus)
1054                         j->clients = sd_bus_track_unref(j->clients);
1055
1056         /* Get rid of queued message on this bus */
1057         if (m->queued_message_bus == *bus) {
1058                 m->queued_message_bus = sd_bus_unref(m->queued_message_bus);
1059
1060                 if (m->queued_message)
1061                         m->queued_message = sd_bus_message_unref(m->queued_message);
1062         }
1063
1064         /* Possibly flush unwritten data, but only if we are
1065          * unprivileged, since we don't want to sync here */
1066         if (m->running_as != SYSTEMD_SYSTEM)
1067                 sd_bus_flush(*bus);
1068
1069         /* And destroy the object */
1070         sd_bus_close(*bus);
1071         *bus = sd_bus_unref(*bus);
1072 }
1073
1074 void bus_done(Manager *m) {
1075         sd_bus *b;
1076
1077         assert(m);
1078
1079         if (m->api_bus)
1080                 destroy_bus(m, &m->api_bus);
1081         if (m->system_bus)
1082                 destroy_bus(m, &m->system_bus);
1083         while ((b = set_steal_first(m->private_buses)))
1084                 destroy_bus(m, &b);
1085
1086         set_free(m->private_buses);
1087         m->private_buses = NULL;
1088
1089         m->subscribed = sd_bus_track_unref(m->subscribed);
1090         strv_free(m->deserialized_subscribed);
1091         m->deserialized_subscribed = NULL;
1092
1093         if (m->private_listen_event_source)
1094                 m->private_listen_event_source = sd_event_source_unref(m->private_listen_event_source);
1095
1096         m->private_listen_fd = safe_close(m->private_listen_fd);
1097
1098         bus_verify_polkit_async_registry_free(m->polkit_registry);
1099 }
1100
1101 int bus_fdset_add_all(Manager *m, FDSet *fds) {
1102         Iterator i;
1103         sd_bus *b;
1104         int fd;
1105
1106         assert(m);
1107         assert(fds);
1108
1109         /* When we are about to reexecute we add all D-Bus fds to the
1110          * set to pass over to the newly executed systemd. They won't
1111          * be used there however, except thatt they are closed at the
1112          * very end of deserialization, those making it possible for
1113          * clients to synchronously wait for systemd to reexec by
1114          * simply waiting for disconnection */
1115
1116         if (m->api_bus) {
1117                 fd = sd_bus_get_fd(m->api_bus);
1118                 if (fd >= 0) {
1119                         fd = fdset_put_dup(fds, fd);
1120                         if (fd < 0)
1121                                 return fd;
1122                 }
1123         }
1124
1125         SET_FOREACH(b, m->private_buses, i) {
1126                 fd = sd_bus_get_fd(b);
1127                 if (fd >= 0) {
1128                         fd = fdset_put_dup(fds, fd);
1129                         if (fd < 0)
1130                                 return fd;
1131                 }
1132         }
1133
1134         /* We don't offer any APIs on the system bus (well, unless it
1135          * is the same as the API bus) hence we don't bother with it
1136          * here */
1137
1138         return 0;
1139 }
1140
1141 int bus_foreach_bus(
1142                 Manager *m,
1143                 sd_bus_track *subscribed2,
1144                 int (*send_message)(sd_bus *bus, void *userdata),
1145                 void *userdata) {
1146
1147         Iterator i;
1148         sd_bus *b;
1149         int r, ret = 0;
1150
1151         /* Send to all direct busses, unconditionally */
1152         SET_FOREACH(b, m->private_buses, i) {
1153                 r = send_message(b, userdata);
1154                 if (r < 0)
1155                         ret = r;
1156         }
1157
1158         /* Send to API bus, but only if somebody is subscribed */
1159         if (sd_bus_track_count(m->subscribed) > 0 ||
1160             sd_bus_track_count(subscribed2) > 0) {
1161                 r = send_message(m->api_bus, userdata);
1162                 if (r < 0)
1163                         ret = r;
1164         }
1165
1166         return ret;
1167 }
1168
1169 void bus_track_serialize(sd_bus_track *t, FILE *f) {
1170         const char *n;
1171
1172         assert(f);
1173
1174         for (n = sd_bus_track_first(t); n; n = sd_bus_track_next(t))
1175                 fprintf(f, "subscribed=%s\n", n);
1176 }
1177
1178 int bus_track_deserialize_item(char ***l, const char *line) {
1179         const char *e;
1180
1181         assert(l);
1182         assert(line);
1183
1184         e = startswith(line, "subscribed=");
1185         if (!e)
1186                 return 0;
1187
1188         return strv_extend(l, e);
1189 }
1190
1191 int bus_track_coldplug(Manager *m, sd_bus_track **t, char ***l) {
1192         int r = 0;
1193
1194         assert(m);
1195         assert(t);
1196         assert(l);
1197
1198         if (!strv_isempty(*l) && m->api_bus) {
1199                 char **i;
1200
1201                 if (!*t) {
1202                         r = sd_bus_track_new(m->api_bus, t, NULL, NULL);
1203                         if (r < 0)
1204                                 return r;
1205                 }
1206
1207                 r = 0;
1208                 STRV_FOREACH(i, *l) {
1209                         int k;
1210
1211                         k = sd_bus_track_add_name(*t, *i);
1212                         if (k < 0)
1213                                 r = k;
1214                 }
1215         }
1216
1217         strv_free(*l);
1218         *l = NULL;
1219
1220         return r;
1221 }
1222
1223 int bus_verify_manage_unit_async(Manager *m, sd_bus_message *call, sd_bus_error *error) {
1224         return bus_verify_polkit_async(call, CAP_SYS_ADMIN, "org.freedesktop.systemd1.manage-units", false, &m->polkit_registry, error);
1225 }
1226
1227 /* Same as bus_verify_manage_unit_async(), but checks for CAP_KILL instead of CAP_SYS_ADMIN */
1228 int bus_verify_manage_unit_async_for_kill(Manager *m, sd_bus_message *call, sd_bus_error *error) {
1229         return bus_verify_polkit_async(call, CAP_KILL, "org.freedesktop.systemd1.manage-units", false, &m->polkit_registry, error);
1230 }
1231
1232 int bus_verify_manage_unit_files_async(Manager *m, sd_bus_message *call, sd_bus_error *error) {
1233         return bus_verify_polkit_async(call, CAP_SYS_ADMIN, "org.freedesktop.systemd1.manage-unit-files", false, &m->polkit_registry, error);
1234 }
1235
1236 int bus_verify_reload_daemon_async(Manager *m, sd_bus_message *call, sd_bus_error *error) {
1237         return bus_verify_polkit_async(call, CAP_SYS_ADMIN, "org.freedesktop.systemd1.reload-daemon", false, &m->polkit_registry, error);
1238 }