chiark / gitweb /
target: implicitly shutdown targets on shutdown, so that they are pulled into the...
[elogind.git] / src / 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 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 <sys/epoll.h>
23 #include <sys/timerfd.h>
24 #include <errno.h>
25 #include <unistd.h>
26 #include <dbus/dbus.h>
27
28 #include "dbus.h"
29 #include "log.h"
30 #include "strv.h"
31 #include "cgroup.h"
32 #include "dbus-unit.h"
33 #include "dbus-job.h"
34 #include "dbus-manager.h"
35 #include "dbus-service.h"
36 #include "dbus-socket.h"
37 #include "dbus-target.h"
38 #include "dbus-device.h"
39 #include "dbus-mount.h"
40 #include "dbus-automount.h"
41 #include "dbus-snapshot.h"
42 #include "dbus-swap.h"
43 #include "dbus-timer.h"
44 #include "dbus-path.h"
45 #include "bus-errors.h"
46 #include "special.h"
47
48 #define CONNECTIONS_MAX 52
49
50 static const char bus_properties_interface[] = BUS_PROPERTIES_INTERFACE;
51 static const char bus_introspectable_interface[] = BUS_INTROSPECTABLE_INTERFACE;
52
53 const char *const bus_interface_table[] = {
54         "org.freedesktop.DBus.Properties",     bus_properties_interface,
55         "org.freedesktop.DBus.Introspectable", bus_introspectable_interface,
56         "org.freedesktop.systemd1.Manager",    bus_manager_interface,
57         "org.freedesktop.systemd1.Job",        bus_job_interface,
58         "org.freedesktop.systemd1.Unit",       bus_unit_interface,
59         "org.freedesktop.systemd1.Service",    bus_service_interface,
60         "org.freedesktop.systemd1.Socket",     bus_socket_interface,
61         "org.freedesktop.systemd1.Target",     bus_target_interface,
62         "org.freedesktop.systemd1.Device",     bus_device_interface,
63         "org.freedesktop.systemd1.Mount",      bus_mount_interface,
64         "org.freedesktop.systemd1.Automount",  bus_automount_interface,
65         "org.freedesktop.systemd1.Snapshot",   bus_snapshot_interface,
66         "org.freedesktop.systemd1.Swap",       bus_swap_interface,
67         "org.freedesktop.systemd1.Timer",      bus_timer_interface,
68         "org.freedesktop.systemd1.Path",       bus_path_interface,
69         NULL
70 };
71
72 static const char *error_to_dbus(int error);
73 static void bus_done_api(Manager *m);
74 static void bus_done_system(Manager *m);
75 static void bus_done_private(Manager *m);
76 static void shutdown_connection(Manager *m, DBusConnection *c);
77
78 static void bus_dispatch_status(DBusConnection *bus, DBusDispatchStatus status, void *data)  {
79         Manager *m = data;
80
81         assert(bus);
82         assert(m);
83
84         /* We maintain two sets, one for those connections where we
85          * requested a dispatch, and another where we didn't. And then,
86          * we move the connections between the two sets. */
87
88         if (status == DBUS_DISPATCH_COMPLETE)
89                 set_move_one(m->bus_connections, m->bus_connections_for_dispatch, bus);
90         else
91                 set_move_one(m->bus_connections_for_dispatch, m->bus_connections, bus);
92 }
93
94 static uint32_t bus_flags_to_events(DBusWatch *bus_watch) {
95         unsigned flags;
96         uint32_t events = 0;
97
98         assert(bus_watch);
99
100         /* no watch flags for disabled watches */
101         if (!dbus_watch_get_enabled(bus_watch))
102                 return 0;
103
104         flags = dbus_watch_get_flags(bus_watch);
105
106         if (flags & DBUS_WATCH_READABLE)
107                 events |= EPOLLIN;
108         if (flags & DBUS_WATCH_WRITABLE)
109                 events |= EPOLLOUT;
110
111         return events | EPOLLHUP | EPOLLERR;
112 }
113
114 static unsigned events_to_bus_flags(uint32_t events) {
115         unsigned flags = 0;
116
117         if (events & EPOLLIN)
118                 flags |= DBUS_WATCH_READABLE;
119         if (events & EPOLLOUT)
120                 flags |= DBUS_WATCH_WRITABLE;
121         if (events & EPOLLHUP)
122                 flags |= DBUS_WATCH_HANGUP;
123         if (events & EPOLLERR)
124                 flags |= DBUS_WATCH_ERROR;
125
126         return flags;
127 }
128
129 void bus_watch_event(Manager *m, Watch *w, int events) {
130         assert(m);
131         assert(w);
132
133         /* This is called by the event loop whenever there is
134          * something happening on D-Bus' file handles. */
135
136         if (!dbus_watch_get_enabled(w->data.bus_watch))
137                 return;
138
139         dbus_watch_handle(w->data.bus_watch, events_to_bus_flags(events));
140 }
141
142 static dbus_bool_t bus_add_watch(DBusWatch *bus_watch, void *data) {
143         Manager *m = data;
144         Watch *w;
145         struct epoll_event ev;
146
147         assert(bus_watch);
148         assert(m);
149
150         if (!(w = new0(Watch, 1)))
151                 return FALSE;
152
153         w->fd = dbus_watch_get_unix_fd(bus_watch);
154         w->type = WATCH_DBUS_WATCH;
155         w->data.bus_watch = bus_watch;
156
157         zero(ev);
158         ev.events = bus_flags_to_events(bus_watch);
159         ev.data.ptr = w;
160
161         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0) {
162
163                 if (errno != EEXIST) {
164                         free(w);
165                         return FALSE;
166                 }
167
168                 /* Hmm, bloody D-Bus creates multiple watches on the
169                  * same fd. epoll() does not like that. As a dirty
170                  * hack we simply dup() the fd and hence get a second
171                  * one we can safely add to the epoll(). */
172
173                 if ((w->fd = dup(w->fd)) < 0) {
174                         free(w);
175                         return FALSE;
176                 }
177
178                 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0) {
179                         free(w);
180                         close_nointr_nofail(w->fd);
181                         return FALSE;
182                 }
183
184                 w->fd_is_dupped = true;
185         }
186
187         dbus_watch_set_data(bus_watch, w, NULL);
188
189         return TRUE;
190 }
191
192 static void bus_remove_watch(DBusWatch *bus_watch, void *data) {
193         Manager *m = data;
194         Watch *w;
195
196         assert(bus_watch);
197         assert(m);
198
199         if (!(w = dbus_watch_get_data(bus_watch)))
200                 return;
201
202         assert(w->type == WATCH_DBUS_WATCH);
203         assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
204
205         if (w->fd_is_dupped)
206                 close_nointr_nofail(w->fd);
207
208         free(w);
209 }
210
211 static void bus_toggle_watch(DBusWatch *bus_watch, void *data) {
212         Manager *m = data;
213         Watch *w;
214         struct epoll_event ev;
215
216         assert(bus_watch);
217         assert(m);
218
219         assert_se(w = dbus_watch_get_data(bus_watch));
220         assert(w->type == WATCH_DBUS_WATCH);
221
222         zero(ev);
223         ev.events = bus_flags_to_events(bus_watch);
224         ev.data.ptr = w;
225
226         assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_MOD, w->fd, &ev) == 0);
227 }
228
229 static int bus_timeout_arm(Manager *m, Watch *w) {
230         struct itimerspec its;
231
232         assert(m);
233         assert(w);
234
235         zero(its);
236
237         if (dbus_timeout_get_enabled(w->data.bus_timeout)) {
238                 timespec_store(&its.it_value, dbus_timeout_get_interval(w->data.bus_timeout) * USEC_PER_MSEC);
239                 its.it_interval = its.it_interval;
240         }
241
242         if (timerfd_settime(w->fd, 0, &its, NULL) < 0)
243                 return -errno;
244
245         return 0;
246 }
247
248 void bus_timeout_event(Manager *m, Watch *w, int events) {
249         assert(m);
250         assert(w);
251
252         /* This is called by the event loop whenever there is
253          * something happening on D-Bus' file handles. */
254
255         if (!(dbus_timeout_get_enabled(w->data.bus_timeout)))
256                 return;
257
258         dbus_timeout_handle(w->data.bus_timeout);
259 }
260
261 static dbus_bool_t bus_add_timeout(DBusTimeout *timeout, void *data) {
262         Manager *m = data;
263         Watch *w;
264         struct epoll_event ev;
265
266         assert(timeout);
267         assert(m);
268
269         if (!(w = new0(Watch, 1)))
270                 return FALSE;
271
272         if (!(w->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
273                 goto fail;
274
275         w->type = WATCH_DBUS_TIMEOUT;
276         w->data.bus_timeout = timeout;
277
278         if (bus_timeout_arm(m, w) < 0)
279                 goto fail;
280
281         zero(ev);
282         ev.events = EPOLLIN;
283         ev.data.ptr = w;
284
285         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0)
286                 goto fail;
287
288         dbus_timeout_set_data(timeout, w, NULL);
289
290         return TRUE;
291
292 fail:
293         if (w->fd >= 0)
294                 close_nointr_nofail(w->fd);
295
296         free(w);
297         return FALSE;
298 }
299
300 static void bus_remove_timeout(DBusTimeout *timeout, void *data) {
301         Manager *m = data;
302         Watch *w;
303
304         assert(timeout);
305         assert(m);
306
307         if (!(w = dbus_timeout_get_data(timeout)))
308                 return;
309
310         assert(w->type == WATCH_DBUS_TIMEOUT);
311         assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
312         close_nointr_nofail(w->fd);
313         free(w);
314 }
315
316 static void bus_toggle_timeout(DBusTimeout *timeout, void *data) {
317         Manager *m = data;
318         Watch *w;
319         int r;
320
321         assert(timeout);
322         assert(m);
323
324         assert_se(w = dbus_timeout_get_data(timeout));
325         assert(w->type == WATCH_DBUS_TIMEOUT);
326
327         if ((r = bus_timeout_arm(m, w)) < 0)
328                 log_error("Failed to rearm timer: %s", strerror(-r));
329 }
330
331 static DBusHandlerResult api_bus_message_filter(DBusConnection *connection, DBusMessage *message, void *data) {
332         Manager *m = data;
333         DBusError error;
334         DBusMessage *reply = NULL;
335
336         assert(connection);
337         assert(message);
338         assert(m);
339
340         dbus_error_init(&error);
341
342         if (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_METHOD_CALL ||
343             dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
344                 log_debug("Got D-Bus request: %s.%s() on %s",
345                           dbus_message_get_interface(message),
346                           dbus_message_get_member(message),
347                           dbus_message_get_path(message));
348
349         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
350                 log_debug("API D-Bus connection terminated.");
351                 bus_done_api(m);
352
353         } else if (dbus_message_is_signal(message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) {
354                 const char *name, *old_owner, *new_owner;
355
356                 if (!dbus_message_get_args(message, &error,
357                                            DBUS_TYPE_STRING, &name,
358                                            DBUS_TYPE_STRING, &old_owner,
359                                            DBUS_TYPE_STRING, &new_owner,
360                                            DBUS_TYPE_INVALID))
361                         log_error("Failed to parse NameOwnerChanged message: %s", error.message);
362                 else  {
363                         if (set_remove(BUS_CONNECTION_SUBSCRIBED(m, connection), (char*) name))
364                                 log_debug("Subscription client vanished: %s (left: %u)", name, set_size(BUS_CONNECTION_SUBSCRIBED(m, connection)));
365
366                         if (old_owner[0] == 0)
367                                 old_owner = NULL;
368
369                         if (new_owner[0] == 0)
370                                 new_owner = NULL;
371
372                         manager_dispatch_bus_name_owner_changed(m, name, old_owner, new_owner);
373                 }
374         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Activator", "ActivationRequest")) {
375                 const char *name;
376
377                 if (!dbus_message_get_args(message, &error,
378                                            DBUS_TYPE_STRING, &name,
379                                            DBUS_TYPE_INVALID))
380                         log_error("Failed to parse ActivationRequest message: %s", error.message);
381                 else  {
382                         int r;
383                         Unit *u;
384
385                         log_debug("Got D-Bus activation request for %s", name);
386
387                         if (manager_unit_pending_inactive(m, SPECIAL_DBUS_SERVICE) ||
388                             manager_unit_pending_inactive(m, SPECIAL_DBUS_SOCKET)) {
389                                 r = -EADDRNOTAVAIL;
390                                 dbus_set_error(&error, BUS_ERROR_SHUTTING_DOWN, "Refusing activation, D-Bus is shutting down.");
391                         } else {
392                                 r = manager_load_unit(m, name, NULL, &error, &u);
393
394                                 if (r >= 0 && u->meta.refuse_manual_start)
395                                         r = -EPERM;
396
397                                 if (r >= 0)
398                                         r = manager_add_job(m, JOB_START, u, JOB_REPLACE, true, &error, NULL);
399                         }
400
401                         if (r < 0) {
402                                 const char *id, *text;
403
404                                 log_warning("D-Bus activation failed for %s: %s", name, strerror(-r));
405
406                                 if (!(reply = dbus_message_new_signal("/org/freedesktop/systemd1", "org.freedesktop.systemd1.Activator", "ActivationFailure")))
407                                         goto oom;
408
409                                 id = error.name ? error.name : error_to_dbus(r);
410                                 text = bus_error(&error, r);
411
412                                 if (!dbus_message_set_destination(reply, DBUS_SERVICE_DBUS) ||
413                                     !dbus_message_append_args(reply,
414                                                               DBUS_TYPE_STRING, &name,
415                                                               DBUS_TYPE_STRING, &id,
416                                                               DBUS_TYPE_STRING, &text,
417                                                               DBUS_TYPE_INVALID))
418                                         goto oom;
419                         }
420
421                         /* On success we don't do anything, the service will be spwaned now */
422                 }
423         }
424
425         dbus_error_free(&error);
426
427         if (reply) {
428                 if (!dbus_connection_send(connection, reply, NULL))
429                         goto oom;
430
431                 dbus_message_unref(reply);
432         }
433
434         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
435
436 oom:
437         if (reply)
438                 dbus_message_unref(reply);
439
440         dbus_error_free(&error);
441
442         return DBUS_HANDLER_RESULT_NEED_MEMORY;
443 }
444
445 static DBusHandlerResult system_bus_message_filter(DBusConnection *connection, DBusMessage *message, void *data) {
446         Manager *m = data;
447         DBusError error;
448
449         assert(connection);
450         assert(message);
451         assert(m);
452
453         dbus_error_init(&error);
454
455         if (m->api_bus != m->system_bus &&
456             (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_METHOD_CALL ||
457              dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL))
458                 log_debug("Got D-Bus request on system bus: %s.%s() on %s",
459                           dbus_message_get_interface(message),
460                           dbus_message_get_member(message),
461                           dbus_message_get_path(message));
462
463         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
464                 log_debug("System D-Bus connection terminated.");
465                 bus_done_system(m);
466
467         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Agent", "Released")) {
468                 const char *cgroup;
469
470                 if (!dbus_message_get_args(message, &error,
471                                            DBUS_TYPE_STRING, &cgroup,
472                                            DBUS_TYPE_INVALID))
473                         log_error("Failed to parse Released message: %s", error.message);
474                 else
475                         cgroup_notify_empty(m, cgroup);
476         }
477
478         dbus_error_free(&error);
479         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
480 }
481
482 static DBusHandlerResult private_bus_message_filter(DBusConnection *connection, DBusMessage *message, void *data) {
483         Manager *m = data;
484         DBusError error;
485
486         assert(connection);
487         assert(message);
488         assert(m);
489
490         dbus_error_init(&error);
491
492         if (dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_METHOD_CALL ||
493             dbus_message_get_type(message) == DBUS_MESSAGE_TYPE_SIGNAL)
494                 log_debug("Got D-Bus request: %s.%s() on %s",
495                           dbus_message_get_interface(message),
496                           dbus_message_get_member(message),
497                           dbus_message_get_path(message));
498
499         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected"))
500                 shutdown_connection(m, connection);
501         else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Agent", "Released")) {
502                 const char *cgroup;
503
504                 if (!dbus_message_get_args(message, &error,
505                                            DBUS_TYPE_STRING, &cgroup,
506                                            DBUS_TYPE_INVALID))
507                         log_error("Failed to parse Released message: %s", error.message);
508                 else
509                         cgroup_notify_empty(m, cgroup);
510         }
511
512         dbus_error_free(&error);
513
514         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
515 }
516
517 unsigned bus_dispatch(Manager *m) {
518         DBusConnection *c;
519
520         assert(m);
521
522         if (m->queued_message) {
523                 /* If we cannot get rid of this message we won't
524                  * dispatch any D-Bus messages, so that we won't end
525                  * up wanting to queue another message. */
526
527                 if (m->queued_message_connection)
528                         if (!dbus_connection_send(m->queued_message_connection, m->queued_message, NULL))
529                                 return 0;
530
531                 dbus_message_unref(m->queued_message);
532                 m->queued_message = NULL;
533                 m->queued_message_connection = NULL;
534         }
535
536         if ((c = set_first(m->bus_connections_for_dispatch))) {
537                 if (dbus_connection_dispatch(c) == DBUS_DISPATCH_COMPLETE)
538                         set_move_one(m->bus_connections, m->bus_connections_for_dispatch, c);
539
540                 return 1;
541         }
542
543         return 0;
544 }
545
546 static void request_name_pending_cb(DBusPendingCall *pending, void *userdata) {
547         DBusMessage *reply;
548         DBusError error;
549
550         dbus_error_init(&error);
551
552         assert_se(reply = dbus_pending_call_steal_reply(pending));
553
554         switch (dbus_message_get_type(reply)) {
555
556         case DBUS_MESSAGE_TYPE_ERROR:
557
558                 assert_se(dbus_set_error_from_message(&error, reply));
559                 log_warning("RequestName() failed: %s", error.message);
560                 break;
561
562         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
563                 uint32_t r;
564
565                 if (!dbus_message_get_args(reply,
566                                            &error,
567                                            DBUS_TYPE_UINT32, &r,
568                                            DBUS_TYPE_INVALID)) {
569                         log_error("Failed to parse RequestName() reply: %s", error.message);
570                         break;
571                 }
572
573                 if (r == 1)
574                         log_debug("Successfully acquired name.");
575                 else
576                         log_error("Name already owned.");
577
578                 break;
579         }
580
581         default:
582                 assert_not_reached("Invalid reply message");
583         }
584
585         dbus_message_unref(reply);
586         dbus_error_free(&error);
587 }
588
589 static int request_name(Manager *m) {
590         const char *name = "org.freedesktop.systemd1";
591         uint32_t flags = 0;
592         DBusMessage *message = NULL;
593         DBusPendingCall *pending = NULL;
594
595         if (!(message = dbus_message_new_method_call(
596                               DBUS_SERVICE_DBUS,
597                               DBUS_PATH_DBUS,
598                               DBUS_INTERFACE_DBUS,
599                               "RequestName")))
600                 goto oom;
601
602         if (!dbus_message_append_args(
603                             message,
604                             DBUS_TYPE_STRING, &name,
605                             DBUS_TYPE_UINT32, &flags,
606                             DBUS_TYPE_INVALID))
607                 goto oom;
608
609         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
610                 goto oom;
611
612         if (!dbus_pending_call_set_notify(pending, request_name_pending_cb, m, NULL))
613                 goto oom;
614
615         dbus_message_unref(message);
616         dbus_pending_call_unref(pending);
617
618         /* We simple ask for the name and don't wait for it. Sooner or
619          * later we'll have it. */
620
621         return 0;
622
623 oom:
624         if (pending) {
625                 dbus_pending_call_cancel(pending);
626                 dbus_pending_call_unref(pending);
627         }
628
629         if (message)
630                 dbus_message_unref(message);
631
632         return -ENOMEM;
633 }
634
635 static void query_name_list_pending_cb(DBusPendingCall *pending, void *userdata) {
636         DBusMessage *reply;
637         DBusError error;
638         Manager *m = userdata;
639
640         assert(m);
641
642         dbus_error_init(&error);
643
644         assert_se(reply = dbus_pending_call_steal_reply(pending));
645
646         switch (dbus_message_get_type(reply)) {
647
648         case DBUS_MESSAGE_TYPE_ERROR:
649
650                 assert_se(dbus_set_error_from_message(&error, reply));
651                 log_warning("ListNames() failed: %s", error.message);
652                 break;
653
654         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
655                 int r;
656                 char **l;
657
658                 if ((r = bus_parse_strv(reply, &l)) < 0)
659                         log_warning("Failed to parse ListNames() reply: %s", strerror(-r));
660                 else {
661                         char **t;
662
663                         STRV_FOREACH(t, l)
664                                 /* This is a bit hacky, we say the
665                                  * owner of the name is the name
666                                  * itself, because we don't want the
667                                  * extra traffic to figure out the
668                                  * real owner. */
669                                 manager_dispatch_bus_name_owner_changed(m, *t, NULL, *t);
670
671                         strv_free(l);
672                 }
673
674                 break;
675         }
676
677         default:
678                 assert_not_reached("Invalid reply message");
679         }
680
681         dbus_message_unref(reply);
682         dbus_error_free(&error);
683 }
684
685 static int query_name_list(Manager *m) {
686         DBusMessage *message = NULL;
687         DBusPendingCall *pending = NULL;
688
689         /* Asks for the currently installed bus names */
690
691         if (!(message = dbus_message_new_method_call(
692                               DBUS_SERVICE_DBUS,
693                               DBUS_PATH_DBUS,
694                               DBUS_INTERFACE_DBUS,
695                               "ListNames")))
696                 goto oom;
697
698         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
699                 goto oom;
700
701         if (!dbus_pending_call_set_notify(pending, query_name_list_pending_cb, m, NULL))
702                 goto oom;
703
704         dbus_message_unref(message);
705         dbus_pending_call_unref(pending);
706
707         /* We simple ask for the list and don't wait for it. Sooner or
708          * later we'll get it. */
709
710         return 0;
711
712 oom:
713         if (pending) {
714                 dbus_pending_call_cancel(pending);
715                 dbus_pending_call_unref(pending);
716         }
717
718         if (message)
719                 dbus_message_unref(message);
720
721         return -ENOMEM;
722 }
723
724 static int bus_setup_loop(Manager *m, DBusConnection *bus) {
725         assert(m);
726         assert(bus);
727
728         dbus_connection_set_exit_on_disconnect(bus, FALSE);
729
730         if (!dbus_connection_set_watch_functions(bus, bus_add_watch, bus_remove_watch, bus_toggle_watch, m, NULL) ||
731             !dbus_connection_set_timeout_functions(bus, bus_add_timeout, bus_remove_timeout, bus_toggle_timeout, m, NULL)) {
732                 log_error("Not enough memory");
733                 return -ENOMEM;
734         }
735
736         if (set_put(m->bus_connections_for_dispatch, bus) < 0) {
737                 log_error("Not enough memory");
738                 return -ENOMEM;
739         }
740
741         dbus_connection_set_dispatch_status_function(bus, bus_dispatch_status, m, NULL);
742         return 0;
743 }
744
745 static dbus_bool_t allow_only_root(DBusConnection *connection, unsigned long uid, void *data) {
746         return uid == 0;
747 }
748
749 static void bus_new_connection(
750                 DBusServer *server,
751                 DBusConnection *new_connection,
752                 void *data) {
753
754         Manager *m = data;
755
756         assert(m);
757
758         if (set_size(m->bus_connections) >= CONNECTIONS_MAX) {
759                 log_error("Too many concurrent connections.");
760                 return;
761         }
762
763         dbus_connection_set_unix_user_function(new_connection, allow_only_root, NULL, NULL);
764
765         if (bus_setup_loop(m, new_connection) < 0)
766                 return;
767
768         if (!dbus_connection_register_object_path(new_connection, "/org/freedesktop/systemd1", &bus_manager_vtable, m) ||
769             !dbus_connection_register_fallback(new_connection, "/org/freedesktop/systemd1/unit", &bus_unit_vtable, m) ||
770             !dbus_connection_register_fallback(new_connection, "/org/freedesktop/systemd1/job", &bus_job_vtable, m) ||
771             !dbus_connection_add_filter(new_connection, private_bus_message_filter, m, NULL)) {
772                 log_error("Not enough memory.");
773                 return;
774         }
775
776         log_debug("Accepted connection on private bus.");
777
778         dbus_connection_ref(new_connection);
779 }
780
781 static int bus_init_system(Manager *m) {
782         DBusError error;
783         int r;
784
785         assert(m);
786
787         dbus_error_init(&error);
788
789         if (m->system_bus)
790                 return 0;
791
792         if (m->running_as == MANAGER_SYSTEM && m->api_bus)
793                 m->system_bus = m->api_bus;
794         else {
795                 if (!(m->system_bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error))) {
796                         log_debug("Failed to get system D-Bus connection, retrying later: %s", error.message);
797                         r = 0;
798                         goto fail;
799                 }
800
801                 if ((r = bus_setup_loop(m, m->system_bus)) < 0)
802                         goto fail;
803         }
804
805         if (!dbus_connection_add_filter(m->system_bus, system_bus_message_filter, m, NULL)) {
806                 log_error("Not enough memory");
807                 r = -EIO;
808                 goto fail;
809         }
810
811         dbus_bus_add_match(m->system_bus,
812                            "type='signal',"
813                            "interface='org.freedesktop.systemd1.Agent',"
814                            "member='Released',"
815                            "path='/org/freedesktop/systemd1/agent'",
816                            &error);
817
818         if (dbus_error_is_set(&error)) {
819                 log_error("Failed to register match: %s", error.message);
820                 r = -EIO;
821                 goto fail;
822         }
823
824         if (m->api_bus != m->system_bus) {
825                 char *id;
826                 log_debug("Successfully connected to system D-Bus bus %s as %s",
827                          strnull((id = dbus_connection_get_server_id(m->system_bus))),
828                          strnull(dbus_bus_get_unique_name(m->system_bus)));
829                 dbus_free(id);
830         }
831
832         return 0;
833
834 fail:
835         bus_done_system(m);
836         dbus_error_free(&error);
837
838         return r;
839 }
840
841 static int bus_init_api(Manager *m) {
842         DBusError error;
843         int r;
844
845         assert(m);
846
847         dbus_error_init(&error);
848
849         if (m->api_bus)
850                 return 0;
851
852         if (m->running_as == MANAGER_SYSTEM && m->system_bus)
853                 m->api_bus = m->system_bus;
854         else {
855                 if (!(m->api_bus = dbus_bus_get_private(m->running_as == MANAGER_SESSION ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error))) {
856                         log_debug("Failed to get API D-Bus connection, retrying later: %s", error.message);
857                         r = 0;
858                         goto fail;
859                 }
860
861                 if ((r = bus_setup_loop(m, m->api_bus)) < 0)
862                         goto fail;
863         }
864
865         if (!dbus_connection_register_object_path(m->api_bus, "/org/freedesktop/systemd1", &bus_manager_vtable, m) ||
866             !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/unit", &bus_unit_vtable, m) ||
867             !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/job", &bus_job_vtable, m) ||
868             !dbus_connection_add_filter(m->api_bus, api_bus_message_filter, m, NULL)) {
869                 log_error("Not enough memory");
870                 r = -ENOMEM;
871                 goto fail;
872         }
873
874         /* Get NameOwnerChange messages */
875         dbus_bus_add_match(m->api_bus,
876                            "type='signal',"
877                            "sender='"DBUS_SERVICE_DBUS"',"
878                            "interface='"DBUS_INTERFACE_DBUS"',"
879                            "member='NameOwnerChanged',"
880                            "path='"DBUS_PATH_DBUS"'",
881                            &error);
882
883         if (dbus_error_is_set(&error)) {
884                 log_error("Failed to register match: %s", error.message);
885                 r = -EIO;
886                 goto fail;
887         }
888
889         /* Get activation requests */
890         dbus_bus_add_match(m->api_bus,
891                            "type='signal',"
892                            "sender='"DBUS_SERVICE_DBUS"',"
893                            "interface='org.freedesktop.systemd1.Activator',"
894                            "member='ActivationRequest',"
895                            "path='"DBUS_PATH_DBUS"'",
896                            &error);
897
898         if (dbus_error_is_set(&error)) {
899                 log_error("Failed to register match: %s", error.message);
900                 r = -EIO;
901                 goto fail;
902         }
903
904         if ((r = request_name(m)) < 0)
905                 goto fail;
906
907         if ((r = query_name_list(m)) < 0)
908                 goto fail;
909
910         if (m->api_bus != m->system_bus) {
911                 char *id;
912                 log_debug("Successfully connected to API D-Bus bus %s as %s",
913                          strnull((id = dbus_connection_get_server_id(m->api_bus))),
914                          strnull(dbus_bus_get_unique_name(m->api_bus)));
915                 dbus_free(id);
916         }
917
918         return 0;
919
920 fail:
921         bus_done_api(m);
922         dbus_error_free(&error);
923
924         return r;
925 }
926
927 static int bus_init_private(Manager *m) {
928         DBusError error;
929         int r;
930         const char *const external_only[] = {
931                 "EXTERNAL",
932                 NULL
933         };
934
935         assert(m);
936
937         dbus_error_init(&error);
938
939         if (m->private_bus)
940                 return 0;
941
942         /* We want the private bus only when running as init */
943         if (getpid() != 1)
944                 return 0;
945
946         if (!(m->private_bus = dbus_server_listen("unix:abstract=/org/freedesktop/systemd1/private", &error))) {
947                 log_error("Failed to create private D-Bus server: %s", error.message);
948                 r = -EIO;
949                 goto fail;
950         }
951
952         if (!dbus_server_set_auth_mechanisms(m->private_bus, (const char**) external_only) ||
953             !dbus_server_set_watch_functions(m->private_bus, bus_add_watch, bus_remove_watch, bus_toggle_watch, m, NULL) ||
954             !dbus_server_set_timeout_functions(m->private_bus, bus_add_timeout, bus_remove_timeout, bus_toggle_timeout, m, NULL)) {
955                 log_error("Not enough memory");
956                 r = -ENOMEM;
957                 goto fail;
958         }
959
960         dbus_server_set_new_connection_function(m->private_bus, bus_new_connection, m, NULL);
961
962         log_debug("Successfully created private D-Bus server.");
963
964         return 0;
965
966 fail:
967         bus_done_private(m);
968         dbus_error_free(&error);
969
970         return r;
971 }
972
973 int bus_init(Manager *m) {
974         int r;
975
976         if (set_ensure_allocated(&m->bus_connections, trivial_hash_func, trivial_compare_func) < 0 ||
977             set_ensure_allocated(&m->bus_connections_for_dispatch, trivial_hash_func, trivial_compare_func) < 0) {
978                 log_error("Not enough memory");
979                 return -ENOMEM;
980         }
981
982         if (m->name_data_slot < 0)
983                 if (!dbus_pending_call_allocate_data_slot(&m->name_data_slot)) {
984                         log_error("Not enough memory");
985                         return -ENOMEM;
986                 }
987
988         if (m->subscribed_data_slot < 0)
989                 if (!dbus_pending_call_allocate_data_slot(&m->subscribed_data_slot)) {
990                         log_error("Not enough memory");
991                         return -ENOMEM;
992                 }
993
994         if ((r = bus_init_system(m)) < 0 ||
995             (r = bus_init_api(m)) < 0 ||
996             (r = bus_init_private(m)) < 0)
997                 return r;
998
999         return 0;
1000 }
1001
1002 static void shutdown_connection(Manager *m, DBusConnection *c) {
1003         Set *s;
1004         Job *j;
1005         Iterator i;
1006
1007         HASHMAP_FOREACH(j, m->jobs, i)
1008                 if (j->bus == c) {
1009                         free(j->bus_client);
1010                         j->bus_client = NULL;
1011
1012                         j->bus = NULL;
1013                 }
1014
1015         set_remove(m->bus_connections, c);
1016         set_remove(m->bus_connections_for_dispatch, c);
1017
1018         if ((s = BUS_CONNECTION_SUBSCRIBED(m, c))) {
1019                 char *t;
1020
1021                 while ((t = set_steal_first(s)))
1022                         free(t);
1023
1024                 set_free(s);
1025         }
1026
1027         if (m->queued_message_connection == c) {
1028                 m->queued_message_connection = NULL;
1029
1030                 if (m->queued_message) {
1031                         dbus_message_unref(m->queued_message);
1032                         m->queued_message = NULL;
1033                 }
1034         }
1035
1036         dbus_connection_set_dispatch_status_function(c, NULL, NULL, NULL);
1037         dbus_connection_flush(c);
1038         dbus_connection_close(c);
1039         dbus_connection_unref(c);
1040 }
1041
1042 static void bus_done_api(Manager *m) {
1043         assert(m);
1044
1045         if (m->api_bus) {
1046                 if (m->system_bus == m->api_bus)
1047                         m->system_bus = NULL;
1048
1049                 shutdown_connection(m, m->api_bus);
1050                 m->api_bus = NULL;
1051         }
1052
1053
1054        if (m->queued_message) {
1055                dbus_message_unref(m->queued_message);
1056                m->queued_message = NULL;
1057        }
1058 }
1059
1060 static void bus_done_system(Manager *m) {
1061         assert(m);
1062
1063         if (m->system_bus == m->api_bus)
1064                 bus_done_api(m);
1065
1066         if (m->system_bus) {
1067                 shutdown_connection(m, m->system_bus);
1068                 m->system_bus = NULL;
1069         }
1070 }
1071
1072 static void bus_done_private(Manager *m) {
1073
1074         if (m->private_bus) {
1075                 dbus_server_disconnect(m->private_bus);
1076                 dbus_server_unref(m->private_bus);
1077                 m->private_bus = NULL;
1078         }
1079 }
1080
1081 void bus_done(Manager *m) {
1082         DBusConnection *c;
1083
1084         bus_done_api(m);
1085         bus_done_system(m);
1086         bus_done_private(m);
1087
1088         while ((c = set_steal_first(m->bus_connections)))
1089                 shutdown_connection(m, c);
1090
1091         while ((c = set_steal_first(m->bus_connections_for_dispatch)))
1092                 shutdown_connection(m, c);
1093
1094         set_free(m->bus_connections);
1095         set_free(m->bus_connections_for_dispatch);
1096
1097         if (m->name_data_slot >= 0)
1098                dbus_pending_call_free_data_slot(&m->name_data_slot);
1099
1100         if (m->subscribed_data_slot >= 0)
1101                 dbus_pending_call_free_data_slot(&m->subscribed_data_slot);
1102 }
1103
1104 static void query_pid_pending_cb(DBusPendingCall *pending, void *userdata) {
1105         Manager *m = userdata;
1106         DBusMessage *reply;
1107         DBusError error;
1108         const char *name;
1109
1110         dbus_error_init(&error);
1111
1112         assert_se(name = BUS_PENDING_CALL_NAME(m, pending));
1113         assert_se(reply = dbus_pending_call_steal_reply(pending));
1114
1115         switch (dbus_message_get_type(reply)) {
1116
1117         case DBUS_MESSAGE_TYPE_ERROR:
1118
1119                 assert_se(dbus_set_error_from_message(&error, reply));
1120                 log_warning("GetConnectionUnixProcessID() failed: %s", error.message);
1121                 break;
1122
1123         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
1124                 uint32_t r;
1125
1126                 if (!dbus_message_get_args(reply,
1127                                            &error,
1128                                            DBUS_TYPE_UINT32, &r,
1129                                            DBUS_TYPE_INVALID)) {
1130                         log_error("Failed to parse GetConnectionUnixProcessID() reply: %s", error.message);
1131                         break;
1132                 }
1133
1134                 manager_dispatch_bus_query_pid_done(m, name, (pid_t) r);
1135                 break;
1136         }
1137
1138         default:
1139                 assert_not_reached("Invalid reply message");
1140         }
1141
1142         dbus_message_unref(reply);
1143         dbus_error_free(&error);
1144 }
1145
1146 int bus_query_pid(Manager *m, const char *name) {
1147         DBusMessage *message = NULL;
1148         DBusPendingCall *pending = NULL;
1149         char *n = NULL;
1150
1151         assert(m);
1152         assert(name);
1153
1154         if (!(message = dbus_message_new_method_call(
1155                               DBUS_SERVICE_DBUS,
1156                               DBUS_PATH_DBUS,
1157                               DBUS_INTERFACE_DBUS,
1158                               "GetConnectionUnixProcessID")))
1159                 goto oom;
1160
1161         if (!(dbus_message_append_args(
1162                               message,
1163                               DBUS_TYPE_STRING, &name,
1164                               DBUS_TYPE_INVALID)))
1165                 goto oom;
1166
1167         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
1168                 goto oom;
1169
1170         if (!(n = strdup(name)))
1171                 goto oom;
1172
1173         if (!dbus_pending_call_set_data(pending, m->name_data_slot, n, free))
1174                 goto oom;
1175
1176         n = NULL;
1177
1178         if (!dbus_pending_call_set_notify(pending, query_pid_pending_cb, m, NULL))
1179                 goto oom;
1180
1181         dbus_message_unref(message);
1182         dbus_pending_call_unref(pending);
1183
1184         return 0;
1185
1186 oom:
1187         free(n);
1188
1189         if (pending) {
1190                 dbus_pending_call_cancel(pending);
1191                 dbus_pending_call_unref(pending);
1192         }
1193
1194         if (message)
1195                 dbus_message_unref(message);
1196
1197         return -ENOMEM;
1198 }
1199
1200 DBusHandlerResult bus_default_message_handler(Manager *m, DBusConnection *c, DBusMessage *message, const char*introspection, const BusProperty *properties) {
1201         DBusError error;
1202         DBusMessage *reply = NULL;
1203         int r;
1204
1205         assert(m);
1206         assert(message);
1207
1208         dbus_error_init(&error);
1209
1210         if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect") && introspection) {
1211
1212                 if (!(reply = dbus_message_new_method_return(message)))
1213                         goto oom;
1214
1215                 if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID))
1216                         goto oom;
1217
1218         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Get") && properties) {
1219                 const char *interface, *property;
1220                 const BusProperty *p;
1221
1222                 if (!dbus_message_get_args(
1223                             message,
1224                             &error,
1225                             DBUS_TYPE_STRING, &interface,
1226                             DBUS_TYPE_STRING, &property,
1227                             DBUS_TYPE_INVALID))
1228                         return bus_send_error_reply(m, c, message, &error, -EINVAL);
1229
1230                 for (p = properties; p->property; p++)
1231                         if (streq(p->interface, interface) && streq(p->property, property))
1232                                 break;
1233
1234                 if (p->property) {
1235                         DBusMessageIter iter, sub;
1236
1237                         if (!(reply = dbus_message_new_method_return(message)))
1238                                 goto oom;
1239
1240                         dbus_message_iter_init_append(reply, &iter);
1241
1242                         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, p->signature, &sub))
1243                                 goto oom;
1244
1245                         if ((r = p->append(m, &sub, property, (void*) p->data)) < 0) {
1246
1247                                 if (r == -ENOMEM)
1248                                         goto oom;
1249
1250                                 dbus_message_unref(reply);
1251                                 return bus_send_error_reply(m, c, message, NULL, r);
1252                         }
1253
1254                         if (!dbus_message_iter_close_container(&iter, &sub))
1255                                 goto oom;
1256                 }
1257
1258         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "GetAll") && properties) {
1259                 const char *interface;
1260                 const BusProperty *p;
1261                 DBusMessageIter iter, sub, sub2, sub3;
1262
1263                 if (!dbus_message_get_args(
1264                             message,
1265                             &error,
1266                             DBUS_TYPE_STRING, &interface,
1267                             DBUS_TYPE_INVALID))
1268                         return bus_send_error_reply(m, c, message, &error, -EINVAL);
1269
1270                 if (!(reply = dbus_message_new_method_return(message)))
1271                         goto oom;
1272
1273                 dbus_message_iter_init_append(reply, &iter);
1274
1275                 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub))
1276                         goto oom;
1277
1278                 for (p = properties; p->property; p++) {
1279                         if (interface[0] && !streq(p->interface, interface))
1280                                 continue;
1281
1282                         if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub2) ||
1283                             !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &p->property) ||
1284                             !dbus_message_iter_open_container(&sub2, DBUS_TYPE_VARIANT, p->signature, &sub3))
1285                                 goto oom;
1286
1287                         if ((r = p->append(m, &sub3, p->property, (void*) p->data)) < 0) {
1288
1289                                 if (r == -ENOMEM)
1290                                         goto oom;
1291
1292                                 dbus_message_unref(reply);
1293                                 return bus_send_error_reply(m, c, message, NULL, r);
1294                         }
1295
1296                         if (!dbus_message_iter_close_container(&sub2, &sub3) ||
1297                             !dbus_message_iter_close_container(&sub, &sub2))
1298                                 goto oom;
1299                 }
1300
1301                 if (!dbus_message_iter_close_container(&iter, &sub))
1302                         goto oom;
1303         }
1304
1305         if (reply) {
1306                 if (!dbus_connection_send(c, reply, NULL))
1307                         goto oom;
1308
1309                 dbus_message_unref(reply);
1310                 return DBUS_HANDLER_RESULT_HANDLED;
1311         }
1312
1313         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1314
1315 oom:
1316         if (reply)
1317                 dbus_message_unref(reply);
1318
1319         dbus_error_free(&error);
1320
1321         return DBUS_HANDLER_RESULT_NEED_MEMORY;
1322 }
1323
1324 static const char *error_to_dbus(int error) {
1325
1326         switch(error) {
1327
1328         case -EINVAL:
1329                 return DBUS_ERROR_INVALID_ARGS;
1330
1331         case -ENOMEM:
1332                 return DBUS_ERROR_NO_MEMORY;
1333
1334         case -EPERM:
1335         case -EACCES:
1336                 return DBUS_ERROR_ACCESS_DENIED;
1337
1338         case -ESRCH:
1339                 return DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN;
1340
1341         case -ENOENT:
1342                 return DBUS_ERROR_FILE_NOT_FOUND;
1343
1344         case -EEXIST:
1345                 return DBUS_ERROR_FILE_EXISTS;
1346
1347         case -ETIMEDOUT:
1348                 return DBUS_ERROR_TIMEOUT;
1349
1350         case -EIO:
1351                 return DBUS_ERROR_IO_ERROR;
1352
1353         case -ENETRESET:
1354         case -ECONNABORTED:
1355         case -ECONNRESET:
1356                 return DBUS_ERROR_DISCONNECTED;
1357         }
1358
1359         return DBUS_ERROR_FAILED;
1360 }
1361
1362 DBusHandlerResult bus_send_error_reply(Manager *m, DBusConnection *c, DBusMessage *message, DBusError *berror, int error) {
1363         DBusMessage *reply = NULL;
1364         const char *name, *text;
1365
1366         if (berror && dbus_error_is_set(berror)) {
1367                 name = berror->name;
1368                 text = berror->message;
1369         } else {
1370                 name = error_to_dbus(error);
1371                 text = strerror(-error);
1372         }
1373
1374         if (!(reply = dbus_message_new_error(message, name, text)))
1375                 goto oom;
1376
1377         if (!dbus_connection_send(c, reply, NULL))
1378                 goto oom;
1379
1380         dbus_message_unref(reply);
1381
1382         if (berror)
1383                 dbus_error_free(berror);
1384
1385         return DBUS_HANDLER_RESULT_HANDLED;
1386
1387 oom:
1388         if (reply)
1389                 dbus_message_unref(reply);
1390
1391         if (berror)
1392                 dbus_error_free(berror);
1393
1394         return DBUS_HANDLER_RESULT_NEED_MEMORY;
1395 }
1396
1397 int bus_broadcast(Manager *m, DBusMessage *message) {
1398         bool oom = false;
1399         Iterator i;
1400         DBusConnection *c;
1401
1402         assert(m);
1403         assert(message);
1404
1405         SET_FOREACH(c, m->bus_connections_for_dispatch, i)
1406                 if (c != m->system_bus || m->running_as == MANAGER_SYSTEM)
1407                         oom = !dbus_connection_send(c, message, NULL);
1408
1409         SET_FOREACH(c, m->bus_connections, i)
1410                 if (c != m->system_bus || m->running_as == MANAGER_SYSTEM)
1411                         oom = !dbus_connection_send(c, message, NULL);
1412
1413         return oom ? -ENOMEM : 0;
1414 }
1415
1416 int bus_property_append_string(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1417         const char *t = data;
1418
1419         assert(m);
1420         assert(i);
1421         assert(property);
1422
1423         if (!t)
1424                 t = "";
1425
1426         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
1427                 return -ENOMEM;
1428
1429         return 0;
1430 }
1431
1432 int bus_property_append_strv(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1433         DBusMessageIter sub;
1434         char **t = data;
1435
1436         assert(m);
1437         assert(i);
1438         assert(property);
1439
1440         if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "s", &sub))
1441                 return -ENOMEM;
1442
1443         STRV_FOREACH(t, t)
1444                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, t))
1445                         return -ENOMEM;
1446
1447         if (!dbus_message_iter_close_container(i, &sub))
1448                 return -ENOMEM;
1449
1450         return 0;
1451 }
1452
1453 int bus_property_append_bool(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1454         bool *b = data;
1455         dbus_bool_t db;
1456
1457         assert(m);
1458         assert(i);
1459         assert(property);
1460         assert(b);
1461
1462         db = *b;
1463
1464         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
1465                 return -ENOMEM;
1466
1467         return 0;
1468 }
1469
1470 int bus_property_append_uint64(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1471         assert(m);
1472         assert(i);
1473         assert(property);
1474         assert(data);
1475
1476         /* Let's ensure that pid_t is actually 64bit, and hence this
1477          * function can be used for usec_t */
1478         assert_cc(sizeof(uint64_t) == sizeof(usec_t));
1479
1480         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, data))
1481                 return -ENOMEM;
1482
1483         return 0;
1484 }
1485
1486 int bus_property_append_uint32(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1487         assert(m);
1488         assert(i);
1489         assert(property);
1490         assert(data);
1491
1492         /* Let's ensure that pid_t and mode_t is actually 32bit, and
1493          * hence this function can be used for pid_t/mode_t */
1494         assert_cc(sizeof(uint32_t) == sizeof(pid_t));
1495         assert_cc(sizeof(uint32_t) == sizeof(mode_t));
1496         assert_cc(sizeof(uint32_t) == sizeof(unsigned));
1497
1498         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT32, data))
1499                 return -ENOMEM;
1500
1501         return 0;
1502 }
1503
1504 int bus_property_append_int32(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1505         assert(m);
1506         assert(i);
1507         assert(property);
1508         assert(data);
1509
1510         assert_cc(sizeof(int32_t) == sizeof(int));
1511
1512         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, data))
1513                 return -ENOMEM;
1514
1515         return 0;
1516 }
1517
1518 int bus_property_append_size(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1519         uint64_t u;
1520
1521         assert(m);
1522         assert(i);
1523         assert(property);
1524         assert(data);
1525
1526         u = (uint64_t) *(size_t*) data;
1527
1528         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
1529                 return -ENOMEM;
1530
1531         return 0;
1532 }
1533
1534 int bus_property_append_ul(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1535         uint64_t u;
1536
1537         assert(m);
1538         assert(i);
1539         assert(property);
1540         assert(data);
1541
1542         u = (uint64_t) *(unsigned long*) data;
1543
1544         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, &u))
1545                 return -ENOMEM;
1546
1547         return 0;
1548 }
1549
1550 int bus_parse_strv(DBusMessage *m, char ***_l) {
1551         DBusMessageIter iter, sub;
1552         unsigned n = 0, i = 0;
1553         char **l;
1554
1555         assert(m);
1556         assert(_l);
1557
1558         if (!dbus_message_iter_init(m, &iter) ||
1559             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1560             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRING)
1561             return -EINVAL;
1562
1563         dbus_message_iter_recurse(&iter, &sub);
1564
1565         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1566                 n++;
1567                 dbus_message_iter_next(&sub);
1568         }
1569
1570         if (!(l = new(char*, n+1)))
1571                 return -ENOMEM;
1572
1573         assert_se(dbus_message_iter_init(m, &iter));
1574         dbus_message_iter_recurse(&iter, &sub);
1575
1576         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1577                 const char *s;
1578
1579                 assert_se(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1580                 dbus_message_iter_get_basic(&sub, &s);
1581
1582                 if (!(l[i++] = strdup(s))) {
1583                         strv_free(l);
1584                         return -ENOMEM;
1585                 }
1586
1587                 dbus_message_iter_next(&sub);
1588         }
1589
1590         assert(i == n);
1591         l[i] = NULL;
1592
1593         if (_l)
1594                 *_l = l;
1595
1596         return 0;
1597 }
1598
1599 bool bus_has_subscriber(Manager *m) {
1600         Iterator i;
1601         DBusConnection *c;
1602
1603         assert(m);
1604
1605         SET_FOREACH(c, m->bus_connections_for_dispatch, i)
1606                 if (bus_connection_has_subscriber(m, c))
1607                         return true;
1608
1609         SET_FOREACH(c, m->bus_connections, i)
1610                 if (bus_connection_has_subscriber(m, c))
1611                         return true;
1612
1613         return false;
1614 }
1615
1616 bool bus_connection_has_subscriber(Manager *m, DBusConnection *c) {
1617         assert(m);
1618         assert(c);
1619
1620         return !set_isempty(BUS_CONNECTION_SUBSCRIBED(m, c));
1621 }
1622
1623 DBusMessage* bus_properties_changed_new(const char *path, const char *interface, const char *properties) {
1624         DBusMessage *m;
1625         DBusMessageIter iter, sub;
1626         const char *i;
1627
1628         assert(interface);
1629         assert(properties);
1630
1631         if (!(m = dbus_message_new_signal(path, "org.freedesktop.DBus.Properties", "PropertiesChanged")))
1632                 goto oom;
1633
1634         dbus_message_iter_init_append(m, &iter);
1635
1636         /* We won't send any property values, since they might be
1637          * large and sometimes not cheap to generated */
1638
1639         if (!dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &interface) ||
1640             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub) ||
1641             !dbus_message_iter_close_container(&iter, &sub) ||
1642             !dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "s", &sub))
1643                 goto oom;
1644
1645         NULSTR_FOREACH(i, properties)
1646                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, &i))
1647                         goto oom;
1648
1649         if (!dbus_message_iter_close_container(&iter, &sub))
1650                 goto oom;
1651
1652         return m;
1653
1654 oom:
1655         if (m)
1656                 dbus_message_unref(m);
1657
1658         return NULL;
1659 }