chiark / gitweb /
dbus: there might be names already registered before we can connect, make sure to...
[elogind.git] / src / dbus.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU General Public License as published by
10   the Free Software Foundation; either version 2 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <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
46 static const char bus_properties_interface[] = BUS_PROPERTIES_INTERFACE;
47 static const char bus_introspectable_interface[] = BUS_INTROSPECTABLE_INTERFACE;
48
49 const char *const bus_interface_table[] = {
50         "org.freedesktop.DBus.Properties",     bus_properties_interface,
51         "org.freedesktop.DBus.Introspectable", bus_introspectable_interface,
52         "org.freedesktop.systemd1.Manager",    bus_manager_interface,
53         "org.freedesktop.systemd1.Job",        bus_job_interface,
54         "org.freedesktop.systemd1.Unit",       bus_unit_interface,
55         "org.freedesktop.systemd1.Service",    bus_service_interface,
56         "org.freedesktop.systemd1.Socket",     bus_socket_interface,
57         "org.freedesktop.systemd1.Target",     bus_target_interface,
58         "org.freedesktop.systemd1.Device",     bus_device_interface,
59         "org.freedesktop.systemd1.Mount",      bus_mount_interface,
60         "org.freedesktop.systemd1.Automount",  bus_automount_interface,
61         "org.freedesktop.systemd1.Snapshot",   bus_snapshot_interface,
62         "org.freedesktop.systemd1.Swap",       bus_swap_interface,
63         "org.freedesktop.systemd1.Timer",      bus_timer_interface,
64         "org.freedesktop.systemd1.Path",       bus_path_interface,
65         NULL
66 };
67
68 static const char *error_to_dbus(int error);
69
70 static void api_bus_dispatch_status(DBusConnection *bus, DBusDispatchStatus status, void *data)  {
71         Manager *m = data;
72
73         assert(bus);
74         assert(m);
75
76         if (!m->api_bus)
77                 return;
78
79         assert(m->api_bus == bus);
80
81         m->request_api_bus_dispatch = status != DBUS_DISPATCH_COMPLETE;
82 }
83
84 static void system_bus_dispatch_status(DBusConnection *bus, DBusDispatchStatus status, void *data)  {
85         Manager *m = data;
86
87         assert(bus);
88         assert(m);
89
90         if (!m->system_bus)
91                 return;
92
93         assert(m->system_bus == bus);
94
95         m->request_system_bus_dispatch = status != DBUS_DISPATCH_COMPLETE;
96 }
97
98 static uint32_t bus_flags_to_events(DBusWatch *bus_watch) {
99         unsigned flags;
100         uint32_t events = 0;
101
102         assert(bus_watch);
103
104         /* no watch flags for disabled watches */
105         if (!dbus_watch_get_enabled(bus_watch))
106                 return 0;
107
108         flags = dbus_watch_get_flags(bus_watch);
109
110         if (flags & DBUS_WATCH_READABLE)
111                 events |= EPOLLIN;
112         if (flags & DBUS_WATCH_WRITABLE)
113                 events |= EPOLLOUT;
114
115         return events | EPOLLHUP | EPOLLERR;
116 }
117
118 static unsigned events_to_bus_flags(uint32_t events) {
119         unsigned flags = 0;
120
121         if (events & EPOLLIN)
122                 flags |= DBUS_WATCH_READABLE;
123         if (events & EPOLLOUT)
124                 flags |= DBUS_WATCH_WRITABLE;
125         if (events & EPOLLHUP)
126                 flags |= DBUS_WATCH_HANGUP;
127         if (events & EPOLLERR)
128                 flags |= DBUS_WATCH_ERROR;
129
130         return flags;
131 }
132
133 void bus_watch_event(Manager *m, Watch *w, int events) {
134         assert(m);
135         assert(w);
136
137         /* This is called by the event loop whenever there is
138          * something happening on D-Bus' file handles. */
139
140         if (!dbus_watch_get_enabled(w->data.bus_watch))
141                 return;
142
143         dbus_watch_handle(w->data.bus_watch, events_to_bus_flags(events));
144 }
145
146 static dbus_bool_t bus_add_watch(DBusWatch *bus_watch, void *data) {
147         Manager *m = data;
148         Watch *w;
149         struct epoll_event ev;
150
151         assert(bus_watch);
152         assert(m);
153
154         if (!(w = new0(Watch, 1)))
155                 return FALSE;
156
157         w->fd = dbus_watch_get_unix_fd(bus_watch);
158         w->type = WATCH_DBUS_WATCH;
159         w->data.bus_watch = bus_watch;
160
161         zero(ev);
162         ev.events = bus_flags_to_events(bus_watch);
163         ev.data.ptr = w;
164
165         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0) {
166
167                 if (errno != EEXIST) {
168                         free(w);
169                         return FALSE;
170                 }
171
172                 /* Hmm, bloody D-Bus creates multiple watches on the
173                  * same fd. epoll() does not like that. As a dirty
174                  * hack we simply dup() the fd and hence get a second
175                  * one we can safely add to the epoll(). */
176
177                 if ((w->fd = dup(w->fd)) < 0) {
178                         free(w);
179                         return FALSE;
180                 }
181
182                 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0) {
183                         free(w);
184                         close_nointr_nofail(w->fd);
185                         return FALSE;
186                 }
187
188                 w->fd_is_dupped = true;
189         }
190
191         dbus_watch_set_data(bus_watch, w, NULL);
192
193         return TRUE;
194 }
195
196 static void bus_remove_watch(DBusWatch *bus_watch, void *data) {
197         Manager *m = data;
198         Watch *w;
199
200         assert(bus_watch);
201         assert(m);
202
203         if (!(w = dbus_watch_get_data(bus_watch)))
204                 return;
205
206         assert(w->type == WATCH_DBUS_WATCH);
207         assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
208
209         if (w->fd_is_dupped)
210                 close_nointr_nofail(w->fd);
211
212         free(w);
213 }
214
215 static void bus_toggle_watch(DBusWatch *bus_watch, void *data) {
216         Manager *m = data;
217         Watch *w;
218         struct epoll_event ev;
219
220         assert(bus_watch);
221         assert(m);
222
223         assert_se(w = dbus_watch_get_data(bus_watch));
224         assert(w->type == WATCH_DBUS_WATCH);
225
226         zero(ev);
227         ev.events = bus_flags_to_events(bus_watch);
228         ev.data.ptr = w;
229
230         assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_MOD, w->fd, &ev) == 0);
231 }
232
233 static int bus_timeout_arm(Manager *m, Watch *w) {
234         struct itimerspec its;
235
236         assert(m);
237         assert(w);
238
239         zero(its);
240
241         if (dbus_timeout_get_enabled(w->data.bus_timeout)) {
242                 timespec_store(&its.it_value, dbus_timeout_get_interval(w->data.bus_timeout) * USEC_PER_MSEC);
243                 its.it_interval = its.it_interval;
244         }
245
246         if (timerfd_settime(w->fd, 0, &its, NULL) < 0)
247                 return -errno;
248
249         return 0;
250 }
251
252 void bus_timeout_event(Manager *m, Watch *w, int events) {
253         assert(m);
254         assert(w);
255
256         /* This is called by the event loop whenever there is
257          * something happening on D-Bus' file handles. */
258
259         if (!(dbus_timeout_get_enabled(w->data.bus_timeout)))
260                 return;
261
262         dbus_timeout_handle(w->data.bus_timeout);
263 }
264
265 static dbus_bool_t bus_add_timeout(DBusTimeout *timeout, void *data) {
266         Manager *m = data;
267         Watch *w;
268         struct epoll_event ev;
269
270         assert(timeout);
271         assert(m);
272
273         if (!(w = new0(Watch, 1)))
274                 return FALSE;
275
276         if (!(w->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
277                 goto fail;
278
279         w->type = WATCH_DBUS_TIMEOUT;
280         w->data.bus_timeout = timeout;
281
282         if (bus_timeout_arm(m, w) < 0)
283                 goto fail;
284
285         zero(ev);
286         ev.events = EPOLLIN;
287         ev.data.ptr = w;
288
289         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0)
290                 goto fail;
291
292         dbus_timeout_set_data(timeout, w, NULL);
293
294         return TRUE;
295
296 fail:
297         if (w->fd >= 0)
298                 close_nointr_nofail(w->fd);
299
300         free(w);
301         return FALSE;
302 }
303
304 static void bus_remove_timeout(DBusTimeout *timeout, void *data) {
305         Manager *m = data;
306         Watch *w;
307
308         assert(timeout);
309         assert(m);
310
311         if (!(w = dbus_timeout_get_data(timeout)))
312                 return;
313
314         assert(w->type == WATCH_DBUS_TIMEOUT);
315         assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
316         close_nointr_nofail(w->fd);
317         free(w);
318 }
319
320 static void bus_toggle_timeout(DBusTimeout *timeout, void *data) {
321         Manager *m = data;
322         Watch *w;
323         int r;
324
325         assert(timeout);
326         assert(m);
327
328         assert_se(w = dbus_timeout_get_data(timeout));
329         assert(w->type == WATCH_DBUS_TIMEOUT);
330
331         if ((r = bus_timeout_arm(m, w)) < 0)
332                 log_error("Failed to rearm timer: %s", strerror(-r));
333 }
334
335 static DBusHandlerResult api_bus_message_filter(DBusConnection  *connection, DBusMessage  *message, void *data) {
336         Manager *m = data;
337         DBusError error;
338         DBusMessage *reply = NULL;
339
340         assert(connection);
341         assert(message);
342         assert(m);
343
344         dbus_error_init(&error);
345
346         /* log_debug("Got D-Bus request: %s.%s() on %s", */
347         /*           dbus_message_get_interface(message), */
348         /*           dbus_message_get_member(message), */
349         /*           dbus_message_get_path(message)); */
350
351         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
352                 log_error("Warning! API D-Bus connection terminated.");
353                 bus_done_api(m);
354
355         } else if (dbus_message_is_signal(message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) {
356                 const char *name, *old_owner, *new_owner;
357
358                 if (!dbus_message_get_args(message, &error,
359                                            DBUS_TYPE_STRING, &name,
360                                            DBUS_TYPE_STRING, &old_owner,
361                                            DBUS_TYPE_STRING, &new_owner,
362                                            DBUS_TYPE_INVALID))
363                         log_error("Failed to parse NameOwnerChanged message: %s", error.message);
364                 else  {
365                         if (set_remove(m->subscribed, (char*) name))
366                                 log_debug("Subscription client vanished: %s (left: %u)", name, set_size(m->subscribed));
367
368                         if (old_owner[0] == 0)
369                                 old_owner = NULL;
370
371                         if (new_owner[0] == 0)
372                                 new_owner = NULL;
373
374                         manager_dispatch_bus_name_owner_changed(m, name, old_owner, new_owner);
375                 }
376         } else if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Activator", "ActivationRequest")) {
377                 const char *name;
378
379                 if (!dbus_message_get_args(message, &error,
380                                            DBUS_TYPE_STRING, &name,
381                                            DBUS_TYPE_INVALID))
382                         log_error("Failed to parse ActivationRequest message: %s", error.message);
383                 else  {
384                         int r;
385                         Unit *u;
386
387                         r = manager_load_unit(m, name, NULL, &u);
388
389                         if (r >= 0 && u->meta.only_by_dependency)
390                                 r = -EPERM;
391
392                         if (r >= 0)
393                                 r = manager_add_job(m, JOB_START, u, JOB_REPLACE, true, NULL);
394
395                         if (r < 0) {
396                                 const char *id, *text;
397
398                                 if (!(reply = dbus_message_new_signal("/org/freedesktop/systemd1", "org.freedesktop.systemd1.Activator", "ActivationFailure")))
399                                         goto oom;
400
401                                 id = error_to_dbus(r);
402                                 text = strerror(-r);
403
404                                 if (!dbus_message_set_destination(reply, DBUS_SERVICE_DBUS) ||
405                                     !dbus_message_append_args(reply,
406                                                               DBUS_TYPE_STRING, &name,
407                                                               DBUS_TYPE_STRING, &id,
408                                                               DBUS_TYPE_STRING, &text,
409                                                               DBUS_TYPE_INVALID))
410                                         goto oom;
411                         }
412
413                         /* On success we don't do anything, the service will be spwaned now */
414                 }
415         }
416
417         dbus_error_free(&error);
418
419         if (reply) {
420                 if (!dbus_connection_send(connection, reply, NULL))
421                         goto oom;
422
423                 dbus_message_unref(reply);
424         }
425
426         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
427
428 oom:
429         if (reply)
430                 dbus_message_unref(reply);
431
432         dbus_error_free(&error);
433
434         return DBUS_HANDLER_RESULT_NEED_MEMORY;
435 }
436
437 static DBusHandlerResult system_bus_message_filter(DBusConnection  *connection, DBusMessage  *message, void *data) {
438         Manager *m = data;
439         DBusError error;
440
441         assert(connection);
442         assert(message);
443         assert(m);
444
445         dbus_error_init(&error);
446
447         /* log_debug("Got D-Bus request: %s.%s() on %s", */
448         /*           dbus_message_get_interface(message), */
449         /*           dbus_message_get_member(message), */
450         /*           dbus_message_get_path(message)); */
451
452         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
453                 log_error("Warning! System D-Bus connection terminated.");
454                 bus_done_system(m);
455
456         } if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Agent", "Released")) {
457                 const char *cgroup;
458
459                 if (!dbus_message_get_args(message, &error,
460                                            DBUS_TYPE_STRING, &cgroup,
461                                            DBUS_TYPE_INVALID))
462                         log_error("Failed to parse Released message: %s", error.message);
463                 else
464                         cgroup_notify_empty(m, cgroup);
465         }
466
467         dbus_error_free(&error);
468         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
469 }
470
471 unsigned bus_dispatch(Manager *m) {
472         assert(m);
473
474         if (m->queued_message) {
475                 /* If we cannot get rid of this message we won't
476                  * dispatch any D-Bus messages, so that we won't end
477                  * up wanting to queue another message. */
478
479                 if (!dbus_connection_send(m->api_bus, m->queued_message, NULL))
480                         return 0;
481
482                 dbus_message_unref(m->queued_message);
483                 m->queued_message = NULL;
484         }
485
486         if (m->request_api_bus_dispatch) {
487                 if (dbus_connection_dispatch(m->api_bus) == DBUS_DISPATCH_COMPLETE)
488                         m->request_api_bus_dispatch = false;
489
490                 return 1;
491         }
492
493         if (m->request_system_bus_dispatch) {
494                 if (dbus_connection_dispatch(m->system_bus) == DBUS_DISPATCH_COMPLETE)
495                         m->request_system_bus_dispatch = false;
496
497                 return 1;
498         }
499
500         return 0;
501 }
502
503 static void request_name_pending_cb(DBusPendingCall *pending, void *userdata) {
504         DBusMessage *reply;
505         DBusError error;
506
507         dbus_error_init(&error);
508
509         assert_se(reply = dbus_pending_call_steal_reply(pending));
510
511         switch (dbus_message_get_type(reply)) {
512
513         case DBUS_MESSAGE_TYPE_ERROR:
514
515                 assert_se(dbus_set_error_from_message(&error, reply));
516                 log_warning("RequestName() failed: %s", error.message);
517                 break;
518
519         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
520                 uint32_t r;
521
522                 if (!dbus_message_get_args(reply,
523                                            &error,
524                                            DBUS_TYPE_UINT32, &r,
525                                            DBUS_TYPE_INVALID)) {
526                         log_error("Failed to parse RequestName() reply: %s", error.message);
527                         break;
528                 }
529
530                 if (r == 1)
531                         log_debug("Successfully acquired name.");
532                 else
533                         log_error("Name already owned.");
534
535                 break;
536         }
537
538         default:
539                 assert_not_reached("Invalid reply message");
540         }
541
542         dbus_message_unref(reply);
543         dbus_error_free(&error);
544 }
545
546 static int request_name(Manager *m) {
547         const char *name = "org.freedesktop.systemd1";
548         uint32_t flags = 0;
549         DBusMessage *message = NULL;
550         DBusPendingCall *pending = NULL;
551
552         if (!(message = dbus_message_new_method_call(
553                               DBUS_SERVICE_DBUS,
554                               DBUS_PATH_DBUS,
555                               DBUS_INTERFACE_DBUS,
556                               "RequestName")))
557                 goto oom;
558
559         if (!dbus_message_append_args(
560                             message,
561                             DBUS_TYPE_STRING, &name,
562                             DBUS_TYPE_UINT32, &flags,
563                             DBUS_TYPE_INVALID))
564                 goto oom;
565
566         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
567                 goto oom;
568
569         if (!dbus_pending_call_set_notify(pending, request_name_pending_cb, m, NULL))
570                 goto oom;
571
572         dbus_message_unref(message);
573         dbus_pending_call_unref(pending);
574
575         /* We simple ask for the name and don't wait for it. Sooner or
576          * later we'll have it. */
577
578         return 0;
579
580 oom:
581         if (pending) {
582                 dbus_pending_call_cancel(pending);
583                 dbus_pending_call_unref(pending);
584         }
585
586         if (message)
587                 dbus_message_unref(message);
588
589         return -ENOMEM;
590 }
591
592 static void query_name_list_pending_cb(DBusPendingCall *pending, void *userdata) {
593         DBusMessage *reply;
594         DBusError error;
595         Manager *m = userdata;
596
597         assert(m);
598
599         dbus_error_init(&error);
600
601         assert_se(reply = dbus_pending_call_steal_reply(pending));
602
603         switch (dbus_message_get_type(reply)) {
604
605         case DBUS_MESSAGE_TYPE_ERROR:
606
607                 assert_se(dbus_set_error_from_message(&error, reply));
608                 log_warning("ListNames() failed: %s", error.message);
609                 break;
610
611         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
612                 int r;
613                 char **l;
614
615                 if ((r = bus_parse_strv(reply, &l)) < 0)
616                         log_warning("Failed to parse ListNames() reply: %s", strerror(-r));
617                 else {
618                         char **t;
619
620                         STRV_FOREACH(t, l)
621                                 /* This is a bit hacky, we say the
622                                  * owner of the name is the name
623                                  * itself, because we don't want the
624                                  * extra traffic to figure out the
625                                  * real owner. */
626                                 manager_dispatch_bus_name_owner_changed(m, *t, NULL, *t);
627
628                         strv_free(l);
629                 }
630
631                 break;
632         }
633
634         default:
635                 assert_not_reached("Invalid reply message");
636         }
637
638         dbus_message_unref(reply);
639         dbus_error_free(&error);
640 }
641
642 static int query_name_list(Manager *m) {
643         DBusMessage *message = NULL;
644         DBusPendingCall *pending = NULL;
645
646         /* Asks for the currently installed bus names */
647
648         if (!(message = dbus_message_new_method_call(
649                               DBUS_SERVICE_DBUS,
650                               DBUS_PATH_DBUS,
651                               DBUS_INTERFACE_DBUS,
652                               "ListNames")))
653                 goto oom;
654
655         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
656                 goto oom;
657
658         if (!dbus_pending_call_set_notify(pending, query_name_list_pending_cb, m, NULL))
659                 goto oom;
660
661         dbus_message_unref(message);
662         dbus_pending_call_unref(pending);
663
664         /* We simple ask for the list and don't wait for it. Sooner or
665          * later we'll get it. */
666
667         return 0;
668
669 oom:
670         if (pending) {
671                 dbus_pending_call_cancel(pending);
672                 dbus_pending_call_unref(pending);
673         }
674
675         if (message)
676                 dbus_message_unref(message);
677
678         return -ENOMEM;
679 }
680
681 static int bus_setup_loop(Manager *m, DBusConnection *bus) {
682         assert(m);
683         assert(bus);
684
685         dbus_connection_set_exit_on_disconnect(bus, FALSE);
686
687         if (!dbus_connection_set_watch_functions(bus, bus_add_watch, bus_remove_watch, bus_toggle_watch, m, NULL) ||
688             !dbus_connection_set_timeout_functions(bus, bus_add_timeout, bus_remove_timeout, bus_toggle_timeout, m, NULL))
689                 return -ENOMEM;
690
691         return 0;
692 }
693
694 int bus_init_system(Manager *m) {
695         DBusError error;
696         char *id;
697         int r;
698
699         assert(m);
700
701         dbus_error_init(&error);
702
703         if (m->system_bus)
704                 return 0;
705
706         if (m->running_as != MANAGER_SESSION && m->api_bus)
707                 m->system_bus = m->api_bus;
708         else {
709                 if (!(m->system_bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error))) {
710                         log_debug("Failed to get system D-Bus connection, retrying later: %s", error.message);
711                         dbus_error_free(&error);
712                         return 0;
713                 }
714
715                 dbus_connection_set_dispatch_status_function(m->system_bus, system_bus_dispatch_status, m, NULL);
716                 m->request_system_bus_dispatch = true;
717
718                 if ((r = bus_setup_loop(m, m->system_bus)) < 0) {
719                         bus_done_system(m);
720                         return r;
721                 }
722         }
723
724         if (!dbus_connection_add_filter(m->system_bus, system_bus_message_filter, m, NULL)) {
725                 bus_done_system(m);
726                 return -ENOMEM;
727         }
728
729         dbus_bus_add_match(m->system_bus,
730                            "type='signal',"
731                            "interface='org.freedesktop.systemd1.Agent',"
732                            "path='/org/freedesktop/systemd1/agent'",
733                            &error);
734
735         if (dbus_error_is_set(&error)) {
736                 log_error("Failed to register match: %s", error.message);
737                 dbus_error_free(&error);
738                 bus_done_system(m);
739                 return -ENOMEM;
740         }
741
742         log_debug("Successfully connected to system D-Bus bus %s as %s",
743                   strnull((id = dbus_connection_get_server_id(m->system_bus))),
744                   strnull(dbus_bus_get_unique_name(m->system_bus)));
745         dbus_free(id);
746
747         return 0;
748 }
749
750 int bus_init_api(Manager *m) {
751         DBusError error;
752         char *id;
753         int r;
754
755         assert(m);
756
757         dbus_error_init(&error);
758
759         if (m->api_bus)
760                 return 0;
761
762         if (m->name_data_slot < 0)
763                 if (!dbus_pending_call_allocate_data_slot(&m->name_data_slot))
764                         return -ENOMEM;
765
766         if (m->running_as != MANAGER_SESSION && m->system_bus)
767                 m->api_bus = m->system_bus;
768         else {
769                 if (!(m->api_bus = dbus_bus_get_private(m->running_as == MANAGER_SESSION ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error))) {
770                         log_debug("Failed to get API D-Bus connection, retrying later: %s", error.message);
771                         dbus_error_free(&error);
772                         return 0;
773                 }
774
775                 dbus_connection_set_dispatch_status_function(m->api_bus, api_bus_dispatch_status, m, NULL);
776                 m->request_api_bus_dispatch = true;
777
778                 if ((r = bus_setup_loop(m, m->api_bus)) < 0) {
779                         bus_done_api(m);
780                         return r;
781                 }
782         }
783
784         if (!dbus_connection_register_object_path(m->api_bus, "/org/freedesktop/systemd1", &bus_manager_vtable, m) ||
785             !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/unit", &bus_unit_vtable, m) ||
786             !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/job", &bus_job_vtable, m) ||
787             !dbus_connection_add_filter(m->api_bus, api_bus_message_filter, m, NULL)) {
788                 bus_done_api(m);
789                 return -ENOMEM;
790         }
791
792         /* Get NameOwnerChange messages */
793         dbus_bus_add_match(m->api_bus,
794                            "type='signal',"
795                            "sender='"DBUS_SERVICE_DBUS"',"
796                            "interface='"DBUS_INTERFACE_DBUS"',"
797                            "path='"DBUS_PATH_DBUS"'",
798                            &error);
799
800         if (dbus_error_is_set(&error)) {
801                 log_error("Failed to register match: %s", error.message);
802                 dbus_error_free(&error);
803                 bus_done_api(m);
804                 return -ENOMEM;
805         }
806
807         /* Get activation requests */
808         dbus_bus_add_match(m->api_bus,
809                            "type='signal',"
810                            "sender='"DBUS_SERVICE_DBUS"',"
811                            "interface='org.freedesktop.systemd1.Activator',"
812                            "path='"DBUS_PATH_DBUS"'",
813                            &error);
814
815         if (dbus_error_is_set(&error)) {
816                 log_error("Failed to register match: %s", error.message);
817                 dbus_error_free(&error);
818                 bus_done_api(m);
819                 return -ENOMEM;
820         }
821
822         if ((r = request_name(m)) < 0) {
823                 bus_done_api(m);
824                 return r;
825         }
826
827         if ((r = query_name_list(m)) < 0) {
828                 bus_done_api(m);
829                 return r;
830         }
831
832         log_debug("Successfully connected to API D-Bus bus %s as %s",
833                   strnull((id = dbus_connection_get_server_id(m->api_bus))),
834                   strnull(dbus_bus_get_unique_name(m->api_bus)));
835         dbus_free(id);
836
837         if (!m->subscribed)
838                 if (!(m->subscribed = set_new(string_hash_func, string_compare_func)))
839                         return -ENOMEM;
840
841         return 0;
842 }
843
844 void bus_done_api(Manager *m) {
845         assert(m);
846
847         if (m->api_bus) {
848                 if (m->system_bus == m->api_bus)
849                         m->system_bus = NULL;
850
851                 dbus_connection_set_dispatch_status_function(m->api_bus, NULL, NULL, NULL);
852                 dbus_connection_flush(m->api_bus);
853                 dbus_connection_close(m->api_bus);
854                 dbus_connection_unref(m->api_bus);
855                 m->api_bus = NULL;
856         }
857
858         if (m->subscribed) {
859                 char *c;
860
861                 while ((c = set_steal_first(m->subscribed)))
862                         free(c);
863
864                 set_free(m->subscribed);
865                 m->subscribed = NULL;
866         }
867
868        if (m->name_data_slot >= 0)
869                dbus_pending_call_free_data_slot(&m->name_data_slot);
870
871        if (m->queued_message) {
872                dbus_message_unref(m->queued_message);
873                m->queued_message = NULL;
874        }
875 }
876
877 void bus_done_system(Manager *m) {
878         assert(m);
879
880         if (m->system_bus == m->api_bus)
881                 bus_done_api(m);
882
883         if (m->system_bus) {
884                 dbus_connection_set_dispatch_status_function(m->system_bus, NULL, NULL, NULL);
885                 dbus_connection_flush(m->system_bus);
886                 dbus_connection_close(m->system_bus);
887                 dbus_connection_unref(m->system_bus);
888                 m->system_bus = NULL;
889         }
890 }
891
892 static void query_pid_pending_cb(DBusPendingCall *pending, void *userdata) {
893         Manager *m = userdata;
894         DBusMessage *reply;
895         DBusError error;
896         const char *name;
897
898         dbus_error_init(&error);
899
900         assert_se(name = dbus_pending_call_get_data(pending, m->name_data_slot));
901         assert_se(reply = dbus_pending_call_steal_reply(pending));
902
903         switch (dbus_message_get_type(reply)) {
904
905         case DBUS_MESSAGE_TYPE_ERROR:
906
907                 assert_se(dbus_set_error_from_message(&error, reply));
908                 log_warning("GetConnectionUnixProcessID() failed: %s", error.message);
909                 break;
910
911         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
912                 uint32_t r;
913
914                 if (!dbus_message_get_args(reply,
915                                            &error,
916                                            DBUS_TYPE_UINT32, &r,
917                                            DBUS_TYPE_INVALID)) {
918                         log_error("Failed to parse GetConnectionUnixProcessID() reply: %s", error.message);
919                         break;
920                 }
921
922                 manager_dispatch_bus_query_pid_done(m, name, (pid_t) r);
923                 break;
924         }
925
926         default:
927                 assert_not_reached("Invalid reply message");
928         }
929
930         dbus_message_unref(reply);
931         dbus_error_free(&error);
932 }
933
934 int bus_query_pid(Manager *m, const char *name) {
935         DBusMessage *message = NULL;
936         DBusPendingCall *pending = NULL;
937         char *n = NULL;
938
939         assert(m);
940         assert(name);
941
942         if (!(message = dbus_message_new_method_call(
943                               DBUS_SERVICE_DBUS,
944                               DBUS_PATH_DBUS,
945                               DBUS_INTERFACE_DBUS,
946                               "GetConnectionUnixProcessID")))
947                 goto oom;
948
949         if (!(dbus_message_append_args(
950                               message,
951                               DBUS_TYPE_STRING, &name,
952                               DBUS_TYPE_INVALID)))
953                 goto oom;
954
955         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
956                 goto oom;
957
958         if (!(n = strdup(name)))
959                 goto oom;
960
961         if (!dbus_pending_call_set_data(pending, m->name_data_slot, n, free))
962                 goto oom;
963
964         n = NULL;
965
966         if (!dbus_pending_call_set_notify(pending, query_pid_pending_cb, m, NULL))
967                 goto oom;
968
969         dbus_message_unref(message);
970         dbus_pending_call_unref(pending);
971
972         return 0;
973
974 oom:
975         free(n);
976
977         if (pending) {
978                 dbus_pending_call_cancel(pending);
979                 dbus_pending_call_unref(pending);
980         }
981
982         if (message)
983                 dbus_message_unref(message);
984
985         return -ENOMEM;
986 }
987
988 DBusHandlerResult bus_default_message_handler(Manager *m, DBusMessage *message, const char*introspection, const BusProperty *properties) {
989         DBusError error;
990         DBusMessage *reply = NULL;
991         int r;
992
993         assert(m);
994         assert(message);
995
996         dbus_error_init(&error);
997
998         if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect") && introspection) {
999
1000                 if (!(reply = dbus_message_new_method_return(message)))
1001                         goto oom;
1002
1003                 if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID))
1004                         goto oom;
1005
1006         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Get") && properties) {
1007                 const char *interface, *property;
1008                 const BusProperty *p;
1009
1010                 if (!dbus_message_get_args(
1011                             message,
1012                             &error,
1013                             DBUS_TYPE_STRING, &interface,
1014                             DBUS_TYPE_STRING, &property,
1015                             DBUS_TYPE_INVALID))
1016                         return bus_send_error_reply(m, message, &error, -EINVAL);
1017
1018                 for (p = properties; p->property; p++)
1019                         if (streq(p->interface, interface) && streq(p->property, property))
1020                                 break;
1021
1022                 if (p->property) {
1023                         DBusMessageIter iter, sub;
1024
1025                         if (!(reply = dbus_message_new_method_return(message)))
1026                                 goto oom;
1027
1028                         dbus_message_iter_init_append(reply, &iter);
1029
1030                         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, p->signature, &sub))
1031                                 goto oom;
1032
1033                         if ((r = p->append(m, &sub, property, (void*) p->data)) < 0) {
1034
1035                                 if (r == -ENOMEM)
1036                                         goto oom;
1037
1038                                 dbus_message_unref(reply);
1039                                 return bus_send_error_reply(m, message, NULL, r);
1040                         }
1041
1042                         if (!dbus_message_iter_close_container(&iter, &sub))
1043                                 goto oom;
1044                 }
1045         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "GetAll") && properties) {
1046                 const char *interface;
1047                 const BusProperty *p;
1048                 DBusMessageIter iter, sub, sub2, sub3;
1049                 bool any = false;
1050
1051                 if (!dbus_message_get_args(
1052                             message,
1053                             &error,
1054                             DBUS_TYPE_STRING, &interface,
1055                             DBUS_TYPE_INVALID))
1056                         return bus_send_error_reply(m, message, &error, -EINVAL);
1057
1058                 if (!(reply = dbus_message_new_method_return(message)))
1059                         goto oom;
1060
1061                 dbus_message_iter_init_append(reply, &iter);
1062
1063                 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub))
1064                         goto oom;
1065
1066                 for (p = properties; p->property; p++) {
1067                         if (!streq(p->interface, interface))
1068                                 continue;
1069
1070                         if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub2) ||
1071                             !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &p->property) ||
1072                             !dbus_message_iter_open_container(&sub2, DBUS_TYPE_VARIANT, p->signature, &sub3))
1073                                 goto oom;
1074
1075                         if ((r = p->append(m, &sub3, p->property, (void*) p->data)) < 0) {
1076
1077                                 if (r == -ENOMEM)
1078                                         goto oom;
1079
1080                                 dbus_message_unref(reply);
1081                                 return bus_send_error_reply(m, message, NULL, r);
1082                         }
1083
1084                         if (!dbus_message_iter_close_container(&sub2, &sub3) ||
1085                             !dbus_message_iter_close_container(&sub, &sub2))
1086                                 goto oom;
1087
1088                         any = true;
1089                 }
1090
1091                 if (!dbus_message_iter_close_container(&iter, &sub))
1092                         goto oom;
1093         }
1094
1095         if (reply) {
1096                 if (!dbus_connection_send(m->api_bus, reply, NULL))
1097                         goto oom;
1098
1099                 dbus_message_unref(reply);
1100                 return DBUS_HANDLER_RESULT_HANDLED;
1101         }
1102
1103         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
1104
1105 oom:
1106         if (reply)
1107                 dbus_message_unref(reply);
1108
1109         dbus_error_free(&error);
1110
1111         return DBUS_HANDLER_RESULT_NEED_MEMORY;
1112 }
1113
1114 static const char *error_to_dbus(int error) {
1115
1116         switch(error) {
1117
1118         case -EINVAL:
1119                 return DBUS_ERROR_INVALID_ARGS;
1120
1121         case -ENOMEM:
1122                 return DBUS_ERROR_NO_MEMORY;
1123
1124         case -EPERM:
1125         case -EACCES:
1126                 return DBUS_ERROR_ACCESS_DENIED;
1127
1128         case -ESRCH:
1129                 return DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN;
1130
1131         case -ENOENT:
1132                 return DBUS_ERROR_FILE_NOT_FOUND;
1133
1134         case -EEXIST:
1135                 return DBUS_ERROR_FILE_EXISTS;
1136
1137         case -ETIMEDOUT:
1138                 return DBUS_ERROR_TIMEOUT;
1139
1140         case -EIO:
1141                 return DBUS_ERROR_IO_ERROR;
1142
1143         case -ENETRESET:
1144         case -ECONNABORTED:
1145         case -ECONNRESET:
1146                 return DBUS_ERROR_DISCONNECTED;
1147         }
1148
1149         return DBUS_ERROR_FAILED;
1150 }
1151
1152 DBusHandlerResult bus_send_error_reply(Manager *m, DBusMessage *message, DBusError *bus_error, int error) {
1153         DBusMessage *reply = NULL;
1154         const char *name, *text;
1155
1156         if (bus_error && dbus_error_is_set(bus_error)) {
1157                 name = bus_error->name;
1158                 text = bus_error->message;
1159         } else {
1160                 name = error_to_dbus(error);
1161                 text = strerror(-error);
1162         }
1163
1164         if (!(reply = dbus_message_new_error(message, name, text)))
1165                 goto oom;
1166
1167         if (!dbus_connection_send(m->api_bus, reply, NULL))
1168                 goto oom;
1169
1170         dbus_message_unref(reply);
1171
1172         if (bus_error)
1173                 dbus_error_free(bus_error);
1174
1175         return DBUS_HANDLER_RESULT_HANDLED;
1176
1177 oom:
1178         if (reply)
1179                 dbus_message_unref(reply);
1180
1181         if (bus_error)
1182                 dbus_error_free(bus_error);
1183
1184         return DBUS_HANDLER_RESULT_NEED_MEMORY;
1185 }
1186
1187 int bus_property_append_string(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1188         const char *t = data;
1189
1190         assert(m);
1191         assert(i);
1192         assert(property);
1193
1194         if (!t)
1195                 t = "";
1196
1197         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
1198                 return -ENOMEM;
1199
1200         return 0;
1201 }
1202
1203 int bus_property_append_strv(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1204         DBusMessageIter sub;
1205         char **t = data;
1206
1207         assert(m);
1208         assert(i);
1209         assert(property);
1210
1211         if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "s", &sub))
1212                 return -ENOMEM;
1213
1214         STRV_FOREACH(t, t)
1215                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, t))
1216                         return -ENOMEM;
1217
1218         if (!dbus_message_iter_close_container(i, &sub))
1219                 return -ENOMEM;
1220
1221         return 0;
1222 }
1223
1224 int bus_property_append_bool(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1225         bool *b = data;
1226         dbus_bool_t db;
1227
1228         assert(m);
1229         assert(i);
1230         assert(property);
1231         assert(b);
1232
1233         db = *b;
1234
1235         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
1236                 return -ENOMEM;
1237
1238         return 0;
1239 }
1240
1241 int bus_property_append_uint64(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1242         assert(m);
1243         assert(i);
1244         assert(property);
1245         assert(data);
1246
1247         /* Let's ensure that pid_t is actually 64bit, and hence this
1248          * function can be used for usec_t */
1249         assert_cc(sizeof(uint64_t) == sizeof(usec_t));
1250
1251         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, data))
1252                 return -ENOMEM;
1253
1254         return 0;
1255 }
1256
1257 int bus_property_append_uint32(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1258         assert(m);
1259         assert(i);
1260         assert(property);
1261         assert(data);
1262
1263         /* Let's ensure that pid_t and mode_t is actually 32bit, and
1264          * hence this function can be used for pid_t/mode_t */
1265         assert_cc(sizeof(uint32_t) == sizeof(pid_t));
1266         assert_cc(sizeof(uint32_t) == sizeof(mode_t));
1267         assert_cc(sizeof(uint32_t) == sizeof(unsigned));
1268
1269         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT32, data))
1270                 return -ENOMEM;
1271
1272         return 0;
1273 }
1274
1275 int bus_property_append_int32(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1276         assert(m);
1277         assert(i);
1278         assert(property);
1279         assert(data);
1280
1281         assert_cc(sizeof(int32_t) == sizeof(int));
1282
1283         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, data))
1284                 return -ENOMEM;
1285
1286         return 0;
1287 }
1288
1289 int bus_parse_strv(DBusMessage *m, char ***_l) {
1290         DBusMessageIter iter, sub;
1291         unsigned n = 0, i = 0;
1292         char **l;
1293
1294         assert(m);
1295         assert(_l);
1296
1297         if (!dbus_message_iter_init(m, &iter) ||
1298             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1299             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRING)
1300             return -EINVAL;
1301
1302         dbus_message_iter_recurse(&iter, &sub);
1303
1304         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1305                 n++;
1306                 dbus_message_iter_next(&sub);
1307         }
1308
1309         if (!(l = new(char*, n+1)))
1310                 return -ENOMEM;
1311
1312         assert_se(dbus_message_iter_init(m, &iter));
1313         dbus_message_iter_recurse(&iter, &sub);
1314
1315         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1316                 const char *s;
1317
1318                 assert_se(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1319                 dbus_message_iter_get_basic(&sub, &s);
1320
1321                 if (!(l[i++] = strdup(s))) {
1322                         strv_free(l);
1323                         return -ENOMEM;
1324                 }
1325
1326                 dbus_message_iter_next(&sub);
1327         }
1328
1329         assert(i == n);
1330         l[i] = NULL;
1331
1332         if (_l)
1333                 *_l = l;
1334
1335         return 0;
1336 }