chiark / gitweb /
6b7896b605527f7fc865bffc34d51348f5a54965
[elogind.git] / 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
36 static void api_bus_dispatch_status(DBusConnection *bus, DBusDispatchStatus status, void *data)  {
37         Manager *m = data;
38
39         assert(bus);
40         assert(m);
41
42         if (!m->api_bus)
43                 return;
44
45         assert(m->api_bus == bus);
46
47         m->request_api_bus_dispatch = status != DBUS_DISPATCH_COMPLETE;
48 }
49
50 static void system_bus_dispatch_status(DBusConnection *bus, DBusDispatchStatus status, void *data)  {
51         Manager *m = data;
52
53         assert(bus);
54         assert(m);
55
56         if (!m->system_bus)
57                 return;
58
59         assert(m->system_bus == bus);
60
61         m->request_system_bus_dispatch = status != DBUS_DISPATCH_COMPLETE;
62 }
63
64 static uint32_t bus_flags_to_events(DBusWatch *bus_watch) {
65         unsigned flags;
66         uint32_t events = 0;
67
68         assert(bus_watch);
69
70         /* no watch flags for disabled watches */
71         if (!dbus_watch_get_enabled(bus_watch))
72                 return 0;
73
74         flags = dbus_watch_get_flags(bus_watch);
75
76         if (flags & DBUS_WATCH_READABLE)
77                 events |= EPOLLIN;
78         if (flags & DBUS_WATCH_WRITABLE)
79                 events |= EPOLLOUT;
80
81         return events | EPOLLHUP | EPOLLERR;
82 }
83
84 static unsigned events_to_bus_flags(uint32_t events) {
85         unsigned flags = 0;
86
87         if (events & EPOLLIN)
88                 flags |= DBUS_WATCH_READABLE;
89         if (events & EPOLLOUT)
90                 flags |= DBUS_WATCH_WRITABLE;
91         if (events & EPOLLHUP)
92                 flags |= DBUS_WATCH_HANGUP;
93         if (events & EPOLLERR)
94                 flags |= DBUS_WATCH_ERROR;
95
96         return flags;
97 }
98
99 void bus_watch_event(Manager *m, Watch *w, int events) {
100         assert(m);
101         assert(w);
102
103         /* This is called by the event loop whenever there is
104          * something happening on D-Bus' file handles. */
105
106         if (!dbus_watch_get_enabled(w->data.bus_watch))
107                 return;
108
109         dbus_watch_handle(w->data.bus_watch, events_to_bus_flags(events));
110 }
111
112 static dbus_bool_t bus_add_watch(DBusWatch *bus_watch, void *data) {
113         Manager *m = data;
114         Watch *w;
115         struct epoll_event ev;
116
117         assert(bus_watch);
118         assert(m);
119
120         if (!(w = new0(Watch, 1)))
121                 return FALSE;
122
123         w->fd = dbus_watch_get_unix_fd(bus_watch);
124         w->type = WATCH_DBUS_WATCH;
125         w->data.bus_watch = bus_watch;
126
127         zero(ev);
128         ev.events = bus_flags_to_events(bus_watch);
129         ev.data.ptr = w;
130
131         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0) {
132
133                 if (errno != EEXIST) {
134                         free(w);
135                         return FALSE;
136                 }
137
138                 /* Hmm, bloody D-Bus creates multiple watches on the
139                  * same fd. epoll() does not like that. As a dirty
140                  * hack we simply dup() the fd and hence get a second
141                  * one we can safely add to the epoll(). */
142
143                 if ((w->fd = dup(w->fd)) < 0) {
144                         free(w);
145                         return FALSE;
146                 }
147
148                 if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0) {
149                         free(w);
150                         close_nointr_nofail(w->fd);
151                         return FALSE;
152                 }
153
154                 w->fd_is_dupped = true;
155         }
156
157         dbus_watch_set_data(bus_watch, w, NULL);
158
159         return TRUE;
160 }
161
162 static void bus_remove_watch(DBusWatch *bus_watch, void *data) {
163         Manager *m = data;
164         Watch *w;
165
166         assert(bus_watch);
167         assert(m);
168
169         if (!(w = dbus_watch_get_data(bus_watch)))
170                 return;
171
172         assert(w->type == WATCH_DBUS_WATCH);
173         assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
174
175         if (w->fd_is_dupped)
176                 close_nointr_nofail(w->fd);
177
178         free(w);
179 }
180
181 static void bus_toggle_watch(DBusWatch *bus_watch, void *data) {
182         Manager *m = data;
183         Watch *w;
184         struct epoll_event ev;
185
186         assert(bus_watch);
187         assert(m);
188
189         assert_se(w = dbus_watch_get_data(bus_watch));
190         assert(w->type == WATCH_DBUS_WATCH);
191
192         zero(ev);
193         ev.events = bus_flags_to_events(bus_watch);
194         ev.data.ptr = w;
195
196         assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_MOD, w->fd, &ev) == 0);
197 }
198
199 static int bus_timeout_arm(Manager *m, Watch *w) {
200         struct itimerspec its;
201
202         assert(m);
203         assert(w);
204
205         zero(its);
206
207         if (dbus_timeout_get_enabled(w->data.bus_timeout)) {
208                 timespec_store(&its.it_value, dbus_timeout_get_interval(w->data.bus_timeout) * USEC_PER_MSEC);
209                 its.it_interval = its.it_interval;
210         }
211
212         if (timerfd_settime(w->fd, 0, &its, NULL) < 0)
213                 return -errno;
214
215         return 0;
216 }
217
218 void bus_timeout_event(Manager *m, Watch *w, int events) {
219         assert(m);
220         assert(w);
221
222         /* This is called by the event loop whenever there is
223          * something happening on D-Bus' file handles. */
224
225         if (!(dbus_timeout_get_enabled(w->data.bus_timeout)))
226                 return;
227
228         dbus_timeout_handle(w->data.bus_timeout);
229 }
230
231 static dbus_bool_t bus_add_timeout(DBusTimeout *timeout, void *data) {
232         Manager *m = data;
233         Watch *w;
234         struct epoll_event ev;
235
236         assert(timeout);
237         assert(m);
238
239         if (!(w = new0(Watch, 1)))
240                 return FALSE;
241
242         if (!(w->fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK|TFD_CLOEXEC)) < 0)
243                 goto fail;
244
245         w->type = WATCH_DBUS_TIMEOUT;
246         w->data.bus_timeout = timeout;
247
248         if (bus_timeout_arm(m, w) < 0)
249                 goto fail;
250
251         zero(ev);
252         ev.events = EPOLLIN;
253         ev.data.ptr = w;
254
255         if (epoll_ctl(m->epoll_fd, EPOLL_CTL_ADD, w->fd, &ev) < 0)
256                 goto fail;
257
258         dbus_timeout_set_data(timeout, w, NULL);
259
260         return TRUE;
261
262 fail:
263         if (w->fd >= 0)
264                 close_nointr_nofail(w->fd);
265
266         free(w);
267         return FALSE;
268 }
269
270 static void bus_remove_timeout(DBusTimeout *timeout, void *data) {
271         Manager *m = data;
272         Watch *w;
273
274         assert(timeout);
275         assert(m);
276
277         if (!(w = dbus_timeout_get_data(timeout)))
278                 return;
279
280         assert(w->type == WATCH_DBUS_TIMEOUT);
281         assert_se(epoll_ctl(m->epoll_fd, EPOLL_CTL_DEL, w->fd, NULL) >= 0);
282         close_nointr_nofail(w->fd);
283         free(w);
284 }
285
286 static void bus_toggle_timeout(DBusTimeout *timeout, void *data) {
287         Manager *m = data;
288         Watch *w;
289         int r;
290
291         assert(timeout);
292         assert(m);
293
294         assert_se(w = dbus_timeout_get_data(timeout));
295         assert(w->type == WATCH_DBUS_TIMEOUT);
296
297         if ((r = bus_timeout_arm(m, w)) < 0)
298                 log_error("Failed to rearm timer: %s", strerror(-r));
299 }
300
301 static DBusHandlerResult api_bus_message_filter(DBusConnection  *connection, DBusMessage  *message, void *data) {
302         Manager *m = data;
303         DBusError error;
304
305         assert(connection);
306         assert(message);
307         assert(m);
308
309         dbus_error_init(&error);
310
311         /* log_debug("Got D-Bus request: %s.%s() on %s", */
312         /*           dbus_message_get_interface(message), */
313         /*           dbus_message_get_member(message), */
314         /*           dbus_message_get_path(message)); */
315
316         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
317                 log_error("Warning! API D-Bus connection terminated.");
318                 bus_done_api(m);
319
320         } else if (dbus_message_is_signal(message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) {
321                 const char *name, *old_owner, *new_owner;
322
323                 if (!dbus_message_get_args(message, &error,
324                                            DBUS_TYPE_STRING, &name,
325                                            DBUS_TYPE_STRING, &old_owner,
326                                            DBUS_TYPE_STRING, &new_owner,
327                                            DBUS_TYPE_INVALID))
328                         log_error("Failed to parse NameOwnerChanged message: %s", error.message);
329                 else  {
330                         if (set_remove(m->subscribed, (char*) name))
331                                 log_debug("Subscription client vanished: %s (left: %u)", name, set_size(m->subscribed));
332
333                         if (old_owner[0] == 0)
334                                 old_owner = NULL;
335
336                         if (new_owner[0] == 0)
337                                 new_owner = NULL;
338
339                         manager_dispatch_bus_name_owner_changed(m, name, old_owner, new_owner);
340                 }
341         }
342
343         dbus_error_free(&error);
344         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
345 }
346
347 static DBusHandlerResult system_bus_message_filter(DBusConnection  *connection, DBusMessage  *message, void *data) {
348         Manager *m = data;
349         DBusError error;
350
351         assert(connection);
352         assert(message);
353         assert(m);
354
355         dbus_error_init(&error);
356
357         /* log_debug("Got D-Bus request: %s.%s() on %s", */
358         /*           dbus_message_get_interface(message), */
359         /*           dbus_message_get_member(message), */
360         /*           dbus_message_get_path(message)); */
361
362         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
363                 log_error("Warning! System D-Bus connection terminated.");
364                 bus_done_system(m);
365
366         } if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Agent", "Released")) {
367                 const char *cgroup;
368
369                 if (!dbus_message_get_args(message, &error,
370                                            DBUS_TYPE_STRING, &cgroup,
371                                            DBUS_TYPE_INVALID))
372                         log_error("Failed to parse Released message: %s", error.message);
373                 else
374                         cgroup_notify_empty(m, cgroup);
375         }
376
377         dbus_error_free(&error);
378         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
379 }
380
381 unsigned bus_dispatch(Manager *m) {
382         assert(m);
383
384         if (m->request_api_bus_dispatch) {
385                 if (dbus_connection_dispatch(m->api_bus) == DBUS_DISPATCH_COMPLETE)
386                         m->request_api_bus_dispatch = false;
387
388                 return 1;
389         }
390
391         if (m->request_system_bus_dispatch) {
392                 if (dbus_connection_dispatch(m->system_bus) == DBUS_DISPATCH_COMPLETE)
393                         m->request_system_bus_dispatch = false;
394
395                 return 1;
396         }
397
398         return 0;
399 }
400
401 static void request_name_pending_cb(DBusPendingCall *pending, void *userdata) {
402         DBusMessage *reply;
403         DBusError error;
404
405         dbus_error_init(&error);
406
407         assert_se(reply = dbus_pending_call_steal_reply(pending));
408
409         switch (dbus_message_get_type(reply)) {
410
411         case DBUS_MESSAGE_TYPE_ERROR:
412
413                 assert_se(dbus_set_error_from_message(&error, reply));
414                 log_warning("RequestName() failed: %s", error.message);
415                 break;
416
417         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
418                 uint32_t r;
419
420                 if (!dbus_message_get_args(reply,
421                                            &error,
422                                            DBUS_TYPE_UINT32, &r,
423                                            DBUS_TYPE_INVALID)) {
424                         log_error("Failed to parse RequestName() reply: %s", error.message);
425                         break;
426                 }
427
428                 if (r == 1)
429                         log_debug("Successfully acquired name.");
430                 else
431                         log_error("Name already owned.");
432
433                 break;
434         }
435
436         default:
437                 assert_not_reached("Invalid reply message");
438         }
439
440         dbus_message_unref(reply);
441         dbus_error_free(&error);
442 }
443
444 static int request_name(Manager *m) {
445         const char *name = "org.freedesktop.systemd1";
446         uint32_t flags = 0;
447         DBusMessage *message = NULL;
448         DBusPendingCall *pending = NULL;
449
450         if (!(message = dbus_message_new_method_call(
451                               DBUS_SERVICE_DBUS,
452                               DBUS_PATH_DBUS,
453                               DBUS_INTERFACE_DBUS,
454                               "RequestName")))
455                 goto oom;
456
457         if (!dbus_message_append_args(
458                             message,
459                             DBUS_TYPE_STRING, &name,
460                             DBUS_TYPE_UINT32, &flags,
461                             DBUS_TYPE_INVALID))
462                 goto oom;
463
464         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
465                 goto oom;
466
467         if (!dbus_pending_call_set_notify(pending, request_name_pending_cb, m, NULL))
468                 goto oom;
469
470         dbus_message_unref(message);
471         dbus_pending_call_unref(pending);
472
473         /* We simple ask for the name and don't wait for it. Sooner or
474          * later we'll have it. */
475
476         return 0;
477
478 oom:
479         if (pending) {
480                 dbus_pending_call_cancel(pending);
481                 dbus_pending_call_unref(pending);
482         }
483
484         if (message)
485                 dbus_message_unref(message);
486
487         return -ENOMEM;
488 }
489
490 static int bus_setup_loop(Manager *m, DBusConnection *bus) {
491         assert(m);
492         assert(bus);
493
494         dbus_connection_set_exit_on_disconnect(bus, FALSE);
495
496         if (!dbus_connection_set_watch_functions(bus, bus_add_watch, bus_remove_watch, bus_toggle_watch, m, NULL) ||
497             !dbus_connection_set_timeout_functions(bus, bus_add_timeout, bus_remove_timeout, bus_toggle_timeout, m, NULL))
498                 return -ENOMEM;
499
500         return 0;
501 }
502
503 int bus_init_system(Manager *m) {
504         DBusError error;
505         char *id;
506         int r;
507
508         assert(m);
509
510         dbus_error_init(&error);
511
512         if (m->system_bus)
513                 return 0;
514
515         if (m->running_as != MANAGER_SESSION && m->api_bus)
516                 m->system_bus = m->api_bus;
517         else {
518                 if (!(m->system_bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error))) {
519                         log_debug("Failed to get system D-Bus connection, retrying later: %s", error.message);
520                         dbus_error_free(&error);
521                         return 0;
522                 }
523
524                 dbus_connection_set_dispatch_status_function(m->system_bus, system_bus_dispatch_status, m, NULL);
525                 m->request_system_bus_dispatch = true;
526
527                 if ((r = bus_setup_loop(m, m->system_bus)) < 0) {
528                         bus_done_system(m);
529                         return r;
530                 }
531         }
532
533         if (!dbus_connection_add_filter(m->system_bus, system_bus_message_filter, m, NULL)) {
534                 bus_done_system(m);
535                 return -ENOMEM;
536         }
537
538         dbus_bus_add_match(m->system_bus,
539                            "type='signal',"
540                            "interface='org.freedesktop.systemd1.Agent',"
541                            "path='/org/freedesktop/systemd1/agent'",
542                            &error);
543
544         if (dbus_error_is_set(&error)) {
545                 log_error("Failed to register match: %s", error.message);
546                 dbus_error_free(&error);
547                 bus_done_system(m);
548                 return -ENOMEM;
549         }
550
551         log_debug("Successfully connected to system D-Bus bus %s as %s",
552                   strnull((id = dbus_connection_get_server_id(m->system_bus))),
553                   strnull(dbus_bus_get_unique_name(m->system_bus)));
554         dbus_free(id);
555
556         return 0;
557 }
558
559 int bus_init_api(Manager *m) {
560         DBusError error;
561         char *id;
562         int r;
563
564         assert(m);
565
566         dbus_error_init(&error);
567
568         if (m->api_bus)
569                 return 0;
570
571         if (m->name_data_slot < 0)
572                 if (!dbus_pending_call_allocate_data_slot(&m->name_data_slot))
573                         return -ENOMEM;
574
575         if (m->running_as != MANAGER_SESSION && m->system_bus)
576                 m->api_bus = m->system_bus;
577         else {
578                 if (!(m->api_bus = dbus_bus_get_private(m->running_as == MANAGER_SESSION ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error))) {
579                         log_debug("Failed to get API D-Bus connection, retrying later: %s", error.message);
580                         dbus_error_free(&error);
581                         return 0;
582                 }
583
584                 dbus_connection_set_dispatch_status_function(m->api_bus, api_bus_dispatch_status, m, NULL);
585                 m->request_api_bus_dispatch = true;
586
587                 if ((r = bus_setup_loop(m, m->api_bus)) < 0) {
588                         bus_done_api(m);
589                         return r;
590                 }
591         }
592
593         if (!dbus_connection_register_object_path(m->api_bus, "/org/freedesktop/systemd1", &bus_manager_vtable, m) ||
594             !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/unit", &bus_unit_vtable, m) ||
595             !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/job", &bus_job_vtable, m) ||
596             !dbus_connection_add_filter(m->api_bus, api_bus_message_filter, m, NULL)) {
597                 bus_done_api(m);
598                 return -ENOMEM;
599         }
600
601         dbus_bus_add_match(m->api_bus,
602                            "type='signal',"
603                            "sender='"DBUS_SERVICE_DBUS"',"
604                            "interface='"DBUS_INTERFACE_DBUS"',"
605                            "path='"DBUS_PATH_DBUS"'",
606                            &error);
607
608         if (dbus_error_is_set(&error)) {
609                 log_error("Failed to register match: %s", error.message);
610                 dbus_error_free(&error);
611                 bus_done_api(m);
612                 return -ENOMEM;
613         }
614
615         if ((r = request_name(m)) < 0) {
616                 bus_done_api(m);
617                 return r;
618         }
619
620         log_debug("Successfully connected to API D-Bus bus %s as %s",
621                   strnull((id = dbus_connection_get_server_id(m->api_bus))),
622                   strnull(dbus_bus_get_unique_name(m->api_bus)));
623         dbus_free(id);
624
625         if (!m->subscribed)
626                 if (!(m->subscribed = set_new(string_hash_func, string_compare_func)))
627                         return -ENOMEM;
628
629         return 0;
630 }
631
632 void bus_done_api(Manager *m) {
633         assert(m);
634
635         if (m->api_bus) {
636                 if (m->system_bus == m->api_bus)
637                         m->system_bus = NULL;
638
639                 dbus_connection_set_dispatch_status_function(m->api_bus, NULL, NULL, NULL);
640                 dbus_connection_flush(m->api_bus);
641                 dbus_connection_close(m->api_bus);
642                 dbus_connection_unref(m->api_bus);
643                 m->api_bus = NULL;
644         }
645
646         if (m->subscribed) {
647                 char *c;
648
649                 while ((c = set_steal_first(m->subscribed)))
650                         free(c);
651
652                 set_free(m->subscribed);
653                 m->subscribed = NULL;
654         }
655
656        if (m->name_data_slot >= 0)
657                dbus_pending_call_free_data_slot(&m->name_data_slot);
658 }
659
660 void bus_done_system(Manager *m) {
661         assert(m);
662
663         if (m->system_bus == m->api_bus)
664                 bus_done_api(m);
665
666         if (m->system_bus) {
667                 dbus_connection_set_dispatch_status_function(m->system_bus, NULL, NULL, NULL);
668                 dbus_connection_flush(m->system_bus);
669                 dbus_connection_close(m->system_bus);
670                 dbus_connection_unref(m->system_bus);
671                 m->system_bus = NULL;
672         }
673 }
674
675 static void query_pid_pending_cb(DBusPendingCall *pending, void *userdata) {
676         Manager *m = userdata;
677         DBusMessage *reply;
678         DBusError error;
679         const char *name;
680
681         dbus_error_init(&error);
682
683         assert_se(name = dbus_pending_call_get_data(pending, m->name_data_slot));
684         assert_se(reply = dbus_pending_call_steal_reply(pending));
685
686         switch (dbus_message_get_type(reply)) {
687
688         case DBUS_MESSAGE_TYPE_ERROR:
689
690                 assert_se(dbus_set_error_from_message(&error, reply));
691                 log_warning("GetConnectionUnixProcessID() failed: %s", error.message);
692                 break;
693
694         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
695                 uint32_t r;
696
697                 if (!dbus_message_get_args(reply,
698                                            &error,
699                                            DBUS_TYPE_UINT32, &r,
700                                            DBUS_TYPE_INVALID)) {
701                         log_error("Failed to parse GetConnectionUnixProcessID() reply: %s", error.message);
702                         break;
703                 }
704
705                 manager_dispatch_bus_query_pid_done(m, name, (pid_t) r);
706                 break;
707         }
708
709         default:
710                 assert_not_reached("Invalid reply message");
711         }
712
713         dbus_message_unref(reply);
714         dbus_error_free(&error);
715 }
716
717 int bus_query_pid(Manager *m, const char *name) {
718         DBusMessage *message = NULL;
719         DBusPendingCall *pending = NULL;
720         char *n = NULL;
721
722         assert(m);
723         assert(name);
724
725         if (!(message = dbus_message_new_method_call(
726                               DBUS_SERVICE_DBUS,
727                               DBUS_PATH_DBUS,
728                               DBUS_INTERFACE_DBUS,
729                               "GetConnectionUnixProcessID")))
730                 goto oom;
731
732         if (!(dbus_message_append_args(
733                               message,
734                               DBUS_TYPE_STRING, &name,
735                               DBUS_TYPE_INVALID)))
736                 goto oom;
737
738         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
739                 goto oom;
740
741         if (!(n = strdup(name)))
742                 goto oom;
743
744         if (!dbus_pending_call_set_data(pending, m->name_data_slot, n, free))
745                 goto oom;
746
747         n = NULL;
748
749         if (!dbus_pending_call_set_notify(pending, query_pid_pending_cb, m, NULL))
750                 goto oom;
751
752         dbus_message_unref(message);
753         dbus_pending_call_unref(pending);
754
755         return 0;
756
757 oom:
758         free(n);
759
760         if (pending) {
761                 dbus_pending_call_cancel(pending);
762                 dbus_pending_call_unref(pending);
763         }
764
765         if (message)
766                 dbus_message_unref(message);
767
768         return -ENOMEM;
769 }
770
771 DBusHandlerResult bus_default_message_handler(Manager *m, DBusMessage *message, const char*introspection, const BusProperty *properties) {
772         DBusError error;
773         DBusMessage *reply = NULL;
774         int r;
775
776         assert(m);
777         assert(message);
778
779         dbus_error_init(&error);
780
781         if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect") && introspection) {
782
783                 if (!(reply = dbus_message_new_method_return(message)))
784                         goto oom;
785
786                 if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID))
787                         goto oom;
788
789         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Get") && properties) {
790                 const char *interface, *property;
791                 const BusProperty *p;
792
793                 if (!dbus_message_get_args(
794                             message,
795                             &error,
796                             DBUS_TYPE_STRING, &interface,
797                             DBUS_TYPE_STRING, &property,
798                             DBUS_TYPE_INVALID))
799                         return bus_send_error_reply(m, message, &error, -EINVAL);
800
801                 for (p = properties; p->property; p++)
802                         if (streq(p->interface, interface) && streq(p->property, property))
803                                 break;
804
805                 if (p->property) {
806                         DBusMessageIter iter, sub;
807
808                         if (!(reply = dbus_message_new_method_return(message)))
809                                 goto oom;
810
811                         dbus_message_iter_init_append(reply, &iter);
812
813                         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, p->signature, &sub))
814                                 goto oom;
815
816                         if ((r = p->append(m, &sub, property, (void*) p->data)) < 0) {
817
818                                 if (r == -ENOMEM)
819                                         goto oom;
820
821                                 dbus_message_unref(reply);
822                                 return bus_send_error_reply(m, message, NULL, r);
823                         }
824
825                         if (!dbus_message_iter_close_container(&iter, &sub))
826                                 goto oom;
827                 }
828         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "GetAll") && properties) {
829                 const char *interface;
830                 const BusProperty *p;
831                 DBusMessageIter iter, sub, sub2, sub3;
832                 bool any = false;
833
834                 if (!dbus_message_get_args(
835                             message,
836                             &error,
837                             DBUS_TYPE_STRING, &interface,
838                             DBUS_TYPE_INVALID))
839                         return bus_send_error_reply(m, message, &error, -EINVAL);
840
841                 if (!(reply = dbus_message_new_method_return(message)))
842                         goto oom;
843
844                 dbus_message_iter_init_append(reply, &iter);
845
846                 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub))
847                         goto oom;
848
849                 for (p = properties; p->property; p++) {
850                         if (!streq(p->interface, interface))
851                                 continue;
852
853                         if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub2) ||
854                             !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &p->property) ||
855                             !dbus_message_iter_open_container(&sub2, DBUS_TYPE_VARIANT, p->signature, &sub3))
856                                 goto oom;
857
858                         if ((r = p->append(m, &sub3, p->property, (void*) p->data)) < 0) {
859
860                                 if (r == -ENOMEM)
861                                         goto oom;
862
863                                 dbus_message_unref(reply);
864                                 return bus_send_error_reply(m, message, NULL, r);
865                         }
866
867                         if (!dbus_message_iter_close_container(&sub2, &sub3) ||
868                             !dbus_message_iter_close_container(&sub, &sub2))
869                                 goto oom;
870
871                         any = true;
872                 }
873
874                 if (!dbus_message_iter_close_container(&iter, &sub))
875                         goto oom;
876         }
877
878         if (reply) {
879                 if (!dbus_connection_send(m->api_bus, reply, NULL))
880                         goto oom;
881
882                 dbus_message_unref(reply);
883                 return DBUS_HANDLER_RESULT_HANDLED;
884         }
885
886         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
887
888 oom:
889         if (reply)
890                 dbus_message_unref(reply);
891
892         dbus_error_free(&error);
893
894         return DBUS_HANDLER_RESULT_NEED_MEMORY;
895 }
896
897 static const char *error_to_dbus(int error) {
898
899         switch(error) {
900
901         case -EINVAL:
902                 return DBUS_ERROR_INVALID_ARGS;
903
904         case -ENOMEM:
905                 return DBUS_ERROR_NO_MEMORY;
906
907         case -EPERM:
908         case -EACCES:
909                 return DBUS_ERROR_ACCESS_DENIED;
910
911         case -ESRCH:
912                 return DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN;
913
914         case -ENOENT:
915                 return DBUS_ERROR_FILE_NOT_FOUND;
916
917         case -EEXIST:
918                 return DBUS_ERROR_FILE_EXISTS;
919
920         case -ETIMEDOUT:
921                 return DBUS_ERROR_TIMEOUT;
922
923         case -EIO:
924                 return DBUS_ERROR_IO_ERROR;
925
926         case -ENETRESET:
927         case -ECONNABORTED:
928         case -ECONNRESET:
929                 return DBUS_ERROR_DISCONNECTED;
930         }
931
932         return DBUS_ERROR_FAILED;
933 }
934
935 DBusHandlerResult bus_send_error_reply(Manager *m, DBusMessage *message, DBusError *bus_error, int error) {
936         DBusMessage *reply = NULL;
937         const char *name, *text;
938
939         if (bus_error && dbus_error_is_set(bus_error)) {
940                 name = bus_error->name;
941                 text = bus_error->message;
942         } else {
943                 name = error_to_dbus(error);
944                 text = strerror(-error);
945         }
946
947         if (!(reply = dbus_message_new_error(message, name, text)))
948                 goto oom;
949
950         if (!dbus_connection_send(m->api_bus, reply, NULL))
951                 goto oom;
952
953         dbus_message_unref(reply);
954
955         if (bus_error)
956                 dbus_error_free(bus_error);
957
958         return DBUS_HANDLER_RESULT_HANDLED;
959
960 oom:
961         if (reply)
962                 dbus_message_unref(reply);
963
964         if (bus_error)
965                 dbus_error_free(bus_error);
966
967         return DBUS_HANDLER_RESULT_NEED_MEMORY;
968 }
969
970 int bus_property_append_string(Manager *m, DBusMessageIter *i, const char *property, void *data) {
971         const char *t = data;
972
973         assert(m);
974         assert(i);
975         assert(property);
976
977         if (!t)
978                 t = "";
979
980         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
981                 return -ENOMEM;
982
983         return 0;
984 }
985
986 int bus_property_append_strv(Manager *m, DBusMessageIter *i, const char *property, void *data) {
987         DBusMessageIter sub;
988         char **t = data;
989
990         assert(m);
991         assert(i);
992         assert(property);
993
994         if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "s", &sub))
995                 return -ENOMEM;
996
997         STRV_FOREACH(t, t)
998                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, t))
999                         return -ENOMEM;
1000
1001         if (!dbus_message_iter_close_container(i, &sub))
1002                 return -ENOMEM;
1003
1004         return 0;
1005 }
1006
1007 int bus_property_append_bool(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1008         bool *b = data;
1009         dbus_bool_t db;
1010
1011         assert(m);
1012         assert(i);
1013         assert(property);
1014         assert(b);
1015
1016         db = *b;
1017
1018         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
1019                 return -ENOMEM;
1020
1021         return 0;
1022 }
1023
1024 int bus_property_append_uint64(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1025         assert(m);
1026         assert(i);
1027         assert(property);
1028         assert(data);
1029
1030         /* Let's ensure that pid_t is actually 64bit, and hence this
1031          * function can be used for usec_t */
1032         assert_cc(sizeof(uint64_t) == sizeof(usec_t));
1033
1034         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, data))
1035                 return -ENOMEM;
1036
1037         return 0;
1038 }
1039
1040 int bus_property_append_uint32(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1041         assert(m);
1042         assert(i);
1043         assert(property);
1044         assert(data);
1045
1046         /* Let's ensure that pid_t and mode_t is actually 32bit, and
1047          * hence this function can be used for pid_t/mode_t */
1048         assert_cc(sizeof(uint32_t) == sizeof(pid_t));
1049         assert_cc(sizeof(uint32_t) == sizeof(mode_t));
1050         assert_cc(sizeof(uint32_t) == sizeof(unsigned));
1051
1052         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT32, data))
1053                 return -ENOMEM;
1054
1055         return 0;
1056 }
1057
1058 int bus_property_append_int32(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1059         assert(m);
1060         assert(i);
1061         assert(property);
1062         assert(data);
1063
1064         assert_cc(sizeof(int32_t) == sizeof(int));
1065
1066         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, data))
1067                 return -ENOMEM;
1068
1069         return 0;
1070 }