chiark / gitweb /
timer: fully implement timer units
[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
45 static const char bus_properties_interface[] = BUS_PROPERTIES_INTERFACE;
46 static const char bus_introspectable_interface[] = BUS_INTROSPECTABLE_INTERFACE;
47
48 const char *const bus_interface_table[] = {
49         "org.freedesktop.DBus.Properties",     bus_properties_interface,
50         "org.freedesktop.DBus.Introspectable", bus_introspectable_interface,
51         "org.freedesktop.systemd1.Manager",    bus_manager_interface,
52         "org.freedesktop.systemd1.Job",        bus_job_interface,
53         "org.freedesktop.systemd1.Unit",       bus_unit_interface,
54         "org.freedesktop.systemd1.Service",    bus_service_interface,
55         "org.freedesktop.systemd1.Socket",     bus_socket_interface,
56         "org.freedesktop.systemd1.Target",     bus_target_interface,
57         "org.freedesktop.systemd1.Device",     bus_device_interface,
58         "org.freedesktop.systemd1.Mount",      bus_mount_interface,
59         "org.freedesktop.systemd1.Automount",  bus_automount_interface,
60         "org.freedesktop.systemd1.Snapshot",   bus_snapshot_interface,
61         "org.freedesktop.systemd1.Swap",       bus_swap_interface,
62         "org.freedesktop.systemd1.Timer",      bus_timer_interface,
63         NULL
64 };
65
66 static void api_bus_dispatch_status(DBusConnection *bus, DBusDispatchStatus status, void *data)  {
67         Manager *m = data;
68
69         assert(bus);
70         assert(m);
71
72         if (!m->api_bus)
73                 return;
74
75         assert(m->api_bus == bus);
76
77         m->request_api_bus_dispatch = status != DBUS_DISPATCH_COMPLETE;
78 }
79
80 static void system_bus_dispatch_status(DBusConnection *bus, DBusDispatchStatus status, void *data)  {
81         Manager *m = data;
82
83         assert(bus);
84         assert(m);
85
86         if (!m->system_bus)
87                 return;
88
89         assert(m->system_bus == bus);
90
91         m->request_system_bus_dispatch = status != DBUS_DISPATCH_COMPLETE;
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
335         assert(connection);
336         assert(message);
337         assert(m);
338
339         dbus_error_init(&error);
340
341         /* log_debug("Got D-Bus request: %s.%s() on %s", */
342         /*           dbus_message_get_interface(message), */
343         /*           dbus_message_get_member(message), */
344         /*           dbus_message_get_path(message)); */
345
346         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
347                 log_error("Warning! API D-Bus connection terminated.");
348                 bus_done_api(m);
349
350         } else if (dbus_message_is_signal(message, DBUS_INTERFACE_DBUS, "NameOwnerChanged")) {
351                 const char *name, *old_owner, *new_owner;
352
353                 if (!dbus_message_get_args(message, &error,
354                                            DBUS_TYPE_STRING, &name,
355                                            DBUS_TYPE_STRING, &old_owner,
356                                            DBUS_TYPE_STRING, &new_owner,
357                                            DBUS_TYPE_INVALID))
358                         log_error("Failed to parse NameOwnerChanged message: %s", error.message);
359                 else  {
360                         if (set_remove(m->subscribed, (char*) name))
361                                 log_debug("Subscription client vanished: %s (left: %u)", name, set_size(m->subscribed));
362
363                         if (old_owner[0] == 0)
364                                 old_owner = NULL;
365
366                         if (new_owner[0] == 0)
367                                 new_owner = NULL;
368
369                         manager_dispatch_bus_name_owner_changed(m, name, old_owner, new_owner);
370                 }
371         }
372
373         dbus_error_free(&error);
374         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
375 }
376
377 static DBusHandlerResult system_bus_message_filter(DBusConnection  *connection, DBusMessage  *message, void *data) {
378         Manager *m = data;
379         DBusError error;
380
381         assert(connection);
382         assert(message);
383         assert(m);
384
385         dbus_error_init(&error);
386
387         /* log_debug("Got D-Bus request: %s.%s() on %s", */
388         /*           dbus_message_get_interface(message), */
389         /*           dbus_message_get_member(message), */
390         /*           dbus_message_get_path(message)); */
391
392         if (dbus_message_is_signal(message, DBUS_INTERFACE_LOCAL, "Disconnected")) {
393                 log_error("Warning! System D-Bus connection terminated.");
394                 bus_done_system(m);
395
396         } if (dbus_message_is_signal(message, "org.freedesktop.systemd1.Agent", "Released")) {
397                 const char *cgroup;
398
399                 if (!dbus_message_get_args(message, &error,
400                                            DBUS_TYPE_STRING, &cgroup,
401                                            DBUS_TYPE_INVALID))
402                         log_error("Failed to parse Released message: %s", error.message);
403                 else
404                         cgroup_notify_empty(m, cgroup);
405         }
406
407         dbus_error_free(&error);
408         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
409 }
410
411 unsigned bus_dispatch(Manager *m) {
412         assert(m);
413
414         if (m->queued_message) {
415                 /* If we cannot get rid of this message we won't
416                  * dispatch any D-Bus messages, so that we won't end
417                  * up wanting to queue another message. */
418
419                 if (!dbus_connection_send(m->api_bus, m->queued_message, NULL))
420                         return 0;
421
422                 dbus_message_unref(m->queued_message);
423                 m->queued_message = NULL;
424         }
425
426         if (m->request_api_bus_dispatch) {
427                 if (dbus_connection_dispatch(m->api_bus) == DBUS_DISPATCH_COMPLETE)
428                         m->request_api_bus_dispatch = false;
429
430                 return 1;
431         }
432
433         if (m->request_system_bus_dispatch) {
434                 if (dbus_connection_dispatch(m->system_bus) == DBUS_DISPATCH_COMPLETE)
435                         m->request_system_bus_dispatch = false;
436
437                 return 1;
438         }
439
440         return 0;
441 }
442
443 static void request_name_pending_cb(DBusPendingCall *pending, void *userdata) {
444         DBusMessage *reply;
445         DBusError error;
446
447         dbus_error_init(&error);
448
449         assert_se(reply = dbus_pending_call_steal_reply(pending));
450
451         switch (dbus_message_get_type(reply)) {
452
453         case DBUS_MESSAGE_TYPE_ERROR:
454
455                 assert_se(dbus_set_error_from_message(&error, reply));
456                 log_warning("RequestName() failed: %s", error.message);
457                 break;
458
459         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
460                 uint32_t r;
461
462                 if (!dbus_message_get_args(reply,
463                                            &error,
464                                            DBUS_TYPE_UINT32, &r,
465                                            DBUS_TYPE_INVALID)) {
466                         log_error("Failed to parse RequestName() reply: %s", error.message);
467                         break;
468                 }
469
470                 if (r == 1)
471                         log_debug("Successfully acquired name.");
472                 else
473                         log_error("Name already owned.");
474
475                 break;
476         }
477
478         default:
479                 assert_not_reached("Invalid reply message");
480         }
481
482         dbus_message_unref(reply);
483         dbus_error_free(&error);
484 }
485
486 static int request_name(Manager *m) {
487         const char *name = "org.freedesktop.systemd1";
488         uint32_t flags = 0;
489         DBusMessage *message = NULL;
490         DBusPendingCall *pending = NULL;
491
492         if (!(message = dbus_message_new_method_call(
493                               DBUS_SERVICE_DBUS,
494                               DBUS_PATH_DBUS,
495                               DBUS_INTERFACE_DBUS,
496                               "RequestName")))
497                 goto oom;
498
499         if (!dbus_message_append_args(
500                             message,
501                             DBUS_TYPE_STRING, &name,
502                             DBUS_TYPE_UINT32, &flags,
503                             DBUS_TYPE_INVALID))
504                 goto oom;
505
506         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
507                 goto oom;
508
509         if (!dbus_pending_call_set_notify(pending, request_name_pending_cb, m, NULL))
510                 goto oom;
511
512         dbus_message_unref(message);
513         dbus_pending_call_unref(pending);
514
515         /* We simple ask for the name and don't wait for it. Sooner or
516          * later we'll have it. */
517
518         return 0;
519
520 oom:
521         if (pending) {
522                 dbus_pending_call_cancel(pending);
523                 dbus_pending_call_unref(pending);
524         }
525
526         if (message)
527                 dbus_message_unref(message);
528
529         return -ENOMEM;
530 }
531
532 static int bus_setup_loop(Manager *m, DBusConnection *bus) {
533         assert(m);
534         assert(bus);
535
536         dbus_connection_set_exit_on_disconnect(bus, FALSE);
537
538         if (!dbus_connection_set_watch_functions(bus, bus_add_watch, bus_remove_watch, bus_toggle_watch, m, NULL) ||
539             !dbus_connection_set_timeout_functions(bus, bus_add_timeout, bus_remove_timeout, bus_toggle_timeout, m, NULL))
540                 return -ENOMEM;
541
542         return 0;
543 }
544
545 int bus_init_system(Manager *m) {
546         DBusError error;
547         char *id;
548         int r;
549
550         assert(m);
551
552         dbus_error_init(&error);
553
554         if (m->system_bus)
555                 return 0;
556
557         if (m->running_as != MANAGER_SESSION && m->api_bus)
558                 m->system_bus = m->api_bus;
559         else {
560                 if (!(m->system_bus = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error))) {
561                         log_debug("Failed to get system D-Bus connection, retrying later: %s", error.message);
562                         dbus_error_free(&error);
563                         return 0;
564                 }
565
566                 dbus_connection_set_dispatch_status_function(m->system_bus, system_bus_dispatch_status, m, NULL);
567                 m->request_system_bus_dispatch = true;
568
569                 if ((r = bus_setup_loop(m, m->system_bus)) < 0) {
570                         bus_done_system(m);
571                         return r;
572                 }
573         }
574
575         if (!dbus_connection_add_filter(m->system_bus, system_bus_message_filter, m, NULL)) {
576                 bus_done_system(m);
577                 return -ENOMEM;
578         }
579
580         dbus_bus_add_match(m->system_bus,
581                            "type='signal',"
582                            "interface='org.freedesktop.systemd1.Agent',"
583                            "path='/org/freedesktop/systemd1/agent'",
584                            &error);
585
586         if (dbus_error_is_set(&error)) {
587                 log_error("Failed to register match: %s", error.message);
588                 dbus_error_free(&error);
589                 bus_done_system(m);
590                 return -ENOMEM;
591         }
592
593         log_debug("Successfully connected to system D-Bus bus %s as %s",
594                   strnull((id = dbus_connection_get_server_id(m->system_bus))),
595                   strnull(dbus_bus_get_unique_name(m->system_bus)));
596         dbus_free(id);
597
598         return 0;
599 }
600
601 int bus_init_api(Manager *m) {
602         DBusError error;
603         char *id;
604         int r;
605
606         assert(m);
607
608         dbus_error_init(&error);
609
610         if (m->api_bus)
611                 return 0;
612
613         if (m->name_data_slot < 0)
614                 if (!dbus_pending_call_allocate_data_slot(&m->name_data_slot))
615                         return -ENOMEM;
616
617         if (m->running_as != MANAGER_SESSION && m->system_bus)
618                 m->api_bus = m->system_bus;
619         else {
620                 if (!(m->api_bus = dbus_bus_get_private(m->running_as == MANAGER_SESSION ? DBUS_BUS_SESSION : DBUS_BUS_SYSTEM, &error))) {
621                         log_debug("Failed to get API D-Bus connection, retrying later: %s", error.message);
622                         dbus_error_free(&error);
623                         return 0;
624                 }
625
626                 dbus_connection_set_dispatch_status_function(m->api_bus, api_bus_dispatch_status, m, NULL);
627                 m->request_api_bus_dispatch = true;
628
629                 if ((r = bus_setup_loop(m, m->api_bus)) < 0) {
630                         bus_done_api(m);
631                         return r;
632                 }
633         }
634
635         if (!dbus_connection_register_object_path(m->api_bus, "/org/freedesktop/systemd1", &bus_manager_vtable, m) ||
636             !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/unit", &bus_unit_vtable, m) ||
637             !dbus_connection_register_fallback(m->api_bus, "/org/freedesktop/systemd1/job", &bus_job_vtable, m) ||
638             !dbus_connection_add_filter(m->api_bus, api_bus_message_filter, m, NULL)) {
639                 bus_done_api(m);
640                 return -ENOMEM;
641         }
642
643         dbus_bus_add_match(m->api_bus,
644                            "type='signal',"
645                            "sender='"DBUS_SERVICE_DBUS"',"
646                            "interface='"DBUS_INTERFACE_DBUS"',"
647                            "path='"DBUS_PATH_DBUS"'",
648                            &error);
649
650         if (dbus_error_is_set(&error)) {
651                 log_error("Failed to register match: %s", error.message);
652                 dbus_error_free(&error);
653                 bus_done_api(m);
654                 return -ENOMEM;
655         }
656
657         if ((r = request_name(m)) < 0) {
658                 bus_done_api(m);
659                 return r;
660         }
661
662         log_debug("Successfully connected to API D-Bus bus %s as %s",
663                   strnull((id = dbus_connection_get_server_id(m->api_bus))),
664                   strnull(dbus_bus_get_unique_name(m->api_bus)));
665         dbus_free(id);
666
667         if (!m->subscribed)
668                 if (!(m->subscribed = set_new(string_hash_func, string_compare_func)))
669                         return -ENOMEM;
670
671         return 0;
672 }
673
674 void bus_done_api(Manager *m) {
675         assert(m);
676
677         if (m->api_bus) {
678                 if (m->system_bus == m->api_bus)
679                         m->system_bus = NULL;
680
681                 dbus_connection_set_dispatch_status_function(m->api_bus, NULL, NULL, NULL);
682                 dbus_connection_flush(m->api_bus);
683                 dbus_connection_close(m->api_bus);
684                 dbus_connection_unref(m->api_bus);
685                 m->api_bus = NULL;
686         }
687
688         if (m->subscribed) {
689                 char *c;
690
691                 while ((c = set_steal_first(m->subscribed)))
692                         free(c);
693
694                 set_free(m->subscribed);
695                 m->subscribed = NULL;
696         }
697
698        if (m->name_data_slot >= 0)
699                dbus_pending_call_free_data_slot(&m->name_data_slot);
700
701        if (m->queued_message) {
702                dbus_message_unref(m->queued_message);
703                m->queued_message = NULL;
704        }
705 }
706
707 void bus_done_system(Manager *m) {
708         assert(m);
709
710         if (m->system_bus == m->api_bus)
711                 bus_done_api(m);
712
713         if (m->system_bus) {
714                 dbus_connection_set_dispatch_status_function(m->system_bus, NULL, NULL, NULL);
715                 dbus_connection_flush(m->system_bus);
716                 dbus_connection_close(m->system_bus);
717                 dbus_connection_unref(m->system_bus);
718                 m->system_bus = NULL;
719         }
720 }
721
722 static void query_pid_pending_cb(DBusPendingCall *pending, void *userdata) {
723         Manager *m = userdata;
724         DBusMessage *reply;
725         DBusError error;
726         const char *name;
727
728         dbus_error_init(&error);
729
730         assert_se(name = dbus_pending_call_get_data(pending, m->name_data_slot));
731         assert_se(reply = dbus_pending_call_steal_reply(pending));
732
733         switch (dbus_message_get_type(reply)) {
734
735         case DBUS_MESSAGE_TYPE_ERROR:
736
737                 assert_se(dbus_set_error_from_message(&error, reply));
738                 log_warning("GetConnectionUnixProcessID() failed: %s", error.message);
739                 break;
740
741         case DBUS_MESSAGE_TYPE_METHOD_RETURN: {
742                 uint32_t r;
743
744                 if (!dbus_message_get_args(reply,
745                                            &error,
746                                            DBUS_TYPE_UINT32, &r,
747                                            DBUS_TYPE_INVALID)) {
748                         log_error("Failed to parse GetConnectionUnixProcessID() reply: %s", error.message);
749                         break;
750                 }
751
752                 manager_dispatch_bus_query_pid_done(m, name, (pid_t) r);
753                 break;
754         }
755
756         default:
757                 assert_not_reached("Invalid reply message");
758         }
759
760         dbus_message_unref(reply);
761         dbus_error_free(&error);
762 }
763
764 int bus_query_pid(Manager *m, const char *name) {
765         DBusMessage *message = NULL;
766         DBusPendingCall *pending = NULL;
767         char *n = NULL;
768
769         assert(m);
770         assert(name);
771
772         if (!(message = dbus_message_new_method_call(
773                               DBUS_SERVICE_DBUS,
774                               DBUS_PATH_DBUS,
775                               DBUS_INTERFACE_DBUS,
776                               "GetConnectionUnixProcessID")))
777                 goto oom;
778
779         if (!(dbus_message_append_args(
780                               message,
781                               DBUS_TYPE_STRING, &name,
782                               DBUS_TYPE_INVALID)))
783                 goto oom;
784
785         if (!dbus_connection_send_with_reply(m->api_bus, message, &pending, -1))
786                 goto oom;
787
788         if (!(n = strdup(name)))
789                 goto oom;
790
791         if (!dbus_pending_call_set_data(pending, m->name_data_slot, n, free))
792                 goto oom;
793
794         n = NULL;
795
796         if (!dbus_pending_call_set_notify(pending, query_pid_pending_cb, m, NULL))
797                 goto oom;
798
799         dbus_message_unref(message);
800         dbus_pending_call_unref(pending);
801
802         return 0;
803
804 oom:
805         free(n);
806
807         if (pending) {
808                 dbus_pending_call_cancel(pending);
809                 dbus_pending_call_unref(pending);
810         }
811
812         if (message)
813                 dbus_message_unref(message);
814
815         return -ENOMEM;
816 }
817
818 DBusHandlerResult bus_default_message_handler(Manager *m, DBusMessage *message, const char*introspection, const BusProperty *properties) {
819         DBusError error;
820         DBusMessage *reply = NULL;
821         int r;
822
823         assert(m);
824         assert(message);
825
826         dbus_error_init(&error);
827
828         if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Introspectable", "Introspect") && introspection) {
829
830                 if (!(reply = dbus_message_new_method_return(message)))
831                         goto oom;
832
833                 if (!dbus_message_append_args(reply, DBUS_TYPE_STRING, &introspection, DBUS_TYPE_INVALID))
834                         goto oom;
835
836         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "Get") && properties) {
837                 const char *interface, *property;
838                 const BusProperty *p;
839
840                 if (!dbus_message_get_args(
841                             message,
842                             &error,
843                             DBUS_TYPE_STRING, &interface,
844                             DBUS_TYPE_STRING, &property,
845                             DBUS_TYPE_INVALID))
846                         return bus_send_error_reply(m, message, &error, -EINVAL);
847
848                 for (p = properties; p->property; p++)
849                         if (streq(p->interface, interface) && streq(p->property, property))
850                                 break;
851
852                 if (p->property) {
853                         DBusMessageIter iter, sub;
854
855                         if (!(reply = dbus_message_new_method_return(message)))
856                                 goto oom;
857
858                         dbus_message_iter_init_append(reply, &iter);
859
860                         if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_VARIANT, p->signature, &sub))
861                                 goto oom;
862
863                         if ((r = p->append(m, &sub, property, (void*) p->data)) < 0) {
864
865                                 if (r == -ENOMEM)
866                                         goto oom;
867
868                                 dbus_message_unref(reply);
869                                 return bus_send_error_reply(m, message, NULL, r);
870                         }
871
872                         if (!dbus_message_iter_close_container(&iter, &sub))
873                                 goto oom;
874                 }
875         } else if (dbus_message_is_method_call(message, "org.freedesktop.DBus.Properties", "GetAll") && properties) {
876                 const char *interface;
877                 const BusProperty *p;
878                 DBusMessageIter iter, sub, sub2, sub3;
879                 bool any = false;
880
881                 if (!dbus_message_get_args(
882                             message,
883                             &error,
884                             DBUS_TYPE_STRING, &interface,
885                             DBUS_TYPE_INVALID))
886                         return bus_send_error_reply(m, message, &error, -EINVAL);
887
888                 if (!(reply = dbus_message_new_method_return(message)))
889                         goto oom;
890
891                 dbus_message_iter_init_append(reply, &iter);
892
893                 if (!dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY, "{sv}", &sub))
894                         goto oom;
895
896                 for (p = properties; p->property; p++) {
897                         if (!streq(p->interface, interface))
898                                 continue;
899
900                         if (!dbus_message_iter_open_container(&sub, DBUS_TYPE_DICT_ENTRY, NULL, &sub2) ||
901                             !dbus_message_iter_append_basic(&sub2, DBUS_TYPE_STRING, &p->property) ||
902                             !dbus_message_iter_open_container(&sub2, DBUS_TYPE_VARIANT, p->signature, &sub3))
903                                 goto oom;
904
905                         if ((r = p->append(m, &sub3, p->property, (void*) p->data)) < 0) {
906
907                                 if (r == -ENOMEM)
908                                         goto oom;
909
910                                 dbus_message_unref(reply);
911                                 return bus_send_error_reply(m, message, NULL, r);
912                         }
913
914                         if (!dbus_message_iter_close_container(&sub2, &sub3) ||
915                             !dbus_message_iter_close_container(&sub, &sub2))
916                                 goto oom;
917
918                         any = true;
919                 }
920
921                 if (!dbus_message_iter_close_container(&iter, &sub))
922                         goto oom;
923         }
924
925         if (reply) {
926                 if (!dbus_connection_send(m->api_bus, reply, NULL))
927                         goto oom;
928
929                 dbus_message_unref(reply);
930                 return DBUS_HANDLER_RESULT_HANDLED;
931         }
932
933         return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
934
935 oom:
936         if (reply)
937                 dbus_message_unref(reply);
938
939         dbus_error_free(&error);
940
941         return DBUS_HANDLER_RESULT_NEED_MEMORY;
942 }
943
944 static const char *error_to_dbus(int error) {
945
946         switch(error) {
947
948         case -EINVAL:
949                 return DBUS_ERROR_INVALID_ARGS;
950
951         case -ENOMEM:
952                 return DBUS_ERROR_NO_MEMORY;
953
954         case -EPERM:
955         case -EACCES:
956                 return DBUS_ERROR_ACCESS_DENIED;
957
958         case -ESRCH:
959                 return DBUS_ERROR_UNIX_PROCESS_ID_UNKNOWN;
960
961         case -ENOENT:
962                 return DBUS_ERROR_FILE_NOT_FOUND;
963
964         case -EEXIST:
965                 return DBUS_ERROR_FILE_EXISTS;
966
967         case -ETIMEDOUT:
968                 return DBUS_ERROR_TIMEOUT;
969
970         case -EIO:
971                 return DBUS_ERROR_IO_ERROR;
972
973         case -ENETRESET:
974         case -ECONNABORTED:
975         case -ECONNRESET:
976                 return DBUS_ERROR_DISCONNECTED;
977         }
978
979         return DBUS_ERROR_FAILED;
980 }
981
982 DBusHandlerResult bus_send_error_reply(Manager *m, DBusMessage *message, DBusError *bus_error, int error) {
983         DBusMessage *reply = NULL;
984         const char *name, *text;
985
986         if (bus_error && dbus_error_is_set(bus_error)) {
987                 name = bus_error->name;
988                 text = bus_error->message;
989         } else {
990                 name = error_to_dbus(error);
991                 text = strerror(-error);
992         }
993
994         if (!(reply = dbus_message_new_error(message, name, text)))
995                 goto oom;
996
997         if (!dbus_connection_send(m->api_bus, reply, NULL))
998                 goto oom;
999
1000         dbus_message_unref(reply);
1001
1002         if (bus_error)
1003                 dbus_error_free(bus_error);
1004
1005         return DBUS_HANDLER_RESULT_HANDLED;
1006
1007 oom:
1008         if (reply)
1009                 dbus_message_unref(reply);
1010
1011         if (bus_error)
1012                 dbus_error_free(bus_error);
1013
1014         return DBUS_HANDLER_RESULT_NEED_MEMORY;
1015 }
1016
1017 int bus_property_append_string(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1018         const char *t = data;
1019
1020         assert(m);
1021         assert(i);
1022         assert(property);
1023
1024         if (!t)
1025                 t = "";
1026
1027         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_STRING, &t))
1028                 return -ENOMEM;
1029
1030         return 0;
1031 }
1032
1033 int bus_property_append_strv(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1034         DBusMessageIter sub;
1035         char **t = data;
1036
1037         assert(m);
1038         assert(i);
1039         assert(property);
1040
1041         if (!dbus_message_iter_open_container(i, DBUS_TYPE_ARRAY, "s", &sub))
1042                 return -ENOMEM;
1043
1044         STRV_FOREACH(t, t)
1045                 if (!dbus_message_iter_append_basic(&sub, DBUS_TYPE_STRING, t))
1046                         return -ENOMEM;
1047
1048         if (!dbus_message_iter_close_container(i, &sub))
1049                 return -ENOMEM;
1050
1051         return 0;
1052 }
1053
1054 int bus_property_append_bool(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1055         bool *b = data;
1056         dbus_bool_t db;
1057
1058         assert(m);
1059         assert(i);
1060         assert(property);
1061         assert(b);
1062
1063         db = *b;
1064
1065         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_BOOLEAN, &db))
1066                 return -ENOMEM;
1067
1068         return 0;
1069 }
1070
1071 int bus_property_append_uint64(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1072         assert(m);
1073         assert(i);
1074         assert(property);
1075         assert(data);
1076
1077         /* Let's ensure that pid_t is actually 64bit, and hence this
1078          * function can be used for usec_t */
1079         assert_cc(sizeof(uint64_t) == sizeof(usec_t));
1080
1081         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT64, data))
1082                 return -ENOMEM;
1083
1084         return 0;
1085 }
1086
1087 int bus_property_append_uint32(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1088         assert(m);
1089         assert(i);
1090         assert(property);
1091         assert(data);
1092
1093         /* Let's ensure that pid_t and mode_t is actually 32bit, and
1094          * hence this function can be used for pid_t/mode_t */
1095         assert_cc(sizeof(uint32_t) == sizeof(pid_t));
1096         assert_cc(sizeof(uint32_t) == sizeof(mode_t));
1097         assert_cc(sizeof(uint32_t) == sizeof(unsigned));
1098
1099         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_UINT32, data))
1100                 return -ENOMEM;
1101
1102         return 0;
1103 }
1104
1105 int bus_property_append_int32(Manager *m, DBusMessageIter *i, const char *property, void *data) {
1106         assert(m);
1107         assert(i);
1108         assert(property);
1109         assert(data);
1110
1111         assert_cc(sizeof(int32_t) == sizeof(int));
1112
1113         if (!dbus_message_iter_append_basic(i, DBUS_TYPE_INT32, data))
1114                 return -ENOMEM;
1115
1116         return 0;
1117 }
1118
1119 int bus_parse_strv(DBusMessage *m, char ***_l) {
1120         DBusMessageIter iter, sub;
1121         unsigned n = 0, i = 0;
1122         char **l;
1123
1124         assert(m);
1125         assert(_l);
1126
1127         if (!dbus_message_iter_init(m, &iter) ||
1128             dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_ARRAY ||
1129             dbus_message_iter_get_element_type(&iter) != DBUS_TYPE_STRING)
1130             return -EINVAL;
1131
1132         dbus_message_iter_recurse(&iter, &sub);
1133
1134         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1135                 n++;
1136                 dbus_message_iter_next(&sub);
1137         }
1138
1139         if (!(l = new(char*, n+1)))
1140                 return -ENOMEM;
1141
1142         assert_se(dbus_message_iter_init(m, &iter));
1143         dbus_message_iter_recurse(&iter, &sub);
1144
1145         while (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_INVALID) {
1146                 const char *s;
1147
1148                 assert_se(dbus_message_iter_get_arg_type(&sub) == DBUS_TYPE_STRING);
1149                 dbus_message_iter_get_basic(&sub, &s);
1150
1151                 if (!(l[i++] = strdup(s))) {
1152                         strv_free(l);
1153                         return -ENOMEM;
1154                 }
1155
1156                 dbus_message_iter_next(&sub);
1157         }
1158
1159         assert(i == n);
1160         l[i] = NULL;
1161
1162         if (_l)
1163                 *_l = l;
1164
1165         return 0;
1166 }